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
Make user-mode runtime logs private (0600 in 0700 directories)
Claudede2cabe66bdb
diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.goindex 739a9524..ef14fb14 100644--- a/cli/beacon-hooks/internal/logging/logging.go+++ b/cli/beacon-hooks/internal/logging/logging.go@@ -27,7 +27,10 @@ var endpointSequence asymptoteobserve.Sequencerconst (defaultEndpointRotateBytes = 10 * 1024 * 1024defaultEndpointRotateArchives = 5- endpointRuntimeFileMode = 0666+ // endpointRuntimeFileMode is the shared (system-mode) log's mode. A log inside the current+ // user's home is private instead; asymptoteobserve.RuntimeLogModes decides, identically in all+ // three writers.+ endpointRuntimeFileMode = asymptoteobserve.SharedRuntimeLogFileMode)// Logger provides structured JSON logging for hook events@@ -472,7 +475,8 @@ func firstEnv(keys ...string) string {var writeEndpointJSON = writeEndpointJSONFilefunc writeEndpointJSONFile(path string, event map[string]interface{}) error {- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ _, dirMode, _ := asymptoteobserve.RuntimeLogModes(path)+ if err := os.MkdirAll(filepath.Dir(path), dirMode); err != nil {return err}data, err := json.Marshal(sanitizeEndpointMap(event))@@ -640,12 +644,13 @@ func truncateEndpoint(value string, limit int) string {return asymptoteobserve.TruncateString(value, limit)}-// Keep this rotation contract mirrored with the endpoint CLI and beaconjson exporter.+// Keep this rotation and file-mode contract mirrored with the endpoint CLI and beaconjson exporter.func appendEndpointJSONL(path string, line []byte, rotateBytes int64, rotateArchives int) error {- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ _, dirMode, _ := asymptoteobserve.RuntimeLogModes(path)+ if err := os.MkdirAll(filepath.Dir(path), dirMode); err != nil {return err}- lock, err := openEndpointRuntimeFile(path+".lock", os.O_CREATE|os.O_RDWR)+ lock, err := openEndpointRuntimeFileAs(path+".lock", path, os.O_CREATE|os.O_RDWR)if err != nil {return err}@@ -673,6 +678,14 @@ func appendEndpointJSONL(path string, line []byte, rotateBytes int64, rotateArch}func openEndpointRuntimeFile(path string, flag int) (*os.File, error) {+ return openEndpointRuntimeFileAs(path, path, flag)+}++// openEndpointRuntimeFileAs opens path (the log or its lock) with the mode logPath calls for. The+// chmod runs on an existing file too: it tightens a private log an older release left world-writable+// (same owner), and a failed chmod on an existing shared log this user does not own is ignored.+func openEndpointRuntimeFileAs(path, logPath string, flag int) (*os.File, error) {+ fileMode, _, _ := asymptoteobserve.RuntimeLogModes(logPath)existed := trueif _, err := os.Stat(path); err != nil {if !os.IsNotExist(err) {@@ -680,11 +693,11 @@ func openEndpointRuntimeFile(path string, flag int) (*os.File, error) {}existed = false}- f, err := os.OpenFile(path, flag, endpointRuntimeFileMode)+ f, err := os.OpenFile(path, flag, fileMode)if err != nil {return nil, err}- if err := os.Chmod(path, endpointRuntimeFileMode); err != nil && !existed {+ if err := os.Chmod(path, fileMode); err != nil && !existed {_ = f.Close()return nil, err}@@ -718,7 +731,11 @@ func rotateEndpointLogIfNeeded(path string, maxSize int64, archives int, nextWrireturn err}}- return os.Rename(path, path+".1")+ if err := os.Rename(path, path+".1"); err != nil {+ return err+ }+ asymptoteobserve.TightenPrivateRuntimeLogArchives(path, archives)+ return nil}func removeOverflowEndpointArchives(path string, archives int) error {diff --git a/cli/beacon-hooks/internal/logging/private_log_unix_test.go b/cli/beacon-hooks/internal/logging/private_log_unix_test.gonew file mode 100644index 00000000..f23297b6--- /dev/null+++ b/cli/beacon-hooks/internal/logging/private_log_unix_test.go@@ -0,0 +1,96 @@+//go:build !windows++package logging++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func assertEndpointPerm(t *testing.T, path string, want os.FileMode) {+ t.Helper()+ info, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat %s: %v", path, err)+ }+ if got := info.Mode().Perm(); got != want {+ t.Fatalf("%s mode = %o, want %o", path, got, want)+ }+}++// The default user-mode log (BEACON_ENDPOINT_MODE with no explicit path) lives in the user's home+// and is written only by that user's processes, so the hook creates it, its lock and its+// directories private. It used to create 0666 files in 0755 directories.+func TestUserModeEndpointLogIsPrivate(t *testing.T) {+ isolateHookHome(t)+ home := os.Getenv("HOME")+ t.Setenv("BEACON_ENDPOINT_LOG", "")+ t.Setenv("BEACON_CLOUD_LOG_PATH", "")+ t.Setenv("BEACON_LOG_PATH", "")+ t.Setenv("BEACON_RUNTIME_LOG", "")+ t.Setenv("BEACON_ENDPOINT_MODE", "1")+ logPath := endpointLogPath()+ if !strings.HasPrefix(logPath, home) {+ t.Fatalf("default endpoint log %s is not under the test home %s", logPath, home)+ }++ logger := NewLoggerForPlatform("agent-thought", "cursor")+ if err := logger.EndpointEvent("agent.reasoning", "session", "info", "Agent reasoning captured", nil); err != nil {+ t.Fatal(err)+ }+ assertEndpointPerm(t, logPath, 0o600)+ assertEndpointPerm(t, logPath+".lock", 0o600)+ for _, dir := range []string{+ filepath.Join(home, ".beacon", "endpoint"),+ filepath.Join(home, ".beacon", "endpoint", "logs"),+ } {+ assertEndpointPerm(t, dir, 0o700)+ }+}++// A log an older release left world-writable is tightened on the next append, and rotation keeps+// archives private, including ones rotated before the change.+func TestUserModeEndpointLogIsTightenedAndRotatesPrivately(t *testing.T) {+ isolateHookHome(t)+ home := os.Getenv("HOME")+ logPath := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")+ if err := os.MkdirAll(filepath.Dir(logPath), 0o755); err != nil {+ t.Fatal(err)+ }+ for _, target := range []string{logPath, logPath + ".lock", logPath + ".1"} {+ if err := os.WriteFile(target, []byte("{}\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.Chmod(target, 0o666); err != nil {+ t.Fatal(err)+ }+ }++ line := []byte(`{"message":"` + strings.Repeat("x", 64) + `"}` + "\n")+ if err := appendEndpointJSONL(logPath, line, 32, defaultEndpointRotateArchives); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(logPath + ".2"); err != nil {+ t.Fatalf("expected the log to rotate: %v", err)+ }+ for _, target := range []string{logPath, logPath + ".lock", logPath + ".1", logPath + ".2"} {+ assertEndpointPerm(t, target, 0o600)+ }+}++// System mode is unchanged: a log outside the user's home (the shared /var/log/beacon-agent log in+// practice) keeps the shared mode so every user's hooks can append to it.+func TestSharedEndpointLogKeepsTheSharedMode(t *testing.T) {+ isolateHookHome(t)+ logPath := filepath.Join(t.TempDir(), "beacon-agent", "runtime.jsonl")+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)++ logger := NewLoggerForPlatform("agent-thought", "cursor")+ if err := logger.EndpointEvent("agent.reasoning", "session", "info", "Agent reasoning captured", nil); err != nil {+ t.Fatal(err)+ }+ assertEndpointPerm(t, logPath, 0o666)+ assertEndpointPerm(t, logPath+".lock", 0o666)+}diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.goindex 0e44bebd..e368c96a 100644--- a/cli/beacon/cmd/endpoint_diagnostics.go+++ b/cli/beacon/cmd/endpoint_diagnostics.go@@ -1155,6 +1155,12 @@ func actionForCheck(check diagnostics.Check, runtimeLog lifecycle.RuntimeLogSourcase "acl_unreadable":return "inspect the access control list on " + check.Target}+ if runtimeLog.EffectiveUserMode {+ // A user-mode log is written only by processes running as its owner, so owner+ // read/write is the whole fix. Advising 666 here would hand the user's prompts and+ // command output to every local account.+ return "chmod 600 " + check.Target+ }return "chmod 666 " + check.Targetcase "runtime_log_source":if runtimeLog.RequestedUserMode && !runtimeLog.EffectiveUserMode {diff --git a/cli/beacon/cmd/endpoint_diagnostics_action_test.go b/cli/beacon/cmd/endpoint_diagnostics_action_test.goindex e1b257d5..9c21d17c 100644--- a/cli/beacon/cmd/endpoint_diagnostics_action_test.go+++ b/cli/beacon/cmd/endpoint_diagnostics_action_test.go@@ -62,6 +62,18 @@ func TestLogPermissionRemediationMatchesThePlatformThatFailed(t *testing.T) {}}+ // A user-mode log is private; the mode remediation must never advise making it world-writable.+ if runtime.GOOS != "windows" {+ userAction := actionForCheck(diagnostics.Check{+ Name: "runtime_log_permissions",+ Target: "/home/someone/.beacon/endpoint/logs/runtime.jsonl",+ Evidence: "not_writable",+ }, lifecycle.RuntimeLogSource{EffectiveUserMode: true})+ if userAction != "chmod 600 /home/someone/.beacon/endpoint/logs/runtime.jsonl" {+ t.Fatalf("the user-mode remediation is %q; want owner-only chmod 600", userAction)+ }+ }+if got := action("runtime_log_missing"); got != "beacon endpoint doctor --fix" {t.Fatalf("missing-log remediation = %q", got)}diff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics.goindex 0c86fb4e..fdf52ec7 100644--- a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics.go@@ -196,6 +196,12 @@ func checkLogPermissions(path string, userMode bool) Check {}}}+ // A user-mode log is private on purpose: Beacon creates it 0600, since it holds that user's+ // prompts and command output and every process that writes it runs as them. Owner-only is the+ // healthy state there, not a readability problem.+ if userMode && mode&0200 != 0 {+ return Check{Name: "runtime_log_permissions", Target: path, Status: StatusOK, Severity: SeverityInfo, Message: fmt.Sprintf("mode %o", mode), Evidence: fmt.Sprintf("mode_%o", mode)}+ }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/logperm_test.go b/cli/beacon/internal/endpoint/diagnostics/logperm_test.goindex 1fba1244..3ff65340 100644--- a/cli/beacon/internal/endpoint/diagnostics/logperm_test.go+++ b/cli/beacon/internal/endpoint/diagnostics/logperm_test.go@@ -71,7 +71,10 @@ func TestSystemLogPermissionsAcceptTheShippedLayout(t *testing.T) {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)+ // Not even a warning: 0600 in a 0700 directory is what the writers create for a user-mode log,+ // and a doctor that warns on the shipped layout trains people to widen it.+ if got := checkLogPermissions(path, true); got.Status != StatusOK {+ t.Errorf("status = %v (%s, %s) for a private user-mode log, which is the layout Beacon creates there; want ok",+ got.Status, got.Evidence, got.Message)}}diff --git a/cli/beacon/internal/endpoint/writer/private_log_test.go b/cli/beacon/internal/endpoint/writer/private_log_test.gonew file mode 100644index 00000000..588cbc56--- /dev/null+++ b/cli/beacon/internal/endpoint/writer/private_log_test.go@@ -0,0 +1,133 @@+package writer++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"+)++func privateLogTestEvent(message string) schema.Event {+ return schema.NewEvent(schema.NewEventOptions{+ Action: "agent.detected",+ Harness: schema.HarnessInfo{Name: "test"},+ Message: message,+ })+}++func assertPerm(t *testing.T, path string, want os.FileMode) {+ t.Helper()+ info, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat %s: %v", path, err)+ }+ if got := info.Mode().Perm(); got != want {+ t.Fatalf("%s mode = %o, want %o", path, got, want)+ }+}++// A user-mode log holds that user's prompts, command output and diffs, and everything that writes+// it runs as that user. It used to be created 0666 in 0755 directories, readable and writable by+// every local account that could traverse the home directory.+func TestUserModeLogIsPrivate(t *testing.T) {+ testenv.RequirePOSIXFileModes(t)+ home := t.TempDir()+ testenv.SetHome(t, home)++ path := DefaultPath(true)+ if !strings.HasPrefix(path, home) {+ t.Fatalf("user log path %s is not under the test home %s", path, home)+ }+ if _, err := AppendEvent(privateLogTestEvent("first"), Options{UserMode: true}); err != nil {+ t.Fatal(err)+ }+ assertPerm(t, path, 0o600)+ assertPerm(t, path+".lock", 0o600)+ for _, dir := range []string{+ filepath.Join(home, ".beacon"),+ filepath.Join(home, ".beacon", "endpoint"),+ filepath.Join(home, ".beacon", "endpoint", "logs"),+ } {+ assertPerm(t, dir, 0o700)+ }+}++// A log an older release created world-writable is tightened the next time it is written. The+// writer owns it, so the chmod cannot fail for want of permission.+func TestExistingWorldWritableUserLogIsTightened(t *testing.T) {+ testenv.RequirePOSIXFileModes(t)+ home := t.TempDir()+ testenv.SetHome(t, home)+ path := DefaultPath(true)+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatal(err)+ }+ for _, target := range []string{path, path + ".lock"} {+ if err := os.WriteFile(target, nil, 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.Chmod(target, 0o666); err != nil {+ t.Fatal(err)+ }+ }+ if _, err := AppendEvent(privateLogTestEvent("again"), Options{UserMode: true}); err != nil {+ t.Fatal(err)+ }+ assertPerm(t, path, 0o600)+ assertPerm(t, path+".lock", 0o600)++ // EnsureRuntimeFile (doctor --fix, Elastic setup) follows the same rule.+ if err := os.Chmod(path, 0o666); err != nil {+ t.Fatal(err)+ }+ if err := EnsureRuntimeFile(path); err != nil {+ t.Fatal(err)+ }+ assertPerm(t, path, 0o600)+}++// Rotation renames the live file, so a fresh archive inherits its private mode; archives an older+// release rotated world-writable are narrowed on the way.+func TestUserModeRotatedArchivesArePrivate(t *testing.T) {+ testenv.RequirePOSIXFileModes(t)+ home := t.TempDir()+ testenv.SetHome(t, home)+ path := DefaultPath(true)+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path+".1", []byte("{}\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.Chmod(path+".1", 0o666); err != nil {+ t.Fatal(err)+ }+ opts := Options{UserMode: true, RotateSize: 256}+ for i := 0; i < 3; i++ {+ if _, err := AppendEvent(privateLogTestEvent(strings.Repeat("x", 100)+string(rune('a'+i))), opts); err != nil {+ t.Fatal(err)+ }+ }+ if _, err := os.Stat(path + ".2"); err != nil {+ t.Fatalf("expected the log to rotate at least twice: %v", err)+ }+ for _, target := range []string{path, path + ".1", path + ".2"} {+ assertPerm(t, target, 0o600)+ }+}++// System mode is unchanged: the shared log stays world-writable so hooks running as each logged-in+// user can append to the log a root collector created.+func TestSharedLogKeepsTheSharedMode(t *testing.T) {+ testenv.RequirePOSIXFileModes(t)+ testenv.SetHome(t, t.TempDir())+ path := filepath.Join(t.TempDir(), "beacon-agent", "runtime.jsonl")+ if _, err := AppendEvent(privateLogTestEvent("shared"), Options{Path: path, UserMode: false}); err != nil {+ t.Fatal(err)+ }+ assertPerm(t, path, 0o666)+ assertPerm(t, path+".lock", 0o666)+}diff --git a/cli/beacon/internal/endpoint/writer/writer.go b/cli/beacon/internal/endpoint/writer/writer.goindex 48980656..19473eec 100644--- a/cli/beacon/internal/endpoint/writer/writer.go+++ b/cli/beacon/internal/endpoint/writer/writer.go@@ -21,7 +21,9 @@ const (DefaultRotateBytes = 10 * 1024 * 1024DefaultRotateArchives = 5RotateBytes = DefaultRotateBytes- runtimeFileMode = 0666+ // runtimeFileMode is the shared (system-mode) log's mode. A log inside the current user's home+ // is private instead; asymptoteobserve.RuntimeLogModes decides, identically in all three writers.+ runtimeFileMode = asymptoteobserve.SharedRuntimeLogFileMode)type Options struct {@@ -157,11 +159,13 @@ func SystemLogWritableByUsers(dir string) (bool, error) {return interactiveUsersCanWrite(dir)}-// EnsureRuntimeFile creates the shared runtime log with the shared writable-// mode without appending an event, for doctor --fix and setup flows that-// pre-create the log so user-run hooks can append to it later.+// EnsureRuntimeFile creates the runtime log without appending an event, for doctor --fix and setup+// flows that pre-create the log so hooks can append to it later. The shared system log gets the+// shared writable mode; a log in the current user's home is private (see+// asymptoteobserve.RuntimeLogModes).func EnsureRuntimeFile(path string) error {- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ _, dirMode, _ := asymptoteobserve.RuntimeLogModes(path)+ if err := os.MkdirAll(filepath.Dir(path), dirMode); err != nil {return err}f, err := openRuntimeFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY)@@ -193,11 +197,13 @@ func SanitizeEvent(event schema.Event, maxBytes int) schema.Event {return asymptoteobserve.SanitizeEvent(event, maxBytes)}+// Keep this rotation and file-mode contract mirrored with the hook adapter and beaconjson exporter.func appendJSONL(path string, line []byte, rotateBytes int64, rotateArchives int, guard *RetentionGuard) error {- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ _, dirMode, _ := asymptoteobserve.RuntimeLogModes(path)+ if err := os.MkdirAll(filepath.Dir(path), dirMode); err != nil {return err}- lock, err := openRuntimeFile(path+".lock", os.O_CREATE|os.O_RDWR)+ lock, err := openRuntimeFileAs(path+".lock", path, os.O_CREATE|os.O_RDWR)if err != nil {return err}@@ -251,6 +257,15 @@ func appendJSONL(path string, line []byte, rotateBytes int64, rotateArchives int}func openRuntimeFile(path string, flag int) (*os.File, error) {+ return openRuntimeFileAs(path, path, flag)+}++// openRuntimeFileAs opens path (the log or its lock) with the mode logPath calls for. The chmod+// runs on an existing file too: it repairs a umask-narrowed shared log, and it tightens a private+// log left world-writable by an older release (same owner, so it succeeds). A failed chmod on an+// existing file is ignored -- a hook appending to a shared log it does not own cannot chmod it.+func openRuntimeFileAs(path, logPath string, flag int) (*os.File, error) {+ fileMode, _, _ := asymptoteobserve.RuntimeLogModes(logPath)existed := trueif _, err := os.Stat(path); err != nil {if !os.IsNotExist(err) {@@ -258,11 +273,11 @@ func openRuntimeFile(path string, flag int) (*os.File, error) {}existed = false}- f, err := os.OpenFile(path, flag, runtimeFileMode)+ f, err := os.OpenFile(path, flag, fileMode)if err != nil {return nil, err}- if err := os.Chmod(path, runtimeFileMode); err != nil && !existed {+ if err := os.Chmod(path, fileMode); err != nil && !existed {_ = f.Close()return nil, err}@@ -300,7 +315,11 @@ func rotateIfNeeded(path string, maxSize int64, archives int, nextWriteBytes int}}rotated := path + ".1"- return os.Rename(path, rotated)+ if err := os.Rename(path, rotated); err != nil {+ return err+ }+ asymptoteobserve.TightenPrivateRuntimeLogArchives(path, archives)+ return nil}// needsRotation reports whether appending nextWriteBytes to path would take it past maxSize, whichdiff --git a/collector-builder/exporter/beaconjsonexporter/private_log_unix_test.go b/collector-builder/exporter/beaconjsonexporter/private_log_unix_test.gonew file mode 100644index 00000000..c16d253e--- /dev/null+++ b/collector-builder/exporter/beaconjsonexporter/private_log_unix_test.go@@ -0,0 +1,87 @@+//go:build !windows++package beaconjsonexporter++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func setExporterTestHome(t *testing.T) string {+ t.Helper()+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)+ return home+}++func assertExporterPerm(t *testing.T, path string, want os.FileMode) {+ t.Helper()+ info, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat %s: %v", path, err)+ }+ if got := info.Mode().Perm(); got != want {+ t.Fatalf("%s mode = %o, want %o", path, got, want)+ }+}++// A user-mode collector runs as its user and writes ~/.beacon/endpoint/logs/runtime.jsonl, which+// holds that user's prompts and command output. It creates the log, lock and directories private.+func TestUserModeExporterLogIsPrivate(t *testing.T) {+ home := setExporterTestHome(t)+ path := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")+ w := jsonlWriter{path: path, maxEventBytes: defaultMaxEventBytes, rotateBytes: defaultRotateBytes, rotateArchives: defaultRotateArchives}+ if err := w.append(beaconEvent{Message: "test"}); err != nil {+ t.Fatal(err)+ }+ assertExporterPerm(t, path, 0o600)+ assertExporterPerm(t, path+".lock", 0o600)+ for _, dir := range []string{+ filepath.Join(home, ".beacon"),+ filepath.Join(home, ".beacon", "endpoint"),+ filepath.Join(home, ".beacon", "endpoint", "logs"),+ } {+ assertExporterPerm(t, dir, 0o700)+ }+}++// An existing world-writable user log is tightened, and rotation keeps archives private.+func TestUserModeExporterLogIsTightenedAndRotatesPrivately(t *testing.T) {+ home := setExporterTestHome(t)+ path := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatal(err)+ }+ for _, target := range []string{path, path + ".lock", path + ".1"} {+ if err := os.WriteFile(target, []byte("{}\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.Chmod(target, 0o666); err != nil {+ t.Fatal(err)+ }+ }+ line := []byte(`{"message":"` + strings.Repeat("x", 64) + `"}` + "\n")+ if err := appendJSONL(path, line, 32, defaultRotateArchives); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(path + ".2"); err != nil {+ t.Fatalf("expected the log to rotate: %v", err)+ }+ for _, target := range []string{path, path + ".lock", path + ".1", path + ".2"} {+ assertExporterPerm(t, target, 0o600)+ }+}++// System mode is unchanged: a log outside the collector's home keeps the shared mode.+func TestSharedExporterLogKeepsTheSharedMode(t *testing.T) {+ setExporterTestHome(t)+ path := filepath.Join(t.TempDir(), "beacon-agent", "runtime.jsonl")+ if err := appendJSONL(path, []byte(`{"message":"test"}`+"\n"), defaultRotateBytes, defaultRotateArchives); err != nil {+ t.Fatal(err)+ }+ assertExporterPerm(t, path, 0o666)+ assertExporterPerm(t, path+".lock", 0o666)+}diff --git a/collector-builder/exporter/beaconjsonexporter/writer.go b/collector-builder/exporter/beaconjsonexporter/writer.goindex cd78f1fa..676b6c51 100644--- a/collector-builder/exporter/beaconjsonexporter/writer.go+++ b/collector-builder/exporter/beaconjsonexporter/writer.go@@ -65,7 +65,8 @@ func (w jsonlWriter) append(event beaconEvent) error {data = stamped}}- if err := os.MkdirAll(filepath.Dir(w.path), 0755); err != nil {+ _, dirMode, _ := asymptoteobserve.RuntimeLogModes(w.path)+ if err := os.MkdirAll(filepath.Dir(w.path), dirMode); err != nil {return err}return appendJSONL(w.path, append(data, '\n'), w.rotateBytes, w.rotateArchives)@@ -199,17 +200,21 @@ func sanitizeTyped[T any](input *T, sanitize func(map[string]interface{}) map[streturn &out}-// The collector usually runs as root, while agent hooks append to the same-// runtime log as the console user, so shared runtime files must stay-// writable by both regardless of which process creates them first.-const runtimeFileMode = 0666+// In system mode the collector runs as root, while agent hooks append to the+// same runtime log as the console user, so the shared runtime files must stay+// writable by both regardless of which process creates them first. A user-mode+// collector writes a log inside its user's home, which is private (0600 in a+// 0700 directory): asymptoteobserve.RuntimeLogModes decides from the path,+// identically in all three writers.+const runtimeFileMode = asymptoteobserve.SharedRuntimeLogFileMode-// Keep this rotation contract mirrored with the endpoint CLI and hook writer.+// Keep this rotation and file-mode contract mirrored with the endpoint CLI and hook writer.func appendJSONL(path string, line []byte, rotateBytes int64, rotateArchives int) error {- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ _, dirMode, _ := asymptoteobserve.RuntimeLogModes(path)+ if err := os.MkdirAll(filepath.Dir(path), dirMode); err != nil {return err}- lock, err := openRuntimeFile(path+".lock", os.O_CREATE|os.O_RDWR)+ lock, err := openRuntimeFileAs(path+".lock", path, os.O_CREATE|os.O_RDWR)if err != nil {return err}@@ -237,6 +242,13 @@ func appendJSONL(path string, line []byte, rotateBytes int64, rotateArchives int}func openRuntimeFile(path string, flag int) (*os.File, error) {+ return openRuntimeFileAs(path, path, flag)+}++// openRuntimeFileAs opens path (the log or its lock) with the mode logPath calls for. The chmod+// runs on an existing file too, which tightens a private log an older release left world-writable.+func openRuntimeFileAs(path, logPath string, flag int) (*os.File, error) {+ fileMode, _, _ := asymptoteobserve.RuntimeLogModes(logPath)existed := trueif _, err := os.Stat(path); err != nil {if !os.IsNotExist(err) {@@ -244,11 +256,11 @@ func openRuntimeFile(path string, flag int) (*os.File, error) {}existed = false}- f, err := os.OpenFile(path, flag, runtimeFileMode)+ f, err := os.OpenFile(path, flag, fileMode)if err != nil {return nil, err}- if err := os.Chmod(path, runtimeFileMode); err != nil && !existed {+ if err := os.Chmod(path, fileMode); err != nil && !existed {_ = f.Close()return nil, err}@@ -282,7 +294,11 @@ func rotateIfNeeded(path string, maxSize int64, archives int, nextWriteBytes intreturn err}}- return os.Rename(path, path+".1")+ if err := os.Rename(path, path+".1"); err != nil {+ return err+ }+ asymptoteobserve.TightenPrivateRuntimeLogArchives(path, archives)+ return nil}func removeOverflowArchives(path string, archives int) error {diff --git a/pkg/asymptoteobserve/runtimelogmode.go b/pkg/asymptoteobserve/runtimelogmode.gonew file mode 100644index 00000000..63e5690b--- /dev/null+++ b/pkg/asymptoteobserve/runtimelogmode.go@@ -0,0 +1,132 @@+package asymptoteobserve++import (+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "strings"+)++// File and directory modes for the endpoint runtime log, its lock file and its rotated archives.+//+// The three writers of that log -- the beacon CLI, the beacon-hooks adapter and the beaconjson+// collector exporter -- all take their modes from RuntimeLogModes so they cannot disagree. A writer+// that chose differently would undo the others: each one chmods the file it opens, so a hook that+// still believed in 0666 would re-widen a log the CLI had just made private.+const (+ // SharedRuntimeLogFileMode is the machine-wide (system-mode) log's mode. It is deliberately+ // world-writable: the collector runs elevated and creates it, while hooks running as each+ // logged-in user append to it. Narrowing it needs a design change (a group, or hooks sending+ // through the collector) rather than a mode change.+ SharedRuntimeLogFileMode os.FileMode = 0o666+ // SharedRuntimeLogDirMode keeps the shared log reachable by those hooks.+ SharedRuntimeLogDirMode os.FileMode = 0o755+ // PrivateRuntimeLogFileMode is a per-user (user-mode) log's mode. Everything that writes it --+ // the user's own hooks, plugins, CLI and user-level collector -- runs as that user, and the log+ // holds their prompts, command output and diffs, so nobody else has a reason to read or write it.+ PrivateRuntimeLogFileMode os.FileMode = 0o600+ // PrivateRuntimeLogDirMode is the mode of the log directories a writer creates for a per-user log.+ PrivateRuntimeLogDirMode os.FileMode = 0o700+)++// unixSystemLogDir is the system-mode log directory on Linux and macOS. It is never private,+// whatever the process's home directory claims, so a service account whose HOME happens to sit+// above it cannot narrow the shared log out from under every other user's hooks.+const unixSystemLogDir = "/var/log/beacon-agent"++// RuntimeLogModes returns the file and directory modes a writer uses for the runtime log at path,+// and whether that log is private to the current user.+//+// The writers cannot all be told which mode the endpoint is in -- a hook only receives a log path --+// so the decision is made from the path, the same way everywhere: a log inside the current user's+// home directory is that user's own log and is private; anything else (the system log under+// /var/log/beacon-agent or %ProgramData%, or a custom path elsewhere) keeps the shared mode it has+// always had.+//+// One exception keeps root from breaking a user's log: when running as root on Unix inside a home+// directory root does not own (sudo preserving HOME), the log keeps the shared mode, because a+// private root-owned file there is one the user's own hooks could never append to again.+func RuntimeLogModes(path string) (file, dir os.FileMode, private bool) {+ if RuntimeLogIsPrivate(path) {+ return PrivateRuntimeLogFileMode, PrivateRuntimeLogDirMode, true+ }+ return SharedRuntimeLogFileMode, SharedRuntimeLogDirMode, false+}++// RuntimeLogIsPrivate reports whether the runtime log at path is the current user's own log. See+// RuntimeLogModes.+func RuntimeLogIsPrivate(path string) bool {+ if strings.TrimSpace(path) == "" {+ return false+ }+ abs, err := filepath.Abs(path)+ if err != nil {+ return false+ }+ if runtime.GOOS != "windows" && pathWithin(abs, unixSystemLogDir) {+ return false+ }+ home, err := os.UserHomeDir()+ if err != nil || strings.TrimSpace(home) == "" {+ return false+ }+ home, err = filepath.Abs(home)+ if err != nil || isFilesystemRoot(home) {+ return false+ }+ within := pathWithin(abs, home)+ if !within {+ // Compare resolved forms too, so a log reached through a symlinked home (macOS /var ->+ // /private/var, or a home on another volume) is still recognized as the user's own.+ resolvedHome, homeErr := filepath.EvalSymlinks(home)+ resolvedDir, dirErr := filepath.EvalSymlinks(filepath.Dir(abs))+ if homeErr == nil && dirErr == nil && !isFilesystemRoot(resolvedHome) {+ within = pathWithin(filepath.Join(resolvedDir, filepath.Base(abs)), resolvedHome)+ }+ }+ if !within {+ return false+ }+ return processOwnsHome(home)+}++// TightenPrivateRuntimeLogArchives narrows the rotated archives of a private log (path.1 ..+// path.archives) to PrivateRuntimeLogFileMode. Archives rotated before logs were private still+// carry the old shared mode, and they hold the same content as the live file. Best effort: a+// missing archive or a failed chmod is not an error, since the append it runs beside must not fail+// over an older file.+func TightenPrivateRuntimeLogArchives(path string, archives int) {+ if !RuntimeLogIsPrivate(path) {+ return+ }+ for i := 1; i <= archives; i++ {+ archive := fmt.Sprintf("%s.%d", path, i)+ info, err := os.Lstat(archive)+ if err != nil || !info.Mode().IsRegular() {+ continue+ }+ if info.Mode().Perm() != PrivateRuntimeLogFileMode {+ _ = os.Chmod(archive, PrivateRuntimeLogFileMode)+ }+ }+}++func pathWithin(path, dir string) bool {+ path = filepath.Clean(path)+ dir = filepath.Clean(dir)+ if runtime.GOOS == "windows" {+ path = strings.ToLower(path)+ dir = strings.ToLower(dir)+ }+ rel, err := filepath.Rel(dir, path)+ if err != nil || rel == "." {+ return false+ }+ return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel)+}++func isFilesystemRoot(path string) bool {+ clean := filepath.Clean(path)+ return clean == filepath.Dir(clean)+}diff --git a/pkg/asymptoteobserve/runtimelogmode_other.go b/pkg/asymptoteobserve/runtimelogmode_other.gonew file mode 100644index 00000000..ee2468d6--- /dev/null+++ b/pkg/asymptoteobserve/runtimelogmode_other.go@@ -0,0 +1,7 @@+//go:build !unix++package asymptoteobserve++// processOwnsHome is always true off Unix: file modes there do not decide who can append (Windows+// uses the profile's ACL), so the root-in-another-home hazard does not arise.+func processOwnsHome(string) bool { return true }diff --git a/pkg/asymptoteobserve/runtimelogmode_test.go b/pkg/asymptoteobserve/runtimelogmode_test.gonew file mode 100644index 00000000..d6793976--- /dev/null+++ b/pkg/asymptoteobserve/runtimelogmode_test.go@@ -0,0 +1,101 @@+package asymptoteobserve++import (+ "os"+ "path/filepath"+ "runtime"+ "testing"+)++func setTestHome(t *testing.T, dir string) {+ t.Helper()+ t.Setenv("HOME", dir)+ t.Setenv("USERPROFILE", dir)+}++// A user-mode log lives in its user's home and is written only by processes running as that user,+// so it is private. Every other path keeps the shared mode the system log needs.+func TestRuntimeLogModesFollowTheHomeDirectory(t *testing.T) {+ home := t.TempDir()+ setTestHome(t, home)+ userLog := filepath.Join(home, ".beacon", "endpoint", "logs", "runtime.jsonl")++ file, dir, private := RuntimeLogModes(userLog)+ if !private || file != PrivateRuntimeLogFileMode || dir != PrivateRuntimeLogDirMode {+ t.Fatalf("user log modes = %o, %o, private=%v; want %o, %o, true",+ file, dir, private, PrivateRuntimeLogFileMode, PrivateRuntimeLogDirMode)+ }++ elsewhere := filepath.Join(t.TempDir(), "runtime.jsonl")+ file, dir, private = RuntimeLogModes(elsewhere)+ if private || file != SharedRuntimeLogFileMode || dir != SharedRuntimeLogDirMode {+ t.Fatalf("log outside home modes = %o, %o, private=%v; want the shared modes", file, dir, private)+ }++ if RuntimeLogIsPrivate("") {+ t.Fatal("an empty path must not be private")+ }+ if RuntimeLogIsPrivate(home) {+ t.Fatal("the home directory itself is not a log inside it")+ }+ // A sibling whose name merely starts with the home path is not inside it.+ if RuntimeLogIsPrivate(home + "-other/runtime.jsonl") {+ t.Fatal("a sibling directory sharing the home prefix was treated as inside home")+ }+}++// The system log is shared even for a process whose HOME sits above it -- a service account with+// HOME=/ or HOME=/var must not narrow the log every user's hooks append to.+func TestSystemLogIsNeverPrivate(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("the Unix system log directory does not exist on Windows")+ }+ for _, home := range []string{"/", "/var", "/var/log"} {+ setTestHome(t, home)+ if RuntimeLogIsPrivate("/var/log/beacon-agent/runtime.jsonl") {+ t.Fatalf("with HOME=%s the system log was treated as private", home)+ }+ }+}++func TestTightenPrivateRuntimeLogArchives(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("Unix permission bits do not exist on Windows")+ }+ home := t.TempDir()+ setTestHome(t, home)+ path := filepath.Join(home, "runtime.jsonl")+ writeWorldWritable := func(name string) {+ t.Helper()+ if err := os.WriteFile(name, []byte("{}\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.Chmod(name, 0o666); err != nil {+ t.Fatal(err)+ }+ }+ writeWorldWritable(path + ".1")+ writeWorldWritable(path + ".2")+ TightenPrivateRuntimeLogArchives(path, 5)+ for _, archive := range []string{path + ".1", path + ".2"} {+ info, err := os.Stat(archive)+ if err != nil {+ t.Fatal(err)+ }+ if got := info.Mode().Perm(); got != PrivateRuntimeLogFileMode {+ t.Fatalf("%s mode = %o, want %o", archive, got, PrivateRuntimeLogFileMode)+ }+ }++ // A shared log's archives are left alone.+ shared := filepath.Join(t.TempDir(), "runtime.jsonl")+ writeWorldWritable(shared + ".1")+ TightenPrivateRuntimeLogArchives(shared, 5)+ info, err := os.Stat(shared + ".1")+ if err != nil {+ t.Fatal(err)+ }+ if got := info.Mode().Perm(); got != SharedRuntimeLogFileMode {+ t.Fatalf("a shared archive was changed to %o", got)+ }+}diff --git a/pkg/asymptoteobserve/runtimelogmode_unix.go b/pkg/asymptoteobserve/runtimelogmode_unix.gonew file mode 100644index 00000000..89b1c14b--- /dev/null+++ b/pkg/asymptoteobserve/runtimelogmode_unix.go@@ -0,0 +1,26 @@+//go:build unix++package asymptoteobserve++import (+ "os"+ "syscall"+)++// processOwnsHome reports whether a private log may be created in home by this process. Only root+// needs the check: root creating a 0600 file in a home it does not own (sudo preserving HOME) would+// leave the owner's hooks unable to append, so that case keeps the shared mode.+func processOwnsHome(home string) bool {+ if os.Geteuid() != 0 {+ return true+ }+ info, err := os.Stat(home)+ if err != nil {+ return false+ }+ stat, ok := info.Sys().(*syscall.Stat_t)+ if !ok {+ return false+ }+ return stat.Uid == 0+}