Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix: address review findings on the Linux packaging and update paths

shukieshah238f872093b0
diff --git a/cli/beacon/.goreleaser.yaml b/cli/beacon/.goreleaser.yaml
index 0498a6f2..97aa9dfa 100644
--- a/cli/beacon/.goreleaser.yaml
+++ b/cli/beacon/.goreleaser.yaml
@@ -123,6 +123,12 @@ nfpms:
- systemd
rpm:
group: Applications/System
+ scripts:
+ # rpm runs the outgoing package's %preun after the incoming package's %post during an
+ # upgrade, so an older package can stop the service the new one just started -- and nothing
+ # in the new package can change what the old script does. %posttrans runs last in the
+ # transaction, which makes it the only place that can have the final say.
+ posttrans: ../../packaging/linux/nfpm/posttrans.sh
deb:
fields:
Bugs: https://github.com/asymptote-labs/agent-beacon/issues
diff --git a/cli/beacon/cmd/endpoint_console_user_test.go b/cli/beacon/cmd/endpoint_console_user_test.go
index 6b38c66c..2debf93a 100644
--- a/cli/beacon/cmd/endpoint_console_user_test.go
+++ b/cli/beacon/cmd/endpoint_console_user_test.go
@@ -3,7 +3,9 @@ package cmd
import (
"os"
"os/user"
+ "path/filepath"
"runtime"
+ "strings"
"testing"
)
@@ -117,3 +119,74 @@ func TestLinuxActiveConsoleUserWithoutSudoOrLogindIsNotAnError(t *testing.T) {
}
_ = os.Getenv("PATH")
}
+
+// fakeLoginctl puts a stub `loginctl` on PATH that answers list-sessions with the given table and
+// reports every session active. A fake binary is the only way to drive this: the resolution shells
+// out, and the answer depends on which session logind names first.
+func fakeLoginctl(t *testing.T, sessionTable string) {
+ t.Helper()
+ dir := t.TempDir()
+ script := "#!/bin/sh\ncase \"$1\" in\n" +
+ "list-sessions) printf '%s' " + shellSingleQuote(sessionTable) + " ;;\n" +
+ "show-session) echo active ;;\n" +
+ "esac\n"
+ if err := os.WriteFile(filepath.Join(dir, "loginctl"), []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
+}
+
+func shellSingleQuote(s string) string {
+ return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
+}
+
+// A host with both a graphical login and an earlier ssh or service session must resolve the person
+// at the machine. loginctl lists sessions oldest-first, so taking the first active one picks the ssh
+// session -- and the postinstall would configure the wrong user's agent runtime. The comment claimed
+// this ordering before the code implemented it.
+func TestLinuxActiveConsoleUserPrefersASeatedSession(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("linux-only resolution")
+ }
+ t.Setenv("SUDO_USER", "")
+ // Unseated session listed first, seated second -- the order that exposes the bug.
+ fakeLoginctl(t, " 7 1002 remote \n 3 1001 desktop seat0 tty2\n")
+
+ var asked []string
+ restore := lookupConsoleUser
+ lookupConsoleUser = func(name string) (consoleUserInfo, bool, error) {
+ asked = append(asked, name)
+ return consoleUserInfo{Username: name, HomeDir: "/home/" + name}, true, nil
+ }
+ t.Cleanup(func() { lookupConsoleUser = restore })
+
+ info, ok, err := linuxActiveConsoleUser()
+ if err != nil || !ok {
+ t.Fatalf("linuxActiveConsoleUser() = %+v, %v, %v; want the seated user", info, ok, err)
+ }
+ if info.Username != "desktop" {
+ t.Errorf("resolved %q, want the seated session's user; lookups=%v", info.Username, asked)
+ }
+}
+
+// An unseated session is still a real human whose agent runs on that host, so it is accepted when
+// there is no seated one -- the preference is an ordering, not a filter.
+func TestLinuxActiveConsoleUserAcceptsAnUnseatedSessionWhenItIsAll(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("linux-only resolution")
+ }
+ t.Setenv("SUDO_USER", "")
+ fakeLoginctl(t, " 7 1002 remote \n")
+
+ restore := lookupConsoleUser
+ lookupConsoleUser = func(name string) (consoleUserInfo, bool, error) {
+ return consoleUserInfo{Username: name, HomeDir: "/home/" + name}, true, nil
+ }
+ t.Cleanup(func() { lookupConsoleUser = restore })
+
+ info, ok, err := linuxActiveConsoleUser()
+ if err != nil || !ok || info.Username != "remote" {
+ t.Fatalf("linuxActiveConsoleUser() = %+v, %v, %v; want the unseated user accepted",
+ info, ok, err)
+ }
+}
diff --git a/cli/beacon/cmd/endpoint_hooks_repair.go b/cli/beacon/cmd/endpoint_hooks_repair.go
index 49bf34cd..8f726f0c 100644
--- a/cli/beacon/cmd/endpoint_hooks_repair.go
+++ b/cli/beacon/cmd/endpoint_hooks_repair.go
@@ -191,29 +191,36 @@ func linuxActiveConsoleUser() (consoleUserInfo, bool, error) {
if u := strings.TrimSpace(os.Getenv("SUDO_USER")); u != "" {
return lookupConsoleUser(u)
}
- // loginctl lists sessions; the seated, active one is the graphical or console login. --value
- // keeps the output a bare field so no parsing of loginctl's table layout is needed.
+ // loginctl lists sessions as: SESSION UID USER SEAT [TTY]. A session with a seat is someone at
+ // the machine; one without is an ssh login or a service. Both can be a real human whose agent
+ // runs there, so both are acceptable -- but a seated session is the better answer when a host
+ // has both, which is why this makes two passes instead of taking whichever loginctl printed
+ // first. An earlier version claimed that ordering in a comment while the code took the first
+ // active session it saw.
out, err := exec.Command("loginctl", "list-sessions", "--no-legend").Output()
if err != nil {
// No logind, or it refused. Not an error worth failing an install over: this is a
// best-effort identification, and the caller already handles "unknown".
return consoleUserInfo{}, false, nil
}
- for _, line := range strings.Split(string(out), "\n") {
- fields := strings.Fields(line)
- if len(fields) < 3 {
- continue
- }
- // SESSION UID USER SEAT ... -- a session with no seat is an ssh login or a service, not
- // someone at the machine, but it is still a real human whose agent runs there, so it is
- // accepted after seated sessions have been considered.
- id := fields[0]
- st, err := exec.Command("loginctl", "show-session", id, "-p", "State", "--value").Output()
- if err != nil || strings.TrimSpace(string(st)) != "active" {
- continue
- }
- if info, ok, err := lookupConsoleUser(fields[2]); ok || err != nil {
- return info, ok, err
+ lines := strings.Split(string(out), "\n")
+ for _, seatedOnly := range []bool{true, false} {
+ for _, line := range lines {
+ fields := strings.Fields(line)
+ if len(fields) < 3 {
+ continue
+ }
+ seated := len(fields) > 3 && strings.TrimSpace(fields[3]) != ""
+ if seated != seatedOnly {
+ continue
+ }
+ st, err := exec.Command("loginctl", "show-session", fields[0], "-p", "State", "--value").Output()
+ if err != nil || strings.TrimSpace(string(st)) != "active" {
+ continue
+ }
+ if info, ok, err := lookupConsoleUser(fields[2]); ok || err != nil {
+ return info, ok, err
+ }
}
}
return consoleUserInfo{}, false, nil
diff --git a/cli/beacon/cmd/endpoint_update.go b/cli/beacon/cmd/endpoint_update.go
index 2fb7a7f7..e2010874 100644
--- a/cli/beacon/cmd/endpoint_update.go
+++ b/cli/beacon/cmd/endpoint_update.go
@@ -240,5 +240,11 @@ func applyUpdate(parent context.Context, current string) error {
return nil
}
fmt.Printf("Updated Beacon to %s.\n", res.ToVersion)
+ // Say what the artifact was checked against. macOS verifies Apple notarization on top of the
+ // checksum and Linux has no OS-level equivalent, so stating it beats letting the reader assume
+ // whichever they are used to.
+ if res.Verification != "" {
+ fmt.Printf("Package verification: %s\n", res.Verification)
+ }
return nil
}
diff --git a/cli/beacon/cmd/endpoint_update_service.go b/cli/beacon/cmd/endpoint_update_service.go
index 780e43c0..0145d8b5 100644
--- a/cli/beacon/cmd/endpoint_update_service.go
+++ b/cli/beacon/cmd/endpoint_update_service.go
@@ -166,7 +166,9 @@ func runUpdateDisable(cmd *cobra.Command, args []string) error {
if err := mgr.Unload(); err != nil {
return fmt.Errorf("unload updater job: %w", err)
}
- _ = os.Remove(mgr.UnitPath())
+ for _, path := range mgr.UnitPaths() {
+ _ = os.Remove(path)
+ }
fmt.Println("Update checks disabled; background updater removed.")
return nil
}
@@ -195,7 +197,9 @@ func runUpdateInstallDaemon(cmd *cobra.Command, args []string) error {
mgr := service.UpdaterManager{}
if mode == selfupdate.ModeOff {
_ = mgr.Unload()
- _ = os.Remove(mgr.UnitPath())
+ for _, path := range mgr.UnitPaths() {
+ _ = os.Remove(path)
+ }
fmt.Println("Auto-update is off; updater daemon not installed.")
return nil
}
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index 09b22bef..9ba1315d 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -29,7 +29,9 @@ var (
removeUpdaterJob = func() {
updater := service.UpdaterManager{}
_ = updater.Unload()
- _ = os.Remove(updater.UnitPath())
+ for _, path := range updater.UnitPaths() {
+ _ = os.Remove(path)
+ }
}
)
diff --git a/cli/beacon/internal/endpoint/selfupdate/apply.go b/cli/beacon/internal/endpoint/selfupdate/apply.go
index 43e64f04..bdd5d5fa 100644
--- a/cli/beacon/internal/endpoint/selfupdate/apply.go
+++ b/cli/beacon/internal/endpoint/selfupdate/apply.go
@@ -181,9 +181,15 @@ func (a *Applier) Apply(ctx context.Context) (ApplyResult, error) {
// path rather than a downgrade. Notarization gives macOS assurance above that; adding a
// comparable Linux story means a signing scheme (GPG-signed metadata or Sigstore) with real
// key management, and that is a deliberate decision rather than something to bolt on here.
- if runtime.GOOS != "darwin" {
+ switch {
+ case runtime.GOOS != "darwin":
result.Verification = "sha256"
- } else if !a.SkipGatekeeper {
+ case a.SkipGatekeeper:
+ // Explicitly named rather than left empty. An empty value is indistinguishable from "we
+ // did not record it", and this is the one case where a macOS update carries less assurance
+ // than a macOS update normally does -- exactly the thing a reader needs told.
+ result.Verification = "sha256 (notarization check skipped)"
+ default:
result.Verification = "sha256+notarization"
if err := a.verifyGatekeeper(ctx, pkgPath, manifest.TeamID); err != nil {
a.emit(false, result, err.Error())
diff --git a/cli/beacon/internal/endpoint/selfupdate/apply_test.go b/cli/beacon/internal/endpoint/selfupdate/apply_test.go
index b259aa04..a0616042 100644
--- a/cli/beacon/internal/endpoint/selfupdate/apply_test.go
+++ b/cli/beacon/internal/endpoint/selfupdate/apply_test.go
@@ -708,3 +708,38 @@ func TestApplyChecksumMismatchAbortsBeforeInstall(t *testing.T) {
t.Errorf("nothing may run after a checksum mismatch; calls=%v", calls)
}
}
+
+// Verification exists so an operator can tell a notarization-verified macOS update from a
+// checksum-only Linux one. It was computed into the result and never written into the event, so both
+// looked identical in the system log -- the field was decorative.
+func TestApplyRecordsVerificationInTelemetry(t *testing.T) {
+ artifact, sha := makeBeaconTarball(t, "9.9.9")
+ srv := manifestServer(t, "9.9.9", sha, artifact)
+ defer srv.Close()
+
+ a := testApplier(t, "0.0.1", srv)
+ a.restart = func() error { return nil }
+ a.run = func(ctx context.Context, name string, args ...string) (string, error) {
+ if filepath.Base(name) == "beacon" {
+ return "beacon version 9.9.9 (new) built on test", nil
+ }
+ return "", nil
+ }
+
+ res, err := a.Apply(context.Background())
+ if err != nil {
+ t.Fatalf("Apply: %v", err)
+ }
+ if res.Verification == "" {
+ t.Fatal("every applied update must name the checks the artifact passed")
+ }
+ log := string(mustRead(t, a.LogPath))
+ if !strings.Contains(log, `"verification"`) || !strings.Contains(log, res.Verification) {
+ t.Errorf("verification %q is missing from the system log:\n%s", res.Verification, log)
+ }
+ // The value must be interpretable, not just present.
+ if !strings.Contains(res.Verification, "sha256") {
+ t.Errorf("verification = %q; SHA-256 is enforced on every platform and should say so",
+ res.Verification)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/selfupdate/telemetry.go b/cli/beacon/internal/endpoint/selfupdate/telemetry.go
index 782ef34f..40407a11 100644
--- a/cli/beacon/internal/endpoint/selfupdate/telemetry.go
+++ b/cli/beacon/internal/endpoint/selfupdate/telemetry.go
@@ -36,6 +36,11 @@ func (a *Applier) emit(success bool, r ApplyResult, message string) {
"to_version": r.ToVersion,
"rolled_back": r.RolledBack,
"reason": message,
+ // Which checks the artifact actually passed. Recorded in the event, not only in the return
+ // value: the point of the field is that an operator reading the system log can tell a
+ // notarization-verified macOS update from a checksum-only Linux one, and it was being
+ // computed and then dropped, so both looked identical in telemetry.
+ "verification": r.Verification,
}
path := a.LogPath
if path == "" {
diff --git a/cli/beacon/internal/endpoint/service/updater.go b/cli/beacon/internal/endpoint/service/updater.go
index ddb0cfa7..60cf81cc 100644
--- a/cli/beacon/internal/endpoint/service/updater.go
+++ b/cli/beacon/internal/endpoint/service/updater.go
@@ -85,6 +85,23 @@ func (m UpdaterManager) UnitPath() string {
return filepath.Join("/Library/LaunchDaemons", UpdaterLabel+".plist")
}
+// UnitPaths returns every file WriteUnit installs, so a caller removing the updater removes all of
+// it.
+//
+// UnitPath is not enough on systemd, and the asymmetry is easy to miss: WriteUnit writes both the
+// timer and the oneshot service it triggers, while UnitPath deliberately names only the timer --
+// the unit an administrator enables and inspects. Every removal site used UnitPath, so
+// beacon-updater.service was left behind under /etc/systemd/system by uninstall and by disable.
+func (m UpdaterManager) UnitPaths() []string {
+ if m.resolvedKind() == KindSystemd {
+ return []string{
+ filepath.Join("/etc/systemd/system", UpdaterTimerUnit),
+ filepath.Join("/etc/systemd/system", UpdaterServiceUnit),
+ }
+ }
+ return []string{m.UnitPath()}
+}
+
// WriteUnit installs the updater definition invoking the given program.
func (m UpdaterManager) WriteUnit(program string) (string, error) {
if !m.Supported() {
diff --git a/packaging/linux/nfpm/posttrans.sh b/packaging/linux/nfpm/posttrans.sh
new file mode 100755
index 00000000..991bae4a
--- /dev/null
+++ b/packaging/linux/nfpm/posttrans.sh
@@ -0,0 +1,26 @@
+#!/bin/sh
+# Runs at the very end of an rpm transaction, after every install and removal script.
+#
+# rpm's ordering makes this necessary. During an upgrade it runs the *old* package's %preun after
+# the new package's %post, so anything the new version started can be stopped again by the version
+# being replaced. The preremove script guards against that for packages built with the guard, but an
+# upgrade *from* an older package runs that older package's script, and nothing in the new package
+# can change what it does.
+#
+# So the last word belongs here: reconcile the endpoint after the dust settles. `endpoint install` is
+# idempotent, so on a transaction that did not disturb anything this is a no-op that costs one exec.
+set -eu
+
+if [ ! -x /opt/beacon/bin/beacon ]; then
+ exit 0
+fi
+
+state="$(systemctl is-active beacon-collector.service 2>/dev/null || true)"
+if [ "$state" = active ]; then
+ exit 0
+fi
+
+echo "beacon: reconciling the endpoint after the transaction (service was $state)"
+if ! /opt/beacon/scripts/install-endpoint.sh; then
+ echo "beacon: endpoint reconcile failed; run 'sudo beacon endpoint doctor --system --fix'" >&2
+fi
diff --git a/packaging/linux/nfpm/preremove.sh b/packaging/linux/nfpm/preremove.sh
index 36b2e6cf..68f9d9e6 100755
--- a/packaging/linux/nfpm/preremove.sh
+++ b/packaging/linux/nfpm/preremove.sh
@@ -12,6 +12,31 @@
# thing that discards it.
set -eu
+# An upgrade must not run any of this, and the reason is not obvious.
+#
+# Both package managers run the *old* package's pre-removal script during an upgrade, and rpm runs
+# it AFTER the new package's postinstall. So on an rpm upgrade this script would execute right after
+# the new version installed and started the collector, and tear down the service the upgrade had
+# just brought up -- leaving an upgraded host with configuration and no running endpoint. dpkg runs
+# prerm before unpacking, which is less destructive but still pointless work the new postinstall has
+# to undo.
+#
+# This also reaches `beacon endpoint update --apply`, which installs with `dpkg -i` / `rpm -U` and so
+# runs the same scripts. Without this guard a self-update would remove the endpoint it was updating.
+#
+# The argument says which case this is:
+# dpkg prerm -> "upgrade" or "failed-upgrade" when upgrading, "remove" when removing
+# rpm %preun -> the count of remaining versions: "1" while upgrading, "0" on the final erase
+#
+# `beacon endpoint install` is idempotent and the new postinstall reconciles the unit, so skipping
+# here is not merely safe -- it is the correct behavior.
+case "${1:-}" in
+ upgrade|failed-upgrade|1)
+ echo "beacon: upgrade in progress, leaving the running endpoint in place"
+ exit 0
+ ;;
+esac
+
CONFIG_DIR=/etc/beacon/endpoint
STASH="$(mktemp -d)"
saved=0
diff --git a/packaging/linux/smoke-package.sh b/packaging/linux/smoke-package.sh
index 32f24ea2..d735ca50 100755
--- a/packaging/linux/smoke-package.sh
+++ b/packaging/linux/smoke-package.sh
@@ -179,11 +179,52 @@ if not svc.get('running'):
print("ok: status reports a running systemd service")
PY
-docker exec "$CONTAINER" /opt/beacon/bin/beacon endpoint doctor --system >/tmp/beacon-doctor.log 2>&1 || true
-if grep -qiE "^fail|\[fail\]" /tmp/beacon-doctor.log; then
- echo "doctor reported failures:" >&2; cat /tmp/beacon-doctor.log >&2; exit 1
-fi
-echo "ok: doctor reports no failures"
+# Read as JSON, not by grepping the human-readable output. The first version of this check greped
+# for "^fail" and "[fail]", neither of which doctor ever prints -- its text form says
+# "<name>: fail ..." -- so a failing doctor passed CI. A check that cannot fail is worse than no
+# check, because it reads as coverage.
+docker exec "$CONTAINER" /opt/beacon/bin/beacon endpoint doctor --system --json \
+ >/tmp/beacon-doctor.json 2>/tmp/beacon-doctor.err || true
+python3 - <<'PY' || exit 1
+import json, sys
+try:
+ with open('/tmp/beacon-doctor.json') as f:
+ report = json.load(f)
+except Exception as exc:
+ print(f" could not read doctor --json ({exc}), so its result is unknown", file=sys.stderr)
+ print(open('/tmp/beacon-doctor.err').read(), file=sys.stderr)
+ sys.exit(1)
+checks = report.get('checks')
+if not checks:
+ print(" doctor reported no checks at all, so nothing was verified", file=sys.stderr)
+ sys.exit(1)
+failed = [c for c in checks if c.get('status') == 'fail']
+if failed:
+ for c in failed:
+ print(f" FAIL {c.get('name')} target={c.get('target')}: {c.get('message')}", file=sys.stderr)
+ sys.exit(1)
+print(f"ok: doctor reports no failures across {len(checks)} checks")
+PY
+
+# Reinstalling the same package is an upgrade as far as both package managers are concerned, and it
+# is the exact sequence `beacon endpoint update --apply` performs. It is worth its own assertion
+# because the old package's pre-removal script runs during an upgrade -- and on rpm it runs *after*
+# the new postinstall, so a script that unconditionally tears the service down would leave an
+# upgraded host with configuration and no running endpoint.
+case "$FORMAT" in
+ deb) docker exec "$CONTAINER" sh -c "dpkg --install /var/tmp/beacon.deb" >/tmp/beacon-upgrade.log 2>&1 ;;
+ rpm) docker exec "$CONTAINER" sh -c "rpm --upgrade --replacepkgs /var/tmp/beacon.rpm" >/tmp/beacon-upgrade.log 2>&1 ;;
+esac || { echo "upgrade failed:" >&2; tail -20 /tmp/beacon-upgrade.log >&2; exit 1; }
+after_upgrade="$(docker exec "$CONTAINER" systemctl is-active beacon-collector.service 2>/dev/null || true)"
+[ "$after_upgrade" = active ] || {
+ echo "collector is $after_upgrade after an upgrade; the upgrade tore down its own service" >&2
+ tail -20 /tmp/beacon-upgrade.log >&2
+ docker exec "$CONTAINER" systemctl status beacon-collector.service --no-pager >&2 || true
+ exit 1
+}
+docker exec "$CONTAINER" test -f /etc/beacon/endpoint/config.json || {
+ echo "an upgrade must not remove the config" >&2; exit 1; }
+echo "ok: upgrade left the service running and the config in place"
# Removal must stop the service while the binaries it points at still exist, and must not destroy
# collected telemetry.