inbuxa relay: install inbuxa Relay on a machine of its own #45
No files matched your search
@@ -152,6 +152,20 @@ This is early. What is built:
|
||||
installing. It exits non-zero when they disagree, so a machine can be
|
||||
asked in a script whether it still matches itself.
|
||||
|
||||
- **`relay install --token -`** -- inbuxa Relay, on a machine of its own in
|
||||
front of the server: the release's static `inbuxa-relay` binary, checked
|
||||
against a checksum in the source and against the inbuxa release keys'
|
||||
signature, owned by a user of its own so an upgrade from the console can
|
||||
replace it, under `inbuxa-relay.service` with ports 25 and 443 and nothing
|
||||
more. It joins with the token the console shows when you add the relay
|
||||
(`--token -` reads it from standard input, `INBUXA_RELAY_JOIN_TOKEN` works
|
||||
too), and refuses on a machine that runs the mail server or where port 25
|
||||
is taken. `--link-listen` puts the link on one address, such as a WireGuard
|
||||
one. Run again, it converges, and leaves a newer binary from the console
|
||||
alone. `relay status` is the relay's own account of itself; `relay
|
||||
uninstall` keeps its state, and `--purge` resets it, which it refuses
|
||||
while it holds mail unless `--discard-held`.
|
||||
|
||||
- **Moving the server** -- `install` run again with the other `--server`
|
||||
moves the mail server between a container and the host, with its
|
||||
configuration and mail. It needs an API key made in the console (`--key -`
|
||||
|
||||
@@ -28,6 +28,7 @@ import (
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/discover"
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/host"
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/plan"
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/relay"
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/state"
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/topology"
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/tui"
|
||||
@@ -58,6 +59,9 @@ const usage = `inbuxa -- install the inbuxa suite on this machine
|
||||
ports present, and with an API key a new
|
||||
order when it needs one
|
||||
inbuxa export [-o FILE] write a topology file from what is here
|
||||
inbuxa relay install|status|uninstall
|
||||
inbuxa Relay, on a machine of its own in front
|
||||
of the server
|
||||
inbuxa version this program's version
|
||||
|
||||
install flags:
|
||||
@@ -110,6 +114,20 @@ certs flags:
|
||||
default: postmaster@DOMAIN
|
||||
--dry-run report, and say what it would do
|
||||
|
||||
relay install flags:
|
||||
--token TOKEN the join token the console shows when you add
|
||||
the relay; "-" reads it from standard input, and
|
||||
INBUXA_RELAY_JOIN_TOKEN works too. Not needed
|
||||
once it has joined
|
||||
--link-listen ADDR where the server's link reaches it; default
|
||||
[::]:443, or what an earlier run set
|
||||
--dry-run, --yes as for install
|
||||
|
||||
relay uninstall flags:
|
||||
--purge its state too: it leaves its server for good
|
||||
--discard-held with --purge, even while it holds mail
|
||||
--dry-run, --yes as for install
|
||||
|
||||
deps flags:
|
||||
--server/--console/--webmail SHAPE the shapes to work out the needs for
|
||||
--install do it, rather than only saying what it would do
|
||||
@@ -156,6 +174,8 @@ func main() {
|
||||
os.Exit(uninstallCmd(os.Args[2:]))
|
||||
case "certs":
|
||||
os.Exit(certsCmd(os.Args[2:]))
|
||||
case "relay":
|
||||
os.Exit(relayCmd(os.Args[2:]))
|
||||
case "version":
|
||||
fmt.Println(version)
|
||||
case "-h", "--help", "help":
|
||||
@@ -990,6 +1010,141 @@ func certsCmd(args []string) int {
|
||||
return 0
|
||||
}
|
||||
|
||||
// relayCmd is inbuxa Relay on this machine, which shares nothing with the
|
||||
// suite's install but the way it is asked for.
|
||||
func relayCmd(args []string) int {
|
||||
if len(args) == 0 {
|
||||
fmt.Fprint(os.Stderr, "inbuxa relay install|status|uninstall\n\n"+usage)
|
||||
return 2
|
||||
}
|
||||
ctx := context.Background()
|
||||
switch args[0] {
|
||||
case "install":
|
||||
return relayInstall(ctx, args[1:])
|
||||
case "status":
|
||||
if os.Geteuid() != 0 {
|
||||
fmt.Fprintln(os.Stderr, "the relay's status needs root: its state is its user's alone")
|
||||
return 1
|
||||
}
|
||||
if !relay.Status(ctx, os.Stdout) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
case "uninstall":
|
||||
return relayUninstall(ctx, args[1:])
|
||||
case "-h", "--help", "help":
|
||||
fmt.Print(usage)
|
||||
return 0
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "unknown relay command %q: install, status or uninstall\n", args[0])
|
||||
return 2
|
||||
}
|
||||
|
||||
func relayInstall(ctx context.Context, args []string) int {
|
||||
fs := flag.NewFlagSet("relay install", flag.ContinueOnError)
|
||||
fs.Usage = func() { fmt.Print(usage) }
|
||||
var (
|
||||
o relay.Options
|
||||
token = fs.String("token", os.Getenv("INBUXA_RELAY_JOIN_TOKEN"), "")
|
||||
dryRun = fs.Bool("dry-run", false, "")
|
||||
yes = fs.Bool("yes", false, "")
|
||||
)
|
||||
fs.StringVar(&o.LinkListen, "link-listen", "", "")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 2
|
||||
}
|
||||
if fs.NArg() > 0 {
|
||||
fmt.Fprintf(os.Stderr, "unexpected %q: the token goes after --token, or \"--token -\" reads it from standard input\n", fs.Arg(0))
|
||||
return 2
|
||||
}
|
||||
// Read before the plan, which needs to know whether there is one; a
|
||||
// plan that then refuses has still read it, and forgets it.
|
||||
t, err := readKey(*token)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err.Error())
|
||||
return 2
|
||||
}
|
||||
o.Token = t
|
||||
p, err := relay.Check(ctx, o)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "cannot install the relay: "+err.Error())
|
||||
return 1
|
||||
}
|
||||
fmt.Print(p.String())
|
||||
if *dryRun {
|
||||
return 0
|
||||
}
|
||||
if !*yes {
|
||||
fmt.Fprintln(os.Stderr, "\nNothing has happened yet. Pass --yes to carry this out.")
|
||||
return 1
|
||||
}
|
||||
fmt.Println("\nInstalling:")
|
||||
if err := relay.Install(ctx, p, o, &printer{}); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "\nstopped: "+err.Error())
|
||||
return 1
|
||||
}
|
||||
fmt.Println()
|
||||
relay.Status(ctx, os.Stdout)
|
||||
fmt.Println("\nDone. Within a few seconds its card in the console says it is linked, and it opens")
|
||||
fmt.Println("port 25 once the server has sent it its settings. `inbuxa relay status` shows it here.")
|
||||
return 0
|
||||
}
|
||||
|
||||
func relayUninstall(ctx context.Context, args []string) int {
|
||||
fs := flag.NewFlagSet("relay uninstall", flag.ContinueOnError)
|
||||
fs.Usage = func() { fmt.Print(usage) }
|
||||
var (
|
||||
purge = fs.Bool("purge", false, "")
|
||||
discardHeld = fs.Bool("discard-held", false, "")
|
||||
dryRun = fs.Bool("dry-run", false, "")
|
||||
yes = fs.Bool("yes", false, "")
|
||||
)
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 2
|
||||
}
|
||||
if *discardHeld && !*purge {
|
||||
fmt.Fprintln(os.Stderr, "--discard-held goes with --purge: without it, the held mail is kept")
|
||||
return 2
|
||||
}
|
||||
if !relay.Installed() {
|
||||
fmt.Println("inbuxa Relay isn't installed here.")
|
||||
return 0
|
||||
}
|
||||
remove, keep := relay.UninstallPlan(*purge)
|
||||
fmt.Println("Taken away:")
|
||||
for _, x := range remove {
|
||||
fmt.Println(" - " + x)
|
||||
}
|
||||
if len(keep) > 0 {
|
||||
fmt.Println("\nKept:")
|
||||
for _, x := range keep {
|
||||
fmt.Println(" - " + x)
|
||||
}
|
||||
}
|
||||
if *purge {
|
||||
fmt.Println("\nWorth knowing:")
|
||||
fmt.Println(" - Remove it in the console too (the bin on its card), or the server goes on trying to link to it.")
|
||||
}
|
||||
if *dryRun {
|
||||
return 0
|
||||
}
|
||||
if !*yes {
|
||||
fmt.Fprintln(os.Stderr, "\nNothing has happened yet. Pass --yes to carry this out.")
|
||||
return 1
|
||||
}
|
||||
if os.Geteuid() != 0 {
|
||||
fmt.Fprintln(os.Stderr, "uninstalling needs root")
|
||||
return 1
|
||||
}
|
||||
fmt.Println("\nUninstalling:")
|
||||
if err := relay.Uninstall(ctx, *purge, *discardHeld, &printer{}); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "\nstopped: "+err.Error())
|
||||
return 1
|
||||
}
|
||||
fmt.Println("\nDone.")
|
||||
return 0
|
||||
}
|
||||
|
||||
func fileExists(p string) bool { _, err := os.Stat(p); return err == nil }
|
||||
|
||||
func shapeComponent(s string) (string, error) {
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
#!/bin/bash
|
||||
# SPDX-FileCopyrightText: 2026 Coffey Labs LLC
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
#
|
||||
# inbuxa Relay on a machine of its own: inbuxa relay install, run again,
|
||||
# status, and uninstall with and without --purge. The relay joins with a
|
||||
# token made here, for a server that never answers: the join itself is the
|
||||
# relay's own, offline step, and what is checked is everything the installer
|
||||
# puts around it -- the user, the directories, the unit, the ports.
|
||||
#
|
||||
# Until a server release carries relay binaries, pass one, taken out of an
|
||||
# image built from inbuxa-server's Dockerfile.relay:
|
||||
# RELAY_BINARY=path e2e/vm/run.sh e2e/cases/relay-host.sh
|
||||
set -uo pipefail
|
||||
|
||||
pass=0; fail=0
|
||||
ok() { echo " ok $*"; pass=$((pass+1)); }
|
||||
bad() { echo " FAIL $*"; fail=$((fail+1)); }
|
||||
|
||||
BIN=/opt/inbuxa-relay/bin/inbuxa-relay
|
||||
STATE=/var/lib/inbuxa-relay
|
||||
UNIT=inbuxa-relay.service
|
||||
[ -f /tmp/inbuxa-relay-test ] && export INBUXA_RELAY_BINARY=/tmp/inbuxa-relay-test
|
||||
listening() { ss -Hltn "sport = :$1" | grep -q .; }
|
||||
|
||||
# A join token as the console makes one: base64url JSON, with a CA pin and a
|
||||
# secret that nothing will ever check.
|
||||
b64() { basenc --base64url -w0 | tr -d =; }
|
||||
TOKEN=$(printf '{"v":1,"relayId":"e2e-relay","caSpki":"%s","secret":"%s","expiresAt":%d}' \
|
||||
"$(head -c32 /dev/urandom | b64)" "$(head -c32 /dev/urandom | b64)" $(( $(date +%s) + 3600 )) | b64)
|
||||
|
||||
echo "==> without a token, it refuses"
|
||||
OUT="$(/tmp/inbuxa relay install --yes 2>&1)"; rc=$?
|
||||
[ $rc -ne 0 ] && echo "$OUT" | grep -q "hasn't joined a server yet" && ok "refused: not joined, no token" || bad "rc $rc: $OUT"
|
||||
[ -e $BIN ] && bad "a binary was put in place anyway" || ok "nothing was installed"
|
||||
|
||||
echo
|
||||
echo "==> without --yes, nothing happens"
|
||||
OUT="$(echo "$TOKEN" | /tmp/inbuxa relay install --token - 2>&1)"; rc=$?
|
||||
[ $rc -eq 1 ] && echo "$OUT" | grep -q "Nothing has happened yet" && ok "it printed the plan and stopped" || bad "rc $rc: $OUT"
|
||||
echo "$OUT" | grep -q "join the server that made the token" && ok "the plan joins" || bad "the plan doesn't join"
|
||||
echo "$OUT" | grep -q -- "--link-listen" && ok "it says to keep the link port to the server" || bad "no word on the link port"
|
||||
|
||||
echo
|
||||
echo "==> installing, joining from standard input"
|
||||
OUT="$(echo "$TOKEN" | /tmp/inbuxa relay install --token - --yes 2>&1)"; rc=$?
|
||||
echo "$OUT" | tail -14 | sed 's/^/ /'
|
||||
[ $rc -eq 0 ] && ok "installed (exit 0)" || { bad "exit $rc"; journalctl -u $UNIT -n 20 --no-pager -o cat | sed 's/^/ | /'; }
|
||||
echo "$OUT" | grep -q "$TOKEN" && bad "the token was printed" || ok "the token wasn't printed"
|
||||
|
||||
echo
|
||||
echo "==> what is here"
|
||||
systemctl is-active --quiet $UNIT && ok "$UNIT is running" || bad "$UNIT is not running"
|
||||
systemctl is-enabled --quiet $UNIT && ok "and starts at boot" || bad "not enabled"
|
||||
PID=$(systemctl show -p MainPID --value $UNIT)
|
||||
[ "$(ps -o user= -p "$PID" 2>/dev/null)" = inbuxa-relay ] && ok "as the inbuxa-relay user" || bad "as '$(ps -o user= -p "$PID" 2>/dev/null)'"
|
||||
CAP=$(awk '/^CapEff/ {print $2}' /proc/$PID/status)
|
||||
[ "$CAP" = 0000000000000400 ] && ok "with CAP_NET_BIND_SERVICE alone" || bad "CapEff $CAP"
|
||||
[ "$(stat -c '%U %a' $BIN)" = "inbuxa-relay 755" ] && ok "the binary is the relay's own, 755" || bad "the binary is $(stat -c '%U %a' $BIN)"
|
||||
[ "$(stat -c '%U %a' /opt/inbuxa-relay)" = "root 755" ] && ok "/opt/inbuxa-relay is root's" || bad "/opt/inbuxa-relay is $(stat -c '%U %a' /opt/inbuxa-relay)"
|
||||
[ "$(stat -c '%U %a' $STATE)" = "inbuxa-relay 700" ] && ok "$STATE is the relay's alone" || bad "$STATE is $(stat -c '%U %a' $STATE)"
|
||||
[ -f $STATE/identity.json ] && ok "it joined (identity.json)" || bad "no identity.json"
|
||||
listening 443 && ok "the link listens on 443" || bad "nothing on 443"
|
||||
listening 25 && bad "port 25 is open before the server sent its settings" || ok "port 25 stays closed until the server sends its settings"
|
||||
getent passwd inbuxa-relay | grep -q nologin && ok "the user can't log in" || bad "$(getent passwd inbuxa-relay)"
|
||||
|
||||
echo
|
||||
echo "==> status"
|
||||
OUT="$(/tmp/inbuxa relay status 2>&1)"; rc=$?
|
||||
echo "$OUT" | sed 's/^/ /'
|
||||
[ $rc -eq 0 ] && ok "status (exit 0)" || bad "exit $rc"
|
||||
echo "$OUT" | grep -q "Relay: *e2e-relay" && ok "the relay's own status, as its user" || bad "no relay status"
|
||||
echo "$OUT" | grep -q "Joined: *waiting for the downstream" && ok "waiting for its server" || bad "not waiting"
|
||||
|
||||
echo
|
||||
echo "==> run again, with no token and no binary: a converge"
|
||||
PID=$(systemctl show -p MainPID --value $UNIT)
|
||||
OUT="$(env -u INBUXA_RELAY_BINARY /tmp/inbuxa relay install --yes 2>&1)"; rc=$?
|
||||
[ $rc -eq 0 ] && ok "converged (exit 0)" || bad "exit $rc: $OUT"
|
||||
echo "$OUT" | grep -q "keep inbuxa-relay" && ok "it kept the binary" || bad "it didn't keep the binary: $OUT"
|
||||
[ "$(systemctl show -p MainPID --value $UNIT)" = "$PID" ] && ok "and left the relay running as it was" || bad "it restarted the relay"
|
||||
|
||||
echo
|
||||
echo "==> the link on another address, then run again without it"
|
||||
OUT="$(env -u INBUXA_RELAY_BINARY /tmp/inbuxa relay install --link-listen 127.0.0.1:8443 --yes 2>&1)"; rc=$?
|
||||
[ $rc -eq 0 ] && ok "moved (exit 0)" || bad "exit $rc: $OUT"
|
||||
listening 8443 && ! listening 443 && ok "the link listens on 8443 only" || bad "$(ss -Hltn)"
|
||||
OUT="$(env -u INBUXA_RELAY_BINARY /tmp/inbuxa relay install --yes 2>&1)"; rc=$?
|
||||
grep -q -- "--link-listen 127.0.0.1:8443" /etc/systemd/system/$UNIT && listening 8443 && ok "a run without --link-listen keeps it" || bad "it went back: $OUT"
|
||||
env -u INBUXA_RELAY_BINARY /tmp/inbuxa relay install --link-listen '[::]:443' --yes >/dev/null 2>&1
|
||||
listening 443 && ok "and back to 443" || bad "not back on 443"
|
||||
|
||||
echo
|
||||
echo "==> something else on port 25 is refused"
|
||||
systemctl stop $UNIT
|
||||
python3 -c 'import socket,time; s=socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1); s.bind(("", 25)); s.listen(); time.sleep(30)' &
|
||||
HOLDER=$!; sleep 1
|
||||
OUT="$(env -u INBUXA_RELAY_BINARY /tmp/inbuxa relay install --yes 2>&1)"; rc=$?
|
||||
[ $rc -ne 0 ] && echo "$OUT" | grep -q "port 25 is held by python3" && ok "refused: port 25 is held by python3" || bad "rc $rc: $OUT"
|
||||
kill $HOLDER; wait $HOLDER 2>/dev/null
|
||||
env -u INBUXA_RELAY_BINARY /tmp/inbuxa relay install --yes >/dev/null 2>&1 && systemctl is-active --quiet $UNIT && ok "and once it's gone, it starts" || bad "it didn't start again"
|
||||
|
||||
echo
|
||||
echo "==> uninstall keeps its state"
|
||||
OUT="$(/tmp/inbuxa relay uninstall --yes 2>&1)"; rc=$?
|
||||
[ $rc -eq 0 ] && ok "uninstalled (exit 0)" || bad "exit $rc: $OUT"
|
||||
[ ! -e /etc/systemd/system/$UNIT ] && [ ! -e /opt/inbuxa-relay ] && ok "the unit and the binary are gone" || bad "left behind: $(ls /etc/systemd/system/$UNIT /opt/inbuxa-relay 2>&1)"
|
||||
[ -f $STATE/identity.json ] && getent passwd inbuxa-relay >/dev/null && ok "its state and its user are kept" || bad "its state or user went"
|
||||
listening 443 && bad "something still listens on 443" || ok "nothing listens on 443"
|
||||
|
||||
echo
|
||||
echo "==> installed again, it is the same relay: no token needed"
|
||||
OUT="$(/tmp/inbuxa relay install --yes 2>&1)"; rc=$?
|
||||
[ $rc -eq 0 ] && ! echo "$OUT" | grep -q "join the server" && ok "back, without joining again" || bad "rc $rc: $OUT"
|
||||
/tmp/inbuxa relay status 2>&1 | grep -q "Relay: *e2e-relay" && ok "as e2e-relay" || bad "a different relay"
|
||||
|
||||
echo
|
||||
echo "==> uninstall --purge"
|
||||
OUT="$(/tmp/inbuxa relay uninstall --purge 2>&1)"; rc=$?
|
||||
[ $rc -eq 1 ] && echo "$OUT" | grep -q "Remove it in the console too" && ok "without --yes it says what it would do" || bad "rc $rc: $OUT"
|
||||
OUT="$(/tmp/inbuxa relay uninstall --purge --yes 2>&1)"; rc=$?
|
||||
echo "$OUT" | tail -8 | sed 's/^/ /'
|
||||
[ $rc -eq 0 ] && ok "purged (exit 0)" || bad "exit $rc"
|
||||
[ ! -e $STATE ] && ok "$STATE is gone" || bad "$STATE is still here"
|
||||
getent passwd inbuxa-relay >/dev/null && bad "the user is still here" || ok "the user is gone"
|
||||
OUT="$(/tmp/inbuxa relay status 2>&1)"; rc=$?
|
||||
[ $rc -eq 1 ] && echo "$OUT" | grep -q "isn't installed here" && ok "status: not installed" || bad "rc $rc: $OUT"
|
||||
|
||||
echo
|
||||
echo "relay-host: $pass passed, $fail failed"
|
||||
[ $fail -eq 0 ]
|
||||
@@ -50,6 +50,12 @@ fi
|
||||
# INBUXA_WEBMAIL_TARBALL in the case).
|
||||
[ -z "${CONSOLE_TARBALL:-}" ] || vm_scp "$CONSOLE_TARBALL" [email protected]:/tmp/inbuxa-console-test.tar.gz >/dev/null
|
||||
[ -z "${WEBMAIL_TARBALL:-}" ] || vm_scp "$WEBMAIL_TARBALL" [email protected]:/tmp/inbuxa-webmail-test.tar.gz >/dev/null
|
||||
# A relay binary (INBUXA_RELAY_BINARY in the case), until a release carries
|
||||
# one: docker cp it out of an image built from Dockerfile.relay.
|
||||
if [ -n "${RELAY_BINARY:-}" ]; then
|
||||
vm_scp "$RELAY_BINARY" [email protected]:/tmp/inbuxa-relay-test >/dev/null
|
||||
vm_ssh 'chmod +x /tmp/inbuxa-relay-test'
|
||||
fi
|
||||
[ -z "${OLD_REF:-}" ] || vm_scp "$LAB/inbuxa-old" [email protected]:/tmp/inbuxa-old >/dev/null
|
||||
vm_scp "$ROOT/$CASE" [email protected]:/tmp/case.sh >/dev/null
|
||||
vm_ssh 'chmod +x /tmp/inbuxa /tmp/case.sh; [ ! -f /tmp/inbuxa-old ] || chmod +x /tmp/inbuxa-old'
|
||||
|
||||
@@ -527,3 +527,10 @@ func (f Facts) Port(n int) (Port, bool) {
|
||||
}
|
||||
return Port{}, false
|
||||
}
|
||||
|
||||
// Systemd says whether systemd runs this machine.
|
||||
func Systemd() bool { return isSystemd() }
|
||||
|
||||
// HolderOf names the process listening on a port, as well as /proc lets it:
|
||||
// "postfix (pid 812)", or "" when it can't tell.
|
||||
func HolderOf(port int) string { return holderOf(port) }
|
||||
@@ -0,0 +1,620 @@
|
||||
// SPDX-FileCopyrightText: 2026 Coffey Labs LLC
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Package relay puts inbuxa Relay on this machine: the edge relay that takes
|
||||
// mail in for a server elsewhere and sends its mail on (the relay spec,
|
||||
// docs/spec/features/relay.md in inbuxa-server, RL-31).
|
||||
//
|
||||
// A relay is a machine of its own. It has nothing of the suite's: no
|
||||
// compose project, no proxy, no state file. What is here is the binary, its
|
||||
// user, its state directory and its unit, and the console sets everything
|
||||
// else once it has joined. So it is a command of its own, not a fourth
|
||||
// component of install.
|
||||
//
|
||||
// The binary is the release's static musl build, checked against the
|
||||
// checksum pinned in this installer and against the inbuxa release keys. It
|
||||
// belongs to the relay's own user, as the server's unit expects, so that an
|
||||
// upgrade sent from the console can replace it in place; an install run
|
||||
// again leaves a newer one alone.
|
||||
package relay
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/deps"
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/host"
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/release"
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/state"
|
||||
)
|
||||
|
||||
const (
|
||||
Unit = "inbuxa-relay.service"
|
||||
User = "inbuxa-relay"
|
||||
Home = "/opt/inbuxa-relay"
|
||||
BinDir = Home + "/bin"
|
||||
Binary = BinDir + "/inbuxa-relay"
|
||||
StateDir = "/var/lib/inbuxa-relay"
|
||||
|
||||
DefaultLinkListen = "[::]:443"
|
||||
|
||||
unitPath = "/etc/systemd/system/" + Unit
|
||||
)
|
||||
|
||||
// Log is where the steps are reported, as apply.Log.
|
||||
type Log interface {
|
||||
Step(format string, a ...any)
|
||||
Info(format string, a ...any)
|
||||
Out() io.Writer
|
||||
}
|
||||
|
||||
// Options are what install is asked for.
|
||||
type Options struct {
|
||||
// Token is the join token the console showed, for a relay that hasn't
|
||||
// joined yet. A joined relay doesn't need one.
|
||||
Token string
|
||||
// LinkListen is where the relay listens for the server's link. Empty
|
||||
// keeps what the unit already says, or [::]:443.
|
||||
LinkListen string
|
||||
}
|
||||
|
||||
// Plan is what install would do here.
|
||||
type Plan struct {
|
||||
Version string // the release this installer installs, as the relay names it
|
||||
Installed string // what the binary here says it is, or ""
|
||||
Fetch bool // put the release binary in place
|
||||
Local string // INBUXA_RELAY_BINARY: a build to test instead
|
||||
LinkListen string
|
||||
Joined bool
|
||||
Join bool // join with the token
|
||||
Running bool
|
||||
Steps []string
|
||||
Notes []string
|
||||
}
|
||||
|
||||
func (p Plan) String() string {
|
||||
var b strings.Builder
|
||||
b.WriteString("inbuxa Relay on this machine:\n")
|
||||
for _, s := range p.Steps {
|
||||
b.WriteString(" - " + s + "\n")
|
||||
}
|
||||
if len(p.Notes) > 0 {
|
||||
b.WriteString("\nWorth knowing:\n")
|
||||
for _, s := range p.Notes {
|
||||
b.WriteString(" - " + s + "\n")
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Check works out what install would do, and refuses what it can't do.
|
||||
func Check(ctx context.Context, o Options) (Plan, error) {
|
||||
p := Plan{Version: release.RelayVersion(), Local: os.Getenv("INBUXA_RELAY_BINARY")}
|
||||
if os.Geteuid() != 0 {
|
||||
return p, errors.New("the relay needs root to install, and to look at what is here")
|
||||
}
|
||||
if !host.Systemd() {
|
||||
return p, errors.New("the relay runs as a systemd service, and systemd doesn't run this machine; " +
|
||||
"run its container image instead (docs.inbuxa.org: inbuxa Relay)")
|
||||
}
|
||||
arch := runtime.GOARCH
|
||||
sum, ok := release.RelaySHA256[arch]
|
||||
if !ok {
|
||||
return p, fmt.Errorf("there is no relay for %s: it is built for amd64 and arm64", arch)
|
||||
}
|
||||
if st, err := state.Load(); err == nil {
|
||||
if _, ok := st.Shapes["server"]; ok && !st.Removed() {
|
||||
return p, errors.New("the mail server is installed on this machine, and the relay would take its port 25: " +
|
||||
"a relay goes on a machine of its own, in front of the server")
|
||||
}
|
||||
}
|
||||
|
||||
p.LinkListen = o.LinkListen
|
||||
if p.LinkListen == "" {
|
||||
p.LinkListen = unitLinkListen(readFile(unitPath))
|
||||
}
|
||||
if p.LinkListen == "" {
|
||||
p.LinkListen = DefaultLinkListen
|
||||
}
|
||||
if _, port, err := net.SplitHostPort(p.LinkListen); err != nil || port == "" {
|
||||
return p, fmt.Errorf("--link-listen %s: an address and port, like [::]:443 or [fd42:1::2]:443", p.LinkListen)
|
||||
}
|
||||
|
||||
_, err := os.Stat(filepath.Join(StateDir, "identity.json"))
|
||||
p.Joined = err == nil
|
||||
p.Running = active(ctx)
|
||||
p.Installed = installedVersion(ctx, Binary)
|
||||
|
||||
switch {
|
||||
case p.Local != "":
|
||||
p.Fetch = true
|
||||
p.Steps = append(p.Steps, fmt.Sprintf("put %s in %s instead of the release, as INBUXA_RELAY_BINARY says (no checksum, no signature)", p.Local, BinDir))
|
||||
case p.Installed == "":
|
||||
p.Fetch = true
|
||||
p.Steps = append(p.Steps, fmt.Sprintf("fetch inbuxa-relay %s for %s, check its checksum and its signature, and put it in %s", p.Version, arch, BinDir))
|
||||
default:
|
||||
c, ok := compareVersions(p.Installed, p.Version)
|
||||
switch {
|
||||
case !ok || c < 0:
|
||||
p.Fetch = true
|
||||
p.Steps = append(p.Steps, fmt.Sprintf("replace inbuxa-relay %s with %s, checked as a new install is", p.Installed, p.Version))
|
||||
case c == 0:
|
||||
p.Steps = append(p.Steps, fmt.Sprintf("keep inbuxa-relay %s, the release this installer installs", p.Installed))
|
||||
default:
|
||||
p.Steps = append(p.Steps, fmt.Sprintf("keep inbuxa-relay %s, which is newer than this installer's %s (an upgrade from the console)", p.Installed, p.Version))
|
||||
}
|
||||
}
|
||||
if p.Fetch && p.Local == "" && sum == "" {
|
||||
return p, fmt.Errorf("this installer's release, inbuxa-server %s, has no relay to install for %s; "+
|
||||
"an installer from a later release has", release.ServerVersion, arch)
|
||||
}
|
||||
if !userExists(ctx) {
|
||||
p.Steps = append(p.Steps, "user "+User+" (system, no login), which owns the binary so an upgrade from the console can replace it")
|
||||
}
|
||||
p.Steps = append(p.Steps,
|
||||
StateDir+" for its state, readable by that user alone",
|
||||
fmt.Sprintf("%s: ports 25 and %s and nothing more, the rest of the machine read-only to it", Unit, portOf(p.LinkListen)))
|
||||
|
||||
switch {
|
||||
case !p.Joined && o.Token == "":
|
||||
return p, errors.New("this relay hasn't joined a server yet: add it in the console (Settings › Mail flow › Sending › Relays, " +
|
||||
"Add a relay…) and pass the join token it shows as --token -, which reads it from standard input")
|
||||
case !p.Joined:
|
||||
p.Join = true
|
||||
p.Steps = append(p.Steps, "join the server that made the token")
|
||||
case o.Token != "":
|
||||
p.Notes = append(p.Notes, "This relay has joined a server already, so the token isn't used. To join another, "+
|
||||
"`inbuxa relay uninstall --purge` first.")
|
||||
}
|
||||
switch {
|
||||
case !p.Running:
|
||||
p.Steps = append(p.Steps, "start it, and at every boot")
|
||||
case p.Fetch:
|
||||
p.Steps = append(p.Steps, "restart it on the new binary")
|
||||
}
|
||||
|
||||
if !p.Running {
|
||||
for _, addr := range []string{":25", p.LinkListen} {
|
||||
if why := held(addr); why != "" {
|
||||
return p, fmt.Errorf("port %s is %s; the relay needs it", portOf(addr), why)
|
||||
}
|
||||
}
|
||||
}
|
||||
if p.LinkListen == DefaultLinkListen {
|
||||
p.Notes = append(p.Notes, "The link listens on port 443 of every address. Let only the server's nodes reach it, "+
|
||||
"with a firewall, or put it on WireGuard with --link-listen [ADDRESS]:443.")
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Install carries out a plan from Check.
|
||||
func Install(ctx context.Context, p Plan, o Options, log Log) error {
|
||||
if !userExists(ctx) {
|
||||
if err := run(ctx, "useradd", "--system", "--user-group", "--no-create-home",
|
||||
"--home-dir", StateDir, "--shell", nologin(), User); err != nil {
|
||||
return fmt.Errorf("creating the %s user: %w", User, err)
|
||||
}
|
||||
log.Info("user %s (system, no login)", User)
|
||||
}
|
||||
for _, d := range []struct {
|
||||
path, owner string
|
||||
mode os.FileMode
|
||||
}{{Home, "root", 0o755}, {BinDir, User, 0o755}, {StateDir, User, 0o700}} {
|
||||
if err := os.MkdirAll(d.path, d.mode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Chmod(d.path, d.mode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := run(ctx, "chown", d.owner+":"+d.owner, d.path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if p.Fetch {
|
||||
if err := putBinary(ctx, p, log); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
unitChanged, err := writeIfChanged(unitPath, unitFile(p.LinkListen), 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if unitChanged {
|
||||
log.Info("%s, link on %s", unitPath, p.LinkListen)
|
||||
if err := run(ctx, "systemctl", "daemon-reload"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if p.Join {
|
||||
log.Step("joining")
|
||||
out, err := exec.CommandContext(ctx, "runuser", "-u", User, "--",
|
||||
Binary, "join", o.Token, "--state", StateDir).CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("the join was refused: %s", strings.TrimSpace(strings.TrimPrefix(string(out), "inbuxa-relay: ")))
|
||||
}
|
||||
log.Info("%s", strings.TrimSpace(string(out)))
|
||||
}
|
||||
|
||||
if err := run(ctx, "systemctl", "enable", "--quiet", Unit); err != nil {
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case !p.Running:
|
||||
log.Step("starting it")
|
||||
err = run(ctx, "systemctl", "start", Unit)
|
||||
case p.Fetch || unitChanged:
|
||||
log.Step("restarting it")
|
||||
err = run(ctx, "systemctl", "restart", Unit)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w\n%s", err, journal(ctx, 20))
|
||||
}
|
||||
// Restart=always would hide a relay that stops at once behind a unit
|
||||
// that is forever starting: give it the time to fail, then look for
|
||||
// the same process.
|
||||
pid := mainPID(ctx)
|
||||
time.Sleep(3 * time.Second)
|
||||
if !active(ctx) || pid == "0" || mainPID(ctx) != pid {
|
||||
return fmt.Errorf("the relay didn't stay up; its log:\n%s", journal(ctx, 20))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// putBinary puts the binary in place: the release's, checked, or a local
|
||||
// build. It is written beside the old one and renamed over it, so a failure
|
||||
// part way leaves the old one running.
|
||||
func putBinary(ctx context.Context, p Plan, log Log) error {
|
||||
work, err := os.MkdirTemp("", "inbuxa-relay-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(work)
|
||||
path := filepath.Join(work, "inbuxa-relay")
|
||||
if p.Local != "" {
|
||||
log.Step("installing %s instead of the release, as INBUXA_RELAY_BINARY says (no checksum, no signature)", p.Local)
|
||||
b, err := os.ReadFile(p.Local)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(path, b, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
arch := runtime.GOARCH
|
||||
log.Step("fetching inbuxa-relay %s for %s", p.Version, arch)
|
||||
url := release.RelayBinary(arch)
|
||||
if err := deps.FetchVerified(ctx, log.Out(), url, release.RelaySHA256[arch], path, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
sig, err := fetchSmall(ctx, url+".sig")
|
||||
if err != nil {
|
||||
return fmt.Errorf("its signature: %w", err)
|
||||
}
|
||||
keys, err := ParseKeys(release.RelayKeys)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := Verify(b, sig, keys, p.Version, release.RelayTarget(arch)); err != nil {
|
||||
return fmt.Errorf("%s: %w -- nothing was installed", url, err)
|
||||
}
|
||||
fmt.Fprintln(log.Out(), " signed by an inbuxa release key")
|
||||
}
|
||||
// Run before it is put in place, as the relay tries a binary before an
|
||||
// upgrade.
|
||||
got := installedVersion(ctx, path)
|
||||
if got == "" {
|
||||
out, _ := exec.CommandContext(ctx, path, "--version").CombinedOutput()
|
||||
return fmt.Errorf("the relay binary does not run here: %s", strings.TrimSpace(string(out)))
|
||||
}
|
||||
if p.Local == "" && got != p.Version {
|
||||
return fmt.Errorf("the relay binary says it is %s, not %s", got, p.Version)
|
||||
}
|
||||
next := filepath.Join(BinDir, ".inbuxa-relay.new")
|
||||
if err := run(ctx, "install", "-o", User, "-g", User, "-m", "0755", path, next); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(next, Binary); err != nil {
|
||||
os.Remove(next)
|
||||
return err
|
||||
}
|
||||
log.Info("%s, inbuxa-relay %s", Binary, got)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Status prints the relay's own account of itself. It is false when there is
|
||||
// no relay here.
|
||||
func Status(ctx context.Context, out io.Writer) bool {
|
||||
v := installedVersion(ctx, Binary)
|
||||
if v == "" {
|
||||
fmt.Fprintln(out, "inbuxa Relay isn't installed here.")
|
||||
return false
|
||||
}
|
||||
state := "stopped"
|
||||
if active(ctx) {
|
||||
state = "running"
|
||||
}
|
||||
enabled, _ := exec.CommandContext(ctx, "systemctl", "is-enabled", Unit).Output()
|
||||
fmt.Fprintf(out, "%s: %s, %s at boot\n", Unit, state, strings.TrimSpace(string(enabled)))
|
||||
fmt.Fprintf(out, "%s: inbuxa-relay %s (this installer installs %s)\n\n", Binary, v, release.RelayVersion())
|
||||
cmd := exec.CommandContext(ctx, "runuser", "-u", User, "--", Binary, "status", "--state", StateDir)
|
||||
cmd.Stdout, cmd.Stderr = out, out
|
||||
cmd.Run()
|
||||
return true
|
||||
}
|
||||
|
||||
// UninstallPlan is what uninstall would take away and keep.
|
||||
func UninstallPlan(purge bool) (remove, keep []string) {
|
||||
remove = []string{Unit + ", stopped and disabled", Home + " (the binary, and the previous one an upgrade keeps)"}
|
||||
if purge {
|
||||
remove = append(remove, StateDir+": its link keys, its settings and the mail it holds", "the "+User+" user")
|
||||
} else {
|
||||
keep = []string{StateDir + ": it still belongs to its server, and holds any mail it was holding; --purge removes it"}
|
||||
}
|
||||
return remove, keep
|
||||
}
|
||||
|
||||
// Installed says whether there is a relay here to take away.
|
||||
func Installed() bool {
|
||||
for _, p := range []string{unitPath, Binary} {
|
||||
if _, err := os.Stat(p); err == nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Uninstall takes the relay away. With purge it resets it first, which
|
||||
// refuses while it holds mail unless discardHeld: that mail is sealed to its
|
||||
// server, and nobody can read it after.
|
||||
func Uninstall(ctx context.Context, purge, discardHeld bool, log Log) error {
|
||||
wasRunning := active(ctx)
|
||||
log.Step("stopping %s", Unit)
|
||||
if err := run(ctx, "systemctl", "disable", "--now", "--quiet", Unit); err != nil && wasRunning {
|
||||
return err
|
||||
}
|
||||
if purge {
|
||||
if _, err := os.Stat(Binary); err == nil {
|
||||
args := []string{"-u", User, "--", Binary, "reset", "--state", StateDir}
|
||||
if discardHeld {
|
||||
args = append(args, "--discard-held")
|
||||
}
|
||||
out, err := exec.CommandContext(ctx, "runuser", args...).CombinedOutput()
|
||||
if err != nil {
|
||||
msg := strings.TrimSpace(strings.TrimPrefix(string(out), "inbuxa-relay: "))
|
||||
msg = strings.ReplaceAll(msg, "Run `inbuxa-relay reset --discard-held`", "Add --discard-held")
|
||||
if wasRunning {
|
||||
run(ctx, "systemctl", "enable", "--now", "--quiet", Unit)
|
||||
msg += " The relay is running again, as it was."
|
||||
}
|
||||
return fmt.Errorf("nothing was removed: %s", msg)
|
||||
}
|
||||
log.Info("%s", strings.TrimSpace(string(out)))
|
||||
}
|
||||
}
|
||||
for _, p := range []string{unitPath, "/etc/systemd/system/" + Unit + ".d"} {
|
||||
if err := os.RemoveAll(p); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := run(ctx, "systemctl", "daemon-reload"); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Info("%s removed", Unit)
|
||||
if err := os.RemoveAll(Home); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Info("%s removed", Home)
|
||||
if !purge {
|
||||
return nil
|
||||
}
|
||||
if err := os.RemoveAll(StateDir); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Info("%s removed", StateDir)
|
||||
if userExists(ctx) {
|
||||
if err := run(ctx, "userdel", User); err != nil {
|
||||
return fmt.Errorf("removing the %s user: %w", User, err)
|
||||
}
|
||||
log.Info("user %s removed", User)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// unitFile is the unit, the one inbuxa-server ships as
|
||||
// resources/systemd/inbuxa-relay.service, with the link where it was asked.
|
||||
func unitFile(linkListen string) string {
|
||||
execStart := Binary + " run --state " + StateDir
|
||||
if linkListen != DefaultLinkListen {
|
||||
execStart += " --link-listen " + linkListen
|
||||
}
|
||||
return `# Written by the inbuxa installer, as inbuxa-server ships it in
|
||||
# resources/systemd/inbuxa-relay.service. Changes here are replaced on its
|
||||
# next run: put yours in a drop-in, with systemctl edit inbuxa-relay.
|
||||
#
|
||||
# The binary lives in ` + BinDir + `, owned by the ` + User + ` user, so an
|
||||
# upgrade from the console can replace it; the relay then exits, and
|
||||
# Restart= starts the new one. It may bind ports 25 and 443 and nothing more.
|
||||
[Unit]
|
||||
Description=inbuxa Relay
|
||||
Documentation=https://docs.inbuxa.org/
|
||||
Conflicts=postfix.service sendmail.service exim4.service
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=` + execStart + `
|
||||
Restart=always
|
||||
RestartSec=2
|
||||
SyslogIdentifier=inbuxa-relay
|
||||
User=` + User + `
|
||||
Group=` + User + `
|
||||
StateDirectory=inbuxa-relay
|
||||
StateDirectoryMode=0700
|
||||
LimitNOFILE=65536
|
||||
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
||||
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
|
||||
NoNewPrivileges=yes
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=` + BinDir + `
|
||||
ProtectHome=yes
|
||||
PrivateTmp=yes
|
||||
PrivateDevices=yes
|
||||
ProtectKernelTunables=yes
|
||||
ProtectKernelModules=yes
|
||||
ProtectKernelLogs=yes
|
||||
ProtectControlGroups=yes
|
||||
ProtectClock=yes
|
||||
ProtectHostname=yes
|
||||
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
||||
RestrictNamespaces=yes
|
||||
RestrictRealtime=yes
|
||||
LockPersonality=yes
|
||||
MemoryDenyWriteExecute=yes
|
||||
SystemCallArchitectures=native
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
`
|
||||
}
|
||||
|
||||
var linkListenArg = regexp.MustCompile(`(?m)^ExecStart=\S+ run .*--link-listen (\S+)`)
|
||||
|
||||
// unitLinkListen is the link address a unit written before names, so a run
|
||||
// without --link-listen keeps it.
|
||||
func unitLinkListen(unit string) string {
|
||||
if m := linkListenArg.FindStringSubmatch(unit); m != nil {
|
||||
return m[1]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// installedVersion is the version a relay binary says it is, or "" when it
|
||||
// isn't there or doesn't run.
|
||||
func installedVersion(ctx context.Context, path string) string {
|
||||
out, err := exec.CommandContext(ctx, path, "--version").Output()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return parseVersionOutput(string(out))
|
||||
}
|
||||
|
||||
func parseVersionOutput(out string) string {
|
||||
f := strings.Fields(out)
|
||||
if len(f) != 2 || f[0] != "inbuxa-relay" {
|
||||
return ""
|
||||
}
|
||||
return f[1]
|
||||
}
|
||||
|
||||
// held says why an address can't be listened on, or "" when it can.
|
||||
func held(addr string) string {
|
||||
l, err := net.Listen("tcp", addr)
|
||||
if err == nil {
|
||||
l.Close()
|
||||
return ""
|
||||
}
|
||||
if errors.Is(err, syscall.EADDRNOTAVAIL) {
|
||||
return "on an address this machine doesn't have"
|
||||
}
|
||||
var port int
|
||||
fmt.Sscan(portOf(addr), &port)
|
||||
if h := host.HolderOf(port); h != "" {
|
||||
return "held by " + h
|
||||
}
|
||||
return "in use"
|
||||
}
|
||||
|
||||
func portOf(addr string) string {
|
||||
_, port, _ := net.SplitHostPort(addr)
|
||||
return port
|
||||
}
|
||||
|
||||
func active(ctx context.Context) bool {
|
||||
return exec.CommandContext(ctx, "systemctl", "is-active", "--quiet", Unit).Run() == nil
|
||||
}
|
||||
|
||||
func mainPID(ctx context.Context) string {
|
||||
out, _ := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", Unit).Output()
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
|
||||
func journal(ctx context.Context, lines int) string {
|
||||
out, _ := exec.CommandContext(ctx, "journalctl", "-u", Unit, "-n", fmt.Sprint(lines),
|
||||
"--no-pager", "-o", "cat").CombinedOutput()
|
||||
return string(out)
|
||||
}
|
||||
|
||||
func userExists(ctx context.Context) bool {
|
||||
return exec.CommandContext(ctx, "getent", "passwd", User).Run() == nil
|
||||
}
|
||||
|
||||
// fetchSmall is a small file, such as a .sig, read whole.
|
||||
func fetchSmall(ctx context.Context, url string) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
resp, err := (&http.Client{Timeout: time.Minute}).Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("%s: %s", url, resp.Status)
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
return string(b), err
|
||||
}
|
||||
|
||||
func readFile(path string) string {
|
||||
b, _ := os.ReadFile(path)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func nologin() string {
|
||||
for _, p := range []string{"/usr/sbin/nologin", "/sbin/nologin", "/usr/bin/nologin"} {
|
||||
if _, err := os.Stat(p); err == nil {
|
||||
return p
|
||||
}
|
||||
}
|
||||
return "/bin/false"
|
||||
}
|
||||
|
||||
func writeIfChanged(path, content string, mode os.FileMode) (bool, error) {
|
||||
if old, err := os.ReadFile(path); err == nil && bytes.Equal(old, []byte(content)) {
|
||||
return false, os.Chmod(path, mode)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(content), mode); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, os.Chmod(path, mode)
|
||||
}
|
||||
|
||||
func run(ctx context.Context, name string, args ...string) error {
|
||||
out, err := exec.CommandContext(ctx, name, args...).CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s %s: %v: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
// SPDX-FileCopyrightText: 2026 Coffey Labs LLC
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package relay
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.coffeylabs.org/inbuxa/inbuxa-installer/internal/release"
|
||||
)
|
||||
|
||||
// The relay's own test of a signature made with openssl, as
|
||||
// tools/release/sign-relay.sh makes them: the same bytes pass here.
|
||||
func TestOpenSSLSignature(t *testing.T) {
|
||||
keys, err := ParseKeys([]string{"VNaWnerWh2UXOrUMtSWPOKJHtigsUdIWUfzHmXbdgIU"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file := "inbuxa-relay release 1\n" +
|
||||
"version 27.1.0-rc.5\n" +
|
||||
"target x86_64-linux-musl\n" +
|
||||
"sha256 ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\n" +
|
||||
"signature zRj90ByVN18fmW-GOZ9cvGBK1ZsYYoNvowGsbSBYcslJhgIgmKrYHgRgq1CSIy4G-EzR5uexCzAUoa3FEcluAA\n"
|
||||
if err := Verify([]byte("abc"), file, keys, "27.1.0-rc.5", "x86_64-linux-musl"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, c := range []struct{ binary, version, target, want string }{
|
||||
{"abd", "27.1.0-rc.5", "x86_64-linux-musl", "another binary"},
|
||||
{"abc", "27.1.0-rc.4", "x86_64-linux-musl", "release 27.1.0-rc.5, not 27.1.0-rc.4"},
|
||||
{"abc", "27.1.0-rc.5", "aarch64-linux-musl", "for x86_64-linux-musl"},
|
||||
} {
|
||||
err := Verify([]byte(c.binary), file, keys, c.version, c.target)
|
||||
if err == nil || !strings.Contains(err.Error(), c.want) {
|
||||
t.Errorf("%+v: %v", c, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignatureFiles(t *testing.T) {
|
||||
pub, priv, _ := ed25519.GenerateKey(nil)
|
||||
other, _, _ := ed25519.GenerateKey(nil)
|
||||
binary := []byte("a relay")
|
||||
sign := func(version string) string {
|
||||
text := fmt.Sprintf("inbuxa-relay release 1\nversion %s\ntarget x86_64-linux-musl\nsha256 %x\n", version, sha256.Sum256(binary))
|
||||
return text + "signature " + base64.RawURLEncoding.EncodeToString(ed25519.Sign(priv, []byte(text))) + "\n"
|
||||
}
|
||||
good := sign("27.1.0-rc.5")
|
||||
if err := Verify(binary, good, []ed25519.PublicKey{other, pub}, "27.1.0-rc.5", "x86_64-linux-musl"); err != nil {
|
||||
t.Fatalf("signed by the second key: %v", err)
|
||||
}
|
||||
if err := Verify(binary, strings.ReplaceAll(good, "\n", "\r\n"), []ed25519.PublicKey{pub}, "27.1.0-rc.5", "x86_64-linux-musl"); err != nil {
|
||||
t.Fatalf("CRLF: %v", err)
|
||||
}
|
||||
for name, c := range map[string]struct {
|
||||
file string
|
||||
keys []ed25519.PublicKey
|
||||
want string
|
||||
}{
|
||||
"other key": {good, []ed25519.PublicKey{other}, "no inbuxa release key"},
|
||||
"no key": {good, nil, "no release key"},
|
||||
"changed": {strings.Replace(good, "rc.5", "rc.6", 1), []ed25519.PublicKey{pub}, "no inbuxa release key"},
|
||||
"not one": {"hello\n", []ed25519.PublicKey{pub}, "doesn't start"},
|
||||
"short": {"inbuxa-relay release 1\nversion 27.1.0\n", []ed25519.PublicKey{pub}, "no target"},
|
||||
"more": {good + "extra\n", []ed25519.PublicKey{pub}, "goes on past"},
|
||||
"bad version": {sign("27.1"), []ed25519.PublicKey{pub}, "not a version"},
|
||||
} {
|
||||
if _, err := VerifySignature(c.file, c.keys); err == nil || !strings.Contains(err.Error(), c.want) {
|
||||
t.Errorf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The keys the installer checks with are the relay's, decodable.
|
||||
func TestReleaseKeys(t *testing.T) {
|
||||
keys, err := ParseKeys(release.RelayKeys)
|
||||
if err != nil || len(keys) != 2 {
|
||||
t.Fatalf("%v %v", keys, err)
|
||||
}
|
||||
if keys[0][0] != 0x27 || keys[1][0] != 0xbc || keys[0][31] != 0xec || keys[1][31] != 0xff {
|
||||
t.Errorf("not the bytes release.rs holds")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionOrder(t *testing.T) {
|
||||
ordered := []string{"27.0.9", "27.1.0-alpha", "27.1.0-rc.2", "27.1.0-rc.10", "27.1.0-rc.10.1", "27.1.0-rcx", "27.1.0", "27.1.1", "28.0.0"}
|
||||
for i := range ordered {
|
||||
for j := range ordered {
|
||||
c, ok := compareVersions(ordered[i], ordered[j])
|
||||
want := 0
|
||||
if i < j {
|
||||
want = -1
|
||||
} else if i > j {
|
||||
want = 1
|
||||
}
|
||||
if !ok || c != want {
|
||||
t.Errorf("%s vs %s: %d %v, want %d", ordered[i], ordered[j], c, ok, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
if c, ok := compareVersions("27.1.0+build", "27.1.0"); !ok || c != 0 {
|
||||
t.Errorf("build metadata counts: %d %v", c, ok)
|
||||
}
|
||||
for _, bad := range []string{"27.1", "27.1.x", "27.1.0-", "27.1.0-a..b", ""} {
|
||||
if _, ok := compareVersions(bad, "27.1.0"); ok {
|
||||
t.Errorf("%q is a version", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCargoVersion(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"27.1-rc.4": "27.1.0-rc.4", "27.1": "27.1.0", "27.1.3": "27.1.3", "27.1.3-rc.1": "27.1.3-rc.1",
|
||||
} {
|
||||
if got := release.CargoVersion(in); got != want {
|
||||
t.Errorf("%s: %s, want %s", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionOutput(t *testing.T) {
|
||||
for out, want := range map[string]string{
|
||||
"inbuxa-relay 27.1.0-rc.5\n": "27.1.0-rc.5",
|
||||
"inbuxa 27.1-rc.4\n": "",
|
||||
"error while loading": "",
|
||||
"": "",
|
||||
} {
|
||||
if got := parseVersionOutput(out); got != want {
|
||||
t.Errorf("%q: %q", out, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnitLinkListen(t *testing.T) {
|
||||
plain := unitFile(DefaultLinkListen)
|
||||
if strings.Contains(plain, "--link-listen") {
|
||||
t.Error("the default needs no --link-listen")
|
||||
}
|
||||
if unitLinkListen(plain) != "" {
|
||||
t.Error("a plain unit names a link address")
|
||||
}
|
||||
wg := unitFile("[fd42:1::2]:443")
|
||||
if !strings.Contains(wg, "ExecStart="+Binary+" run --state "+StateDir+" --link-listen [fd42:1::2]:443\n") {
|
||||
t.Errorf("ExecStart: %s", wg)
|
||||
}
|
||||
if got := unitLinkListen(wg); got != "[fd42:1::2]:443" {
|
||||
t.Errorf("read back %q", got)
|
||||
}
|
||||
for _, want := range []string{"User=inbuxa-relay", "ReadWritePaths=/opt/inbuxa-relay/bin", "CapabilityBoundingSet=CAP_NET_BIND_SERVICE", "Restart=always"} {
|
||||
if !strings.Contains(plain, want+"\n") {
|
||||
t.Errorf("no %s", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
// SPDX-FileCopyrightText: 2026 Coffey Labs LLC
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package relay
|
||||
|
||||
// A relay binary's .sig file, checked as the relay checks one before an
|
||||
// upgrade (crates/relay-proto/src/release.rs): five lines, the first four
|
||||
// signed with Ed25519 by an inbuxa release key.
|
||||
//
|
||||
// inbuxa-relay release 1
|
||||
// version 27.1.0-rc.5
|
||||
// target x86_64-linux-musl
|
||||
// sha256 <hex>
|
||||
// signature <base64url>
|
||||
//
|
||||
// The pinned checksum already says the download is the release's; the
|
||||
// signature says the release is inbuxa's, the same check the relay makes of
|
||||
// every binary the console sends it.
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const sigHeader = "inbuxa-relay release 1"
|
||||
|
||||
// Signed is what a signature file says, once a key is found to have signed
|
||||
// it.
|
||||
type Signed struct {
|
||||
Version, Target string
|
||||
SHA256 [32]byte
|
||||
}
|
||||
|
||||
// ParseKeys decodes base64url public keys.
|
||||
func ParseKeys(keys []string) ([]ed25519.PublicKey, error) {
|
||||
var out []ed25519.PublicKey
|
||||
for _, k := range keys {
|
||||
b, err := base64.RawURLEncoding.DecodeString(k)
|
||||
if err != nil || len(b) != ed25519.PublicKeySize {
|
||||
return nil, fmt.Errorf("release key %q is not an Ed25519 public key", k)
|
||||
}
|
||||
out = append(out, ed25519.PublicKey(b))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// VerifySignature reads a signature file and checks it against keys, but not
|
||||
// the binary.
|
||||
func VerifySignature(file string, keys []ed25519.PublicKey) (Signed, error) {
|
||||
var s Signed
|
||||
lines := strings.Split(strings.ReplaceAll(file, "\r\n", "\n"), "\n")
|
||||
if lines[0] != sigHeader {
|
||||
return s, errors.New("the signature file doesn't start as one")
|
||||
}
|
||||
rest := lines[1:]
|
||||
field := func(name string) (string, error) {
|
||||
if len(rest) == 0 {
|
||||
return "", fmt.Errorf("the signature file has no %s", name)
|
||||
}
|
||||
v, ok := strings.CutPrefix(rest[0], name+" ")
|
||||
rest = rest[1:]
|
||||
v = strings.TrimSpace(v)
|
||||
if !ok || v == "" {
|
||||
return "", fmt.Errorf("the signature file has no %s", name)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
var err error
|
||||
if s.Version, err = field("version"); err != nil {
|
||||
return s, err
|
||||
}
|
||||
if s.Target, err = field("target"); err != nil {
|
||||
return s, err
|
||||
}
|
||||
sum, err := field("sha256")
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
if b, err := hex.DecodeString(sum); err != nil || len(b) != 32 {
|
||||
return s, errors.New("the signature file's sha256 is not a SHA-256")
|
||||
} else {
|
||||
copy(s.SHA256[:], b)
|
||||
}
|
||||
sigText, err := field("signature")
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
sig, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(sigText, "="))
|
||||
if err != nil || len(sig) != ed25519.SignatureSize {
|
||||
return s, errors.New("the signature file's signature is not an Ed25519 signature")
|
||||
}
|
||||
if _, ok := parseVersion(s.Version); !ok {
|
||||
return s, fmt.Errorf("the signature file's version %q is not a version", s.Version)
|
||||
}
|
||||
for _, l := range rest {
|
||||
if strings.TrimSpace(l) != "" {
|
||||
return s, errors.New("the signature file goes on past the signature")
|
||||
}
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return s, errors.New("there is no release key to check the signature with")
|
||||
}
|
||||
signed := fmt.Sprintf("%s\nversion %s\ntarget %s\nsha256 %x\n", sigHeader, s.Version, s.Target, s.SHA256)
|
||||
for _, k := range keys {
|
||||
if ed25519.Verify(k, []byte(signed), sig) {
|
||||
return s, nil
|
||||
}
|
||||
}
|
||||
return s, errors.New("no inbuxa release key signed it")
|
||||
}
|
||||
|
||||
// Verify checks a binary against its signature file, and that the file is
|
||||
// for the release and the architecture wanted.
|
||||
func Verify(binary []byte, file string, keys []ed25519.PublicKey, version, target string) error {
|
||||
s, err := VerifySignature(file, keys)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if sha256.Sum256(binary) != s.SHA256 {
|
||||
return errors.New("the signature is for another binary")
|
||||
}
|
||||
if s.Version != version {
|
||||
return fmt.Errorf("the signature is for release %s, not %s", s.Version, version)
|
||||
}
|
||||
if s.Target != target {
|
||||
return fmt.Errorf("the signature is for %s, not %s", s.Target, target)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// version is MAJOR.MINOR.PATCH[-PRE][+BUILD], ordered as SemVer §11 orders
|
||||
// them, as the relay orders them.
|
||||
type version struct {
|
||||
core [3]uint64
|
||||
pre []string
|
||||
}
|
||||
|
||||
func parseVersion(text string) (version, bool) {
|
||||
var v version
|
||||
text, _, _ = strings.Cut(strings.TrimSpace(text), "+")
|
||||
core, pre, hasPre := strings.Cut(text, "-")
|
||||
parts := strings.Split(core, ".")
|
||||
if len(parts) != 3 {
|
||||
return v, false
|
||||
}
|
||||
for i, p := range parts {
|
||||
n, err := strconv.ParseUint(p, 10, 64)
|
||||
if err != nil {
|
||||
return v, false
|
||||
}
|
||||
v.core[i] = n
|
||||
}
|
||||
if hasPre {
|
||||
v.pre = strings.Split(pre, ".")
|
||||
for _, id := range v.pre {
|
||||
if id == "" || strings.Trim(id, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-") != "" {
|
||||
return v, false
|
||||
}
|
||||
}
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
|
||||
// compareVersions is -1, 0 or 1 as a is before, the same as, or after b.
|
||||
// ok is false when either is not a version.
|
||||
func compareVersions(a, b string) (c int, ok bool) {
|
||||
va, oka := parseVersion(a)
|
||||
vb, okb := parseVersion(b)
|
||||
if !oka || !okb {
|
||||
return 0, false
|
||||
}
|
||||
for i := range va.core {
|
||||
if va.core[i] != vb.core[i] {
|
||||
return cmp(va.core[i] < vb.core[i]), true
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case len(va.pre) == 0 && len(vb.pre) == 0:
|
||||
return 0, true
|
||||
case len(va.pre) == 0:
|
||||
return 1, true
|
||||
case len(vb.pre) == 0:
|
||||
return -1, true
|
||||
}
|
||||
for i := 0; i < len(va.pre) && i < len(vb.pre); i++ {
|
||||
x, y := va.pre[i], vb.pre[i]
|
||||
if x == y {
|
||||
continue
|
||||
}
|
||||
nx, ex := strconv.ParseUint(x, 10, 64)
|
||||
ny, ey := strconv.ParseUint(y, 10, 64)
|
||||
switch {
|
||||
case ex == nil && ey == nil:
|
||||
return cmp(nx < ny), true
|
||||
case ex == nil: // numeric identifiers come first
|
||||
return -1, true
|
||||
case ey == nil:
|
||||
return 1, true
|
||||
}
|
||||
return cmp(x < y), true
|
||||
}
|
||||
if len(va.pre) == len(vb.pre) {
|
||||
return 0, true
|
||||
}
|
||||
return cmp(len(va.pre) < len(vb.pre)), true
|
||||
}
|
||||
|
||||
func cmp(less bool) int {
|
||||
if less {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
@@ -14,7 +14,10 @@
|
||||
// releases/latest, and so a plain install, never reaches one.
|
||||
package release
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ServerVersion is the inbuxa-server release this installer installs.
|
||||
const ServerVersion = "27.1-rc.4"
|
||||
@@ -65,3 +68,60 @@ func WebmailTarball(arch string) string {
|
||||
return fmt.Sprintf("https://git.coffeylabs.org/inbuxa/inbuxa-webmail/releases/download/inbuxa-v%s/inbuxa-webmail-linux-%s.tar.gz",
|
||||
WebmailVersion, arch)
|
||||
}
|
||||
|
||||
// inbuxa Relay, for a machine of its own in front of the server: the
|
||||
// static inbuxa-relay binary each server release attaches since
|
||||
// inbuxa-server #271, with a .sig file beside it signed by an inbuxa release
|
||||
// key. Its release is the server's, so a relay this installer puts in place
|
||||
// runs the version the server it joins does. A version with an empty
|
||||
// checksum has no relay to install. INBUXA_RELAY_BINARY names a local file
|
||||
// instead, for testing.
|
||||
//
|
||||
// RelaySHA256 is the SHA-256 of each architecture's relay binary.
|
||||
var RelaySHA256 = map[string]string{
|
||||
"amd64": "",
|
||||
"arm64": "",
|
||||
}
|
||||
|
||||
// RelayKeys are the inbuxa release keys that sign a relay binary, as
|
||||
// crates/relay-proto/src/release.rs holds them: the CI key, then the one
|
||||
// kept offline. Base64url, no padding.
|
||||
var RelayKeys = []string{
|
||||
"J0kY_vzXTC8T8gxErBMYI6cVk4Bwki65HlJGoDp15uw",
|
||||
"vGsTE95CJ3vbGKVtfQctFEp0fOZ4wQ9QWTOFe0KF7_8",
|
||||
}
|
||||
|
||||
// RelayVersion is the server's release as the relay names itself, in its
|
||||
// --version and its .sig file: the Cargo version, 27.1.0-rc.4 for 27.1-rc.4.
|
||||
func RelayVersion() string { return CargoVersion(ServerVersion) }
|
||||
|
||||
// CargoVersion is a release version with the patch number SemVer wants:
|
||||
// 27.1 is 27.1.0, and 27.1-rc.4 is 27.1.0-rc.4.
|
||||
func CargoVersion(v string) string {
|
||||
core, pre, hasPre := strings.Cut(v, "-")
|
||||
if strings.Count(core, ".") == 1 {
|
||||
core += ".0"
|
||||
}
|
||||
if hasPre {
|
||||
return core + "-" + pre
|
||||
}
|
||||
return core
|
||||
}
|
||||
|
||||
// RelayTarget is what a relay binary's .sig file names an architecture.
|
||||
func RelayTarget(arch string) string {
|
||||
switch arch {
|
||||
case "amd64":
|
||||
return "x86_64-linux-musl"
|
||||
case "arm64":
|
||||
return "aarch64-linux-musl"
|
||||
}
|
||||
return arch + "-linux-musl"
|
||||
}
|
||||
|
||||
// RelayBinary is where the release's relay binary for an architecture is;
|
||||
// its .sig file is beside it, with ".sig" added.
|
||||
func RelayBinary(arch string) string {
|
||||
return fmt.Sprintf("https://git.coffeylabs.org/inbuxa/inbuxa-server/releases/download/v%s/inbuxa-relay-%s",
|
||||
ServerVersion, RelayTarget(arch))
|
||||
}
|
||||
Reference in new issue
Block a user