| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 11 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 12 | ) |
| 13 | |
| 14 | type approvalAPI struct{ values []runnerproto.Question } |
| 15 | |
| 16 | func (a *approvalAPI) Call(_ context.Context, _ string, _ runnerproto.RunnerRequest, out any) error { |
| 17 | *out.(*[]runnerproto.Question) = a.values |
| 18 | return nil |
| 19 | } |
| 20 | |
| 21 | func TestDirectStaleAnswerNativeCurrent(t *testing.T) { |
| 22 | q := runnerproto.Question{ID: "q", TaskID: "task", Attempt: 1, Fence: 7, AgentID: "agent", SessionID: "session", PermissionID: "7", Revision: 1, AnsweredBy: "person", RawRequest: json.RawMessage(`{"command":"printf hello"}`), Answer: &runnerproto.QuestionAnswer{Behavior: "allow"}} |
| 23 | for _, change := range []string{"removed", "person", "payload", "answer", "fence", "attempt", "task", "revision"} { |
| 24 | t.Run(change, func(t *testing.T) { |
| 25 | saved := q |
| 26 | api := &approvalAPI{values: []runnerproto.Question{saved}} |
| 27 | switch change { |
| 28 | case "removed": |
| 29 | api.values = nil |
| 30 | case "person": |
| 31 | api.values[0].AnsweredBy = "other" |
| 32 | case "payload": |
| 33 | api.values[0].RawRequest = json.RawMessage(`{"command":"changed"}`) |
| 34 | case "answer": |
| 35 | api.values[0].Answer = &runnerproto.QuestionAnswer{Behavior: "deny"} |
| 36 | case "fence": |
| 37 | api.values[0].Fence++ |
| 38 | case "attempt": |
| 39 | api.values[0].Attempt++ |
| 40 | case "task": |
| 41 | api.values[0].TaskID = "other" |
| 42 | case "revision": |
| 43 | api.values[0].Revision++ |
| 44 | } |
| 45 | s := &Supervisor{api: api} |
| 46 | if _, err := s.currentDirectQuestion(context.Background(), &attemptState{}, q, func(context.Context) error { return nil }); err == nil { |
| 47 | t.Fatal("stale answer accepted", change) |
| 48 | } |
| 49 | }) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | type nativeAnswerLauncher struct { |
| 54 | directAnswerLauncher |
| 55 | event provider.Event |
| 56 | change func(provider.Event) provider.Event |
| 57 | sent int |
| 58 | before func() |
| 59 | } |
| 60 | |
| 61 | func (l *nativeAnswerLauncher) Respond(ctx context.Context, _ provider.Session, a provider.Answer) error { |
| 62 | if l.before != nil { |
| 63 | l.before() |
| 64 | } |
| 65 | if a.Behavior == "allow" { |
| 66 | if a.Authorize == nil { |
| 67 | return provider.ErrPolicy |
| 68 | } |
| 69 | ev := l.event |
| 70 | if l.change != nil { |
| 71 | ev = l.change(ev) |
| 72 | } |
| 73 | if err := a.Authorize(ctx, ev); err != nil { |
| 74 | return err |
| 75 | } |
| 76 | } |
| 77 | l.sent++ |
| 78 | return nil |
| 79 | } |
| 80 | func TestCodexApprovalJournalAndExactRequest(t *testing.T) { |
| 81 | for _, change := range []string{"none", "id", "item", "turn", "session", "command", "cwd", "revoked", "redacted"} { |
| 82 | t.Run(change, func(t *testing.T) { |
| 83 | b := directToolFixture(t) |
| 84 | ctx := context.Background() |
| 85 | ev := provider.Event{Kind: "request", RequestID: "7", SessionID: b.Session.ID, TurnID: b.TurnID, Payload: json.RawMessage(`{"id":7,"method":"item/commandExecution/requestApproval","params":{"threadId":"session","turnId":"provider-turn","itemId":"item","command":"printf hello","cwd":"/workspace"}}`)} |
| 86 | if change == "redacted" { |
| 87 | ev.Payload = json.RawMessage(strings.Replace(string(ev.Payload), "printf hello", "printf Bearer secret-token-value", 1)) |
| 88 | } |
| 89 | l := &nativeAnswerLauncher{event: ev} |
| 90 | l.before = func() { |
| 91 | var records []runnerproto.Question |
| 92 | mustJournal(t, b.Journal.readStates(ctx, "profile-approval", &records)) |
| 93 | if len(records) == 0 || records[0].AnsweredBy != "person@example.com" { |
| 94 | t.Fatal("approval was not durable before provider I/O") |
| 95 | } |
| 96 | } |
| 97 | current := true |
| 98 | l.change = func(ev provider.Event) provider.Event { |
| 99 | switch change { |
| 100 | case "id": |
| 101 | ev.RequestID = "8" |
| 102 | case "turn": |
| 103 | ev.TurnID = "other" |
| 104 | case "session": |
| 105 | ev.SessionID = "other" |
| 106 | case "item": |
| 107 | ev.Payload = json.RawMessage(strings.Replace(string(ev.Payload), `"itemId":"item"`, `"itemId":"other"`, 1)) |
| 108 | case "command": |
| 109 | ev.Payload = json.RawMessage(strings.Replace(string(ev.Payload), "printf hello", "printf changed", 1)) |
| 110 | case "cwd": |
| 111 | ev.Payload = json.RawMessage(strings.Replace(string(ev.Payload), "/workspace", "/elsewhere", 1)) |
| 112 | case "revoked": |
| 113 | current = false |
| 114 | } |
| 115 | return ev |
| 116 | } |
| 117 | person := "person@example.com" |
| 118 | relay := DirectQuestionRelay{Binding: b, Launcher: l, Answerer: func(context.Context, runnerproto.Question) (string, error) { return person, nil }, Current: func(context.Context, runnerproto.Question) (time.Time, error) { |
| 119 | if !current { |
| 120 | return time.Time{}, provider.ErrPolicy |
| 121 | } |
| 122 | return b.LeaseDeadline, nil |
| 123 | }} |
| 124 | asks := 0 |
| 125 | ask := func(context.Context, runnerproto.Question) (runnerproto.QuestionAnswer, error) { |
| 126 | asks++ |
| 127 | return runnerproto.QuestionAnswer{Behavior: "allow"}, nil |
| 128 | } |
| 129 | err := relay.Handle(ctx, ev, ask) |
| 130 | if change != "none" { |
| 131 | if err == nil || l.sent != 0 { |
| 132 | t.Fatal("changed or revoked request approved", change) |
| 133 | } |
| 134 | return |
| 135 | } |
| 136 | mustJournal(t, err) |
| 137 | ev.RequestID = "8" |
| 138 | ev.Payload = json.RawMessage(strings.Replace(string(ev.Payload), `"id":7`, `"id":8`, 1)) |
| 139 | l.event = ev |
| 140 | mustJournal(t, relay.Handle(ctx, ev, ask)) |
| 141 | if asks != 2 || l.sent != 2 { |
| 142 | t.Fatal("later identical request reused approval", asks, l.sent) |
| 143 | } |
| 144 | var saved []runnerproto.Question |
| 145 | mustJournal(t, b.Journal.readStates(ctx, "profile-approval", &saved)) |
| 146 | if len(saved) != 2 { |
| 147 | t.Fatal("durable approval absent", len(saved)) |
| 148 | } |
| 149 | for _, q := range saved { |
| 150 | if q.AnsweredBy != "person@example.com" || !strings.Contains(string(q.RawRequest), "printf hello") || !strings.Contains(string(q.RawRequest), "provider-turn") || q.Answer == nil || q.Answer.Behavior != "allow" { |
| 151 | t.Fatal("journal lost request or allowing person", q) |
| 152 | } |
| 153 | } |
| 154 | person = "other@example.com" |
| 155 | if relay.Handle(ctx, ev, ask) == nil { |
| 156 | t.Fatal("changed allowing person replay accepted") |
| 157 | } |
| 158 | |
| 159 | }) |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | func TestCodexApprovalJournalWriteFailure(t *testing.T) { |
| 164 | b := directToolFixture(t) |
| 165 | ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 166 | defer cancel() |
| 167 | ev := provider.Event{Kind: "request", RequestID: "7", SessionID: b.Session.ID, TurnID: b.TurnID, Payload: json.RawMessage(`{"id":7,"method":"item/commandExecution/requestApproval","params":{"threadId":"session","turnId":"provider-turn","itemId":"item","command":"printf hello","cwd":"/workspace"}}`)} |
| 168 | q, err := DirectQuestionFromEvent(ev, b) |
| 169 | mustJournal(t, err) |
| 170 | q.AnsweredBy = "person@example.com" |
| 171 | _, err = b.Journal.db.Exec("CREATE TRIGGER reject_approval BEFORE INSERT ON journal_supervisor WHEN NEW.kind='profile-approval' BEGIN SELECT RAISE(ABORT,'approval write refused'); END") |
| 172 | mustJournal(t, err) |
| 173 | client := &answerClient{} |
| 174 | relay := QuestionRelay{Journal: b.Journal, Client: client, Agent: b.Agent, DirectSession: b.Session, TurnID: b.TurnID, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return b.LeaseDeadline, nil }} |
| 175 | err = relay.Deliver(ctx, q, runnerproto.QuestionAnswer{Behavior: "allow"}) |
| 176 | if err == nil || len(client.responses) != 0 { |
| 177 | t.Fatal("approval sent without durable evidence", err) |
| 178 | } |
| 179 | if ctx.Err() != nil { |
| 180 | t.Fatal("journal failure waited for the request deadline instead of releasing the write transaction") |
| 181 | } |
| 182 | if b.Journal.AdmissionAllowed(context.Background()) == nil { |
| 183 | t.Fatal("journal failure did not fence admission") |
| 184 | } |
| 185 | var count int |
| 186 | mustJournal(t, b.Journal.db.QueryRow("SELECT count(*) FROM journal_answers").Scan(&count)) |
| 187 | if count != 0 { |
| 188 | t.Fatal("partial approval transaction persisted") |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | func TestClaudeApprovalJournalBeyondProfile(t *testing.T) { |
| 193 | b := directToolFixture(t) |
| 194 | j, _, session, _ := directFixture(t, "claude") |
| 195 | ctx := context.Background() |
| 196 | mustJournal(t, j.BeginTurn(ctx, session, directTurn())) |
| 197 | mustJournal(t, j.consumeTurn(ctx, session.AttemptKey, session.ID, "hello")) |
| 198 | b.Journal = j |
| 199 | b.Session = session |
| 200 | b.Agent.Provider = "claude" |
| 201 | b.Agent.AgentID = session.AttemptKey |
| 202 | b.Agent.ProviderSessionID = session.ID |
| 203 | ev := provider.Event{Kind: "request", RequestID: "permission:write", SessionID: session.ID, TurnID: b.TurnID, Payload: json.RawMessage(`{"tool_name":"Write","tool_use_id":"write","input":{"file_path":"/outside/file","content":"x"}}`)} |
| 204 | l := &nativeAnswerLauncher{event: ev} |
| 205 | relay := DirectQuestionRelay{Binding: b, Launcher: l, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return b.LeaseDeadline, nil }, Answerer: func(context.Context, runnerproto.Question) (string, error) { return "person@example.com", nil }} |
| 206 | mustJournal(t, relay.Handle(ctx, ev, func(_ context.Context, q runnerproto.Question) (runnerproto.QuestionAnswer, error) { |
| 207 | if q.ValidateAnswer(runnerproto.QuestionAnswer{Behavior: "allow"}) != nil || q.ValidateAnswer(runnerproto.QuestionAnswer{Behavior: "deny"}) != nil { |
| 208 | t.Fatal("missing Allow once/Deny") |
| 209 | } |
| 210 | return runnerproto.QuestionAnswer{Behavior: "allow"}, nil |
| 211 | })) |
| 212 | var records []runnerproto.Question |
| 213 | mustJournal(t, j.readStates(ctx, "profile-approval", &records)) |
| 214 | if len(records) != 1 { |
| 215 | t.Fatal("out-of-profile approval not journaled") |
| 216 | } |
| 217 | } |
| 218 | |