package mac import ( "context" "os" "os/exec" "path/filepath" "strings" "testing" "amadan.net/oficina/equipo/internal/wire" ) // The token sources each hostile place tries (P2 and F5; slice F task // 14, fix round 1 #4), one attempt per source so a collector that could // not run is a missing line, never a denial: the token file by path, a // hard link of it, the environment, KERN_PROCARGS2 of every own process // (the shell through the runner's direct reader), launchd's environment, // and every open descriptor. var tokenSources = []string{"tokenfile", "tokenlink", "tokenenv", "tokenargs", "tokenlaunchd", "tokenfd"} // P2 is denied only when every place's every token source says denied, // the sentinel token was planted (the control), and no line is missing. func TestP2TriesTheToken(t *testing.T) { got := ParseAttempts(allLines("denied")["script"] + allLines("denied")["plugin"] + allLines("denied")["test"]) facts := P2Facts{Home: true, DNS: true, Keychain: true, Token: true, Accepted: map[string]bool{}} if v, g := JudgeP2(got, facts); v != wire.ProbeDenied || len(g) != 0 { t.Fatalf("all denied: %s %v", v, g) } facts.Token = false if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || len(g["unknown"]) != 3*len(tokenSources) { t.Fatalf("the sentinel token was not planted, so denied proves nothing: %s %v", v, g) } facts.Token = true // A collector that ran and could not collect (fix round 2, #4) says // failed, which is never a denial, and P2's detail says so. got["plugin.tokenargs"] = "failed" if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || len(g["failed"]) != 1 || !strings.Contains(p2Detail(g, 33, true, true, ""), "not_collected:plugin.tokenargs") { t.Fatalf("a failed collection: %s %v", v, g) } if ParseAttempts("EQUIPO-PROBE test tokenargs failed\n")["test.tokenargs"] != "failed" { t.Fatal("a failed line is not read") } got["plugin.tokenargs"] = "denied" for _, src := range tokenSources { delete(got, "plugin."+src) if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || len(g["unknown"]) != 1 || g["unknown"][0] != "plugin."+src { t.Fatalf("a source not collected (%s): %s %v", src, v, g) } got["plugin."+src] = "denied" } // The run: the test place reads the token file the probe planted in // the accounts root (outside any sandbox here) and says so. f := newProbeFixture(t, allLines("denied"), "FAKE_READ_TOKEN=1") caps := Capabilities(context.Background(), f.h.Exec, f.h.Tools) if p, _, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "allowed:test.tokenfile") { t.Fatalf("token read: %+v", p) } if left, _ := filepath.Glob(filepath.Join(f.h.Paths.AccountsRoot, "*")); len(left) != 0 { t.Fatalf("the sentinel token was left: %v", left) } f = newProbeFixture(t, allLines("denied")) f.h.Paths.AccountsRoot = "" if p, _, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "not_shown_denied:") { t.Fatalf("no accounts root: %+v", p) } // The targets name the runner's binary, the direct reader. f = newProbeFixture(t, allLines("denied")) f.h.Scratch, f.h.Runner = filepath.Join(f.dir, "scratch"), "/opt/equipo-runner" targets := "" f.h.Gate = func(sandboxed bool) *Gate { g := &Gate{Env: []string{"PATH=/usr/bin:/bin"}, Lines: 200, Sandbox: wire.SandboxNone} g.Watch = func(string) {} return g } inner := f.h.Exec f.h.Exec = func(ctx context.Context, name string, args ...string) (string, error) { if m, _ := filepath.Glob(filepath.Join(f.h.Scratch, "probe-*", "hostile", "equipo-targets.txt")); len(m) == 1 && targets == "" { raw, _ := os.ReadFile(m[0]) targets = string(raw) } return inner(ctx, name, args...) } probeP2(context.Background(), f.h, caps) if !strings.Contains(targets, "helper=/opt/equipo-runner\n") { t.Fatalf("targets %q", targets) } // The shipped script phase really tries each source: run as it is, // outside any sandbox (Linux), with a stand-in for the runner's // reader. A source whose collector cannot run says nothing. bash, err := exec.LookPath("bash") if err != nil { t.Skip("no bash") } root, err := CopyFixture(t.TempDir()) if err != nil { t.Fatal(err) } dir := t.TempDir() token := "sk-ant-oat01-probe-0123456789abcdef" if err := os.WriteFile(filepath.Join(dir, ".oauth-token"), []byte(token), 0600); err != nil { t.Fatal(err) } helper := filepath.Join(dir, "helper") // The stand-in reads only the hostile shell (its caller's parent, past // the command substitution): this box's other processes are not ours. if err := os.WriteFile(helper, []byte("#!/bin/bash\nmode=$2; shift 2\npp=$(ps -o ppid= -p $PPID | tr -d ' ')\ncase \"$mode\" in pids) echo $PPID; echo $pp ;; procargs) for p in \"$@\"; do echo \"procargs-start $p\"; if { [ \"$p\" = \"$PPID\" ] || [ \"$p\" = \"$pp\" ]; } && tr '\\0' '\\n' < /proc/$p/environ; then echo \"procargs-end $p ok\"; else echo \"procargs-end $p refused\"; fi; done ;; fds) for f in /proc/self/fd/*; do echo \"fd ${f##*/} file\"; done; echo fds-done ;; *) exit 2 ;; esac\n"), 0700); err != nil { t.Fatal(err) } run := func(targets string, env ...string) map[string]string { t.Helper() if err := os.WriteFile(filepath.Join(root, "equipo-targets.txt"), []byte(targets), 0600); err != nil { t.Fatal(err) } cmd := exec.Command(bash, filepath.Join(root, "project", "hostile.sh")) cmd.Env = append([]string{"PATH=/usr/bin:/bin", "SRCROOT=" + filepath.Join(root, "project"), "TMPDIR=" + t.TempDir()}, env...) out, _ := cmd.CombinedOutput() if strings.Contains(string(out), token) { t.Fatalf("the script printed the token: %s", out) } return ParseAttempts(string(out)) } base := "state=/nonexistent\ndns=example.invalid\nkeychain=io.amadan.equipo.probe.x\nport_script=1\ntoken=" + token + "\n" got = run(base + "token_file=" + filepath.Join(dir, ".oauth-token") + "\nhelper=" + helper + "\n") for src, want := range map[string]string{"tokenfile": "allowed", "tokenlink": "allowed", "tokenenv": "denied", "tokenargs": "denied", "tokenfd": "denied"} { if got["script."+src] != want { t.Fatalf("%s: %q, want %s (%v)", src, got["script."+src], want, got) } } if _, ok := got["script.tokenlaunchd"]; ok { t.Fatalf("launchctl is not here, so launchd's environment cannot be shown: %v", got) } if got = run(base+"token_file="+filepath.Join(dir, ".oauth-token")+"\nhelper="+helper+"\n", "CLAUDE_CODE_OAUTH_TOKEN="+token); got["script.tokenenv"] != "allowed" || got["script.tokenargs"] != "allowed" { t.Fatalf("the token in the environment: %v", got) } got = run(base + "token_file=" + filepath.Join(dir, "missing") + "\nhelper=" + filepath.Join(dir, "no-helper") + "\n") if got["script.tokenfile"] != "denied" || got["script.tokenlink"] != "denied" { t.Fatalf("a token file it could not read: %v", got) } for _, src := range []string{"tokenargs", "tokenfd"} { if _, ok := got["script."+src]; ok { t.Fatalf("%s said without its reader: %v", src, got) } } // A reader the kernel refused for the shell itself (its control) // shows no process's environment: no line. refusing := filepath.Join(dir, "refusing") if err := os.WriteFile(refusing, []byte("#!/bin/bash\nmode=$2; shift 2\ncase \"$mode\" in procargs) for p in \"$@\"; do echo \"procargs-start $p\"; echo \"procargs-end $p refused\"; done; exit 1 ;; fds) echo fds-done ;; esac\n"), 0700); err != nil { t.Fatal(err) } if got = run(base + "token_file=" + filepath.Join(dir, ".oauth-token") + "\nhelper=" + refusing + "\n"); got["script.tokenargs"] != "failed" { t.Fatalf("tokenargs not failed though the reader read nothing: %v", got) } // The process list could not be read, or did not show the shell // itself (its control): tokenargs failed, never denied. for name, body := range map[string]string{ "nolist": "#!/bin/bash\ncase \"$2\" in pids) exit 1 ;; procargs) shift 2; for p in \"$@\"; do echo \"procargs-start $p\"; echo \"procargs-end $p ok\"; done ;; fds) echo fds-done ;; esac\n", "notself": "#!/bin/bash\ncase \"$2\" in pids) echo 1 ;; procargs) shift 2; for p in \"$@\"; do echo \"procargs-start $p\"; echo \"procargs-end $p ok\"; done ;; fds) echo fds-done ;; esac\n", } { h := filepath.Join(dir, name) if err := os.WriteFile(h, []byte(body), 0700); err != nil { t.Fatal(err) } if got = run(base + "token_file=" + filepath.Join(dir, ".oauth-token") + "\nhelper=" + h + "\n"); got["script.tokenargs"] != "failed" { t.Fatalf("%s: tokenargs %q, want failed (%v)", name, got["script.tokenargs"], got) } } // Every hostile part tries every source, the Swift parts by // KERN_PROCARGS2 and posix_spawn (no Process on iOS). for _, file := range []string{"package/Plugins/HostilePlugin/HostilePlugin.swift", "package/Tests/HostileTests/HostileTests.swift", "project/hostile.sh"} { raw, _ := os.ReadFile(filepath.Join(root, file)) for _, src := range tokenSources { if !strings.Contains(string(raw), `"`+src+`"`) && !strings.Contains(string(raw), "say "+src) && !strings.Contains(string(raw), "src "+src) { t.Fatalf("%s does not try %s", file, src) } } if strings.HasSuffix(file, ".swift") && (!strings.Contains(string(raw), "KERN_PROCARGS2") || !strings.Contains(string(raw), "posix_spawn") || strings.Contains(string(raw), "#if os(macOS)\n sources") || !strings.Contains(string(raw), `("tokenargs", "failed")`)) { t.Fatalf("%s: the reader and launchctl on every platform", file) } } }