The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
fix(endpoint): configure the installing user's agent runtime on Linux
shukieshah692f7139b33b
diff --git a/cli/beacon/cmd/endpoint_console_user_test.go b/cli/beacon/cmd/endpoint_console_user_test.gonew file mode 100644index 00000000..6b38c66c--- /dev/null+++ b/cli/beacon/cmd/endpoint_console_user_test.go@@ -0,0 +1,119 @@+package cmd++import (+ "os"+ "os/user"+ "runtime"+ "testing"+)++// A system install configures root's agent runtime, so identifying the human who ran it is what+// makes the collector capture anything. These assert the identification cannot quietly succeed+// with a user that does not exist, or quietly claim root.+func TestResolveConsoleUserRejectsUnusableAccounts(t *testing.T) {+ for _, name := range []string{"", " ", "root", "beacon-no-such-user-9d2f"} {+ info, ok, err := resolveConsoleUser(name)+ if err != nil {+ t.Fatalf("resolveConsoleUser(%q) error = %v, want a clean not-found", name, err)+ }+ if ok {+ t.Errorf("resolveConsoleUser(%q) reported %+v; root and unknown users are not console users", name, info)+ }+ }+}++func TestResolveConsoleUserAcceptsTheCurrentUser(t *testing.T) {+ u, err := user.Current()+ if err != nil || u.Username == "root" || u.HomeDir == "" {+ t.Skip("needs a non-root current user with a home directory")+ }+ info, ok, err := resolveConsoleUser(u.Username)+ if err != nil || !ok {+ t.Fatalf("resolveConsoleUser(%q) = %+v, %v, %v; want the current user resolved", u.Username, info, ok, err)+ }+ if info.HomeDir != u.HomeDir {+ t.Errorf("HomeDir = %q, want %q -- the settings file is written there", info.HomeDir, u.HomeDir)+ }+}++// SUDO_USER is what every realistic Linux install path sets (`sudo apt install ./beacon.deb`), so+// it must be preferred over logind. Stubbed at the lookup seam rather than relying on the test+// machine's accounts: as root in a container there is no non-root user to name, and the version of+// this test that used one skipped everywhere it mattered.+func TestLinuxActiveConsoleUserPrefersSudoUser(t *testing.T) {+ if runtime.GOOS != "linux" {+ t.Skip("linux-only resolution")+ }+ 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 })++ t.Setenv("SUDO_USER", "operator")+ info, ok, err := linuxActiveConsoleUser()+ if err != nil || !ok {+ t.Fatalf("linuxActiveConsoleUser() = %+v, %v, %v; want SUDO_USER honored", info, ok, err)+ }+ if info.Username != "operator" || info.HomeDir != "/home/operator" {+ t.Errorf("resolved %+v, want the SUDO_USER account", info)+ }+ // Exactly one lookup proves logind was never consulted. Two would mean the ordering is+ // accidental and a machine with an active session could win over the person who ran sudo.+ if len(asked) != 1 || asked[0] != "operator" {+ t.Errorf("lookups = %v, want exactly [operator]", asked)+ }+}++// A SUDO_USER that does not resolve must not fall through to logind. It names who ran the install,+// so silently configuring some other logged-in user instead would point telemetry at the wrong+// person's agent and report success.+func TestLinuxActiveConsoleUserDoesNotFallThroughFromABadSudoUser(t *testing.T) {+ if runtime.GOOS != "linux" {+ t.Skip("linux-only resolution")+ }+ calls := 0+ restore := lookupConsoleUser+ lookupConsoleUser = func(string) (consoleUserInfo, bool, error) {+ calls+++ return consoleUserInfo{}, false, nil+ }+ t.Cleanup(func() { lookupConsoleUser = restore })++ t.Setenv("SUDO_USER", "deleted-account")+ if _, ok, err := linuxActiveConsoleUser(); ok || err != nil {+ t.Fatalf("want an unresolved result, got ok=%v err=%v", ok, err)+ }+ if calls != 1 {+ t.Errorf("lookups = %d, want 1: logind must not be consulted after SUDO_USER is set", calls)+ }+}++func TestDefaultActiveConsoleUserIsSilentOnUnsupportedPlatforms(t *testing.T) {+ if runtime.GOOS == "darwin" || runtime.GOOS == "linux" {+ t.Skip("both have real implementations")+ }+ if _, ok, err := defaultActiveConsoleUser(); ok || err != nil {+ t.Fatalf("want a clean not-supported result, got ok=%v err=%v", ok, err)+ }+}++// The Linux fallback must not fail an install when logind is absent -- a container or a minimal+// image has no sessions, and that is a skip, not an error.+func TestLinuxActiveConsoleUserWithoutSudoOrLogindIsNotAnError(t *testing.T) {+ if runtime.GOOS != "linux" {+ t.Skip("linux-only resolution")+ }+ t.Setenv("SUDO_USER", "")+ // An empty PATH makes loginctl unfindable, which is the same observable situation as a host+ // without logind.+ t.Setenv("PATH", t.TempDir())+ if _, ok, err := linuxActiveConsoleUser(); err != nil {+ t.Fatalf("err = %v, want nil: an install must not fail because logind is missing", err)+ } else if ok {+ t.Error("reported a console user with no sudo environment and no logind")+ }+ _ = os.Getenv("PATH")+}diff --git a/cli/beacon/cmd/endpoint_hooks_repair.go b/cli/beacon/cmd/endpoint_hooks_repair.goindex ebd1163f..49bf34cd 100644--- a/cli/beacon/cmd/endpoint_hooks_repair.go+++ b/cli/beacon/cmd/endpoint_hooks_repair.go@@ -6,6 +6,7 @@ import ("fmt""os""os/exec"+ "os/user""runtime""strings""time"@@ -37,7 +38,11 @@ type endpointHookRepairResult struct {}var (- activeConsoleUser = defaultActiveConsoleUser+ activeConsoleUser = defaultActiveConsoleUser+ // lookupConsoleUser is a seam so the SUDO_USER-before-logind ordering can be tested without+ // depending on which accounts happen to exist on the machine running the tests -- as root in+ // a container, the obvious test skips, which left the ordering unverified.+ lookupConsoleUser = resolveConsoleUserrunHookRepairAsUser = defaultRunHookRepairAsUser)@@ -157,10 +162,87 @@ func withUserHome[T any](homeDir string, fn func() (T, error)) (T, error) {return fn()}+// defaultActiveConsoleUser resolves the human whose runtime configuration a system install should+// reach.+//+// A system endpoint runs as root, and `endpoint install` configures the *installing* user's+// Claude Code and Codex settings -- which for a package install is root, not the person at the+// keyboard. Everything the operator actually wants captured therefore depends on resolving that+// person, which is what this does. When it cannot, callers report "no active console user" and+// skip rather than pretending to have configured someone.func defaultActiveConsoleUser() (consoleUserInfo, bool, error) {- if runtime.GOOS != "darwin" {+ switch runtime.GOOS {+ case "darwin":+ return darwinActiveConsoleUser()+ case "linux":+ return linuxActiveConsoleUser()+ }+ return consoleUserInfo{}, false, nil+}++// linuxActiveConsoleUser resolves the console user from sudo's environment, then from logind.+//+// SUDO_USER comes first because it is the exact question being asked -- "who invoked this install"+// -- and it is set for every realistic path (`sudo apt install ./beacon.deb`, `sudo dpkg -i`,+// `sudo rpm -U`, `sudo ./install-endpoint.sh`). logind is the fallback for the cases sudo cannot+// answer: an unattended fleet run, a root shell, or a re-run from a systemd unit. Neither is+// guessed at: an unresolvable user is reported as absent.+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.+ 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+ }+ }+ return consoleUserInfo{}, false, nil+}++// resolveConsoleUser validates a username and resolves its home directory.+//+// root is rejected: a system install has already configured root, and treating it as the console+// user would report success for configuring nobody. A user without a real home is rejected for+// the same reason -- there is nowhere for a settings file to go.+func resolveConsoleUser(username string) (consoleUserInfo, bool, error) {+ username = strings.TrimSpace(username)+ if username == "" || username == "root" {+ return consoleUserInfo{}, false, nil+ }+ u, err := user.Lookup(username)+ if err != nil {+ return consoleUserInfo{}, false, nil+ }+ if u.HomeDir == "" || u.HomeDir == "/" || u.HomeDir == "/nonexistent" {return consoleUserInfo{}, false, nil}+ if _, err := os.Stat(u.HomeDir); err != nil {+ return consoleUserInfo{}, false, nil+ }+ return consoleUserInfo{Username: username, HomeDir: u.HomeDir}, true, nil+}++func darwinActiveConsoleUser() (consoleUserInfo, bool, error) {out, err := exec.Command("stat", "-f", "%Su", "/dev/console").Output()if err != nil {return consoleUserInfo{}, false, err@@ -187,9 +269,20 @@ func defaultRunHookRepairAsUser(info consoleUserInfo, args ...string) error {}ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)defer cancel()- cmdArgs := []string{"-u", info.Username, "env", "HOME=" + info.HomeDir, "USER=" + info.Username, "LOGNAME=" + info.Username, bin}+ // runuser is the root-side tool for this and ships with util-linux, so it is present on a+ // minimal Debian or RPM system where sudo may not be installed at all -- and a package+ // postinstall runs as root, which is exactly runuser's precondition. sudo remains the path+ // everywhere else, including macOS.+ launcher, cmdArgs := "sudo", []string{"-u", info.Username}+ if runtime.GOOS == "linux" && os.Geteuid() == 0 {+ if path, err := exec.LookPath("runuser"); err == nil {+ launcher, cmdArgs = path, []string{"-u", info.Username, "--"}+ }+ }+ cmdArgs = append(cmdArgs, "env", "HOME="+info.HomeDir, "USER="+info.Username,+ "LOGNAME="+info.Username, bin)cmdArgs = append(cmdArgs, args...)- out, err := exec.CommandContext(ctx, "sudo", cmdArgs...).CombinedOutput()+ out, err := exec.CommandContext(ctx, launcher, cmdArgs...).CombinedOutput()if err != nil {return fmt.Errorf("refresh hooks for %s: %s: %w", info.Username, strings.TrimSpace(string(out)), err)}diff --git a/packaging/linux/nfpm/postinstall.sh b/packaging/linux/nfpm/postinstall.shindex 317a4b17..cc459791 100755--- a/packaging/linux/nfpm/postinstall.sh+++ b/packaging/linux/nfpm/postinstall.sh@@ -14,6 +14,20 @@ if ! /opt/beacon/scripts/install-endpoint.sh; thenexit 1fi+# A system endpoint runs as root, and `endpoint install` above configured root's own Claude Code+# and Codex settings. The person who ran the install is who actually needs pointing at the+# collector, so this second step resolves them (from SUDO_USER, else logind) and configures their+# runtime. Without it the collector runs perfectly and captures nothing anyone cares about.+#+# Non-fatal, and it prints why when it cannot: on an unattended install there may be no such user,+# which is a legitimate outcome rather than a failure.+if [ -x /opt/beacon/bin/beacon ]; then+ /opt/beacon/bin/beacon endpoint user-config repair-installed \+ --system --harness "${BEACON_ENDPOINT_HARNESSES:-claude,codex}" || \+ echo "beacon: could not configure the installing user's agent runtime; run" \+ "'beacon endpoint user-config repair-installed --system' once logged in" >&2+fi+# Reconcile the scheduled updater against the configured mode. Non-fatal: a missing or refused# scheduler must not fail the package install, since the endpoint itself is already collecting.if [ -x /opt/beacon/bin/beacon ]; thendiff --git a/packaging/linux/smoke-package.sh b/packaging/linux/smoke-package.shindex bb9b6df9..4af4c8f3 100755--- a/packaging/linux/smoke-package.sh+++ b/packaging/linux/smoke-package.sh@@ -21,6 +21,7 @@ if [ -z "$ARCH" ]; thenesacfiFORMAT="${BEACON_SMOKE_FORMAT:-deb}"+SMOKE_USER="${BEACON_SMOKE_USER:-beaconsmoke}"PKG="${BEACON_SMOKE_PKG:-}"if [ -z "$PKG" ]; then@@ -92,7 +93,17 @@ echo "ok: systemd is PID 1"# mounts a tmpfs over /tmp once PID 1 starts -- so a file copied to /tmp before that is shadowed# and dnf reports it as unopenable. Ubuntu does not do this, which is why only the rpm lane hit it.docker cp "$PKG" "$CONTAINER":/var/tmp/beacon."$FORMAT" >/dev/null-if ! docker exec "$CONTAINER" sh -c "$PKGMGR_INSTALL" >/tmp/beacon-pkg-install.log 2>&1; then++# A human has to exist for the install to have anyone to configure. A system endpoint runs as root,+# so `endpoint install` configures root's agent settings -- and the postinstall's second step is what+# points the actual operator's Claude Code at the collector. SUDO_USER is how that operator is+# identified, and dpkg/rpm pass their environment through to maintainer scripts, so setting it here+# is the same thing `sudo apt install ./beacon.deb` does.+docker exec "$CONTAINER" useradd -m -s /bin/bash "$SMOKE_USER" >/dev/null 2>&1 || true+docker exec "$CONTAINER" test -d "/home/$SMOKE_USER" || {+ echo "could not create the test user $SMOKE_USER" >&2; exit 1; }++if ! docker exec -e SUDO_USER="$SMOKE_USER" "$CONTAINER" sh -c "$PKGMGR_INSTALL" >/tmp/beacon-pkg-install.log 2>&1; thenecho "package install failed:" >&2tail -30 /tmp/beacon-pkg-install.log >&2exit 1@@ -118,6 +129,24 @@ for f in /etc/beacon/endpoint/config.json /etc/beacon/endpoint/otelcol.yaml; dodoneecho "ok: system config written to /etc/beacon/endpoint"+# The step that makes any of this useful. A running collector with nothing exporting to it captures+# an empty file, and that failure is silent -- status and doctor both look fine.+SETTINGS="/home/$SMOKE_USER/.claude/settings.json"+docker exec "$CONTAINER" test -f "$SETTINGS" || {+ echo "$SETTINGS was not written, so $SMOKE_USER's agent exports nowhere" >&2+ grep -i "user-config\|could not configure" /tmp/beacon-pkg-install.log >&2 || true+ exit 1+}+docker exec "$CONTAINER" grep -q "127.0.0.1:4317" "$SETTINGS" || {+ echo "$SETTINGS does not point at the local collector" >&2+ docker exec "$CONTAINER" cat "$SETTINGS" >&2 || true+ exit 1+}+owner="$(docker exec "$CONTAINER" stat -c %U "$SETTINGS" 2>/dev/null || true)"+[ "$owner" = "$SMOKE_USER" ] || {+ echo "$SETTINGS is owned by $owner, so $SMOKE_USER cannot read it" >&2; exit 1; }+echo "ok: the installing user's Claude Code points at the collector"+# The two commands the docs tell a new user to run. Both must report healthy with no manual setup.if ! docker exec "$CONTAINER" /opt/beacon/bin/beacon endpoint status --system --json >/tmp/beacon-status.json 2>&1; thenecho "endpoint status failed:" >&2; cat /tmp/beacon-status.json >&2; exit 1