| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "path/filepath" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 12 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 13 | ) |
| 14 | |
| 15 | type answerClient struct { |
| 16 | responses []provider.PermissionResponse |
| 17 | sends int |
| 18 | } |
| 19 | |
| 20 | func (c *answerClient) Respond(_ context.Context, _ provider.Agent, r provider.PermissionResponse) error { |
| 21 | c.responses = append(c.responses, r) |
| 22 | return nil |
| 23 | } |
| 24 | func (c *answerClient) Send(_ context.Context, _ provider.Agent, _, _ string) error { |
| 25 | c.sends++ |
| 26 | return nil |
| 27 | } |
| 28 | func TestQuestionPermissionID(t *testing.T) { |
| 29 | a := provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} |
| 30 | q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "original", Kind: "question", Revision: 1, RawRequest: json.RawMessage(`{"id":"original","kind":"question","provider":"claude","name":"AskUserQuestion","input":{"questions":[{"question":"Which?","header":"Which?"}]}}`)} |
| 31 | q.ExpiresAt = time.Now().Add(time.Minute) |
| 32 | c := &answerClient{} |
| 33 | answer := runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"Which?":"Yes"}}`)} |
| 34 | if err := DeliverAnswer(context.Background(), c, a, q, answer); err != nil { |
| 35 | t.Fatal(err) |
| 36 | } |
| 37 | if c.sends != 0 || len(c.responses) != 1 || c.responses[0].RequestID != "original" || string(c.responses[0].UpdatedInput) != string(answer.UpdatedInput) { |
| 38 | t.Fatal("answer must Respond with original ID and answers") |
| 39 | } |
| 40 | q.Kind = "unknown" |
| 41 | if DeliverAnswer(context.Background(), c, a, q, answer) == nil { |
| 42 | t.Fatal("unknown permission approved") |
| 43 | } |
| 44 | q.Kind = "permission" |
| 45 | if DeliverAnswer(context.Background(), c, a, q, answer) == nil { |
| 46 | t.Fatal("permission widened policy") |
| 47 | } |
| 48 | q.Kind = "question" |
| 49 | a.ProviderSessionID = "replacement" |
| 50 | if DeliverAnswer(context.Background(), c, a, q, answer) == nil { |
| 51 | t.Fatal("replaced session answered") |
| 52 | } |
| 53 | } |
| 54 | func TestQuestionFollowupAdmission(t *testing.T) { |
| 55 | c := &answerClient{} |
| 56 | a := provider.Agent{AgentID: "agent"} |
| 57 | if SendFollowup(context.Background(), c, a, "hello", "turn", nil) == nil || c.sends != 0 { |
| 58 | t.Fatal("hidden turn without admission") |
| 59 | } |
| 60 | if SendFollowup(context.Background(), c, a, "hello", "denied", func(context.Context, string) error { return runnerproto.ErrInvalid }) == nil || c.sends != 0 { |
| 61 | t.Fatal("turn sent without budget admission") |
| 62 | } |
| 63 | if err := SendFollowup(context.Background(), c, a, "hello", "turn", func(context.Context, string) error { return nil }); err != nil || c.sends != 1 { |
| 64 | t.Fatal("admitted conversational followup did not Send", err) |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | func TestQuestionDeliveryReplay(t *testing.T) { |
| 69 | j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db")) |
| 70 | mustJournal(t, err) |
| 71 | defer j.Close() |
| 72 | q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "original", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(time.Minute), RawRequest: json.RawMessage(`{"id":"original","kind":"question","provider":"claude","name":"AskUserQuestion","input":{"questions":[{"question":"Which?"}]}}`)} |
| 73 | c := &answerClient{} |
| 74 | current := true |
| 75 | relay := QuestionRelay{Journal: j, Client: c, Agent: provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) (time.Time, error) { |
| 76 | if !current { |
| 77 | return time.Time{}, runnerproto.ErrInvalid |
| 78 | } |
| 79 | return q.ExpiresAt, nil |
| 80 | }} |
| 81 | answer := runnerproto.QuestionAnswer{Behavior: "deny"} |
| 82 | mustJournal(t, relay.Deliver(context.Background(), q, answer)) |
| 83 | mustJournal(t, relay.Deliver(context.Background(), q, answer)) |
| 84 | if len(c.responses) != 1 { |
| 85 | t.Fatal("answer replay duplicated Respond") |
| 86 | } |
| 87 | answer = runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"Which?":"yes"}}`)} |
| 88 | if relay.Deliver(context.Background(), q, answer) == nil { |
| 89 | t.Fatal("changed answer replay accepted") |
| 90 | } |
| 91 | changed := q |
| 92 | changed.RawRequest = json.RawMessage(`{"id":"original","kind":"question","title":"Changed request"}`) |
| 93 | if relay.Deliver(context.Background(), changed, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil { |
| 94 | t.Fatal("changed permission request replay accepted") |
| 95 | } |
| 96 | current = false |
| 97 | if relay.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil { |
| 98 | t.Fatal("stale replay accepted") |
| 99 | } |
| 100 | } |
| 101 | func TestQuestionSanitizedFixtures(t *testing.T) { |
| 102 | for _, providerName := range []string{"claude", "codex"} { |
| 103 | name := "AskUserQuestion" |
| 104 | if providerName == "codex" { |
| 105 | name = "request_user_input" |
| 106 | } |
| 107 | payload := json.RawMessage(`{"request":{"id":"original","kind":"question","provider":"` + providerName + `","name":"` + name + `","input":{"questions":[{"question":"Which?"}],"api_token":"secret-sentinel"}}}`) |
| 108 | q, err := QuestionFromEvent(provider.RecordedEvent{PermissionID: "original", ServerID: "server", AgentID: "agent", ProviderSessionID: "session", Payload: payload}, "q", "task", []string{"secret-sentinel"}) |
| 109 | mustJournal(t, err) |
| 110 | if strings.Contains(string(q.RawRequest), "secret-sentinel") || !strings.Contains(string(q.RawRequest), "Which?") { |
| 111 | t.Fatal("sanitization lost request or leaked secret") |
| 112 | } |
| 113 | } |
| 114 | if _, err := QuestionFromEvent(provider.RecordedEvent{PermissionID: "id", Payload: json.RawMessage(`{"request":"unknown"}`)}, "q", "task", nil); err == nil { |
| 115 | t.Fatal("unsupported shape answered") |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | func TestQuestionExpiredWaitContains(t *testing.T) { |
| 120 | j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db")) |
| 121 | mustJournal(t, err) |
| 122 | defer j.Close() |
| 123 | q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(-time.Second), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} |
| 124 | c := &answerClient{} |
| 125 | r := QuestionRelay{Journal: j, Client: c, Agent: provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return q.ExpiresAt, nil }} |
| 126 | contained := 0 |
| 127 | if r.Wait(context.Background(), q, func(context.Context) (*runnerproto.QuestionAnswer, error) { |
| 128 | t.Fatal("polled expired wait") |
| 129 | return nil, nil |
| 130 | }, func(context.Context) error { contained++; return nil }) == nil || contained != 1 { |
| 131 | t.Fatal("expired wait not contained") |
| 132 | } |
| 133 | q.ExpiresAt = time.Now().Add(time.Minute) |
| 134 | if r.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil || len(c.responses) != 0 { |
| 135 | t.Fatal("expired permission ID revived") |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | type uncertainAnswerClient struct{ answerClient } |
| 140 | |
| 141 | func (c *uncertainAnswerClient) Respond(ctx context.Context, a provider.Agent, r provider.PermissionResponse) error { |
| 142 | _ = c.answerClient.Respond(ctx, a, r) |
| 143 | return provider.ErrUncertain |
| 144 | } |
| 145 | func TestQuestionUncertainDelivery(t *testing.T) { |
| 146 | path := filepath.Join(t.TempDir(), "private", "journal.db") |
| 147 | j, err := OpenJournal(context.Background(), path) |
| 148 | mustJournal(t, err) |
| 149 | q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(time.Minute), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} |
| 150 | c := &uncertainAnswerClient{} |
| 151 | r := QuestionRelay{Journal: j, Client: c, Agent: provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return q.ExpiresAt, nil }} |
| 152 | if r.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil { |
| 153 | t.Fatal("lost response treated as delivered") |
| 154 | } |
| 155 | mustJournal(t, j.Close()) |
| 156 | j, err = OpenJournal(context.Background(), path) |
| 157 | mustJournal(t, err) |
| 158 | defer j.Close() |
| 159 | r.Journal = j |
| 160 | if r.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil || len(c.responses) != 1 { |
| 161 | t.Fatal("uncertain response resent after restart") |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | func TestQuestionAnswerFormats(t *testing.T) { |
| 166 | a := runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"Which?":"yes"}}`)} |
| 167 | q := runnerproto.Question{RawRequest: json.RawMessage(`{"provider":"claude","name":"AskUserQuestion","input":{"questions":[{"question":"Which?","header":"Header"}]}}`), Kind: "question"} |
| 168 | mustJournal(t, q.ValidateAnswer(a)) |
| 169 | for _, raw := range []string{`{"answers":{"unasked":"yes"}}`, `{"answers":{"Which?":"yes"},"permissions":["all"]}`, `{"answers":{"Which?":[]}}`, `{"answers":{"Which?":""}}`, `{"answers":{"Which?":"yes","Which?":"no"}}`} { |
| 170 | bad := a |
| 171 | bad.UpdatedInput = json.RawMessage(raw) |
| 172 | if q.ValidateAnswer(bad) == nil { |
| 173 | t.Fatal("unsupported answers accepted", raw) |
| 174 | } |
| 175 | } |
| 176 | q.RawRequest = json.RawMessage(`{"provider":"codex","name":"request_user_input","input":{"questions":[{"question":"Question text","header":"Which?"}]}}`) |
| 177 | mustJournal(t, q.ValidateAnswer(a)) |
| 178 | q.RawRequest = json.RawMessage(`{"provider":"future","name":"AskUserQuestion","input":{"questions":[{"question":"Which?"}]}}`) |
| 179 | if q.ValidateAnswer(a) == nil { |
| 180 | t.Fatal("unknown provider shape approved") |
| 181 | } |
| 182 | for _, kind := range []string{"tool", "plan", "mode", "other"} { |
| 183 | if a.Validate(kind) == nil { |
| 184 | t.Fatal("permission policy widened", kind) |
| 185 | } |
| 186 | mustJournal(t, (runnerproto.QuestionAnswer{Behavior: "deny"}).Validate(kind)) |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | func TestQuestionRejectsMalformedBeforeSanitizing(t *testing.T) { |
| 191 | e := provider.RecordedEvent{PermissionID: "p", ServerID: "server", AgentID: "agent", ProviderSessionID: "session", Payload: json.RawMessage(`{"request":{"id":"p","kind":"unknown","kind":"question"}}`)} |
| 192 | if _, err := QuestionFromEvent(e, "q", "task", nil); err == nil { |
| 193 | t.Fatal("sanitization hid malformed permission") |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | func TestQuestionDeliveryBindingAndExpiry(t *testing.T) { |
| 198 | q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} |
| 199 | a := provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} |
| 200 | answer := runnerproto.QuestionAnswer{Behavior: "deny"} |
| 201 | for _, field := range []string{"server", "agent", "session", "expiry", "zero_expiry"} { |
| 202 | bad := q |
| 203 | bad.ExpiresAt = time.Now().Add(time.Minute) |
| 204 | switch field { |
| 205 | case "server": |
| 206 | bad.ServerID = "other" |
| 207 | case "agent": |
| 208 | bad.AgentID = "other" |
| 209 | case "session": |
| 210 | bad.SessionID = "other" |
| 211 | case "zero_expiry": |
| 212 | bad.ExpiresAt = time.Time{} |
| 213 | case "expiry": |
| 214 | bad.ExpiresAt = time.Now().Add(-time.Second) |
| 215 | } |
| 216 | if DeliverAnswer(context.Background(), &answerClient{}, a, bad, answer) == nil { |
| 217 | t.Fatal("answer binding accepted", field) |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | func TestQuestionWaitRenewedLease(t *testing.T) { |
| 223 | j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db")) |
| 224 | mustJournal(t, err) |
| 225 | defer j.Close() |
| 226 | q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(-time.Second), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} |
| 227 | c := &answerClient{} |
| 228 | live := time.Now().Add(time.Minute) |
| 229 | r := QuestionRelay{Journal: j, Client: c, Agent: provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}} |
| 230 | // The supervisor has renewed the lease before the earlier bound expired. |
| 231 | r.Current = func(context.Context, runnerproto.Question) (time.Time, error) { return live, nil } |
| 232 | contained := 0 |
| 233 | mustJournal(t, r.Wait(context.Background(), q, func(context.Context) (*runnerproto.QuestionAnswer, error) { |
| 234 | return &runnerproto.QuestionAnswer{Behavior: "deny"}, nil |
| 235 | }, func(context.Context) error { contained++; return nil })) |
| 236 | if len(c.responses) != 1 || contained != 0 { |
| 237 | t.Fatal("renewed wait lost answer") |
| 238 | } |
| 239 | live = time.Now().Add(-time.Second) |
| 240 | if r.Wait(context.Background(), q, func(context.Context) (*runnerproto.QuestionAnswer, error) { |
| 241 | t.Fatal("polled lost lease") |
| 242 | return nil, nil |
| 243 | }, func(context.Context) error { contained++; return nil }) == nil || contained != 1 { |
| 244 | t.Fatal("lost wait not contained") |
| 245 | } |
| 246 | live = time.Now().Add(time.Minute) |
| 247 | if r.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil || len(c.responses) != 1 { |
| 248 | t.Fatal("lost permission revived") |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | func TestQuestionWaitRenewedDuringPoll(t *testing.T) { |
| 253 | j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db")) |
| 254 | mustJournal(t, err) |
| 255 | defer j.Close() |
| 256 | q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(200 * time.Millisecond), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} |
| 257 | bound := q.ExpiresAt |
| 258 | c := &answerClient{} |
| 259 | r := QuestionRelay{Journal: j, Client: c, Agent: provider.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return bound, nil }} |
| 260 | polls := 0 |
| 261 | err = r.Wait(context.Background(), q, func(ctx context.Context) (*runnerproto.QuestionAnswer, error) { |
| 262 | polls++ |
| 263 | if polls == 1 { |
| 264 | bound = bound.Add(time.Second) |
| 265 | <-ctx.Done() |
| 266 | return nil, ctx.Err() |
| 267 | } |
| 268 | return &runnerproto.QuestionAnswer{Behavior: "deny"}, nil |
| 269 | }, func(context.Context) error { t.Error("renewal during poll contained live wait"); return nil }) |
| 270 | mustJournal(t, err) |
| 271 | if len(c.responses) != 1 { |
| 272 | t.Fatal("renewal during poll lost answer") |
| 273 | } |
| 274 | } |
| 275 | |