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(hooks): recognize the flags form when detecting installed hooks
shukieshah20a8f760cfe8
diff --git a/cli/beacon/internal/endpoint/hooks/command_parse_test.go b/cli/beacon/internal/endpoint/hooks/command_parse_test.gonew file mode 100644index 00000000..05bdd16f--- /dev/null+++ b/cli/beacon/internal/endpoint/hooks/command_parse_test.go@@ -0,0 +1,198 @@+package hooks++import (+ "reflect"+ "testing"+)++// TestCommandFieldsKeepsQuotedPathsWhole is the reason this parser exists.+//+// strings.Fields was enough while every path was POSIX. The default Windows install locations are+// under %ProgramFiles% and a user profile, both of which routinely contain a space, so a quoted path+// splits into fragments and every token comparison after it is made against half a path.+func TestCommandFieldsKeepsQuotedPathsWhole(t *testing.T) {+ cases := []struct {+ name string+ command string+ want []string+ }{+ {+ name: "the Windows form",+ command: `"C:\Program Files\Beacon\hooks\beacon-hooks.exe" pre-tool --platform cursor`,+ want: []string{`C:\Program Files\Beacon\hooks\beacon-hooks.exe`, "pre-tool", "--platform", "cursor"},+ },+ {+ name: "the POSIX form, single quotes and an env prefix",+ command: `BEACON_ENDPOINT_MODE=1 BEACON_ENDPOINT_LOG='/var/log/beacon-agent/runtime.jsonl' '/opt/beacon/hooks/beacon-hooks' --platform cursor`,+ want: []string{+ "BEACON_ENDPOINT_MODE=1",+ "BEACON_ENDPOINT_LOG=/var/log/beacon-agent/runtime.jsonl",+ "/opt/beacon/hooks/beacon-hooks",+ "--platform", "cursor",+ },+ },+ {+ // A dropped empty argument would shift every token after it left by one, which is how a+ // value gets read as a flag name.+ name: "an empty quoted value is still an argument",+ command: `beacon-hooks --platform "" --log x`,+ want: []string{"beacon-hooks", "--platform", "", "--log", "x"},+ },+ {+ name: "runs of whitespace and tabs collapse",+ command: "beacon-hooks\t--platform cursor ",+ want: []string{"beacon-hooks", "--platform", "cursor"},+ },+ {+ // A backslash is a path separator here, not an escape. Treating it as one would corrupt+ // every Windows path this parses.+ name: "backslashes survive",+ command: `C:\beacon\beacon-hooks.exe --log C:\logs\runtime.jsonl`,+ want: []string{`C:\beacon\beacon-hooks.exe`, "--log", `C:\logs\runtime.jsonl`},+ },+ {+ name: "empty",+ command: " ",+ want: nil,+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := commandFields(tc.command); !reflect.DeepEqual(got, tc.want) {+ t.Fatalf("commandFields = %#v, want %#v", got, tc.want)+ }+ })+ }+}++// TestFlagsFormIsRecognizedAsAnEndpointHook covers the regression that motivated this change.+//+// The flags form carries no BEACON_ENDPOINT_MODE=1 prefix and does name a platform, so it fell past+// both branches of isEndpointHookCommand and reported false. Every runtime's repair would have added+// a duplicate hook beside the one Beacon had just written, and uninstall would have left it behind --+// with nothing failing anywhere to say so.+func TestFlagsFormIsRecognizedAsAnEndpointHook(t *testing.T) {+ command := `"C:\Program Files\Beacon\hooks\beacon-hooks.exe" --platform cursor` ++ ` --log "C:\ProgramData\Beacon\Endpoint\logs\runtime.jsonl"` ++ ` --config "C:\ProgramData\Beacon\Endpoint\config.json"`++ if !isEndpointHookCommand(command, "cursor") {+ t.Fatal("the flags form is not recognized as an endpoint hook; repair would duplicate it")+ }+ // Still scoped to its own runtime: matching another platform is the direction that rewrites+ // somebody else's hook.+ if isEndpointHookCommand(command, "vscode") {+ t.Fatal("a cursor hook matched when asked about vscode")+ }+}++func TestEnvPrefixFormIsStillRecognized(t *testing.T) {+ // Already installed on every POSIX machine. A repair rewrites it, but it has to be found first.+ command := `BEACON_ENDPOINT_MODE=1 BEACON_ENDPOINT_LOG='/var/log/beacon-agent/runtime.jsonl' ` ++ `BEACON_ENDPOINT_CONFIG='/etc/beacon/endpoint/config.json' '/opt/beacon/hooks/beacon-hooks' --platform cursor`++ if !isEndpointHookCommand(command, "cursor") {+ t.Fatal("the env-prefix form is no longer recognized; a repair would duplicate every " ++ "already-installed POSIX hook")+ }+ if isEndpointHookCommand(command, "vscode") {+ t.Fatal("a cursor hook matched when asked about vscode")+ }+}++// TestAPlatformNamedWithAnEqualsSignCountsAsNamingOne closes a false positive.+//+// The old check asked whether the command contained "--platform " with a trailing space, which missed+// `--platform=cursor`. A command naming no platform is treated as an any-platform install, so that+// spelling made a hook match when asked about *every* runtime -- and repair rewrites what it matches.+//+// Both halves are asserted, because the fix is only safe if it did not also stop recognizing Beacon's+// own hooks written that way.+func TestAPlatformNamedWithAnEqualsSignCountsAsNamingOne(t *testing.T) {+ // No endpoint settings, so this belongs to whoever wrote it -- and must not be claimed for a+ // runtime it does not name. Before the fix, it was claimed for all of them.+ foreign := `/opt/beacon/hooks/beacon-hooks --platform=grok`+ if isEndpointHookCommand(foreign, "cursor") {+ t.Fatal("--platform=grok was claimed when asked about cursor; repair would rewrite it")+ }++ // With endpoint settings it is Beacon's, and the equals spelling must still resolve to the+ // platform it names.+ own := `/opt/beacon/hooks/beacon-hooks --platform=cursor --log=/var/log/beacon-agent/runtime.jsonl`+ if !isEndpointHookCommand(own, "cursor") {+ t.Fatal("an endpoint hook written with --platform=cursor is not matched for cursor")+ }+ if isEndpointHookCommand(own, "vscode") {+ t.Fatal("--platform=cursor matched when asked about vscode")+ }+}++func TestAPlatformlessBeaconHookStillMatchesAnyRuntime(t *testing.T) {+ // Written before --platform existed. Repair has to keep finding these or it will leave two.+ if !isEndpointHookCommand(`/opt/beacon/hooks/beacon-hooks pre-tool`, "cursor") {+ t.Fatal("a hook naming no platform should match any runtime")+ }+}++func TestCommandHasPlatformReadsQuotedAndSeparatedValues(t *testing.T) {+ cases := []struct {+ command string+ platform string+ want bool+ }{+ {`beacon-hooks --platform cursor`, "cursor", true},+ {`beacon-hooks --platform "cursor"`, "cursor", true},+ {`beacon-hooks --platform=cursor`, "cursor", true},+ {`beacon-hooks --platform cursor`, "vscode", false},+ // The path contains a space and the platform follows it. With whitespace splitting the path+ // becomes two tokens; the flag still has to be found after them.+ {`"C:\Program Files\Beacon\beacon-hooks.exe" --platform vscode`, "vscode", true},+ // Nothing to compare against.+ {`beacon-hooks --platform`, "cursor", false},+ {`beacon-hooks`, "cursor", false},+ }+ for _, tc := range cases {+ if got := commandHasPlatform(tc.command, tc.platform); got != tc.want {+ t.Fatalf("commandHasPlatform(%q, %q) = %v, want %v", tc.command, tc.platform, got, tc.want)+ }+ }+}++// TestABareBeaconHooksInvocationIsNotClaimedAsAnEndpointHook keeps the false-positive direction shut.+//+// Someone may run this binary for a reason Beacon did not configure. Such a command names a platform+// and carries no endpoint settings, so it belongs to whoever wrote it.+func TestABareBeaconHooksInvocationIsNotClaimedAsAnEndpointHook(t *testing.T) {+ if isEndpointHookCommand(`beacon-hooks pre-tool --platform grok`, "cursor") {+ t.Fatal("a hook for another platform with no endpoint settings was claimed")+ }+}++func TestCommandCarriesEndpointSettingsRecognizesBothSpellings(t *testing.T) {+ carries := []string{+ `BEACON_ENDPOINT_MODE=1 beacon-hooks --platform cursor`,+ `beacon-hooks --platform cursor --log /var/log/beacon-agent/runtime.jsonl`,+ `beacon-hooks --platform cursor --config /etc/beacon/endpoint/config.json`,+ `beacon-hooks --platform cursor --cli /opt/beacon/bin/beacon`,+ `beacon-hooks --platform cursor --log=/var/log/beacon-agent/runtime.jsonl`,+ }+ for _, command := range carries {+ if !commandCarriesEndpointSettings(command) {+ t.Fatalf("endpoint settings not detected in %q", command)+ }+ }++ // A path that merely contains the text of a flag is not that flag. This is what token comparison+ // buys over a substring search, and why the quoted path has to stay whole.+ notCarries := []string{+ `beacon-hooks --platform cursor`,+ `"C:\tools\--log\beacon-hooks.exe" --platform cursor`,+ `beacon-hooks --platform cursor --logfile /tmp/x`,+ }+ for _, command := range notCarries {+ if commandCarriesEndpointSettings(command) {+ t.Fatalf("endpoint settings falsely detected in %q", command)+ }+ }+}diff --git a/cli/beacon/internal/endpoint/hooks/runtime.go b/cli/beacon/internal/endpoint/hooks/runtime.goindex 56950199..f892d886 100644--- a/cli/beacon/internal/endpoint/hooks/runtime.go+++ b/cli/beacon/internal/endpoint/hooks/runtime.go@@ -119,33 +119,132 @@ func endpointCommandPrefix(platform, binaryPath, logPath, configPath string) strreturn fmt.Sprintf("BEACON_ENDPOINT_MODE=1 BEACON_ENDPOINT_LOG=%s BEACON_ENDPOINT_CONFIG=%s%s %s --platform %s", shellQuote(logPath), shellQuote(configPath), cliEnv, shellQuote(binaryPath), platform)}+// isEndpointHookCommand decides whether a command already in a runtime's config is one Beacon wrote.+//+// This is the detection surface for status, repair and uninstall across every runtime, so both+// directions are costly. A false negative makes repair add a second hook beside the first and leaves+// uninstall's behind; a false positive rewrites or deletes a hook somebody else installed.func isEndpointHookCommand(command, platform string) bool {hasPlatform := platform == "" || commandHasPlatform(command, platform)+ namesPlatform := commandNamesPlatform(command)hasBeaconBinary := strings.Contains(command, embedded.BinaryStem)hasLegacyBinary := strings.Contains(command, "asym-hooks")- if strings.Contains(command, "BEACON_ENDPOINT_MODE=1") && hasBeaconBinary {- return hasPlatform || !strings.Contains(command, "--platform ")+ if commandCarriesEndpointSettings(command) && hasBeaconBinary {+ return hasPlatform || !namesPlatform}- if hasBeaconBinary && !strings.Contains(command, "--platform ") {+ if hasBeaconBinary && !namesPlatform {return true}return hasLegacyBinary && hasPlatform}+// commandCarriesEndpointSettings reports whether a command was written by an endpoint install, as+// opposed to being some other invocation of the same binary.+//+// Two spellings, because the values moved from the environment to flags. An inline+// `BEACON_ENDPOINT_MODE=1 ...` prefix is a POSIX shell construct that neither Windows shell accepts,+// so a Windows hook carries `--log`/`--config`/`--cli` instead. Both must be recognized: already+// installed POSIX hooks use the prefix, and until a repair rewrites them one machine has both.+//+// Recognizing only the prefix is what made this worth extracting. A flags-form command matched+// nothing -- it has no prefix, and it does name a platform, so it fell past both branches above and+// reported false. Every runtime's repair would have added a duplicate hook next to the one Beacon+// had just written, and uninstall would have left it in place.+func commandCarriesEndpointSettings(command string) bool {+ for _, field := range commandFields(command) {+ if field == "BEACON_ENDPOINT_MODE=1" {+ return true+ }+ for _, name := range []string{"--log", "--config", "--cli"} {+ if field == name || strings.HasPrefix(field, name+"=") {+ return true+ }+ }+ }+ return false+}++// commandNamesPlatform reports whether a command specifies a platform at all.+//+// A command that names none is treated as an any-platform install, which is how hooks written before+// the flag existed are still recognized. Asked as a token rather than by searching for the substring+// "--platform " with a trailing space: that spelling missed `--platform=cursor`, so such a hook was+// treated as platform-less and matched when asked about *any* runtime -- the false-positive direction,+// where repair rewrites somebody else's hook.+func commandNamesPlatform(command string) bool {+ for _, field := range commandFields(command) {+ if field == "--platform" || strings.HasPrefix(field, "--platform=") {+ return true+ }+ }+ return false+}+func commandHasPlatform(command, platform string) bool {- fields := strings.Fields(command)+ fields := commandFields(command)for i, field := range fields {- if field == "--platform" && i+1 < len(fields) {- return strings.Trim(fields[i+1], `"'`) == platform+ if field == "--platform" {+ return i+1 < len(fields) && fields[i+1] == platform}- if strings.HasPrefix(field, "--platform=") {- return strings.Trim(strings.TrimPrefix(field, "--platform="), `"'`) == platform+ if value, found := strings.CutPrefix(field, "--platform="); found {+ return value == platform}}return false}+// commandFields splits a hook command into argv-like tokens, keeping quoted runs together.+//+// strings.Fields is not enough once paths are Windows paths. The default install location is under+// %ProgramFiles% or a user profile, both of which routinely contain a space, so a quoted path splits+// into fragments and any token comparison after it is being made against half a path. Quoting is+// stripped rather than preserved because callers compare against bare values like "cursor".+//+// Both quote characters, because the command may have been written for either shell -- POSIX hooks+// are single-quoted and Windows ones double-quoted -- and this function only has to recover tokens,+// not to reproduce a particular shell's semantics. It deliberately does not handle backslash escapes:+// on Windows a backslash is a path separator, and treating it as an escape would corrupt every path+// this parses.+func commandFields(command string) []string {+ var (+ fields []string+ current strings.Builder+ quote rune+ started bool+ )+ flush := func() {+ if started {+ fields = append(fields, current.String())+ current.Reset()+ started = false+ }+ }+ for _, r := range command {+ switch {+ case quote != 0:+ if r == quote {+ quote = 0+ break+ }+ current.WriteRune(r)+ case r == '"' || r == '\'':+ // Marks the token as started even if the quotes turn out to be empty, so `--platform ""`+ // yields an empty value rather than dropping the argument and shifting every token after+ // it left by one.+ quote = r+ started = true+ case r == ' ' || r == '\t':+ flush()+ default:+ current.WriteRune(r)+ started = true+ }+ }+ flush()+ return fields+}+func writeEndpointHookBinary(userMode bool) (string, error) {path, err := endpointHookBinaryPath(userMode)if err != nil {