package mac import ( "context" "errors" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/mac/proc" ) // Follow-up fix round 1 (Astra 9f round 1). Synthetic tables, rows made // up 2026-11-29 in the darwin table's shape (see sweep_test.go). // #1: a process that left the runner user (a setuid program that called // setuid), in no group or session the record got, is invisible to an // idle read. A setuid program cannot run under Seatbelt on 27.2 (task 1, // R4), so an idle read clears only a turn whose record shows nothing ran // outside a sandbox; any other clears only by a reboot. func TestIdleRefusedWhereUnsandboxedCodeRan(t *testing.T) { for name, c := range map[string]struct { edit func(*proc.Obligation) clear bool }{ "unsandboxed code ran": {func(o *proc.Obligation) { o.UnsandboxedRan = true }, false}, "the flag not on record": {func(o *proc.Obligation) { o.FlagsKnown = false }, false}, "everything in a sandbox": {func(*proc.Obligation) {}, true}, } { tb := parseTable(t, turnBegan) // The survivor, now root's, that the record never got. tb.add(row(99001, 1, 99001, 99001, 5000, 0, ""), "/usr/bin/login") turns, x, _, before := clearRig(t, tb, sameBoot, nil) o := owed(before) c.edit(&o) if err := turns.debts.Owe(o); err != nil { t.Fatal(err) } if got := x.Verify(RecordID(0, "attempt-c")); got != c.clear { t.Fatalf("%s: proven %v, want %v", name, got, c.clear) } } } // #1: an unsandboxed check puts the flag on its turn's record before // anything of it starts; a flag that cannot be written starts nothing; // a sandboxed check leaves it unset. func TestUnsandboxedCheckFlagsItsTurnFirst(t *testing.T) { for _, sandboxed := range []bool{false, true} { g, dir := gateFixture(t, sandboxed) g.Turns = NewTurns(filepath.Join(t.TempDir(), "lock")) got := false res := g.Run(context.Background(), "checks-u-2", dir, []string{"/bin/sh", "-c", "true"}, time.Minute, func(id string) error { if strings.HasPrefix(id, "pg:0:") { r, ok, _ := g.Turns.loadTurn() got = ok && r.FlagsKnown && r.UnsandboxedRan } return nil }) if res.Code != 0 || got == sandboxed { t.Fatalf("sandboxed %v: flag on record before the start %v (%+v)", sandboxed, got, res) } } g, dir := gateFixture(t, false) g.Turns = NewTurns(filepath.Join(t.TempDir(), "lock")) writes := 0 g.Turns.beforeWrite = func() error { // The turn's own record, then the flag. if writes++; writes == 2 { return errors.New("disk full") } return nil } ran := filepath.Join(t.TempDir(), "ran") if res, _ := run(g, dir, "checks-u-3", time.Minute, "touch "+quote(ran)); res.Reason != "checks_unavailable" || exists(ran) { t.Fatalf("ran without its flag on record: %+v", res) } } // #2: both idle reads and the acceptance happen holding the turn. Every // exempt process predates every unresolved turn, and every process of // the old turn was absent from both reads, so none can fork after the // second: a process an exempt service starts after it is not a // survivor. The clearance stands, and what the turn owed was gone. func TestAcceptanceAfterTheSecondRead(t *testing.T) { me := os.Getuid() tb := parseTable(t, turnBegan) turns, x, _, before := clearRig(t, tb, sameBoot, nil) o := owed(before) o.Groups, o.Killed = proc.Span{99100: 4000}, []ProcID{{PID: 99101, Start: 4001}} if err := turns.debts.Owe(o); err != nil { t.Fatal(err) } reads := 0 tb.afterList = func(tb *table, _ int, _ []string) { // The recovery turn's read, then the two idle reads: right after // the second, the exempt trustd (40200) starts a process. if reads++; reads == 3 { tb.procs[99200] = row(99200, 40200, 99200, 99200, 9000, me, "") tb.paths[99200] = "/usr/libexec/trustd-helper" } } if !x.Verify(RecordID(0, "attempt-c")) || turns.debts.Owes("attempt-c") { t.Fatal("not proven over") } if !tb.has(99200) { t.Fatal("the service's new process was touched") } for pid, q := range tb.procs { if q.PGID == 99100 || pid == 99101 { t.Fatalf("what the turn owed was not gone: %+v", q) } } } // #3: a process is exempt only if it existed before the earliest // unresolved turn began. P, born in turn A and still owed by A, is in // later turn B's table: B does not clear while P lives. Once A and B are // resolved, a later turn's table exempts as before. func TestEarliestUnresolvedTurnIsTheBaseline(t *testing.T) { me := os.Getuid() tb := parseTable(t, turnBegan) turns, x, _, beforeA := clearRig(t, tb, sameBoot, nil) p := row(99300, 1, 99300, 99300, 5000, me, "") tb.add(p, "/Users/paulequipo/w/p") beforeB := append(append([]ProcID{}, beforeA...), p.ID) a := owed(beforeA) a.Markers = []string{"attempt-a"} b := owed(beforeB) b.Markers, b.Began = []string{"attempt-b"}, turnStart.Add(time.Hour) for _, o := range []proc.Obligation{a, b} { if err := turns.debts.Owe(o); err != nil { t.Fatal(err) } } if x.Verify(RecordID(0, "attempt-b")) { t.Fatal("B cleared while A's survivor lives") } tb.remove(p.PID) if !x.Verify(RecordID(0, "attempt-a")) || !x.Verify(RecordID(0, "attempt-b")) { t.Fatal("A and B not proven once P is gone") } r := row(99301, 1, 99301, 99301, 6000, me, "") tb.add(r, "/Users/paulequipo/w/r") c := owed(append(append([]ProcID{}, beforeA...), r.ID)) c.Markers, c.Began = []string{"attempt-c2"}, turnStart.Add(2*time.Hour) if err := turns.debts.Owe(c); err != nil { t.Fatal(err) } if !x.Verify(RecordID(0, "attempt-c2")) { t.Fatal("with nothing older owed, a turn's own table no longer exempts") } } // #4: a proven reboot is a clearance qualified by boot: the old boot's // process checks no longer apply. Its recorded group id, now another // process's in this boot, neither blocks the proof nor is signalled; nor // does a pending user-temp cleanup's. func TestRebootIgnoresTheOldBootsGroups(t *testing.T) { me := os.Getuid() for _, viaRecord := range []bool{true, false} { tb := parseTable(t, turnBegan) turns, x, _, before := clearRig(t, tb, laterBoot, nil) tb.add(row(99400, 1, 99400, 99400, 5000, me, ""), "/Users/paulequipo/w/this-boot") if viaRecord { if err := turns.saveTurn(turnRecord{ID: "old", Op: OpEngineering, Runner: selfID(), Sweep: true, Before: before, Markers: []string{"attempt-c"}, Began: turnStart, BootID: "boot-1"}); err != nil { t.Fatal(err) } } else { if err := turns.debts.Owe(owed(before)); err != nil { t.Fatal(err) } // And a user-temp cleanup the old boot's attempt left. _, temp := userTempFixture(t) x.UserTemp = temp s, err := openTemp(temp, nil) if err != nil { t.Fatal(err) } if err := turns.writePending(pendingRecord{Attempt: "attempt-c", PGID: 99400, Before: s.before, Runner: ProcID{PID: 1 << 30, Start: 1}, Began: turnStart, BootID: "boot-1"}); err != nil { t.Fatal(err) } s.close() } if !x.Verify(RecordID(99400, "attempt-c")) || turns.Pending() { t.Fatalf("record %v: a reused group id of the old boot blocked a proven reboot", viaRecord) } // Proven again after a runner restart, twice: the completion stays // until both consumers have acknowledged it. again := NewTurns(turns.lock).Sweep(tb) again.own, again.Settle, again.boot = turns.own, turns.Settle, turns.boot y := &Executor{Turns: again, Settle: x.Settle} first, second := y.Verify(RecordID(99400, "attempt-c")), y.Verify(RecordID(99400, "attempt-c")) if !first || !second { t.Fatalf("record %v: a later proof of the same record failed", viaRecord) } y.Acknowledge(RecordID(99400, "attempt-c"), ConsumerStep) if !again.debts.Owes("attempt-c") { t.Fatalf("record %v: the completion went before the Keychain acknowledged it", viaRecord) } y.Acknowledge(RecordID(99400, "attempt-c"), ConsumerKeychain) if again.debts.Owes("attempt-c") { t.Fatalf("record %v: the completion stayed after every consumer had it", viaRecord) } if sig := tb.signalled(); len(sig) != 0 { t.Fatalf("record %v: signalled %v", viaRecord, sig) } } } // #5: the clearance is under Verify's one deadline and removes nothing // unless the whole proof succeeds in time: a read slow enough to spend // the budget leaves the debt in place. func TestClearanceUnderTheOneDeadline(t *testing.T) { tb := &slowTable{table: parseTable(t, turnBegan), delay: 120 * time.Millisecond} turns, x, _, before := clearRig(t, tb, sameBoot, nil) if err := turns.debts.Owe(owed(before)); err != nil { t.Fatal(err) } tb.slow.Store(true) if x.Verify(RecordID(0, "attempt-c")) { t.Fatal("proven after its deadline") } tb.slow.Store(false) if !turns.debts.Owes("attempt-c") { t.Fatal("the debt went though the proof expired") } } // #1: the flag goes from the turn's record into what it owes once a // restart settles it, so an unsandboxed turn left incomplete is never // idle-cleared later. func TestUnsandboxedFlagSurvivesIntoTheDebt(t *testing.T) { tb := parseTable(t, turnBegan) turns, x, _, before := clearRig(t, tb, sameBoot, nil) if err := turns.saveTurn(turnRecord{ID: "old", Op: OpCheck, Runner: selfID(), Sweep: true, Before: before, Markers: []string{"attempt-c"}, Began: turnStart, BootID: "boot-1", FlagsKnown: true, UnsandboxedRan: true}); err != nil { t.Fatal(err) } if x.Verify(RecordID(0, "attempt-c")) || !turns.Incomplete() { t.Fatal("an unsandboxed turn, left incomplete, was idle-cleared") } } // #5: the debt goes only with the whole proof: met by an idle read, but // its recorded group, held by a process from before the turn, still // alive, the proof fails and the debt stays; once that group ends, the // proof holds and the debt goes. func TestDebtKeptWhenTheRestOfTheProofFails(t *testing.T) { me := os.Getuid() tb := parseTable(t, turnBegan) tb.add(row(99500, 1, 99500, 99500, 900, me, ""), "/Users/paulequipo/w/old") turns, x, _, before := clearRig(t, tb, sameBoot, nil) if err := turns.debts.Owe(owed(before)); err != nil { t.Fatal(err) } if x.Verify(RecordID(99500, "attempt-c")) || !turns.debts.Owes("attempt-c") { t.Fatal("the debt went with the proof not whole") } tb.remove(99500) if !x.Verify(RecordID(99500, "attempt-c")) || turns.debts.Owes("attempt-c") { t.Fatal("not proven, or the debt stayed, once everything ended") } }