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(windows): repair four install-path defects review found
shukieshah05d1972036a7
diff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics.goindex 92692573..52d58307 100644--- a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics.go@@ -39,7 +39,7 @@ func Run(cfg endpointconfig.Config) []Check {checkFile("config", endpointconfig.ConfigPath(cfg.UserMode), true),checkFile("collector_config", cfg.Collector.ConfigPath, true),checkFile("runtime_log", cfg.LogPath, false),- checkLogPermissions(cfg.LogPath),+ checkLogPermissions(cfg.LogPath, cfg.UserMode),checkCollectorHealth(cfg),}// The service definition check is named after whichever manager is actually in use, so@@ -118,12 +118,18 @@ func checkFile(name, path string, required bool) Check {return Check{Name: name, Target: path, Status: StatusOK, Severity: SeverityInfo, Message: path, Evidence: "file_exists"}}-func checkLogPermissions(path string) Check {+func checkLogPermissions(path string, userMode bool) Check {info, err := os.Stat(path)if err != nil {return Check{Name: "runtime_log_permissions", Target: path, Status: StatusWarn, Severity: SeverityLow, Message: "runtime log not created yet", Evidence: "runtime_log_missing"}}if runtime.GOOS == "windows" {+ // The two scopes fail differently there, so they are asked different questions. Only a+ // system-mode install has a privileged writer and unprivileged hooks; a user-mode log lives+ // in that user's own profile and is written by processes running as them.+ if userMode {+ return checkLogWritableByThisUser(path)+ }return checkLogACL(path)}mode := info.Mode().Perm()@@ -136,8 +142,33 @@ func checkLogPermissions(path string) Check {return Check{Name: "runtime_log_permissions", Target: path, Status: StatusOK, Severity: SeverityInfo, Message: fmt.Sprintf("mode %o", mode), Evidence: fmt.Sprintf("mode_%o", mode)}}-// checkLogACL is the Windows form of the same question: can the people whose sessions this-// endpoint captures write to its log?+// checkLogWritableByThisUser is the user-mode Windows form of the question.+//+// The INTERACTIVE grant that system mode installs is deliberately absent here: a user-mode log+// holds that person's prompt text, and widening its ACL to every interactive account would hand it+// to anyone else who logs on. Running the system-mode check anyway would report a high-severity+// failure on every correctly configured user-mode endpoint -- a doctor that cries wolf on the+// normal case is one nobody reads when it finally has something to say.+//+// A test write is the right instrument in this scope, and only in this scope. The trap it falls+// into in system mode -- doctor runs elevated, so it proves access for a user whose access was+// never in question -- does not apply when the hooks run as the same person doctor does.+func checkLogWritableByThisUser(path string) Check {+ f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0)+ if err != nil {+ return Check{Name: "runtime_log_permissions", Target: path, Status: StatusFail,+ Severity: SeverityHigh,+ Message: "the runtime log is not writable by this user: " + err.Error(),+ Evidence: "not_writable"}+ }+ _ = f.Close()+ return Check{Name: "runtime_log_permissions", Target: path, Status: StatusOK,+ Severity: SeverityInfo, Message: "the runtime log is writable by this user",+ Evidence: "writable_by_owner"}+}++// checkLogACL is the system-mode Windows form of the same question: can the people whose sessions+// this endpoint captures write to its log?//// The mode-bit check above cannot answer it there. Windows reports 0666 for any ordinary file// regardless of its ACL, so `mode&0222 == 0` is never true and the check would report OK fordiff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.goindex d31d8467..245c6642 100644--- a/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics_test.go@@ -7,6 +7,7 @@ import (endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv")func TestCheckFileRequiredOptionalAndDirectory(t *testing.T) {@@ -33,38 +34,41 @@ func TestCheckFileRequiredOptionalAndDirectory(t *testing.T) {}func TestCheckLogPermissions(t *testing.T) {+ // Mode bits are the POSIX form of this question; Windows answers it through the ACL and the+ // per-user write test instead, both of which need a real Windows host to exercise.+ testenv.RequirePOSIXFileModes(t)dir := t.TempDir()logPath := filepath.Join(dir, "runtime.jsonl")- if check := checkLogPermissions(logPath); check.Status != "warn" || check.Severity != "low" {+ if check := checkLogPermissions(logPath, false); check.Status != "warn" || check.Severity != "low" {t.Fatalf("missing log permissions check = %#v", check)}if err := os.WriteFile(logPath, []byte("{}\n"), 0644); err != nil {t.Fatalf("write log: %v", err)}- if check := checkLogPermissions(logPath); check.Status != "ok" {+ if check := checkLogPermissions(logPath, false); check.Status != "ok" {t.Fatalf("0644 log permissions check = %#v", check)}if err := os.Chmod(logPath, 0666); err != nil {t.Fatalf("chmod writable log: %v", err)}- if check := checkLogPermissions(logPath); check.Status != "ok" {+ if check := checkLogPermissions(logPath, false); check.Status != "ok" {t.Fatalf("0666 log permissions check = %#v", check)}if err := os.Chmod(logPath, 0200); err != nil {t.Fatalf("chmod unreadable log: %v", err)}- if check := checkLogPermissions(logPath); check.Status != "warn" || check.Severity != "low" {+ if check := checkLogPermissions(logPath, false); check.Status != "warn" || check.Severity != "low" {t.Fatalf("0200 log permissions check = %#v", check)}if err := os.Chmod(logPath, 0444); err != nil {t.Fatalf("chmod non-writable log: %v", err)}- if check := checkLogPermissions(logPath); check.Status != "fail" || check.Severity != "high" || check.Evidence != "not_writable" {+ if check := checkLogPermissions(logPath, false); check.Status != "fail" || check.Severity != "high" || check.Evidence != "not_writable" {t.Fatalf("0444 log permissions check = %#v", check)}}diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.goindex 43fe5311..a3bc6864 100644--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go@@ -294,7 +294,7 @@ func Uninstall(opts UninstallOptions) error {// 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.Kind{service.KindLaunchd, service.KindSystemd, service.KindSupervised} {+ for _, kind := range service.ManagedKinds() {_ = (service.Manager{UserMode: cfg.UserMode, Kind: kind}).Unload()}if !cfg.UserMode && !opts.KeepUpdater {diff --git a/cli/beacon/internal/endpoint/service/kinds_test.go b/cli/beacon/internal/endpoint/service/kinds_test.gonew file mode 100644index 00000000..3a7e1b1d--- /dev/null+++ b/cli/beacon/internal/endpoint/service/kinds_test.go@@ -0,0 +1,57 @@+package service++import "testing"++// TestManagedKindsCoversEveryBackend is the guard on a failure that reports success.+//+// Uninstall unloads every kind in ManagedKinds. A backend that exists but is missing from the list+// is not unloaded, so uninstall prints that it removed the endpoint while the service is still+// registered and still starts at boot -- and there is nothing in the output to suggest otherwise.+// The Windows service backend shipped that way until review caught it.+//+// Every spelling ParseKind accepts must resolve to a kind on the list, so adding a backend without+// adding it here fails rather than silently leaking.+func TestManagedKindsCoversEveryBackend(t *testing.T) {+ managed := make(map[Kind]bool, len(ManagedKinds()))+ for _, kind := range ManagedKinds() {+ if managed[kind] {+ t.Fatalf("ManagedKinds lists %q twice", kind)+ }+ managed[kind] = true+ }++ // Every accepted spelling, canonical and alias. KindAuto is excluded deliberately: it is a+ // request to detect, not a backend, and Manager resolves it to one of these before unloading.+ spellings := []string{+ "launchd",+ "systemd",+ "none", "supervised",+ "windows-service", "scm", "windows",+ }+ for _, spelling := range spellings {+ kind, err := ParseKind(spelling)+ if err != nil {+ t.Fatalf("ParseKind(%q): %v", spelling, err)+ }+ if !managed[kind] {+ t.Fatalf("ParseKind(%q) = %q, which ManagedKinds does not list; "++ "an endpoint installed under it would survive uninstall", spelling, kind)+ }+ }++ // Each listed kind must resolve to a backend that agrees it is that kind. A typo in the list+ // would otherwise unload nothing and still look right.+ for _, kind := range ManagedKinds() {+ for _, userMode := range []bool{false, true} {+ got := (Manager{UserMode: userMode, Kind: kind}).backend()+ if got == nil {+ t.Fatalf("kind %q (userMode=%v) resolves to no backend", kind, userMode)+ }+ // Windows user mode intentionally routes to supervised: there is no per-user service+ // manager to route it to. Every other pairing must round-trip.+ if got.kind() != kind && !(kind == KindWindowsService && userMode) {+ t.Fatalf("kind %q (userMode=%v) resolves to backend %q", kind, userMode, got.kind())+ }+ }+ }+}diff --git a/cli/beacon/internal/endpoint/service/service.go b/cli/beacon/internal/endpoint/service/service.goindex 9e4ae4f6..7674b668 100644--- a/cli/beacon/internal/endpoint/service/service.go+++ b/cli/beacon/internal/endpoint/service/service.go@@ -58,6 +58,18 @@ const (KindWindowsService Kind = "windows-service")+// ManagedKinds is every concrete backend a Beacon install could be running under.+//+// Uninstall and repair unload all of them rather than only the one detection picks right now, so an+// endpoint installed under one manager and removed under another leaves nothing registered. The+// list lives here, beside the kinds themselves, because the bug it prevents is silent at the call+// site: a backend added without being added to the caller's own list leaves a service running after+// an uninstall that reported success, and nothing surfaces it until the machine is rebooted and the+// collector comes back from the dead.+func ManagedKinds() []Kind {+ return []Kind{KindLaunchd, KindSystemd, KindSupervised, KindWindowsService}+}+// ParseKind validates a user-supplied service kind.func ParseKind(s string) (Kind, error) {switch Kind(strings.ToLower(strings.TrimSpace(s))) {diff --git a/cli/beacon/internal/endpoint/service/windows_scm.go b/cli/beacon/internal/endpoint/service/windows_scm.goindex 710e6e33..3db0d580 100644--- a/cli/beacon/internal/endpoint/service/windows_scm.go+++ b/cli/beacon/internal/endpoint/service/windows_scm.go@@ -107,8 +107,20 @@ func setRecoveryActions(s *mgr.Service) error {// CreateService takes the executable and its arguments separately and quotes them itself, but// UpdateConfig takes one string, so the quoting is ours to get right. An unquoted path breaks at// the first space -- and the default install location is under %ProgramFiles%, which contains one.+//+// Escaped exactly the way CreateService escapes, by calling the same function it calls. Go's %q is+// the wrong tool and fails in a way that only shows up on the upgrade path: it doubles every+// backslash, so `C:\Program Files\Beacon\bin\beacon-otelcol.exe` is written to the registry as+// `C:\\Program Files\\...`, which the SCM does not unescape. A fresh install would work, the+// upgrade would report success, and the service would fail to start after the next reboot with a+// file-not-found the operator has no reason to connect to an upgrade. Sharing the escaper also+// means create and update cannot drift apart.func serviceBinaryPath(program, configPath string) string {- return fmt.Sprintf("%q --config %q", program, configPath)+ parts := make([]string, 0, 3)+ for _, arg := range []string{program, "--config", configPath} {+ parts = append(parts, windows.EscapeArg(arg))+ }+ return strings.Join(parts, " ")}func startService() error {diff --git a/cli/beacon/internal/endpoint/service/windows_scm_test.go b/cli/beacon/internal/endpoint/service/windows_scm_test.gonew file mode 100644index 00000000..456d17a0--- /dev/null+++ b/cli/beacon/internal/endpoint/service/windows_scm_test.go@@ -0,0 +1,51 @@+//go:build windows++package service++import (+ "strings"+ "testing"+)++// TestServiceBinaryPathIsEscapedTheWayTheSCMReadsIt guards the upgrade path.+//+// A fresh install goes through CreateService, which escapes the ImagePath itself. An upgrade goes+// through UpdateConfig, which takes one already-rendered string -- so this is the only place the+// two can disagree, and a disagreement here does not show up until the service is next started,+// long after the upgrade reported success.+//+// The specific mistake this replaced was Go's %q, which escapes for a Go string literal rather than+// for the SCM: every backslash doubled, and the default install path lives under %ProgramFiles%.+func TestServiceBinaryPathIsEscapedTheWayTheSCMReadsIt(t *testing.T) {+ const (+ program = `C:\Program Files\Beacon\bin\beacon-otelcol.exe`+ config = `C:\ProgramData\Beacon\Endpoint\collector.yaml`+ )+ got := serviceBinaryPath(program, config)++ // Quoted because of the space, and left alone because there is not one.+ want := `"` + program + `" --config ` + config+ if got != want {+ t.Fatalf("serviceBinaryPath = %s, want %s", got, want)+ }+ if strings.Contains(got, `\\`) {+ t.Fatalf("serviceBinaryPath doubled a backslash: %s; "++ "the SCM does not unescape those, so the service would fail to start after an upgrade", got)+ }+ // The path has to survive as one argument. Anything that splits it at the space leaves the SCM+ // looking for C:\Program.+ if !strings.HasPrefix(got, `"`+program+`"`) {+ t.Fatalf("serviceBinaryPath left a path containing a space unquoted: %s", got)+ }+}++func TestServiceBinaryPathQuotesOnlyWhenItMustAndAlwaysCarriesTheConfig(t *testing.T) {+ got := serviceBinaryPath(`C:\Beacon\beacon-otelcol.exe`, `C:\Beacon\collector.yaml`)+ if got != `C:\Beacon\beacon-otelcol.exe --config C:\Beacon\collector.yaml` {+ t.Fatalf("serviceBinaryPath = %s", got)+ }+ if !strings.Contains(got, "--config") {+ t.Fatalf("serviceBinaryPath dropped the config flag: %s; "++ "the collector would start with its default configuration and write nowhere Beacon reads", got)+ }+}diff --git a/cli/beacon/internal/endpoint/writer/acl_windows.go b/cli/beacon/internal/endpoint/writer/acl_windows.goindex 78310931..dad2bed7 100644--- a/cli/beacon/internal/endpoint/writer/acl_windows.go+++ b/cli/beacon/internal/endpoint/writer/acl_windows.go@@ -6,6 +6,9 @@ import ("fmt""os/exec""strings"+ "unsafe"++ "golang.org/x/sys/windows")// grantInteractiveUsersWrite makes a machine-wide log directory writable by ordinary users.@@ -32,6 +35,9 @@ func grantInteractiveUsersWrite(dir string) error {// icacls rather than the security APIs directly: it is present on every supported Windows,// its argument form is stable, and the equivalent through SetNamedSecurityInfo means building// an ACL by hand for a grant an administrator can read and audit in one line.+ //+ // The `*` prefix passes the well-known SID literally, so this does not depend on the machine's+ // display language the way a `INTERACTIVE` or `INTERAKTIV` spelling would.cmd := exec.Command("icacls", dir, "/grant", `*S-1-5-4:(OI)(CI)(M)`, "/T")out, err := cmd.CombinedOutput()if err != nil {@@ -41,31 +47,101 @@ func grantInteractiveUsersWrite(dir string) error {return nil}+// Rights that answer the question doctor is actually asking: can a hook running as the logged-on+// user create the runtime log if it is missing, and append to it if it is not.+//+// Both bits are required. FILE_APPEND_DATA alone cannot create the file, and FILE_WRITE_DATA alone+// on a directory does not permit adding entries to it, so a grant carrying only one of them leaves+// a hook that still fails -- just at a different call.+const writeAccessMask = uint32(windows.FILE_WRITE_DATA | windows.FILE_APPEND_DATA)++// inheritOnlyACE marks an entry that applies to children but not to the object carrying it.+// Not exported by x/sys/windows, and needed here because such an entry must not read as a grant:+// the directory itself has to be writable for a hook to create the log in the first place.+const inheritOnlyACE = 0x08++type aceVerdict int++const (+ aceIrrelevant aceVerdict = iota+ aceAllowsWrite+ aceDeniesWrite+)++// classifyACE decides what one access control entry says about interactive write access.+//+// Split out from the DACL walk so it can be tested against entry shapes that are tedious to+// construct on a real directory -- inherit-only grants, deny entries, partial masks.+func classifyACE(aceType, aceFlags uint8, mask uint32, matchesSID bool) aceVerdict {+ if !matchesSID || aceFlags&inheritOnlyACE != 0 {+ return aceIrrelevant+ }+ switch aceType {+ case windows.ACCESS_DENIED_ACE_TYPE:+ // Any overlap denies. A deny of one of the two bits is enough to break a hook, and Windows+ // evaluates a matching deny ahead of any grant, so partial credit would be wrong here.+ if mask&writeAccessMask != 0 {+ return aceDeniesWrite+ }+ case windows.ACCESS_ALLOWED_ACE_TYPE:+ // GENERIC_WRITE is normally mapped to its specific rights when an entry is stored, but it+ // survives in entries written by some tooling, and it subsumes both bits.+ if mask&writeAccessMask == writeAccessMask || mask&windows.GENERIC_WRITE != 0 {+ return aceAllowsWrite+ }+ }+ return aceIrrelevant+}+// interactiveUsersCanWrite reports whether the grant is in place, for doctor.//// Checked by reading the ACL rather than by attempting a write: doctor runs elevated, so a test// write would succeed regardless and report healthy for exactly the configuration that is broken.// That is the trap this check exists to avoid, so it must not fall into it.+//+// Read through the security APIs rather than by parsing `icacls` output. The text form is a+// rendering for humans and varies with the things a rendering varies with: it resolves the SID to a+// localized account name, so a correctly granted directory reads as ungranted on a German or+// Japanese install, and it prints an expanded rights list instead of the short `(M)` alias whenever+// the mask is not exactly one of the aliases. Both produce the same wrong answer -- doctor telling+// an administrator their working endpoint is broken -- and neither is visible from an English test+// machine, which is every machine this would be tested on.func interactiveUsersCanWrite(dir string) (bool, error) {- out, err := exec.Command("icacls", dir).CombinedOutput()+ sd, err := windows.GetNamedSecurityInfo(dir, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION)if err != nil {- return false, fmt.Errorf("read the ACL on %s: %w: %s", dir, err, strings.TrimSpace(string(out)))+ return false, fmt.Errorf("read the access control list on %s: %w", dir, err)+ }+ dacl, _, err := sd.DACL()+ if err != nil {+ return false, fmt.Errorf("read the discretionary access control list on %s: %w", dir, err)+ }+ if dacl == nil {+ // A NULL DACL grants everyone full control. Alarming, and worth surfacing elsewhere, but+ // the question here is only whether hooks can write -- and they can.+ return true, nil}- text := string(out)- // icacls renders the well-known SID as a localized account name, so the SID itself is not- // reliably present in the output. Both spellings are accepted: the localized name varies by- // system language, and matching only the English one would report a correct grant as missing- // on a German or Japanese install.- for _, marker := range []string{"S-1-5-4", "INTERACTIVE"} {- for _, line := range strings.Split(text, "\n") {- if !strings.Contains(strings.ToUpper(line), strings.ToUpper(marker)) {- continue- }- // (M) is modify, (F) is full control; either is enough to append.- if strings.Contains(line, "(M)") || strings.Contains(line, "(F)") || strings.Contains(line, "(W)") {- return true, nil- }++ interactive, err := windows.CreateWellKnownSid(windows.WinInteractiveSid)+ if err != nil {+ return false, fmt.Errorf("resolve the INTERACTIVE security identifier: %w", err)+ }++ allowed := false+ for i := uint32(0); i < uint32(dacl.AceCount); i++ {+ var ace *windows.ACCESS_ALLOWED_ACE+ if err := windows.GetAce(dacl, i, &ace); err != nil {+ return false, fmt.Errorf("read access control entry %d on %s: %w", i, dir, err)+ }+ // Every ACE type this cares about carries its SID at the same offset; the field is named+ // SidStart because the identifier is variable length and runs past the struct.+ sid := (*windows.SID)(unsafe.Pointer(&ace.SidStart))+ switch classifyACE(ace.Header.AceType, ace.Header.AceFlags, uint32(ace.Mask), sid.Equals(interactive)) {+ case aceDeniesWrite:+ // A deny anywhere in the list settles it, whatever else grants.+ return false, nil+ case aceAllowsWrite:+ allowed = true}}- return false, nil+ return allowed, nil}diff --git a/cli/beacon/internal/endpoint/writer/acl_windows_test.go b/cli/beacon/internal/endpoint/writer/acl_windows_test.gonew file mode 100644index 00000000..cf049668--- /dev/null+++ b/cli/beacon/internal/endpoint/writer/acl_windows_test.go@@ -0,0 +1,167 @@+//go:build windows++package writer++import (+ "os/exec"+ "strings"+ "testing"++ "golang.org/x/sys/windows"+)++func TestClassifyACEReadsTheEntryShapesThatDecideAccess(t *testing.T) {+ const (+ writeData = uint32(windows.FILE_WRITE_DATA)+ appendData = uint32(windows.FILE_APPEND_DATA)+ readData = uint32(windows.FILE_READ_DATA)+ )++ cases := []struct {+ name string+ aceType uint8+ aceFlags uint8+ mask uint32+ matchesSID bool+ want aceVerdict+ }{+ {+ name: "the grant install writes",+ aceType: windows.ACCESS_ALLOWED_ACE_TYPE,+ mask: writeData | appendData,+ matchesSID: true,+ want: aceAllowsWrite,+ },+ {+ // The whole reason this is not a substring search for a rendered name.+ name: "another principal's full control says nothing about INTERACTIVE",+ aceType: windows.ACCESS_ALLOWED_ACE_TYPE,+ mask: writeData | appendData,+ matchesSID: false,+ want: aceIrrelevant,+ },+ {+ // A hook that cannot create the log fails as surely as one that cannot append to it,+ // so half the mask is not half a pass.+ name: "append without write cannot create the log",+ aceType: windows.ACCESS_ALLOWED_ACE_TYPE,+ mask: appendData,+ matchesSID: true,+ want: aceIrrelevant,+ },+ {+ name: "write without append cannot extend the log",+ aceType: windows.ACCESS_ALLOWED_ACE_TYPE,+ mask: writeData,+ matchesSID: true,+ want: aceIrrelevant,+ },+ {+ name: "read access is not write access",+ aceType: windows.ACCESS_ALLOWED_ACE_TYPE,+ mask: readData,+ matchesSID: true,+ want: aceIrrelevant,+ },+ {+ name: "generic write subsumes both bits",+ aceType: windows.ACCESS_ALLOWED_ACE_TYPE,+ mask: windows.GENERIC_WRITE,+ matchesSID: true,+ want: aceAllowsWrite,+ },+ {+ // The directory itself must be writable: a hook creates the log when it is missing.+ name: "an inherit-only grant does not make this directory writable",+ aceType: windows.ACCESS_ALLOWED_ACE_TYPE,+ aceFlags: inheritOnlyACE,+ mask: writeData | appendData,+ matchesSID: true,+ want: aceIrrelevant,+ },+ {+ name: "a deny of either bit is a deny",+ aceType: windows.ACCESS_DENIED_ACE_TYPE,+ mask: appendData,+ matchesSID: true,+ want: aceDeniesWrite,+ },+ {+ name: "a deny of unrelated rights is not a deny of write",+ aceType: windows.ACCESS_DENIED_ACE_TYPE,+ mask: readData,+ matchesSID: true,+ want: aceIrrelevant,+ },+ {+ name: "an inherit-only deny does not apply to this directory",+ aceType: windows.ACCESS_DENIED_ACE_TYPE,+ aceFlags: inheritOnlyACE,+ mask: writeData | appendData,+ matchesSID: true,+ want: aceIrrelevant,+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := classifyACE(tc.aceType, tc.aceFlags, tc.mask, tc.matchesSID)+ if got != tc.want {+ t.Fatalf("classifyACE = %v, want %v", got, tc.want)+ }+ })+ }+}++// TestGrantAndReadBackAgree exercises the halves against each other on a real directory.+//+// They are written against different interfaces -- the grant shells out to icacls, the read walks+// the DACL through the security APIs -- so nothing but a test like this catches them drifting+// apart. A reader that silently answered "no" to a directory the granter had just fixed would make+// doctor report a working endpoint as broken, and it would do so only on machines nobody develops+// on.+//+// Every step here needs administrator rights, which the endpoint install already requires and the+// Windows CI runner already has. Skipped rather than failed elsewhere: a contributor running the+// suite unelevated should not see a red suite for a check their shell cannot perform.+func TestGrantAndReadBackAgree(t *testing.T) {+ dir := t.TempDir()++ // Strip inheritance so the starting state is known: administrators only, no INTERACTIVE. This+ // is what makes the negative half real -- without it the answer could be "true" before the+ // grant, and a reader hardcoded to return true would pass.+ if out, err := exec.Command("icacls", dir, "/inheritance:r", "/grant", `*S-1-5-32-544:(OI)(CI)(F)`).CombinedOutput(); err != nil {+ t.Skipf("could not take ownership of the ACL on %s (needs an elevated shell): %v: %s",+ dir, err, strings.TrimSpace(string(out)))+ }++ if writable, err := interactiveUsersCanWrite(dir); err != nil {+ t.Fatalf("read the ACL before granting: %v", err)+ } else if writable {+ t.Fatal("a directory granting only administrators reported interactive users can write; " ++ "the reader cannot distinguish a granted directory from an ungranted one")+ }++ if err := grantInteractiveUsersWrite(dir); err != nil {+ t.Fatalf("grant interactive write access: %v", err)+ }++ if writable, err := interactiveUsersCanWrite(dir); err != nil {+ t.Fatalf("read the ACL after granting: %v", err)+ } else if !writable {+ t.Fatal("the directory the granter just fixed reads as not writable by interactive users; " ++ "doctor would report a healthy endpoint as broken")+ }++ // A deny entry outranks the grant, and doctor must say so: hooks would fail here despite the+ // allow entry still being present.+ if out, err := exec.Command("icacls", dir, "/deny", `*S-1-5-4:(WD)`).CombinedOutput(); err != nil {+ t.Fatalf("add a deny entry: %v: %s", err, strings.TrimSpace(string(out)))+ }+ if writable, err := interactiveUsersCanWrite(dir); err != nil {+ t.Fatalf("read the ACL after denying: %v", err)+ } else if writable {+ t.Fatal("an explicit deny of write access reported as writable; " ++ "the grant was read without the deny that overrides it")+ }+}diff --git a/cli/beacon/internal/endpoint/writer/ensure_test.go b/cli/beacon/internal/endpoint/writer/ensure_test.gonew file mode 100644index 00000000..b572e940--- /dev/null+++ b/cli/beacon/internal/endpoint/writer/ensure_test.go@@ -0,0 +1,47 @@+package writer++import (+ "os"+ "path/filepath"+ "testing"+)++// TestEnsureSystemLogWritableCreatesTheDirectoryItIsAskedAbout covers an ordering bug that took+// down the whole install.+//+// Install calls this before anything has written a log, so on a fresh system-mode install the+// directory does not exist yet. The Windows implementation grants access by path; granting access+// to a path that is not there fails, and the failure came back from Install as "prepare the log+// directory" before the service was ever registered -- so the first install on a clean machine was+// the one case that could not work.+//+// Platform-neutral on purpose. The POSIX grant is a no-op and the Windows one is not, but the+// directory has to exist either way, and keeping that guarantee in the shared function is what+// stops the next platform from reintroducing it.+func TestEnsureSystemLogWritableCreatesTheDirectoryItIsAskedAbout(t *testing.T) {+ // Nested, so this fails if the implementation only creates a leaf under an existing parent.+ dir := filepath.Join(t.TempDir(), "Beacon", "Endpoint", "logs")++ if err := EnsureSystemLogWritable(dir); err != nil {+ t.Fatalf("EnsureSystemLogWritable on a directory that does not exist yet: %v", err)+ }++ info, err := os.Stat(dir)+ if err != nil {+ t.Fatalf("stat the log directory afterwards: %v", err)+ }+ if !info.IsDir() {+ t.Fatalf("%s is not a directory", dir)+ }+}++func TestEnsureSystemLogWritableIsRepeatable(t *testing.T) {+ // Repair and reinstall both call this over a live endpoint, so a second call must not fail on+ // the directory it created the first time.+ dir := filepath.Join(t.TempDir(), "logs")+ for i := 0; i < 2; i++ {+ if err := EnsureSystemLogWritable(dir); err != nil {+ t.Fatalf("EnsureSystemLogWritable call %d: %v", i+1, err)+ }+ }+}diff --git a/cli/beacon/internal/endpoint/writer/writer.go b/cli/beacon/internal/endpoint/writer/writer.goindex 59eb9204..6a762896 100644--- a/cli/beacon/internal/endpoint/writer/writer.go+++ b/cli/beacon/internal/endpoint/writer/writer.go@@ -96,7 +96,15 @@ func AppendEvent(event schema.Event, opts Options) (string, error) {// did: %ProgramData% denies ordinary users write access, hooks run as the console user, and// nothing reports an error because status and doctor both describe the collector rather than the// hooks exporting to it.+//+// Creates the directory first. Install calls this before anything has written a log there, so on a+// fresh system-mode install the directory does not exist yet -- and granting access to a path that+// is not there fails, taking the whole install down before the service is ever registered. Ensure+// means ensure.func EnsureSystemLogWritable(dir string) error {+ if err := os.MkdirAll(dir, 0755); err != nil {+ return fmt.Errorf("create the log directory %s: %w", dir, err)+ }return grantInteractiveUsersWrite(dir)}