package mac import ( "context" "fmt" "os" "strings" "sync" "testing" "amadan.net/oficina/equipo/internal/wire" ) // warned records what P2 said to runner.log. type warned struct { mu sync.Mutex calls [][]any } func (w *warned) warn(msg string, args ...any) { w.mu.Lock() defer w.mu.Unlock() w.calls = append(w.calls, append([]any{msg}, args...)) } func (w *warned) attr(i int, key string) string { w.mu.Lock() defer w.mu.Unlock() c := w.calls[i] for j := 1; j+1 < len(c); j += 2 { if c[j] == key { return fmt.Sprint(c[j+1]) } } return "" } // A real build and test prints far more than the gate keeps (its last // 200 lines), the script build's report lines and success line first: // P2 reads the whole output as it comes, so a full run is still judged. func TestP2ReadsTheWholeOutput(t *testing.T) { f := newProbeFixture(t, allLines("denied"), "FAKE_NOISE=1") var w warned f.h.Warn = w.warn p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)) if p.Verdict != wire.ProbeDenied || !ran || len(w.calls) != 0 { t.Fatalf("a long, complete run: %+v ran=%v warned=%v", p, ran, w.calls) } } // Each step of the srt run that fails is named in P2's detail with its // exit and first error line, and once in runner.log with the bounded // excerpt; P2 is never denied for it. func TestP2SaysWhichStepFailed(t *testing.T) { for _, c := range []struct{ env, phase, detail string }{ {"FAKE_BUILD_FAIL=1", "script build", "srt_failed:script build exit 65"}, {"FAKE_RESOLVE_FAIL=1", "package resolve", "srt_failed:package resolve exit 74"}, {"FAKE_TEST_BUILD_FAIL=error: no such module 'XCTest'", "test build", "srt_failed:test build exit 65"}, {"FAKE_BOOT_FAIL=1", "simulator boot", "srt_failed:simulator boot exit 149"}, {"FAKE_RUN_FAIL=1", "test run", "srt_failed:test run exit 65"}, } { f := newProbeFixture(t, allLines("denied"), c.env) var w warned f.h.Warn = w.warn p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)) // The phase and its exit, never the output (whole-branch fix 1, // #6: the excerpt goes only to the runner's log). codedProbes(t, p) if ran || p.Verdict != wire.ProbeFailed || !strings.HasSuffix(p.Detail, c.detail) { t.Fatalf("%s: %+v ran=%v", c.phase, p, ran) } if err := wire.ValidCapabilities(wire.Capabilities{Probes: []wire.Probe{p}}); err != nil { t.Fatalf("%s: detail outside the capability rules: %v", c.phase, err) } if len(w.calls) != 1 || w.calls[0][0] != "p2 srt run failed" || w.attr(0, "phase") != c.phase || w.attr(0, "excerpt") == "" || w.attr(0, "timed_out") != "false" { t.Fatalf("%s: warned %v", c.phase, w.calls) } } // No step reported at all: srt itself did not start the command. f := newProbeFixture(t, allLines("denied")) if err := os.WriteFile(f.h.Tools.SRT, []byte("#!/bin/bash\necho 'Error: Refusing to run with the built-in defaults' >&2\nexit 1\n"), 0700); err != nil { t.Fatal(err) } var w warned f.h.Warn = w.warn p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)) if p.Detail != "not_shown_denied:script.* plugin.* test.*;srt_failed:srt start exit 1" || w.attr(0, "phase") != "srt start" { t.Fatalf("srt did not start: %+v %v", p, w.calls) } } // What P2 says about a failure never carries the sentinel secret, the // Keychain service, the targets file's contents or a path under a home, // even when the failing tool prints all of them. func TestP2FailureIsRedacted(t *testing.T) { leak := `t=../equipo-targets.txt; echo "error: cannot read $(sed -n 's/^state=//p' $t)"; echo "error: no item $(sed -n 's/^keychain=//p' $t) in $(sed -n 's/^keychain_file=//p' $t)"; echo "error: $(tr '\n' ' ' < $t)"; printf 'error: \033[31mred\033[0m and \001bell\n'` f := newProbeFixture(t, allLines("denied")) xb, _ := os.ReadFile(f.h.Tools.Xcodebuild) patched := strings.Replace(string(xb), `[ -n "$FAKE_TEST_BUILD_FAIL" ] &&`, `{ `+leak+`; exit 65; }; [ -n "$FAKE_TEST_BUILD_FAIL" ] &&`, 1) if err := os.WriteFile(f.h.Tools.Xcodebuild, []byte(patched), 0700); err != nil { t.Fatal(err) } var w warned f.h.Warn = w.warn f.h.Paths.OtherHomes = []string{"/Users/paul"} p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)) if len(w.calls) != 1 || w.attr(0, "phase") != "test build" { t.Fatalf("warned %v", w.calls) } excerpt := w.attr(0, "excerpt") said := p.Detail + "\n" + fmt.Sprint(w.calls) for _, bad := range []string{f.dir, "/Users/paul", "io.amadan.equipo.probe.", "probe-sentinel-", "login.keychain", "port_", "keychain=", "example.com", "\x1b", "\x01"} { if strings.Contains(said, bad) { t.Fatalf("%q left in %q", bad, said) } } if !strings.Contains(excerpt, "error: cannot read [redacted] | error: no item [redacted] in [redacted]") || !strings.Contains(excerpt, "red and bell") || len(excerpt) > p2ExcerptBytes { t.Fatalf("excerpt %q", excerpt) } } // The judge of a failure from recorded gate outputs: the step a timeout // stopped, srt or the gate not starting, every step passing yet no // success line, and the excerpt's bounds (five lines, 400 bytes, no // control characters). func TestP2FailureFromGateOutput(t *testing.T) { red := newRedactor([]string{"0123456789abcdef"}, []string{"/Users/equipo-paul"}) feed := func(lines ...string) *p2Watch { w := newP2Watch() for _, l := range lines { w.line(l) } return w } for name, c := range map[string]struct { w *p2Watch res Result phase string short string timeup bool }{ "timed out in the test build": {feed("EQUIPO-PHASE script-build 0", "EQUIPO-PHASE package-resolve 0"), Result{Code: -1, Reason: "checks_timeout"}, "test build", "test build timed out", true}, "a failure, then a timeout": {feed("EQUIPO-PHASE script-build 65", "EQUIPO-PHASE package-resolve 0"), Result{Code: -1, Reason: "checks_timeout"}, "script build", "script build exit 65, test build timed out", true}, "stopped by the run's limit": {feed(), Result{Code: -1, Reason: "cancelled"}, "script build", "script build stopped", false}, "srt refused its settings": {feed("Error: /Users/equipo-paul/.local/s.json does not exist."), Result{Code: 1}, "srt start", "srt start exit 1: Error: [home]...s.json does not exist.", false}, "the gate could not start": {feed(), Result{Code: -1, Reason: "checks_unavailable"}, "gate start", "gate start failed", false}, "no success line": {feed("EQUIPO-PHASE script-build 0", "EQUIPO-PHASE package-resolve 0", "EQUIPO-PHASE test-build 0", "EQUIPO-PHASE simulator-boot 0", "EQUIPO-PHASE test-run 0", "** BUILD SUCCEEDED **"), Result{Code: 0}, "run end", "run end exit 0", false}, } { if c.w.ran(c.res) { t.Fatalf("%s: taken as ran", name) } f := c.w.failure(c.res, red) if f.Phase != c.phase || f.short() != c.short || f.TimedOut != c.timeup { t.Fatalf("%s: %+v short %q", name, f, f.short()) } } var lines []string for i := 0; i < 9; i++ { lines = append(lines, fmt.Sprintf("/Users/equipo-paul/x/f%d.swift:1:2: error: \x1b[1m%s\x07 0123456789abcdef", i, strings.Repeat("é", 60))) } lines = append(lines, lines[0]) f := feed(lines...).failure(Result{Code: 65}, red) if n := strings.Count(f.Excerpt, " | ") + 1; n > p2ErrorLines || len(f.Excerpt) > p2ExcerptBytes || len(f.First) > p2ShortBytes || !strings.HasPrefix(f.First, "[home]...f0.swift:1:2: error: é") { t.Fatalf("bounds: %d lines, %d bytes, first %q", n, len(f.Excerpt), f.First) } for _, r := range f.Excerpt { if r < 0x20 || r == 0x7f || r == '�' { t.Fatalf("control or broken character in %q", f.Excerpt) } } if strings.Contains(f.Excerpt, "0123456789abcdef") || strings.Contains(f.Excerpt, "equipo-paul") { t.Fatalf("not redacted: %q", f.Excerpt) } // A run that did everything, by every account. all := feed("EQUIPO-PHASE script-build 0", "EQUIPO-PHASE package-resolve 0", "EQUIPO-PHASE test-build 0", "EQUIPO-PHASE simulator-boot 0", "EQUIPO-PHASE test-run 0", "** BUILD SUCCEEDED **", "** TEST BUILD SUCCEEDED **", "** TEST EXECUTE SUCCEEDED **") if !all.ran(Result{Code: 0}) || all.ran(Result{Code: 1}) { t.Fatal("ran") } } // However long the reason, the detail keeps what decides trust (the // end not proven) and stays a capability string: the reason is cut. func TestP2DetailKeepsTheEnd(t *testing.T) { unknown := []string{"script.state", "script.tcp", "script.dns", "script.keychain", "plugin.state", "plugin.tcp", "plugin.dns", "plugin.keychain", "test.state", "test.tcp", "test.dns", "test.keychain"} d := p2Detail(map[string][]string{"unknown": unknown[:11], "allowed": unknown[11:]}, 12, false, false, "test build exit 65: "+strings.Repeat("error: x ", 60)) if parts, ok := wire.ParseProbeDetail(d); !ok || !strings.Contains(d, ";end_unproven") || len(d) > wire.MaxCapabilityString || len(parts) < 3 { t.Fatalf("detail %q", d) } if d := p2Detail(map[string][]string{"unknown": unknown}, 12, false, true, ""); d != wire.ProbeDetail("not_shown_denied", strings.Join(unknown, " "))+";srt_not_run" { t.Fatalf("detail %q", d) } } // P2's script runs every step it names, in order, under the gate's // TMPDIR, with the package's plugins allowed to run unvalidated and // nothing that reaches the network. func TestP2Script(t *testing.T) { s := P2Script(quote("/usr/bin/xcodebuild"), quote("/usr/bin/xcrun"), "ABCDEF01-2345-6789-ABCD-EF0123456789") last := -1 for _, p := range p2Phases { i := strings.Index(s, "phase "+p.key+" ") if i < last { t.Fatalf("%s missing or out of order in %s", p.key, s) } last = i } if strings.Count(s, "-skipPackagePluginValidation") != 3 || strings.Count(s, XcodeWrites) != 5 || strings.Count(s, `-resultBundlePath "$TMPDIR/Results/`) != 4 || strings.Contains(s, "http") { t.Fatalf("script %s", s) } }