interface: join a server from the screens, as inbuxa join does #28
No files matched your search
@@ -418,6 +418,18 @@ func (installer) Run(ctx context.Context, p plan.Plan, f host.Facts, log apply.L
|
||||
return apply.Run(ctx, p, f, log)
|
||||
}
|
||||
|
||||
func (installer) JoinCheck(ctx context.Context, o plan.Options, key string) error {
|
||||
return apply.JoinCheck(ctx, o, key)
|
||||
}
|
||||
|
||||
func (installer) Join(ctx context.Context, p plan.Plan, f host.Facts, key string, log apply.Log) (*apply.Result, error) {
|
||||
return apply.Join(ctx, p, f, key, log)
|
||||
}
|
||||
|
||||
func (installer) JoinVerify(ctx context.Context, res *apply.Result, console, webmail plan.Shape, log apply.Log) []string {
|
||||
return apply.JoinVerify(ctx, res, console, webmail, log)
|
||||
}
|
||||
|
||||
func (installer) Verify(ctx context.Context, res *apply.Result, o plan.Options, log apply.Log) []string {
|
||||
return apply.Verify(ctx, res, o, true, log)
|
||||
}
|
||||
|
||||
Executable
+225
@@ -0,0 +1,225 @@
|
||||
#!/bin/bash
|
||||
# SPDX-FileCopyrightText: 2026 Coffey Labs LLC
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
#
|
||||
# Joining from the interface: `inbuxa` with no arguments in a terminal (a
|
||||
# pseudo-terminal here), the mail server skipped, and the Server screen
|
||||
# filled in with a server and an API key, as a person would. Two machines are
|
||||
# played by one, as in join.sh, and the result is held to what join.sh checks
|
||||
# of the command: the server lists the front ends, the console may call it,
|
||||
# and a person signs in to the joined webmail.
|
||||
#
|
||||
# What only the interface can get wrong is checked too: skipping the server
|
||||
# leads to the Server screen rather than a refusal, the key is never on
|
||||
# screen, the server is asked before the plan, the plan shows `inbuxa join`
|
||||
# with `--key -`, nothing happens before the "y", and the summary says where
|
||||
# it joined and that the key wasn't kept.
|
||||
#
|
||||
# Run from the host with: e2e/vm/run.sh e2e/cases/interface-join.sh
|
||||
set -uo pipefail
|
||||
pass=0; fail=0
|
||||
ok() { echo " ok $*"; pass=$((pass+1)); }
|
||||
bad() { echo " FAIL $*"; fail=$((fail+1)); }
|
||||
|
||||
SERVER_DIR=/var/lib/inbuxa
|
||||
DIR=/var/lib/inbuxa-joined
|
||||
SERVER=http://127.0.0.1:8081
|
||||
if [ -x /tmp/inbuxa-server-test ]; then
|
||||
export INBUXA_SERVER_BINARY=/tmp/inbuxa-server-test
|
||||
# A debug build needs a deeper stack than a release one, as the server's
|
||||
# own test suites do (RUST_MIN_STACK in its CI). A drop-in made before the
|
||||
# unit exists applies when it does.
|
||||
mkdir -p /etc/systemd/system/inbuxa-server.service.d
|
||||
printf '[Service]\nEnvironment=RUST_MIN_STACK=16777216\n' > /etc/systemd/system/inbuxa-server.service.d/test-build.conf
|
||||
fi
|
||||
|
||||
rt() { command -v docker >/dev/null 2>&1 && echo docker || echo podman; }
|
||||
compose() {
|
||||
if [ "$(rt)" = docker ]; then
|
||||
docker compose -f "$DIR/compose.yaml" "$@"
|
||||
else
|
||||
DOCKER_HOST=unix:///run/podman/podman.sock \
|
||||
/usr/local/lib/docker/cli-plugins/docker-compose -f "$DIR/compose.yaml" "$@"
|
||||
fi
|
||||
}
|
||||
jmap() { # jmap TOKEN-or-user:pass CAPABILITY JSON-CALLS
|
||||
local auth
|
||||
case "$1" in *:*) auth=(-u "$1") ;; *) auth=(-H "Authorization: Bearer $1") ;; esac
|
||||
curl -s "${auth[@]}" -H 'Content-Type: application/json' \
|
||||
-d "{\"using\":[\"urn:ietf:params:jmap:core\",\"$2\"],\"methodCalls\":$3}" "$SERVER/jmap/"
|
||||
}
|
||||
wait_server() { for _ in $(seq 1 60); do [ "$(curl -s -o /dev/null -w '%{http_code}' $SERVER/.well-known/jmap)" != 000 ] && return 0; sleep 2; done; return 1; }
|
||||
|
||||
echo "==> the server, on its own"
|
||||
OUT="$(/tmp/inbuxa install --local --domain example.test --server host --console skip --webmail skip --yes 2>&1)"; rc=$?
|
||||
if [ $rc -eq 0 ]; then ok "installed the server alone"; else
|
||||
bad "server install exit $rc"; echo "$OUT" | tail -15 | sed 's/^/ /'
|
||||
journalctl -u inbuxa-server -n 30 --no-pager -o cat | sed 's/^/ | /'
|
||||
echo; echo "==> $pass passed, $fail failed (stopped: no server to join)"; exit 1
|
||||
fi
|
||||
[ -n "${INBUXA_SERVER_BINARY:-}" ] && echo " (server: $(/usr/local/bin/inbuxa-server --version 2>&1 | head -1), from the build given)"
|
||||
|
||||
echo
|
||||
echo "==> an API key, as an administrator makes one in the console"
|
||||
# The console is a browser; here the server takes the administrator's
|
||||
# password for one restart, the way the installer's own setup does.
|
||||
AUSER=$(awk '/^administrator/ {print $2}' "$SERVER_DIR/credentials.txt")
|
||||
APASS=$(awk '/^administrator/{getline; print $2}' "$SERVER_DIR/credentials.txt")
|
||||
echo "INBUXA_HTTP_BASIC_AUTH=all" >> "$SERVER_DIR/server.env"
|
||||
systemctl restart inbuxa-server; wait_server
|
||||
EXPIRES=$(date -u -d '+1 hour' +%Y-%m-%dT%H:%M:%SZ)
|
||||
ANSWER=$(jmap "$AUSER:$APASS" urn:inbuxa:jmap:registry "[[\"x:ApiKey/set\",{\"create\":{\"k\":{\"description\":\"join test\",\"expiresAt\":\"$EXPIRES\",\"permissions\":{\"@type\":\"Inherit\"}}}},\"0\"]]")
|
||||
KEY=$(sed -n 's/.*"secret":"\([^"]*\)".*/\1/p' <<<"$ANSWER")
|
||||
sed -i '/^INBUXA_HTTP_BASIC_AUTH=/d' "$SERVER_DIR/server.env"
|
||||
systemctl restart inbuxa-server; wait_server
|
||||
[ -n "$KEY" ] && ok "an API key for the administrator" || { bad "no API key"; head -c 300 <<<"$ANSWER" | sed 's/^/ /'; }
|
||||
|
||||
ACCOUNT=$(curl -s -H "Authorization: Bearer $KEY" $SERVER/jmap/session | grep -o '"primaryAccounts":{[^}]*}' | sed -n 's/^"primaryAccounts":{"[^"]*":"\([^"]*\)".*/\1/p')
|
||||
[ -n "$ACCOUNT" ] || bad "no account id in the key's session"
|
||||
|
||||
# From here this is "another machine": no install recorded on it.
|
||||
mv /etc/inbuxa/install.json /etc/inbuxa/install.server.json
|
||||
|
||||
# From here this is "another machine": no install recorded on it.
|
||||
|
||||
command -v python3 >/dev/null || { bad "no python3 on this machine to drive a terminal with"; echo "==> $pass passed, $fail failed"; exit 1; }
|
||||
cat > /tmp/drive-join.py <<'PY'
|
||||
import os, pty, re, select, struct, sys, time, fcntl, termios
|
||||
KEY = os.environ.pop("KEY")
|
||||
pid, fd = pty.fork()
|
||||
if pid == 0:
|
||||
os.environ["TERM"] = "xterm-256color"
|
||||
os.execv("/tmp/inbuxa", ["/tmp/inbuxa"])
|
||||
fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 32, 110, 0, 0))
|
||||
seen = ""
|
||||
def plain(s):
|
||||
return re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", "", s)
|
||||
def pump(t):
|
||||
global seen
|
||||
end = time.time() + t
|
||||
while time.time() < end:
|
||||
r, _, _ = select.select([fd], [], [], 0.1)
|
||||
if r:
|
||||
try:
|
||||
seen += os.read(fd, 65536).decode("utf-8", "replace")
|
||||
except OSError:
|
||||
return False
|
||||
return True
|
||||
def frame():
|
||||
return plain(seen.split("\x1b[H")[-1])
|
||||
def wait_for(text, timeout, label):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
if text in " ".join(frame().replace("|", " ").split()):
|
||||
print("OK", label); return True
|
||||
if not pump(0.5):
|
||||
break
|
||||
print("FAIL", label, "-- never saw:", text)
|
||||
print("\n".join(" | " + l for l in frame().split("\r\n")[:30]))
|
||||
return False
|
||||
def wait_done(timeout, label):
|
||||
# Done, or Stopped with the reason: either way the screen has its answer.
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
words = " ".join(frame().replace("|", " ").split())
|
||||
if "Done." in words:
|
||||
print("OK", label); return True
|
||||
if "Stopped:" in words:
|
||||
break
|
||||
if not pump(0.5):
|
||||
break
|
||||
print("FAIL", label, "-- the screen says:")
|
||||
print("\n".join(" | " + l for l in frame().split("\r\n")[:30]))
|
||||
return False
|
||||
def keys(s):
|
||||
os.write(fd, s.encode()); pump(0.4)
|
||||
ENTER, DOWN, CTRL_U = "\r", "\x1b[B", "\x15"
|
||||
wait_for("What this machine allows", 30, "screen 1: what it found")
|
||||
keys(ENTER)
|
||||
wait_for("Where it will be reached", 10, "screen 2: names")
|
||||
keys(DOWN * 5 + CTRL_U + "/var/lib/inbuxa-joined" + DOWN + " ")
|
||||
wait_for("example.test", 5, "loopback, in a directory of its own")
|
||||
keys(ENTER)
|
||||
wait_for("What goes on this machine", 10, "screen 3: components")
|
||||
keys("s")
|
||||
keys(ENTER)
|
||||
wait_for("The server these front ends are for", 10, "skipping the server leads to the Server screen")
|
||||
wait_for("Server › Reach", 5, "and the steps say so")
|
||||
keys("http://127.0.0.1:8081" + DOWN + KEY)
|
||||
print("FAIL the key is on screen" if KEY in plain(seen) else "OK the key is typed, not shown")
|
||||
keys(DOWN + ENTER)
|
||||
wait_for("The key works, and the server can take these front ends", 30, "the server is asked before the plan")
|
||||
wait_for("publishes nothing", 10, "then reach, on loopback")
|
||||
keys(ENTER)
|
||||
wait_for("Nothing has happened yet", 10, "the plan")
|
||||
wait_for("Register these front ends with the server", 5, "the plan registers them with the server")
|
||||
keys("\x1b[6~" * 4)
|
||||
wait_for("inbuxa join http://127.0.0.1:8081 --key - --local --domain example.test --dir /var/lib/inbuxa-joined --install-deps --yes", 5, "the plan shows the join command, with --key -")
|
||||
keys(ENTER)
|
||||
wait_for("Join now?", 5, "a confirmation before anything happens")
|
||||
print("OK nothing joined before the y" if not os.path.exists("/var/lib/inbuxa-joined/compose.yaml") else "FAIL something was written before the y")
|
||||
keys("y")
|
||||
wait_done(1500, "the join finishes on screen")
|
||||
keys("q")
|
||||
pump(2)
|
||||
after = plain(seen.split("\x1b[?1049l")[-1]) if "\x1b[?1049l" in seen else ""
|
||||
print("OK the terminal is given back" if "\x1b[?1049l" in seen and "\x1b[?25h" in seen else "FAIL the terminal was not restored")
|
||||
print("OK the summary says where it joined" if "joined to" in after and "127.0.0.1:8081" in after else "FAIL no join in the summary: " + repr(after[-300:]))
|
||||
print("OK and that the key wasn't kept" if "not kept here" in after else "FAIL the summary doesn't say the key wasn't kept")
|
||||
print("FAIL the key appeared on screen at some point" if KEY in plain(seen) else "OK the key never appeared on screen")
|
||||
_, status = os.waitpid(pid, 0)
|
||||
code = os.waitstatus_to_exitcode(status)
|
||||
print(("OK" if code == 0 else "FAIL") + f" exit status {code}")
|
||||
PY
|
||||
echo
|
||||
echo "==> joining from the interface"
|
||||
OUT="$(KEY="$KEY" python3 /tmp/drive-join.py 2>&1)"
|
||||
while IFS= read -r line; do
|
||||
case "$line" in
|
||||
OK\ *) ok "${line#OK }" ;;
|
||||
FAIL\ *) bad "${line#FAIL }" ;;
|
||||
*) echo "$line" ;;
|
||||
esac
|
||||
done <<<"$OUT"
|
||||
|
||||
echo
|
||||
echo "==> what it joined"
|
||||
grep -q "$KEY" <<<"$(cat $DIR/* 2>/dev/null)" && bad "the API key was written down here" || ok "the API key was not kept"
|
||||
STATE="$(compose ps --format '{{.Service}} {{.State}}')"
|
||||
for s in console webmail; do
|
||||
grep -q "^$s running" <<<"$STATE" && ok "$s is running" || { bad "$s is not running"; echo "$STATE" | sed 's/^/ /'; }
|
||||
done
|
||||
grep -q "^ server:" "$DIR/compose.yaml" && bad "a server was put here too" || ok "no server here"
|
||||
grep -q '"serverUrl": "http://127.0.0.1:8081"' /etc/inbuxa/install.json && ok "the install record names the server it joined" || bad "no serverUrl in the install record"
|
||||
echo "==> the server knows the front ends"
|
||||
FE=$(jmap "$KEY" urn:inbuxa:jmap '[["inbuxa:FrontEnds/get",{"accountId":"'"$ACCOUNT"'"},"0"]]')
|
||||
grep -q '"adminUrl":"http://127.0.0.1:8082"' <<<"$FE" && ok "the console's address" || bad "adminUrl: $FE"
|
||||
grep -q '"webmailUrl":"http://127.0.0.1:8080"' <<<"$FE" && ok "the webmail's address" || bad "webmailUrl: $FE"
|
||||
grep -q '"webmailClientSecretSet":true' <<<"$FE" && ok "and a webmail secret, which it does not show" || bad "no webmail secret: $FE"
|
||||
ALLOW=$(curl -s -o /dev/null -D - -X OPTIONS $SERVER/jmap/session -H 'Origin: http://127.0.0.1:8082' \
|
||||
-H 'Access-Control-Request-Method: GET' -H 'Access-Control-Request-Headers: authorization' | tr -d '\r' | awk -F': ' 'tolower($1)=="access-control-allow-origin"{print $2}')
|
||||
[ "$ALLOW" = "http://127.0.0.1:8082" ] && ok "the console's origin may call the server" || bad "access-control-allow-origin: '$ALLOW'"
|
||||
curl -fsS http://127.0.0.1:8082/ 2>/dev/null | grep -q "content=\"$SERVER\"" && ok "the console points at the server" || bad "the console's api-base-url is not $SERVER"
|
||||
|
||||
echo
|
||||
echo "==> a person signs in to the joined webmail"
|
||||
USER=$(awk '/^first mailbox/ {print $3}' "$SERVER_DIR/credentials.txt")
|
||||
PASS=$(awk '/^first mailbox/{getline; print $2}' "$SERVER_DIR/credentials.txt")
|
||||
rm -f /tmp/jar
|
||||
LOC=$(curl -s -o /dev/null -c /tmp/jar -w '%{redirect_url}' "http://127.0.0.1:8080/api/auth/oauth/start?username=$USER&remember=1")
|
||||
grep -q "^$SERVER/" <<<"$LOC" && ok "the webmail sends sign-in to the server" || bad "sign-in went to '${LOC:-nowhere}'"
|
||||
q() { sed -n "s/.*[?&]$1=\([^&]*\).*/\1/p" <<<"$LOC"; }
|
||||
urldecode() { printf '%b' "${1//%/\\x}"; }
|
||||
STATE=$(q state); CHALLENGE=$(q code_challenge); REDIRECT=$(urldecode "$(q redirect_uri)")
|
||||
ANSWER=$(curl -s -X POST $SERVER/api/auth -H 'Content-Type: application/json' -H 'Accept: application/json' \
|
||||
-d "{\"type\":\"authCode\",\"accountName\":\"$USER\",\"accountSecret\":\"$PASS\",\"clientId\":\"ihasmail-inbuxa\",\"redirectUri\":\"$REDIRECT\",\"codeChallenge\":\"$CHALLENGE\",\"codeChallengeMethod\":\"S256\"}")
|
||||
AUTHCODE=$(sed -n 's/.*"client_\{0,1\}[cC]ode":"\([^"]*\)".*/\1/p' <<<"$ANSWER")
|
||||
[ -n "$AUTHCODE" ] && ok "the server takes the joined webmail's redirect" || { bad "the server's sign-in answered"; head -c 200 <<<"$ANSWER" | sed 's/^/ /'; }
|
||||
BACK=$(curl -s -o /dev/null -b /tmp/jar -c /tmp/jar -w '%{redirect_url}' "$REDIRECT?code=$AUTHCODE&state=$STATE")
|
||||
grep -q "signin_error" <<<"$BACK" && bad "the webmail's code exchange failed (its secret?): $BACK" || ok "the webmail exchanges the code with the secret made here"
|
||||
CODE=$(curl -s -o /tmp/login.json -b /tmp/jar -w '%{http_code}' -H 'X-Requested-With: ihasmail' http://127.0.0.1:8080/api/auth/session)
|
||||
[ "$CODE" = 200 ] && grep -q "urn:ietf:params:jmap:mail" /tmp/login.json && ok "signed in, with mail" || { bad "the session answered $CODE"; head -c 200 /tmp/login.json | sed 's/^/ /'; }
|
||||
|
||||
echo
|
||||
echo "==> $pass passed, $fail failed"
|
||||
[ "$fail" -eq 0 ]
|
||||
+84
-12
@@ -5,6 +5,8 @@ package tui
|
||||
|
||||
// The installer's interface: six screens, always in this order, with the
|
||||
// plan in front of the operator before anything happens (installer spec §4).
|
||||
// With the mail server skipped, it joins a server on another machine instead,
|
||||
// and a seventh screen, Join, asks for that server and an API key (join.go).
|
||||
//
|
||||
// It is a way of filling in the flags with the machine's own facts on
|
||||
// screen, not a second implementation. Every screen writes into the same
|
||||
@@ -29,18 +31,23 @@ const (
|
||||
screenFound = iota
|
||||
screenNames
|
||||
screenComponents
|
||||
screenJoin
|
||||
screenReach
|
||||
screenPlan
|
||||
screenApply
|
||||
)
|
||||
|
||||
var screenTitles = []string{"What it found", "Names", "Components", "Reach", "The plan", "Install"}
|
||||
var screenTitles = []string{"What it found", "Names", "Components", "Server", "Reach", "The plan", "Install"}
|
||||
|
||||
// Installer carries out an install. In the program it is apply.Run and
|
||||
// apply.Verify; tests give it something that changes nothing.
|
||||
type Installer interface {
|
||||
Run(ctx context.Context, p plan.Plan, f host.Facts, log apply.Log) (*apply.Result, error)
|
||||
Verify(ctx context.Context, res *apply.Result, o plan.Options, log apply.Log) []string
|
||||
// The same for a join: apply.JoinCheck, apply.Join and apply.JoinVerify.
|
||||
JoinCheck(ctx context.Context, o plan.Options, key string) error
|
||||
Join(ctx context.Context, p plan.Plan, f host.Facts, key string, log apply.Log) (*apply.Result, error)
|
||||
JoinVerify(ctx context.Context, res *apply.Result, console, webmail plan.Shape, log apply.Log) []string
|
||||
}
|
||||
|
||||
// Wizard is the interface's state.
|
||||
@@ -61,6 +68,8 @@ type Wizard struct {
|
||||
|
||||
proxy int // 0 caddy, 1 snippets for your own, 2 none
|
||||
|
||||
join joinState // the Join screen, when the server is skipped (join.go)
|
||||
|
||||
built plan.Plan
|
||||
buildErr error
|
||||
confirming bool
|
||||
@@ -76,6 +85,7 @@ type field struct {
|
||||
value []rune
|
||||
cursor int
|
||||
toggle bool // a yes/no field, in value "yes" or ""
|
||||
secret bool // typed but never shown: the API key
|
||||
placeholder func(o plan.Options) string
|
||||
}
|
||||
|
||||
@@ -105,6 +115,7 @@ func NewWizard(f host.Facts, inst Installer) *Wizard {
|
||||
for _, f := range w.fields {
|
||||
f.cursor = len(f.value)
|
||||
}
|
||||
w.join.fields = joinFields()
|
||||
w.shapes = map[plan.Component]plan.Shape{plan.Server: plan.Container, plan.Console: plan.Container, plan.Webmail: plan.Container}
|
||||
for _, c := range []plan.Component{plan.Server, plan.Console, plan.Webmail} {
|
||||
w.shapes[c] = w.defaultShape(c)
|
||||
@@ -150,6 +161,9 @@ func (w *Wizard) Options() plan.Options {
|
||||
for _, c := range []plan.Component{plan.Server, plan.Console, plan.Webmail} {
|
||||
o.Choices = append(o.Choices, plan.Choice{Component: c, Shape: w.shapes[c]})
|
||||
}
|
||||
if w.joining() {
|
||||
w.joinOptions(&o)
|
||||
}
|
||||
// What the machine lacks for the shapes chosen is installed rather
|
||||
// than refused: the components screen says what that will be.
|
||||
o.InstallDeps = len(w.needs(o)) > 0
|
||||
@@ -175,9 +189,13 @@ func withDeps(o plan.Options) plan.Options {
|
||||
|
||||
// Update handles one key.
|
||||
func (w *Wizard) Update(k Key) bool {
|
||||
w.settle()
|
||||
if w.screen == screenApply {
|
||||
return w.updateApply(k)
|
||||
}
|
||||
if w.join.checking() {
|
||||
return w.updateChecking(k)
|
||||
}
|
||||
if k.Kind == KeyCtrlC {
|
||||
return true
|
||||
}
|
||||
@@ -194,11 +212,14 @@ func (w *Wizard) Update(k Key) bool {
|
||||
}
|
||||
w.message = ""
|
||||
// q quits everywhere but in a text field, where it is a letter
|
||||
if k.Kind == KeyRune && k.Rune == 'q' && !(w.screen == screenNames && !w.fields[w.focus].toggle) {
|
||||
if k.Kind == KeyRune && k.Rune == 'q' && !w.typing() {
|
||||
return true
|
||||
}
|
||||
if k.Kind == KeyEsc && w.screen > screenFound {
|
||||
w.screen--
|
||||
if w.screen == screenJoin && !w.joining() {
|
||||
w.screen--
|
||||
}
|
||||
w.scroll = 0
|
||||
return false
|
||||
}
|
||||
@@ -212,6 +233,8 @@ func (w *Wizard) Update(k Key) bool {
|
||||
w.updateNames(k)
|
||||
case screenComponents:
|
||||
w.updateComponents(k)
|
||||
case screenJoin:
|
||||
w.updateJoin(k)
|
||||
case screenReach:
|
||||
w.updateReach(k)
|
||||
case screenPlan:
|
||||
@@ -222,6 +245,8 @@ func (w *Wizard) Update(k Key) bool {
|
||||
w.message = "The plan can't be carried out as it stands: Esc to go back and change it."
|
||||
case !w.Facts.Root:
|
||||
w.message = "Installing needs root: run it again as root (sudo inbuxa). Nothing has happened."
|
||||
case w.joining() && !w.joinChecked():
|
||||
w.message = "The server hasn't been asked about this exact join: Esc back to the Server screen and ask it again."
|
||||
default:
|
||||
w.confirming = true
|
||||
}
|
||||
@@ -232,6 +257,9 @@ func (w *Wizard) Update(k Key) bool {
|
||||
|
||||
func (w *Wizard) next() {
|
||||
w.screen++
|
||||
if w.screen == screenJoin && !w.joining() {
|
||||
w.screen++
|
||||
}
|
||||
w.scroll = 0
|
||||
if w.screen == screenPlan {
|
||||
w.built, w.buildErr = plan.Build(w.Facts, w.Options())
|
||||
@@ -284,6 +312,19 @@ func (w *Wizard) updateNames(k Key) {
|
||||
}
|
||||
return
|
||||
}
|
||||
f.edit(k)
|
||||
default:
|
||||
f.edit(k)
|
||||
}
|
||||
}
|
||||
|
||||
// edit is a key in a text field: typing, deleting and moving the cursor.
|
||||
func (f *field) edit(k Key) {
|
||||
switch k.Kind {
|
||||
case KeyRune:
|
||||
if f.toggle {
|
||||
return
|
||||
}
|
||||
f.value = append(f.value[:f.cursor], append([]rune{k.Rune}, f.value[f.cursor:]...)...)
|
||||
f.cursor++
|
||||
case KeyBackspace:
|
||||
@@ -434,8 +475,10 @@ func (w *Wizard) componentsProblem() string {
|
||||
if !any {
|
||||
return "Choose at least one component."
|
||||
}
|
||||
if w.shapes[plan.Server] == plan.Skip {
|
||||
return "Front ends for a server on another machine are installed with inbuxa join, not here: keep the server, or quit and use join."
|
||||
if w.joining() {
|
||||
if s := recordedServer(); s != "" {
|
||||
return fmt.Sprintf("This machine runs the mail server itself (a %s install), so its console and webmail are added with it, not joined to it: keep the mail server here.", s)
|
||||
}
|
||||
}
|
||||
// What each choice can do on its own is above; what the choices can't
|
||||
// do together -- a console of files on loopback, with no web server to
|
||||
@@ -472,16 +515,23 @@ func (w *Wizard) View(width, height int) []string {
|
||||
if width < 60 || height < 16 {
|
||||
return []string{"", " The window is too small for the installer.", " Make it at least 60 by 16, or press q to quit."}
|
||||
}
|
||||
w.settle()
|
||||
var out []string
|
||||
steps := make([]string, len(screenTitles))
|
||||
var steps []string
|
||||
for i, t := range screenTitles {
|
||||
if i == screenJoin && !w.joining() {
|
||||
continue
|
||||
}
|
||||
if i == screenApply && w.joining() {
|
||||
t = "Join"
|
||||
}
|
||||
switch {
|
||||
case i == w.screen:
|
||||
steps[i] = Bold(Accent(t))
|
||||
steps = append(steps, Bold(Accent(t)))
|
||||
case i < w.screen:
|
||||
steps[i] = t
|
||||
steps = append(steps, t)
|
||||
default:
|
||||
steps[i] = Dim(t)
|
||||
steps = append(steps, Dim(t))
|
||||
}
|
||||
}
|
||||
out = append(out, " "+Bold("inbuxa installer")+Dim(" · ")+strings.Join(steps, Dim(" › ")), "")
|
||||
@@ -496,6 +546,8 @@ func (w *Wizard) View(width, height int) []string {
|
||||
body, help = w.viewNames(width)
|
||||
case screenComponents:
|
||||
body, help = w.viewComponents(width)
|
||||
case screenJoin:
|
||||
body, help = w.viewJoin(width)
|
||||
case screenReach:
|
||||
body, help = w.viewReach(width)
|
||||
case screenPlan:
|
||||
@@ -522,6 +574,8 @@ func (w *Wizard) View(width, height int) []string {
|
||||
out = append(out, "")
|
||||
}
|
||||
switch {
|
||||
case w.confirming && w.joining():
|
||||
out = append(out, " "+Bold(Warn("Join now? This changes this machine and the server's front ends. y to go ahead, any other key not to.")))
|
||||
case w.confirming:
|
||||
out = append(out, " "+Bold(Warn("Install now? This changes this machine. y to go ahead, any other key not to.")))
|
||||
case w.message != "":
|
||||
@@ -630,7 +684,7 @@ func (w *Wizard) viewComponents(width int) ([]string, string) {
|
||||
body = append(body, "",
|
||||
" "+Dim("container: an image, run with this machine's docker or podman"),
|
||||
" "+Dim("host: from its release, under systemd or as files a web server serves"),
|
||||
" "+Dim("skip: not on this machine"))
|
||||
" "+Dim("skip: not on this machine; skip the mail server to join one that runs elsewhere"))
|
||||
return body, "↑↓: component ←→ or s/c/h: choose Enter: next Esc: back q: quit"
|
||||
}
|
||||
|
||||
@@ -682,12 +736,19 @@ func (w *Wizard) viewPlan(width int) ([]string, string) {
|
||||
for _, l := range Wrap(Command(w.built.Options), width-6) {
|
||||
body = append(body, " "+Accent(l))
|
||||
}
|
||||
return body, "Enter: install ↑↓ PgUp PgDn: scroll Esc: back q: quit"
|
||||
verb := "install"
|
||||
if w.joining() {
|
||||
verb = "join"
|
||||
}
|
||||
return body, "Enter: " + verb + " ↑↓ PgUp PgDn: scroll Esc: back q: quit"
|
||||
}
|
||||
|
||||
// Command is the flags that do what the screens chose, leaving out what
|
||||
// would be the default anyway.
|
||||
func Command(o plan.Options) string {
|
||||
if o.ServerURL != "" {
|
||||
return joinCommand(o)
|
||||
}
|
||||
args := []string{"inbuxa", "install"}
|
||||
add := func(flag, v, def string) {
|
||||
if v != "" && v != def {
|
||||
@@ -727,6 +788,7 @@ type progress struct {
|
||||
err error
|
||||
result *apply.Result
|
||||
problems []string
|
||||
extra []string // after the summary: what a join leaves to say
|
||||
poke func()
|
||||
}
|
||||
|
||||
@@ -763,6 +825,10 @@ func (l lineWriter) Write(b []byte) (int, error) {
|
||||
}
|
||||
|
||||
func (w *Wizard) startInstall() {
|
||||
if w.joining() {
|
||||
w.startJoin()
|
||||
return
|
||||
}
|
||||
w.screen = screenApply
|
||||
w.message = ""
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
@@ -827,6 +893,7 @@ func (w *Wizard) viewApply(width, room int) ([]string, string) {
|
||||
if pr.done {
|
||||
body = append(body, "")
|
||||
body = append(body, Summary(pr.result, pr.err, pr.problems)...)
|
||||
body = append(body, pr.extra...)
|
||||
return body, "Enter or q: leave (the summary stays in your terminal)"
|
||||
}
|
||||
// Under the steps, the last of what is being said
|
||||
@@ -871,7 +938,9 @@ func Summary(res *apply.Result, err error, problems []string) []string {
|
||||
}
|
||||
row("administrator", res.AdminUser)
|
||||
row("first mailbox", res.FirstUser)
|
||||
row("passwords", filepath.Join(res.Dir, "credentials.txt"))
|
||||
if res.AdminUser != "" { // a join makes no accounts, so writes no passwords
|
||||
row("passwords", filepath.Join(res.Dir, "credentials.txt"))
|
||||
}
|
||||
row("console", res.ConsoleURL)
|
||||
row("webmail", res.WebmailURL)
|
||||
if res.Certificate != "" {
|
||||
@@ -894,7 +963,10 @@ func (w *Wizard) Outcome() (summary []string, ran, ok bool) {
|
||||
pr.mu.Lock()
|
||||
defer pr.mu.Unlock()
|
||||
if !pr.done {
|
||||
if w.joining() {
|
||||
return []string{" The join was left before it finished; run inbuxa again to pick it up."}, true, false
|
||||
}
|
||||
return []string{" The install was left before it finished; run inbuxa again to pick it up."}, true, false
|
||||
}
|
||||
return Summary(pr.result, pr.err, pr.problems), true, pr.err == nil && len(pr.problems) == 0
|
||||
return append(Summary(pr.result, pr.err, pr.problems), pr.extra...), true, pr.err == nil && len(pr.problems) == 0
|
||||
}
|
||||
@@ -33,6 +33,13 @@ type fakeInstaller struct {
|
||||
got *plan.Plan
|
||||
fail error
|
||||
hold chan struct{} // when set, Run waits on it
|
||||
|
||||
// joins (join_test.go)
|
||||
checkErr error
|
||||
checkHold chan struct{} // when set, JoinCheck waits on it
|
||||
checkedOn []string // the keys JoinCheck was given
|
||||
joined *plan.Plan
|
||||
joinKey string
|
||||
}
|
||||
|
||||
func (f *fakeInstaller) Run(ctx context.Context, p plan.Plan, _ host.Facts, log apply.Log) (*apply.Result, error) {
|
||||
@@ -154,12 +161,20 @@ func TestWhatCannotBeBuiltIsRefusedOnItsScreen(t *testing.T) {
|
||||
if w.screen != screenComponents || !strings.Contains(w.message, "web server") {
|
||||
t.Errorf("a console host install on loopback got through: screen %d, %q", w.screen, w.message)
|
||||
}
|
||||
w.Update(Key{Kind: KeyRune, Rune: 'c'})
|
||||
press(w, KeyUp)
|
||||
w.Update(Key{Kind: KeyRune, Rune: 's'}) // no server
|
||||
w.Update(Key{Kind: KeyRune, Rune: 's'}) // no console
|
||||
press(w, KeyDown)
|
||||
w.Update(Key{Kind: KeyRune, Rune: 's'}) // no webmail
|
||||
press(w, KeyUp, KeyUp)
|
||||
w.Update(Key{Kind: KeyRune, Rune: 's'}) // and no server: nothing at all
|
||||
press(w, KeyEnter)
|
||||
if w.screen != screenComponents || !strings.Contains(w.message, "join") {
|
||||
t.Errorf("front ends without a server got through: %q", w.message)
|
||||
if w.screen != screenComponents || !strings.Contains(w.message, "at least one") {
|
||||
t.Errorf("nothing at all got through: %q", w.message)
|
||||
}
|
||||
press(w, KeyDown)
|
||||
w.Update(Key{Kind: KeyRune, Rune: 'c'}) // a console, for a server elsewhere: a join
|
||||
press(w, KeyEnter)
|
||||
if w.screen != screenJoin {
|
||||
t.Errorf("front ends without a server did not lead to the Server screen: %d, %q", w.screen, w.message)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
// SPDX-FileCopyrightText: 2026 Coffey Labs LLC
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package tui
|
||||
|
||||
// Joining from the interface: the mail server skipped on the components
|
||||
// screen means the console and the webmail are for a server that already
|
||||
// runs on another machine, as `inbuxa join` installs them. One more screen
|
||||
// asks which server and for an API key made in its console; leaving it asks
|
||||
// the server, as join does before anything else, whether the key works and
|
||||
// whether it can take these front ends. The rest is the same screens, the
|
||||
// same plan.Options, and apply.Join instead of apply.Run.
|
||||
//
|
||||
// The key is typed, never shown, never written down and never put in the
|
||||
// command the plan screen shows (that says --key -). It is dropped once the
|
||||
// join has used it.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/plan"
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/state"
|
||||
)
|
||||
|
||||
// recordedServer is how the mail server is installed on this machine, from
|
||||
// its install record, or "". A machine that runs the server adds front ends
|
||||
// with install, so the interface says so before a join gets anywhere, as
|
||||
// apply.Join would refuse it after. Tests replace it.
|
||||
var recordedServer = func() string {
|
||||
if st, err := state.Load(); err == nil {
|
||||
return st.Shapes["server"]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// joinState is the Join screen and the check it makes.
|
||||
type joinState struct {
|
||||
fields []*field
|
||||
focus int
|
||||
|
||||
mu sync.Mutex
|
||||
running bool
|
||||
done bool
|
||||
err error
|
||||
cancel context.CancelFunc
|
||||
checked string // the address and choices the key was last checked against
|
||||
}
|
||||
|
||||
const (
|
||||
joinAddress = iota
|
||||
joinKey
|
||||
joinReplace
|
||||
)
|
||||
|
||||
func joinFields() []*field {
|
||||
return []*field{
|
||||
{label: "Server", hint: "the mail server's address, as a browser reaches it", placeholder: func(o plan.Options) string { return defaultServerURL(o) }},
|
||||
{label: "API key", hint: "made in that server's console: your account, API keys; used once, never kept", secret: true},
|
||||
{label: "Replace", hint: "put these in place of a console or webmail the server already lists", toggle: true},
|
||||
}
|
||||
}
|
||||
|
||||
// joining is whether the screens describe a join: the server is elsewhere.
|
||||
func (w *Wizard) joining() bool { return w.shapes[plan.Server] == plan.Skip }
|
||||
|
||||
// typing is whether a key is a letter for a text field rather than a command.
|
||||
func (w *Wizard) typing() bool {
|
||||
switch w.screen {
|
||||
case screenNames:
|
||||
return !w.fields[w.focus].toggle
|
||||
case screenJoin:
|
||||
return !w.join.fields[w.join.focus].toggle
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// defaultServerURL is the server a join would reach if nothing else is
|
||||
// typed: the mail server's name from the Names screen, over HTTPS.
|
||||
func defaultServerURL(o plan.Options) string {
|
||||
switch {
|
||||
case o.MailHost != "":
|
||||
return "https://" + o.MailHost
|
||||
case o.Domain != "":
|
||||
return "https://mail." + o.Domain
|
||||
}
|
||||
return "https://mail.example.com"
|
||||
}
|
||||
|
||||
// serverURL is the address typed, the way `inbuxa join` reads its argument.
|
||||
func serverURL(typed string, o plan.Options) string {
|
||||
u := strings.TrimRight(strings.TrimSpace(typed), "/")
|
||||
if u == "" {
|
||||
u = defaultServerURL(o)
|
||||
}
|
||||
if !strings.HasPrefix(u, "https://") && !strings.HasPrefix(u, "http://") {
|
||||
u = "https://" + u
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// joinOptions turns Options into a join's: the server's address and
|
||||
// --replace, and no mail host of its own, as the join command builds them.
|
||||
func (w *Wizard) joinOptions(o *plan.Options) {
|
||||
o.ServerURL = serverURL(w.join.fields[joinAddress].text(), *o)
|
||||
o.Replace = w.join.fields[joinReplace].text() == "yes"
|
||||
o.MailHost = ""
|
||||
}
|
||||
|
||||
func (w *Wizard) joinKeyText() string { return strings.TrimSpace(w.join.fields[joinKey].text()) }
|
||||
|
||||
func (w *Wizard) updateJoin(k Key) {
|
||||
j := &w.join
|
||||
f := j.fields[j.focus]
|
||||
switch k.Kind {
|
||||
case KeyUp, KeyBackTab:
|
||||
if j.focus > 0 {
|
||||
j.focus--
|
||||
}
|
||||
case KeyDown, KeyTab:
|
||||
if j.focus < len(j.fields)-1 {
|
||||
j.focus++
|
||||
}
|
||||
case KeyEnter:
|
||||
if j.focus < len(j.fields)-1 {
|
||||
j.focus++
|
||||
return
|
||||
}
|
||||
if why := w.joinProblem(); why != "" {
|
||||
w.message = why
|
||||
return
|
||||
}
|
||||
w.startCheck()
|
||||
case KeyRune:
|
||||
if f.toggle {
|
||||
if k.Rune == ' ' || k.Rune == 'y' || k.Rune == 'n' {
|
||||
if (k.Rune == ' ' && f.text() != "yes") || k.Rune == 'y' {
|
||||
f.value = []rune("yes")
|
||||
} else {
|
||||
f.value = nil
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
f.edit(k)
|
||||
default:
|
||||
f.edit(k)
|
||||
}
|
||||
}
|
||||
|
||||
// joinProblem is why the Join screen can't be left yet, or "".
|
||||
func (w *Wizard) joinProblem() string {
|
||||
o := w.Options()
|
||||
host := strings.TrimPrefix(strings.TrimPrefix(o.ServerURL, "https://"), "http://")
|
||||
host = strings.SplitN(host, "/", 2)[0]
|
||||
if host == "" || strings.ContainsAny(host, " @") {
|
||||
return fmt.Sprintf("%q is not a server address like https://mail.example.com.", o.ServerURL)
|
||||
}
|
||||
if h, _, err := net.SplitHostPort(host); err == nil {
|
||||
host = h
|
||||
}
|
||||
if net.ParseIP(host) == nil && !strings.Contains(host, ".") {
|
||||
return fmt.Sprintf("%q is not a server address like https://mail.example.com.", o.ServerURL)
|
||||
}
|
||||
if w.joinKeyText() == "" {
|
||||
return "An API key is needed: make one in the server's console (your account, API keys) and type it here."
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// startCheck asks the server, in the background, what `inbuxa join` asks
|
||||
// before anything else. The screen says it is asking; Esc stops waiting.
|
||||
func (w *Wizard) startCheck() {
|
||||
o := w.Options()
|
||||
key := w.joinKeyText()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
j := &w.join
|
||||
j.mu.Lock()
|
||||
j.running, j.done, j.err, j.cancel = true, false, nil, cancel
|
||||
j.mu.Unlock()
|
||||
w.message = "Asking " + o.ServerURL + " whether the key works…"
|
||||
go func() {
|
||||
err := w.Installer.JoinCheck(ctx, o, key)
|
||||
cancel()
|
||||
j.mu.Lock()
|
||||
if j.running { // not abandoned meanwhile
|
||||
j.running, j.done, j.err = false, true, err
|
||||
if err == nil {
|
||||
j.checked = checkedAs(o)
|
||||
}
|
||||
}
|
||||
j.mu.Unlock()
|
||||
w.poke()
|
||||
}()
|
||||
}
|
||||
|
||||
// checkedAs is what a check vouched for: the server, and which front ends
|
||||
// it was asked about. Changing any of it sends the operator back through
|
||||
// the check before the plan.
|
||||
func checkedAs(o plan.Options) string {
|
||||
return fmt.Sprintf("%s|%s|%s|%s|%s|%t|%t", o.ServerURL, o.Shape(plan.Console), o.Shape(plan.Webmail), o.ConsoleHost, o.WebmailHost, o.Local, o.Replace)
|
||||
}
|
||||
|
||||
func (j *joinState) checking() bool {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
return j.running
|
||||
}
|
||||
|
||||
// updateChecking is the keys while the server is being asked: Esc or Ctrl-C
|
||||
// stops waiting, everything else waits.
|
||||
func (w *Wizard) updateChecking(k Key) bool {
|
||||
if k.Kind == KeyEsc || k.Kind == KeyCtrlC {
|
||||
j := &w.join
|
||||
j.mu.Lock()
|
||||
if j.cancel != nil {
|
||||
j.cancel()
|
||||
}
|
||||
j.running = false
|
||||
j.mu.Unlock()
|
||||
w.message = "Stopped asking. Nothing has happened."
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// settle takes in a finished check: on to the next screen if the server
|
||||
// agreed, the server's answer on screen if it didn't.
|
||||
func (w *Wizard) settle() {
|
||||
j := &w.join
|
||||
j.mu.Lock()
|
||||
done, err := j.done, j.err
|
||||
j.done = false
|
||||
j.mu.Unlock()
|
||||
if !done {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
w.message = err.Error()
|
||||
return
|
||||
}
|
||||
if w.screen == screenJoin {
|
||||
w.message = "The key works, and the server can take these front ends."
|
||||
w.next()
|
||||
}
|
||||
}
|
||||
|
||||
// joinChecked is whether the server agreed to exactly what the plan would do.
|
||||
func (w *Wizard) joinChecked() bool {
|
||||
j := &w.join
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
return j.checked != "" && j.checked == checkedAs(w.Options())
|
||||
}
|
||||
|
||||
func (w *Wizard) viewJoin(width int) ([]string, string) {
|
||||
o := w.Options()
|
||||
body := []string{" " + Bold("The server these front ends are for"), ""}
|
||||
for i, f := range w.join.fields {
|
||||
label := Pad(f.label, 20)
|
||||
var val string
|
||||
switch {
|
||||
case f.toggle:
|
||||
val = "[ ]"
|
||||
if f.text() == "yes" {
|
||||
val = "[x]"
|
||||
}
|
||||
if i == w.join.focus {
|
||||
val = Reverse(val)
|
||||
}
|
||||
case f.secret:
|
||||
// Never the key itself, only that something was typed.
|
||||
val = strings.Repeat("•", len(f.value))
|
||||
if len(f.value) == 0 && i != w.join.focus {
|
||||
val = Dim("none yet")
|
||||
}
|
||||
if i == w.join.focus {
|
||||
val += Reverse(" ")
|
||||
}
|
||||
case len(f.value) == 0 && i != w.join.focus:
|
||||
val = Dim(f.placeholder(o))
|
||||
case i == w.join.focus:
|
||||
s := f.value
|
||||
before, at, after := string(s[:f.cursor]), " ", ""
|
||||
if f.cursor < len(s) {
|
||||
at, after = string(s[f.cursor]), string(s[f.cursor+1:])
|
||||
}
|
||||
val = before + Reverse(at) + after
|
||||
if len(f.value) == 0 {
|
||||
val = Reverse(" ") + Dim(f.placeholder(o))
|
||||
}
|
||||
default:
|
||||
val = f.text()
|
||||
}
|
||||
line := " "
|
||||
if i == w.join.focus {
|
||||
line = Accent("› ")
|
||||
}
|
||||
body = append(body, line+label+val)
|
||||
if i == w.join.focus {
|
||||
body = append(body, " "+Dim(Pad("", 18)+f.hint))
|
||||
}
|
||||
}
|
||||
body = append(body, "")
|
||||
for _, l := range WrapProse("The server is reached only as a browser reaches it, over its own address. "+
|
||||
"The key goes to it once, to register these front ends; it isn't kept on this machine, "+
|
||||
"and you can remove it in the console when the join is done.", width-6) {
|
||||
body = append(body, " "+Dim(l))
|
||||
}
|
||||
if w.join.checking() {
|
||||
return body, "Asking the server… Esc: stop waiting"
|
||||
}
|
||||
return body, "↑↓ Tab: move type to edit Space: toggle Enter: ask the server Esc: back Ctrl-C: quit"
|
||||
}
|
||||
|
||||
// joinCommand is `inbuxa join` with the flags the screens chose. The key
|
||||
// is read from standard input there, never written on a command line.
|
||||
func joinCommand(o plan.Options) string {
|
||||
args := []string{"inbuxa", "join", o.ServerURL, "--key", "-"}
|
||||
add := func(flag, v, def string) {
|
||||
if v != "" && v != def {
|
||||
args = append(args, flag, v)
|
||||
}
|
||||
}
|
||||
if o.Local {
|
||||
args = append(args, "--local")
|
||||
}
|
||||
add("--domain", o.Domain, joinDomain(o.ServerURL))
|
||||
add("--console-host", o.ConsoleHost, "admin."+o.Domain)
|
||||
add("--webmail-host", o.WebmailHost, "webmail."+o.Domain)
|
||||
add("--email", o.ACMEEmail, "postmaster@"+o.Domain)
|
||||
add("--console", string(o.Shape(plan.Console)), "container")
|
||||
add("--webmail", string(o.Shape(plan.Webmail)), "container")
|
||||
if !o.Local {
|
||||
add("--proxy", o.Proxy, "caddy")
|
||||
}
|
||||
add("--dir", o.Dir, "/var/lib/inbuxa")
|
||||
if o.InstallDeps {
|
||||
args = append(args, "--install-deps")
|
||||
}
|
||||
if o.Replace {
|
||||
args = append(args, "--replace")
|
||||
}
|
||||
return strings.Join(append(args, "--yes"), " ")
|
||||
}
|
||||
|
||||
// joinDomain is the domain `inbuxa join` takes from the server's address
|
||||
// when --domain isn't given, so the command leaves it out when they agree.
|
||||
func joinDomain(serverURL string) string {
|
||||
host := strings.TrimPrefix(strings.TrimPrefix(serverURL, "https://"), "http://")
|
||||
host = strings.SplitN(strings.SplitN(host, "/", 2)[0], ":", 2)[0]
|
||||
if net.ParseIP(host) != nil {
|
||||
return ""
|
||||
}
|
||||
if _, rest, ok := strings.Cut(host, "."); ok && strings.Contains(rest, ".") {
|
||||
return rest
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
// startJoin carries out the join, as `inbuxa join` does after its check.
|
||||
func (w *Wizard) startJoin() {
|
||||
w.screen = screenApply
|
||||
w.message = ""
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
w.cancel = cancel
|
||||
pr := &progress{poke: w.poke}
|
||||
w.progress = pr
|
||||
p := w.built
|
||||
key := w.joinKeyText()
|
||||
// The key leaves the screen's memory now; the join below has its copy.
|
||||
w.join.fields[joinKey].value, w.join.fields[joinKey].cursor = nil, 0
|
||||
go func() {
|
||||
res, err := w.Installer.Join(ctx, p, w.Facts, key, pr)
|
||||
var problems []string
|
||||
var extra []string
|
||||
if err == nil {
|
||||
pr.Step("checking it works")
|
||||
problems = w.Installer.JoinVerify(ctx, res, p.Options.Shape(plan.Console), p.Options.Shape(plan.Webmail), pr)
|
||||
extra = []string{
|
||||
" joined to " + p.Options.ServerURL,
|
||||
"",
|
||||
" The API key is not kept here; you can remove it in the console now.",
|
||||
}
|
||||
}
|
||||
pr.mu.Lock()
|
||||
pr.done, pr.err, pr.result, pr.problems, pr.extra = true, err, res, problems, extra
|
||||
pr.mu.Unlock()
|
||||
pr.poke()
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
// SPDX-FileCopyrightText: 2026 Coffey Labs LLC
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/apply"
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/host"
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/plan"
|
||||
)
|
||||
|
||||
func (f *fakeInstaller) JoinCheck(ctx context.Context, o plan.Options, key string) error {
|
||||
f.mu.Lock()
|
||||
f.checkedOn = append(f.checkedOn, key)
|
||||
hold := f.checkHold
|
||||
f.mu.Unlock()
|
||||
if hold != nil {
|
||||
select {
|
||||
case <-hold:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return f.checkErr
|
||||
}
|
||||
|
||||
func (f *fakeInstaller) Join(ctx context.Context, p plan.Plan, _ host.Facts, key string, log apply.Log) (*apply.Result, error) {
|
||||
f.mu.Lock()
|
||||
f.joined, f.joinKey = &p, key
|
||||
f.mu.Unlock()
|
||||
log.Step("registering these front ends with %s", p.Options.ServerURL)
|
||||
return &apply.Result{Dir: p.Options.Dir, ConsoleURL: "https://admin." + p.Options.Domain, WebmailURL: "https://webmail." + p.Options.Domain, ServerURL: p.Options.ServerURL}, nil
|
||||
}
|
||||
|
||||
func (f *fakeInstaller) JoinVerify(context.Context, *apply.Result, plan.Shape, plan.Shape, apply.Log) []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
const testKey = "k3y-that-must-never-show"
|
||||
|
||||
// The tests never read this machine's own install record.
|
||||
func init() { recordedServer = func() string { return "" } }
|
||||
|
||||
// toJoin goes from the first screen to the Server screen: a domain, the
|
||||
// defaults for the names, and the mail server skipped.
|
||||
func toJoin(t *testing.T, w *Wizard, domain string) {
|
||||
t.Helper()
|
||||
press(w, KeyEnter)
|
||||
typeText(w, domain)
|
||||
for i := 0; i < len(w.fields); i++ {
|
||||
press(w, KeyEnter)
|
||||
}
|
||||
w.Update(Key{Kind: KeyRune, Rune: 's'}) // the mail server: skip
|
||||
press(w, KeyEnter)
|
||||
if w.screen != screenJoin {
|
||||
t.Fatalf("skipping the server did not lead to the Server screen, at %d: %q", w.screen, w.message)
|
||||
}
|
||||
}
|
||||
|
||||
// waitCheck waits for the question to the server to be answered, then lets
|
||||
// the wizard take the answer in, as the next redraw would.
|
||||
func waitCheck(t *testing.T, w *Wizard) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for w.join.checking() {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the check never finished")
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
w.View(100, 30)
|
||||
}
|
||||
|
||||
func TestSkippingTheServerJoinsOne(t *testing.T) {
|
||||
inst := &fakeInstaller{}
|
||||
w := NewWizard(debian13(true), inst)
|
||||
toJoin(t, w, "example.org")
|
||||
|
||||
head := w.View(100, 30)[0]
|
||||
if !strings.Contains(head, "Server") || !strings.Contains(head, "Join") || strings.Contains(head, "Install") {
|
||||
t.Errorf("the steps don't say this is a join: %q", head)
|
||||
}
|
||||
if got := w.Options().ServerURL; got != "https://mail.example.org" {
|
||||
t.Errorf("the server defaults to %q", got)
|
||||
}
|
||||
|
||||
press(w, KeyDown, KeyDown) // to Replace, past an empty key
|
||||
press(w, KeyEnter)
|
||||
if !strings.Contains(w.message, "API key") || w.join.checking() {
|
||||
t.Fatalf("no key, and it asked the server anyway: %q", w.message)
|
||||
}
|
||||
|
||||
press(w, KeyUp) // the key
|
||||
typeText(w, testKey)
|
||||
view := strings.Join(w.View(100, 30), "\n")
|
||||
if strings.Contains(view, testKey) || !strings.Contains(view, "••••") {
|
||||
t.Fatalf("the key is on screen:\n%s", view)
|
||||
}
|
||||
press(w, KeyDown, KeyEnter)
|
||||
waitCheck(t, w)
|
||||
if w.screen != screenReach || len(inst.checkedOn) != 1 || inst.checkedOn[0] != testKey {
|
||||
t.Fatalf("after the check: screen %d, %q, asked with %q", w.screen, w.message, inst.checkedOn)
|
||||
}
|
||||
|
||||
press(w, KeyEnter) // reach
|
||||
if w.screen != screenPlan {
|
||||
t.Fatalf("not at the plan: %q", w.message)
|
||||
}
|
||||
view = strings.Join(w.View(140, 60), "\n")
|
||||
if !strings.Contains(view, "inbuxa join https://mail.example.org --key - ") || strings.Contains(view, testKey) {
|
||||
t.Errorf("the plan's command:\n%s", view)
|
||||
}
|
||||
|
||||
press(w, KeyEnter)
|
||||
if !w.confirming || !strings.Contains(strings.Join(w.View(140, 30), "\n"), "Join now?") {
|
||||
t.Fatal("no confirmation before joining")
|
||||
}
|
||||
w.Update(Key{Kind: KeyRune, Rune: 'y'})
|
||||
waitDone(t, w)
|
||||
if inst.got != nil {
|
||||
t.Error("a join ran an install")
|
||||
}
|
||||
if inst.joined == nil || inst.joinKey != testKey || inst.joined.Options.ServerURL != "https://mail.example.org" || inst.joined.Options.Shape(plan.Server) != plan.Skip {
|
||||
t.Fatalf("joined %+v with %q", inst.joined, inst.joinKey)
|
||||
}
|
||||
if len(w.join.fields[joinKey].value) != 0 {
|
||||
t.Error("the key is still held after the join used it")
|
||||
}
|
||||
summary, ran, ok := w.Outcome()
|
||||
text := strings.Join(summary, "\n")
|
||||
if !ran || !ok || !strings.Contains(text, "joined to https://mail.example.org") || !strings.Contains(text, "not kept here") || strings.Contains(text, "credentials.txt") {
|
||||
t.Errorf("outcome %v %v:\n%s", ran, ok, text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAKeyTheServerRefusesStaysOnItsScreen(t *testing.T) {
|
||||
inst := &fakeInstaller{checkErr: errors.New("the server refused the API key; make one in the console under your account's API keys, then pass it with --key")}
|
||||
w := NewWizard(debian13(true), inst)
|
||||
toJoin(t, w, "example.org")
|
||||
press(w, KeyDown)
|
||||
typeText(w, testKey)
|
||||
press(w, KeyDown, KeyEnter)
|
||||
waitCheck(t, w)
|
||||
if w.screen != screenJoin || !strings.Contains(w.message, "refused the API key") {
|
||||
t.Fatalf("a refused key: screen %d, %q", w.screen, w.message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitingOnTheServerCanBeStopped(t *testing.T) {
|
||||
inst := &fakeInstaller{checkHold: make(chan struct{})}
|
||||
w := NewWizard(debian13(true), inst)
|
||||
toJoin(t, w, "example.org")
|
||||
press(w, KeyDown)
|
||||
typeText(w, testKey)
|
||||
press(w, KeyDown, KeyEnter)
|
||||
if !w.join.checking() {
|
||||
t.Fatal("not asking the server")
|
||||
}
|
||||
if quit := w.Update(Key{Kind: KeyRune, Rune: 'q'}); quit || w.screen != screenJoin {
|
||||
t.Fatal("a key other than Esc did something while asking")
|
||||
}
|
||||
press(w, KeyEsc)
|
||||
if w.join.checking() || w.screen != screenJoin || !strings.Contains(w.message, "Stopped asking") {
|
||||
t.Fatalf("Esc did not stop waiting: %q", w.message)
|
||||
}
|
||||
close(inst.checkHold)
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
w.View(100, 30)
|
||||
if w.screen != screenJoin {
|
||||
t.Error("an abandoned check moved the screens on when it finished")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAJoinChangedAfterItsCheckIsAskedAgain(t *testing.T) {
|
||||
inst := &fakeInstaller{}
|
||||
w := NewWizard(debian13(true), inst)
|
||||
toJoin(t, w, "example.org")
|
||||
press(w, KeyDown)
|
||||
typeText(w, testKey)
|
||||
press(w, KeyDown, KeyEnter)
|
||||
waitCheck(t, w)
|
||||
press(w, KeyEnter) // reach
|
||||
w.join.fields[joinReplace].value = []rune("yes") // what the server was not asked about
|
||||
press(w, KeyEnter)
|
||||
if w.confirming || !strings.Contains(w.message, "asked about this exact join") {
|
||||
t.Fatalf("a join the server didn't see was offered: %q", w.message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnInstallNeverShowsTheServerStep(t *testing.T) {
|
||||
w := NewWizard(debian13(true), &fakeInstaller{})
|
||||
if head := w.View(120, 30)[0]; strings.Contains(head, "Server") {
|
||||
t.Errorf("an install shows the join's step: %q", head)
|
||||
}
|
||||
toPlan(t, w, "example.org") // components → reach, never the Server screen
|
||||
press(w, KeyEsc, KeyEsc)
|
||||
if w.screen != screenComponents {
|
||||
t.Errorf("Esc from reach went to %d, not components", w.screen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheJoinCommandLeavesOutWhatJoinWouldWorkOut(t *testing.T) {
|
||||
o := plan.Options{ServerURL: "https://mail.example.org", Domain: "example.org", Dir: "/var/lib/inbuxa", Proxy: "caddy",
|
||||
Choices: []plan.Choice{{Component: plan.Server, Shape: plan.Skip}, {Component: plan.Console, Shape: plan.Container}, {Component: plan.Webmail, Shape: plan.Host}}}
|
||||
if got, want := Command(o), "inbuxa join https://mail.example.org --key - --webmail host --yes"; got != want {
|
||||
t.Errorf("Command = %q, want %q", got, want)
|
||||
}
|
||||
// The names the plan fills in are the defaults, and left out too.
|
||||
o.ConsoleHost, o.WebmailHost, o.ACMEEmail = "admin.example.org", "webmail.example.org", "[email protected]"
|
||||
if got, want := Command(o), "inbuxa join https://mail.example.org --key - --webmail host --yes"; got != want {
|
||||
t.Errorf("Command = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMachineThatRunsTheServerIsNotJoinedToIt(t *testing.T) {
|
||||
was := recordedServer
|
||||
recordedServer = func() string { return "host" }
|
||||
defer func() { recordedServer = was }()
|
||||
w := NewWizard(debian13(true), &fakeInstaller{})
|
||||
press(w, KeyEnter)
|
||||
typeText(w, "example.org")
|
||||
for i := 0; i < len(w.fields); i++ {
|
||||
press(w, KeyEnter)
|
||||
}
|
||||
w.Update(Key{Kind: KeyRune, Rune: 's'})
|
||||
press(w, KeyEnter)
|
||||
if w.screen != screenComponents || !strings.Contains(w.message, "runs the mail server itself") {
|
||||
t.Fatalf("a join on the server's own machine got through: screen %d, %q", w.screen, w.message)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user