Skip to content

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

fix(endpoint): three high-severity lifecycle defects, and sandbox probes that catch them

shukieshahac848c2e5fb2
diff --git a/beacon-sandbox/check/lifecycle.go b/beacon-sandbox/check/lifecycle.go
new file mode 100644
index 00000000..b5846962
--- /dev/null
+++ b/beacon-sandbox/check/lifecycle.go
@@ -0,0 +1,89 @@
+package check
+
+// Lifecycle is what the runner observed about reinstalling and about an unprivileged removal.
+//
+// Strings rather than bools, for the same reason as Removal: empty means the probe did not make the
+// observation, which is a third state. Reading "did not run" as false would let a probe that never
+// executed report a passing result, which is the shape of failure these checks exist to prevent.
+type Lifecycle struct {
+ // Restarted is "true"/"false" when a reinstall was performed, empty when it was not.
+ Restarted string
+ PIDBefore string
+ PIDAfter string
+ ReinstallErr string
+
+ // UnprivilegedRefused is "true"/"false" when an unprivileged removal was attempted.
+ UnprivilegedRefused string
+ UnprivilegedOutput string
+}
+
+// Reinstall judges whether installing over a running endpoint replaced the collector.
+//
+// A reinstall rewrites the collector config, and during a package upgrade the package manager has
+// already replaced the collector binary underneath the running process. If install only ever calls
+// Load -- a no-op on a live service in every backend -- the previous collector keeps serving: it
+// holds a deleted inode, ignores the new config, answers on the ports, and reports healthy. The
+// endpoint stays a version behind until the machine reboots.
+//
+// The pid is the only evidence that separates the two cases. "Is it running?" is true in both.
+func Reinstall(v *Verdict, l Lifecycle) {
+ if l.Restarted == "" && l.ReinstallErr == "" {
+ return // the scenario did not ask
+ }
+ if l.ReinstallErr != "" {
+ v.Add(Finding{
+ Check: "reinstall.restarted",
+ Severity: SevWarn,
+ Summary: l.ReinstallErr,
+ Why: "Recorded as unproven rather than passed. The probe could not establish whether a " +
+ "reinstall replaces the collector, which is not evidence that it does.",
+ })
+ return
+ }
+ if l.Restarted == "true" {
+ v.Add(Finding{
+ Check: "reinstall.restarted",
+ Severity: SevInfo,
+ Summary: "installing over a running endpoint replaced the collector (pid " + l.PIDBefore + " -> " + l.PIDAfter + ")",
+ })
+ return
+ }
+ v.Add(Finding{
+ Check: "reinstall.restarted",
+ Severity: SevFail,
+ Summary: "the collector kept pid " + l.PIDBefore + " across a reinstall, so it is still " +
+ "running the binary and configuration from before it",
+ Why: "An upgrade that leaves the previous collector serving looks entirely healthy -- ports " +
+ "answer, status reports running -- while exporting through a version the package manager " +
+ "has already deleted. Install must restart a service it finds already running.",
+ })
+}
+
+// UnprivilegedUninstall judges whether a system removal without privileges was refused.
+//
+// verify_uninstall cannot catch this, because it removes the endpoint elevated, which is the path
+// that works. The failure worth catching is the other one: an unprivileged `uninstall --system`
+// that printed "Endpoint service, config, and managed files removed." and exited 0 while every
+// operation it attempted had failed, leaving the unit enabled and the collector due back at the
+// next reboot.
+func UnprivilegedUninstall(v *Verdict, l Lifecycle) {
+ switch l.UnprivilegedRefused {
+ case "":
+ return // the scenario did not ask
+ case "true":
+ v.Add(Finding{
+ Check: "uninstall.unprivileged_refused",
+ Severity: SevInfo,
+ Summary: "an unprivileged system uninstall was refused",
+ })
+ default:
+ v.Add(Finding{
+ Check: "uninstall.unprivileged_refused",
+ Severity: SevFail,
+ Summary: "an unprivileged `endpoint uninstall --system` exited 0: " + oneLineOf(l.UnprivilegedOutput),
+ Why: "Reporting success for a removal it had no privileges to perform tells the operator " +
+ "the endpoint is gone while the service is still registered. It returns at the next " +
+ "reboot, after they were told otherwise.",
+ })
+ }
+}
diff --git a/beacon-sandbox/cmd/beacon-sandbox/main.go b/beacon-sandbox/cmd/beacon-sandbox/main.go
index dd454add..6aa96b0d 100644
--- a/beacon-sandbox/cmd/beacon-sandbox/main.go
+++ b/beacon-sandbox/cmd/beacon-sandbox/main.go
@@ -411,6 +411,16 @@ func judge(sc scenario.Scenario, art runner.Artifacts, creds credentials.Resolve
LogRetained: art.Meta["uninstall_log_retained"],
Status: art.Meta["uninstall_status"],
})
+ lifecycle := check.Lifecycle{
+ Restarted: art.Meta["reinstall_restarted"],
+ PIDBefore: art.Meta["reinstall_pid_before"],
+ PIDAfter: art.Meta["reinstall_pid_after"],
+ ReinstallErr: art.Meta["reinstall_error"],
+ UnprivilegedRefused: art.Meta["unprivileged_uninstall_refused"],
+ UnprivilegedOutput: art.Meta["unprivileged_uninstall_output"],
+ }
+ check.Reinstall(&v, lifecycle)
+ check.UnprivilegedUninstall(&v, lifecycle)
v.Resolve()
return v, log
}
diff --git a/beacon-sandbox/runner/runner.go b/beacon-sandbox/runner/runner.go
index 63ed5f3f..bd0ce29b 100644
--- a/beacon-sandbox/runner/runner.go
+++ b/beacon-sandbox/runner/runner.go
@@ -468,6 +468,17 @@ func Run(ctx context.Context, p sandbox.Provider, sc scenario.Scenario, opts Opt
art.RuntimeLog = localLog
logf("collected %s", localLog)
+ // Reinstall before uninstall, for the same reason uninstall runs here at all: the log is already
+ // on the host, so restarting the collector cannot disturb a capture assertion.
+ if sc.VerifiesRestartOnReinstall() {
+ probeReinstall(ctx, g, sc, privileged, agent, &art, logf)
+ }
+
+ // Unprivileged first, while there is still something installed for it to fail to remove.
+ if sc.VerifiesUnprivilegedUninstallFails() {
+ probeUnprivilegedUninstall(ctx, g, agent, &art, logf)
+ }
+
// Uninstall last, and only when the scenario asked. The runtime log is already on the host, so
// removing the endpoint cannot affect any capture assertion -- which is what makes it safe to do
// inside the same run rather than needing a scenario of its own.
@@ -956,6 +967,69 @@ func teardownInstall(ctx context.Context, g guest, sc scenario.Scenario,
// status` reporting "not installed" is Beacon's opinion of its own state; whether the service is
// still registered is a fact about the machine, and those are exactly the two that came apart in the
// bug this exists to catch.
+// probeReinstall installs a second time and checks the collector process was replaced.
+//
+// Runs after the runtime log has been collected, so restarting the collector cannot affect any
+// capture assertion -- the same reason probeUninstall runs where it does.
+//
+// The pid is the evidence. Asking the service whether it is "running" proves nothing here: the
+// stale collector is running, which is precisely the bug. Only a changed pid distinguishes "the
+// install restarted it" from "the install found it alive and left it there".
+func probeReinstall(ctx context.Context, g guest, sc scenario.Scenario,
+ privileged, agent sandbox.ExecOpts, art *Artifacts, logf func(string, ...any)) {
+
+ scope := "--user"
+ opts := agent
+ if sc.Install.Mode == "system" {
+ scope = "--system"
+ opts = privileged
+ }
+
+ before, _ := g.Exec(ctx, "pgrep -n beacon-otelcol", opts)
+ pidBefore := strings.TrimSpace(before.Stdout)
+ if pidBefore == "" {
+ art.Meta["reinstall_error"] = "no collector was running before the reinstall, so a restart cannot be observed"
+ logf("reinstall probe: %s", art.Meta["reinstall_error"])
+ return
+ }
+
+ args := "beacon endpoint install " + scope + " --harness claude"
+ if svc := sc.Install.Service; svc != "" {
+ args += " --service=" + svc
+ }
+ r, err := g.Exec(ctx, args+" 2>&1", opts)
+ art.Meta["reinstall_rc"] = fmt.Sprintf("%d", r.ExitCode)
+ art.Meta["reinstall_output"] = oneLine(r.Stdout + r.Stderr)
+ if err != nil || r.ExitCode != 0 {
+ art.Meta["reinstall_error"] = "the second install failed: " + art.Meta["reinstall_output"]
+ logf("reinstall probe: %s", art.Meta["reinstall_error"])
+ return
+ }
+
+ after, _ := g.Exec(ctx, "pgrep -n beacon-otelcol", opts)
+ pidAfter := strings.TrimSpace(after.Stdout)
+
+ art.Meta["reinstall_pid_before"] = pidBefore
+ art.Meta["reinstall_pid_after"] = pidAfter
+ art.Meta["reinstall_restarted"] = fmt.Sprintf("%v", pidAfter != "" && pidAfter != pidBefore)
+ logf("reinstall: collector pid %s -> %s (restarted=%s)", pidBefore, pidAfter, art.Meta["reinstall_restarted"])
+}
+
+// probeUnprivilegedUninstall checks that a system removal without privileges reports failure.
+//
+// Run before the real uninstall, and deliberately as the unprivileged agent user. What makes this
+// worth its own probe is that the bug it catches is invisible from the elevated path: the removal
+// reported success, exited 0, and left the service registered.
+func probeUnprivilegedUninstall(ctx context.Context, g guest, agent sandbox.ExecOpts,
+ art *Artifacts, logf func(string, ...any)) {
+
+ r, _ := g.Exec(ctx, "beacon endpoint uninstall --system --keep-logs 2>&1", agent)
+ art.Meta["unprivileged_uninstall_rc"] = fmt.Sprintf("%d", r.ExitCode)
+ art.Meta["unprivileged_uninstall_output"] = oneLine(r.Stdout + r.Stderr)
+ art.Meta["unprivileged_uninstall_refused"] = fmt.Sprintf("%v", r.ExitCode != 0)
+ logf("unprivileged uninstall: rc=%d refused=%s", r.ExitCode, art.Meta["unprivileged_uninstall_refused"])
+}
+
func probeUninstall(ctx context.Context, g guest, sc scenario.Scenario,
privileged, agent sandbox.ExecOpts, lay image.Layout, sh shell,
art *Artifacts, logf func(string, ...any)) {
diff --git a/beacon-sandbox/scenario/scenario.go b/beacon-sandbox/scenario/scenario.go
index 0fa302ed..2908f00e 100644
--- a/beacon-sandbox/scenario/scenario.go
+++ b/beacon-sandbox/scenario/scenario.go
@@ -75,6 +75,22 @@ type Install struct {
// refuses. Rather than make a scenario describe VM lanes and Docker, it states the
// requirement and the runner arranges it.
NeedsRealSystemd bool `yaml:"needs_real_systemd,omitempty"`
+ // VerifyRestartOnReinstall installs a second time over the running endpoint and checks that the
+ // collector process was actually replaced.
+ //
+ // Load is a no-op on a live service in every backend, so an install that only ever calls Load
+ // leaves the previous collector running -- serving the old config, and during a package upgrade
+ // a binary the package manager has already deleted. Ports answer, status reports healthy, and
+ // the endpoint is a version behind until reboot. Nothing short of a real service manager and a
+ // real second install exercises that.
+ VerifyRestartOnReinstall bool `yaml:"verify_restart_on_reinstall,omitempty"`
+ // VerifyUnprivilegedUninstallFails checks that a system uninstall run without privileges
+ // reports failure instead of pretending it removed anything.
+ //
+ // verify_uninstall alone cannot catch this: it runs the removal elevated, which is the path
+ // that works. The failure worth catching is the unprivileged one, which returned success while
+ // leaving the service registered.
+ VerifyUnprivilegedUninstallFails bool `yaml:"verify_unprivileged_uninstall_fails,omitempty"`
// NSSOnlyUser makes the session account resolvable through NSS but absent from /etc/passwd.
//
// This reproduces a directory-backed fleet -- OpenLDAP, SSSD, AD -- where `getent passwd alice`
@@ -227,6 +243,12 @@ func (s Scenario) Validate() error {
return fmt.Errorf("%s: nss_only_user requires mode=system; a user-mode install "+
"resolves $HOME and never looks the account up by name", s.ID)
}
+ // A user-mode uninstall needs no privileges, so there is no privilege failure to catch
+ // and the probe would assert something that cannot happen.
+ if s.Install.VerifyUnprivilegedUninstallFails && s.Install.Mode != "system" {
+ return fmt.Errorf("%s: verify_unprivileged_uninstall_fails requires mode=system; "+
+ "a user-mode uninstall is supposed to succeed unprivileged", s.ID)
+ }
switch s.Install.ExpectServiceKind {
case "", "systemd", "launchd", "windows-service", "none":
default:
@@ -401,6 +423,16 @@ func isFilenameByte(b byte) bool {
return false
}
+// VerifiesRestartOnReinstall reports whether a second install must replace the collector process.
+func (s Scenario) VerifiesRestartOnReinstall() bool {
+ return s.Install != nil && s.Install.VerifyRestartOnReinstall
+}
+
+// VerifiesUnprivilegedUninstallFails reports whether an unprivileged removal must be refused.
+func (s Scenario) VerifiesUnprivilegedUninstallFails() bool {
+ return s.Install != nil && s.Install.VerifyUnprivilegedUninstallFails
+}
+
// NeedsNSSOnlyUser reports whether the session account must be resolvable only through NSS.
func (s Scenario) NeedsNSSOnlyUser() bool {
return s.Install != nil && s.Install.NSSOnlyUser
diff --git a/beacon-sandbox/scenarios/i02-install-systemd.yaml b/beacon-sandbox/scenarios/i02-install-systemd.yaml
index 574703f1..ccd04cad 100644
--- a/beacon-sandbox/scenarios/i02-install-systemd.yaml
+++ b/beacon-sandbox/scenarios/i02-install-systemd.yaml
@@ -23,6 +23,13 @@ install:
# Not redundant with the above. The supervised backend also reports running, so without this a
# host where systemd detection failed would pass this scenario while testing the fallback.
expect_service_kind: systemd
+ # Both of these need a real service manager, which is why they live here rather than on i01.
+ # `systemctl enable --now` does not restart an active unit, so an install that only calls Load
+ # leaves the previous collector serving -- the failure a package upgrade produces.
+ verify_restart_on_reinstall: true
+ # And an unprivileged removal has to be refused rather than reported as done, which the elevated
+ # uninstall below cannot show.
+ verify_unprivileged_uninstall_fails: true
verify_uninstall: true
prompt: >-
diff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics.go
index 619e87bc..0083f8a2 100644
--- a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go
+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics.go
@@ -136,6 +136,32 @@ func checkLogPermissions(path string, userMode bool) Check {
if mode&0222 == 0 {
return Check{Name: "runtime_log_permissions", Target: path, Status: StatusFail, Severity: SeverityHigh, Message: fmt.Sprintf("runtime log is not writable: %o", mode), Evidence: "not_writable"}
}
+ // System mode asks a sharper question than "is this writable by somebody".
+ //
+ // The collector runs as root and hooks run as the logged-in user, so the check that matters is
+ // whether a *non-root* process can write here. mode&0222 cannot answer that: it is satisfied by
+ // the owner's write bit, so a root-owned 0600 log -- which no hook can write -- passed as OK.
+ // The Windows branch above was added for exactly this reason; the POSIX branch had the same
+ // hole and nobody had looked.
+ //
+ // Both parts have to hold. The file needs a world-write bit, and the directory needs to be
+ // traversable, because a hook that cannot enter the directory never gets as far as the file.
+ if !userMode {
+ if mode&0002 == 0 {
+ return Check{Name: "runtime_log_permissions", Target: path, Status: StatusFail, Severity: SeverityHigh,
+ Message: fmt.Sprintf("runtime log is mode %o, so hooks running as the logged-in user cannot append to it and their events are lost", mode),
+ Evidence: "not_writable_by_hooks", Action: "sudo chmod 0666 " + path}
+ }
+ if dir := filepath.Dir(path); dir != "" {
+ if dirInfo, dirErr := os.Stat(dir); dirErr == nil {
+ if dirMode := dirInfo.Mode().Perm(); dirMode&0001 == 0 || dirMode&0004 == 0 {
+ return Check{Name: "runtime_log_permissions", Target: dir, Status: StatusFail, Severity: SeverityHigh,
+ Message: fmt.Sprintf("log directory is mode %o, so hooks running as the logged-in user cannot reach the runtime log inside it", dirMode),
+ Evidence: "log_dir_not_traversable", Action: "sudo chmod 0755 " + dir}
+ }
+ }
+ }
+ }
if mode&0044 == 0 {
return Check{Name: "runtime_log_permissions", Target: path, Status: StatusWarn, Severity: SeverityLow, Message: fmt.Sprintf("runtime log may not be readable by Wazuh: %o", mode), Evidence: "not_group_or_world_readable"}
}
diff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go
index 245c6642..c46156bd 100644
--- a/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go
+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go
@@ -44,13 +44,19 @@ func TestCheckLogPermissions(t *testing.T) {
t.Fatalf("missing log permissions check = %#v", check)
}
+ // 0644 is owner-write only. In system mode the owner is root and the hooks are not, so this is
+ // a log no hook can append to -- their events are lost silently. This case asserted "ok" until
+ // the check learned to ask whether a *non-root* process can write, rather than whether anyone
+ // can.
if err := os.WriteFile(logPath, []byte("{}\n"), 0644); err != nil {
t.Fatalf("write log: %v", err)
}
- if check := checkLogPermissions(logPath, false); check.Status != "ok" {
+ if check := checkLogPermissions(logPath, false); check.Status != "fail" || check.Evidence != "not_writable_by_hooks" {
t.Fatalf("0644 log permissions check = %#v", check)
}
+ // 0666 is what install actually creates, and the only mode that lets the root collector and
+ // the user's hooks share one file.
if err := os.Chmod(logPath, 0666); err != nil {
t.Fatalf("chmod writable log: %v", err)
}
@@ -58,10 +64,12 @@ func TestCheckLogPermissions(t *testing.T) {
t.Fatalf("0666 log permissions check = %#v", check)
}
+ // 0200 is owner-write, no read for anyone. Previously reported as a low-severity readability
+ // warning; the more serious half is that hooks cannot write it either.
if err := os.Chmod(logPath, 0200); err != nil {
t.Fatalf("chmod unreadable log: %v", err)
}
- if check := checkLogPermissions(logPath, false); check.Status != "warn" || check.Severity != "low" {
+ if check := checkLogPermissions(logPath, false); check.Status != "fail" || check.Evidence != "not_writable_by_hooks" {
t.Fatalf("0200 log permissions check = %#v", check)
}
diff --git a/cli/beacon/internal/endpoint/diagnostics/logperm_test.go b/cli/beacon/internal/endpoint/diagnostics/logperm_test.go
new file mode 100644
index 00000000..1fba1244
--- /dev/null
+++ b/cli/beacon/internal/endpoint/diagnostics/logperm_test.go
@@ -0,0 +1,77 @@
+//go:build !windows
+
+package diagnostics
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func logAt(t *testing.T, dirMode, fileMode os.FileMode) string {
+ t.Helper()
+ dir := filepath.Join(t.TempDir(), "beacon-agent")
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(dir, "runtime.jsonl")
+ if err := os.WriteFile(path, []byte("{}\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(path, fileMode); err != nil {
+ t.Fatal(err)
+ }
+ // Directory last: chmod on a file inside it must happen while it is still traversable.
+ if err := os.Chmod(dir, dirMode); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.Chmod(dir, 0o755) })
+ return path
+}
+
+// In system mode the collector runs as root and hooks run as the logged-in user, so the question
+// is whether a non-root process can write. mode&0222 could not answer it -- the owner's write bit
+// satisfies it, so a root-owned 0600 log passed as healthy while every hook write failed.
+func TestSystemLogPermissionsRejectAnOwnerOnlyLog(t *testing.T) {
+ path := logAt(t, 0o755, 0o600)
+
+ got := checkLogPermissions(path, false)
+ if got.Status != StatusFail {
+ t.Errorf("status = %v for a 0600 log in system mode, want fail: no hook can write it", got.Status)
+ }
+ if got.Action == "" {
+ t.Error("a failure an operator can fix should say how")
+ }
+}
+
+// The file mode alone is not enough. A hook that cannot traverse the directory never reaches the
+// log, however permissive the log itself is -- which is the state a hardened umask produces.
+func TestSystemLogPermissionsRejectAnUnreachableDirectory(t *testing.T) {
+ path := logAt(t, 0o700, 0o666)
+
+ got := checkLogPermissions(path, false)
+ if got.Status != StatusFail {
+ t.Errorf("status = %v for a 0666 log inside a 0700 directory, want fail", got.Status)
+ }
+ if got.Evidence != "log_dir_not_traversable" {
+ t.Errorf("evidence = %q, want the directory named as the cause", got.Evidence)
+ }
+}
+
+func TestSystemLogPermissionsAcceptTheShippedLayout(t *testing.T) {
+ path := logAt(t, 0o755, 0o666)
+
+ if got := checkLogPermissions(path, false); got.Status != StatusOK {
+ t.Errorf("status = %v (%s) for the layout install actually creates, want ok", got.Status, got.Message)
+ }
+}
+
+// User mode is a different question: the log lives in that user's own profile and is written by
+// processes running as them, so an owner-only file is correct and must not be failed.
+func TestUserModeLogPermissionsAllowAnOwnerOnlyLog(t *testing.T) {
+ path := logAt(t, 0o700, 0o600)
+
+ if got := checkLogPermissions(path, true); got.Status == StatusFail {
+ t.Errorf("status = fail (%s) for a private user-mode log, which is the correct layout there", got.Message)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index b7b003a1..23a1d4e8 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path/filepath"
+ "strings"
"time"
beaconauth "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"
@@ -236,7 +237,26 @@ func Install(opts InstallOptions) (InstallResult, error) {
return InstallResult{}, err
}
if opts.StartService {
- if err := manager.Load(); err != nil {
+ // Restart when something is already running, rather than Load.
+ //
+ // Load is a no-op on a live service in every backend: `systemctl enable --now` does not
+ // restart an active unit, launchd's bootstrap refuses an already-bootstrapped label, and the
+ // supervised backend returns early on a live pid. That is correct for a first install and
+ // wrong for every subsequent one, because by this point the install has already rewritten
+ // the collector config and, during a package upgrade, the package manager has already
+ // replaced the collector binary underneath the running process.
+ //
+ // Without this, `apt install ./beacon.deb` over an older version left the previous
+ // collector serving OTLP -- holding a deleted inode, ignoring the new config -- while the
+ // install reported success and the ports answered. The endpoint looked healthy and was a
+ // version behind until the machine rebooted. The same path made `endpoint install
+ // --splunk-hec-endpoint ...` write a destination that never took effect.
+ if manager.Status().Running {
+ if err := manager.Restart(); err != nil {
+ tx.Rollback(manifest)
+ return InstallResult{}, err
+ }
+ } else if err := manager.Load(); err != nil {
tx.Rollback(manifest)
return InstallResult{}, err
}
@@ -287,15 +307,40 @@ func Install(opts InstallOptions) (InstallResult, error) {
}, nil
}
+// Uninstall removes the endpoint and reports what it could not remove.
+//
+// Every step used to discard its error and the function could only return nil, so
+// `beacon endpoint uninstall --system` without privileges printed "Endpoint service, config, and
+// managed files removed." and exited 0 while the systemd unit stayed enabled -- the collector came
+// back at the next reboot, after the operator had been told it was gone.
+//
+// Removal still continues past a failure rather than stopping at the first one: a partial uninstall
+// that removes what it can is more useful than one that abandons the job halfway, and the caller
+// needs to hear about every leftover, not just the first. The failures are collected and returned
+// together.
func Uninstall(opts UninstallOptions) error {
cfg := loadOrDefault(opts.UserMode, opts.LogPath)
+ // Refuse a system uninstall we cannot carry out, instead of half-doing it and reporting
+ // success. Install has always had this gate; uninstall never did, which is the asymmetry that
+ // let an unprivileged removal look like it worked.
+ if !cfg.UserMode && !HasSystemPrivileges() {
+ return fmt.Errorf("removing a system endpoint needs root: rerun with sudo, or pass --user to remove a user-mode install")
+ }
+
+ var problems []string
+ fail := func(what string, err error) {
+ if err != nil && !os.IsNotExist(err) {
+ problems = append(problems, fmt.Sprintf("%s: %v", what, err))
+ }
+ }
+
// Unload every backend that could plausibly hold this service, not just the one
// detection picks now. An install performed under systemd and uninstalled from a
// container would otherwise leave the unit enabled, and "uninstall" has to mean nothing
// is left behind. Unload already tolerates a backend that is unusable here.
manager := service.Manager{UserMode: cfg.UserMode}
for _, kind := range service.ManagedKinds() {
- _ = (service.Manager{UserMode: cfg.UserMode, Kind: kind}).Unload()
+ fail(fmt.Sprintf("unload %s service", kind), (service.Manager{UserMode: cfg.UserMode, Kind: kind}).Unload())
}
if !cfg.UserMode && !opts.KeepUpdater {
removeUpdaterJob()
@@ -305,22 +350,49 @@ func Uninstall(opts UninstallOptions) error {
restoreBackups(manifest.Backups)
}
for _, path := range manifest.Files {
- _ = os.Remove(path)
+ fail("remove "+path, os.Remove(path))
}
if len(manifest.Files) == 0 {
if path, err := manager.UnitPath(); err == nil {
- _ = os.Remove(path)
+ fail("remove "+path, os.Remove(path))
}
- _ = os.Remove(cfg.Collector.ConfigPath)
- _ = os.Remove(endpointconfig.ConfigPath(cfg.UserMode))
+ fail("remove "+cfg.Collector.ConfigPath, os.Remove(cfg.Collector.ConfigPath))
+ fail("remove endpoint config", os.Remove(endpointconfig.ConfigPath(cfg.UserMode)))
}
if !opts.KeepLogs {
- _ = os.Remove(cfg.LogPath)
+ for _, path := range runtimeLogFiles(cfg.LogPath) {
+ fail("remove "+path, os.Remove(path))
+ }
+ }
+ fail("remove install manifest", os.Remove(manifestPath(cfg.UserMode)))
+
+ if len(problems) > 0 {
+ return fmt.Errorf("endpoint uninstall left %d item(s) behind:\n %s",
+ len(problems), strings.Join(problems, "\n "))
}
- _ = os.Remove(manifestPath(cfg.UserMode))
return nil
}
+// runtimeLogFiles lists the runtime log and everything rotation has produced from it.
+//
+// Removing only runtime.jsonl left up to five rotated archives holding retained prompt text and
+// command lines on disk after an uninstall that was not asked to keep logs -- the opposite of what
+// the operator requested, and invisible because the file they would check was gone.
+func runtimeLogFiles(logPath string) []string {
+ if logPath == "" {
+ return nil
+ }
+ paths := []string{logPath, logPath + ".lock"}
+ if rotated, err := filepath.Glob(logPath + ".*"); err == nil {
+ for _, p := range rotated {
+ if p != logPath+".lock" {
+ paths = append(paths, p)
+ }
+ }
+ }
+ return paths
+}
+
func Repair(opts InstallOptions) (InstallResult, error) {
configPath := endpointconfig.ConfigPath(opts.UserMode)
configSnapshot := snapshotFile(configPath)
diff --git a/cli/beacon/internal/endpoint/lifecycle/uninstall_reporting_test.go b/cli/beacon/internal/endpoint/lifecycle/uninstall_reporting_test.go
new file mode 100644
index 00000000..2bb08fb2
--- /dev/null
+++ b/cli/beacon/internal/endpoint/lifecycle/uninstall_reporting_test.go
@@ -0,0 +1,93 @@
+package lifecycle
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// The failure this exists to catch: `beacon endpoint uninstall --system` without privileges used to
+// print "Endpoint service, config, and managed files removed." and exit 0 while the systemd unit
+// stayed enabled, so the collector returned at the next reboot after the operator had been told it
+// was gone. Install has always refused unprivileged system writes; uninstall never did.
+func TestUninstallRefusesAnUnprivilegedSystemRemoval(t *testing.T) {
+ if HasSystemPrivileges() {
+ t.Skip("running as root, so the unprivileged path cannot be exercised here")
+ }
+
+ err := Uninstall(UninstallOptions{UserMode: false})
+ if err == nil {
+ t.Fatal("an unprivileged system uninstall returned nil, which the CLI prints as success")
+ }
+ if !strings.Contains(err.Error(), "root") {
+ t.Errorf("error %q should say privileges are the problem, so the operator knows to rerun with sudo", err)
+ }
+}
+
+// A user-mode uninstall needs no privileges and must not be caught by that gate.
+func TestUninstallAllowsUserModeWithoutPrivileges(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+
+ if err := Uninstall(UninstallOptions{UserMode: true}); err != nil {
+ t.Errorf("user-mode uninstall failed with nothing installed: %v", err)
+ }
+}
+
+// Rotation turns one log into six files. Removing only runtime.jsonl left the archives -- up to
+// 50 MB of retained prompt text and command lines -- on disk after an uninstall that was not asked
+// to keep logs, and invisible, because the file an operator would look for was gone.
+func TestUninstallRemovesRotatedArchivesToo(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+
+ logDir := filepath.Join(home, ".beacon", "endpoint", "logs")
+ if err := os.MkdirAll(logDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ logPath := filepath.Join(logDir, "runtime.jsonl")
+ written := []string{logPath, logPath + ".1", logPath + ".2", logPath + ".lock"}
+ for _, p := range written {
+ if err := os.WriteFile(p, []byte("{}\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ if err := Uninstall(UninstallOptions{UserMode: true, LogPath: logPath}); err != nil {
+ t.Fatal(err)
+ }
+
+ for _, p := range written {
+ if _, err := os.Stat(p); err == nil {
+ t.Errorf("%s survived an uninstall that was not asked to keep logs", filepath.Base(p))
+ }
+ }
+}
+
+// --keep-logs has to keep all of them, not just the current one.
+func TestUninstallKeepLogsKeepsTheArchives(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+
+ logDir := filepath.Join(home, ".beacon", "endpoint", "logs")
+ if err := os.MkdirAll(logDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ logPath := filepath.Join(logDir, "runtime.jsonl")
+ for _, p := range []string{logPath, logPath + ".1"} {
+ if err := os.WriteFile(p, []byte("{}\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ if err := Uninstall(UninstallOptions{UserMode: true, LogPath: logPath, KeepLogs: true}); err != nil {
+ t.Fatal(err)
+ }
+
+ for _, p := range []string{logPath, logPath + ".1"} {
+ if _, err := os.Stat(p); err != nil {
+ t.Errorf("%s was removed despite --keep-logs", filepath.Base(p))
+ }
+ }
+}
diff --git a/cli/beacon/internal/endpoint/writer/logdir_perm_test.go b/cli/beacon/internal/endpoint/writer/logdir_perm_test.go
new file mode 100644
index 00000000..1e6ec18f
--- /dev/null
+++ b/cli/beacon/internal/endpoint/writer/logdir_perm_test.go
@@ -0,0 +1,70 @@
+//go:build !windows
+
+package writer
+
+import (
+ "os"
+ "path/filepath"
+ "syscall"
+ "testing"
+)
+
+// A hardened host sets a restrictive umask, and MkdirAll's mode argument is masked by it. Under
+// umask 027 the log directory came out 0750 root:root; under 077, 0700. The runtime log inside is
+// deliberately 0666 so hooks can append, but a process that cannot traverse the directory never
+// reaches the file -- so every hook-sourced event was lost while the root-owned collector stayed
+// healthy and doctor reported nothing wrong.
+func TestSystemLogDirIsTraversableUnderARestrictiveUmask(t *testing.T) {
+ for name, mask := range map[string]int{
+ "umask 022 (default)": 0o022,
+ "umask 027 (CIS)": 0o027,
+ "umask 077 (strict)": 0o077,
+ } {
+ t.Run(name, func(t *testing.T) {
+ old := syscall.Umask(mask)
+ t.Cleanup(func() { syscall.Umask(old) })
+
+ dir := filepath.Join(t.TempDir(), "beacon-agent")
+ if err := EnsureSystemLogWritable(dir); err != nil {
+ t.Fatal(err)
+ }
+
+ info, err := os.Stat(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mode := info.Mode().Perm()
+ // Traverse (x) and read (r) for other: a hook runs as the logged-in user, not as the
+ // root process that created this.
+ if mode&0o001 == 0 || mode&0o004 == 0 {
+ t.Errorf("log directory is mode %o under umask %o; hooks running as another user "+
+ "cannot reach the runtime log inside it", mode, mask)
+ }
+ })
+ }
+}
+
+// The directory may already exist from an earlier install performed under a different umask.
+// Creating it correctly is not enough if an existing one is left as it was found.
+func TestSystemLogDirIsCorrectedWhenItAlreadyExists(t *testing.T) {
+ dir := filepath.Join(t.TempDir(), "beacon-agent")
+ if err := os.MkdirAll(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := EnsureSystemLogWritable(dir); err != nil {
+ t.Fatal(err)
+ }
+
+ info, err := os.Stat(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if mode := info.Mode().Perm(); mode&0o001 == 0 {
+ t.Errorf("an existing 0700 log directory was left at %o; a reinstall or repair is exactly "+
+ "when an operator expects this to be put right", mode)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/writer/writer.go b/cli/beacon/internal/endpoint/writer/writer.go
index 6a762896..3c18f86f 100644
--- a/cli/beacon/internal/endpoint/writer/writer.go
+++ b/cli/beacon/internal/endpoint/writer/writer.go
@@ -105,6 +105,21 @@ func EnsureSystemLogWritable(dir string) error {
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("create the log directory %s: %w", dir, err)
}
+ // Chmod after MkdirAll, and for an existing directory too.
+ //
+ // MkdirAll's mode is masked by the process umask, so on a host with umask 027 or 077 -- any
+ // CIS-hardened build -- this directory came out 0750 or 0700 owned by root. The runtime log
+ // inside it is deliberately 0666 so hooks running as the logged-in user can append, but a
+ // non-root process cannot open a file it cannot traverse to. Every hook write then failed with
+ // EACCES while the root-owned collector stayed perfectly healthy, so the endpoint looked fine
+ // and silently lost every hook-sourced event.
+ //
+ // 0755 rather than something narrower: hooks need traverse, and the sticky-bit dance that would
+ // let them create files here is not needed because the collector owns rotation. The file mode
+ // is what grants write, and openRuntimeFile sets that explicitly for the same umask reason.
+ if err := os.Chmod(dir, 0755); err != nil {
+ return fmt.Errorf("make the log directory %s traversable: %w", dir, err)
+ }
return grantInteractiveUsersWrite(dir)
}
diff --git a/docs/platforms/linux-deployment-profile.mdx b/docs/platforms/linux-deployment-profile.mdx
index 0d4cf221..8a3c4b1d 100644
--- a/docs/platforms/linux-deployment-profile.mdx
+++ b/docs/platforms/linux-deployment-profile.mdx
@@ -61,16 +61,17 @@ Measured on Ubuntu 24.04 / amd64 after a live Claude Code session.
| | Measured | Notes |
|---|---|---|
-| Resident memory | ~57 MiB | Hard ceiling 128 MiB (`memory_limiter`) |
-| CPU, idle | 0.1–0.3% of one core | Two timers: 1s memory check, 5s batch flush |
+| Resident memory | 28–58 MiB | Hard ceiling 128 MiB (`memory_limiter`) |
+| CPU, idle | 0.03–0.3% of one core | Two timers: 1s memory check, 5s batch flush |
| Threads | 15 | Go runtime, scales with available cores |
| Disk | ≤60 MB | 10 MiB × 5 rotations, oldest discarded |
| Per agent event | one `fork`/`exec`, one `flock`, one append | Process exits immediately |
### Caveats
-- The CPU figure is a range, not an average. Repeated 30-second samples came out between 0.1% and
- 0.3% of one core.
+- Both figures are ranges, not averages. They come from a supervised collector and a
+ systemd-managed one, which is most of the spread — memory in particular depends on how much the
+ Go runtime has been asked to do before it settles.
- These numbers come from a virtualized sandbox, where syscalls are slower than on bare metal.
Expect equal or better on your own hardware.