| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "net/http" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "sync/atomic" |
| 12 | "testing" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/runner/forge" |
| 16 | "amadan.net/oficina/equipo/internal/wire" |
| 17 | ) |
| 18 | |
| 19 | func TestAccessContractRequiresConfirmedFields(t *testing.T) { |
| 20 | for _, field := range []string{"target", "role", "reason", "approve_url", "expires", "state"} { |
| 21 | t.Run(field, func(t *testing.T) { |
| 22 | f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| 23 | v := accessResponse("ar_one", "pending") |
| 24 | v.Existing = true |
| 25 | raw, _ := json.Marshal(v) |
| 26 | var body map[string]any |
| 27 | json.Unmarshal(raw, &body) |
| 28 | body["events"] = []any{} |
| 29 | delete(body, field) |
| 30 | json.NewEncoder(w).Encode(body) |
| 31 | }) |
| 32 | if _, err := f.RequestAccess(context.Background(), accessCommand()); err == nil { |
| 33 | t.Fatal("incomplete existing response reused", field) |
| 34 | } |
| 35 | }) |
| 36 | } |
| 37 | } |
| 38 | func TestAccessHostileApprovalURL(t *testing.T) { |
| 39 | for _, url := range []string{"https://amadan.net/other/ar_one", "https://amadan.net/settings/agents/requests/other", "https://amadan.net/settings/agents/requests/ar_one?x=1", "https://user@amadan.net/settings/agents/requests/ar_one", "https://amadan.net/settings/agents/requests/ar_one\\other", "https://amadan.net/settings/agents/requests/%61r_one", "https://amadan.net/settings/agents/requests/ar_one#x"} { |
| 40 | t.Run(url, func(t *testing.T) { |
| 41 | f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| 42 | v := accessResponse("ar_one", "pending") |
| 43 | v.ApproveURL = url |
| 44 | w.WriteHeader(201) |
| 45 | writeAccessInfo(w, v) |
| 46 | }) |
| 47 | if _, err := f.RequestAccess(context.Background(), accessCommand()); err == nil { |
| 48 | t.Fatal("hostile approval URL accepted") |
| 49 | } |
| 50 | }) |
| 51 | } |
| 52 | var redirected atomic.Int32 |
| 53 | f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| 54 | if r.URL.Path == "/other" { |
| 55 | redirected.Add(1) |
| 56 | writeAccess(w, "ar_one", "pending") |
| 57 | return |
| 58 | } |
| 59 | http.Redirect(w, r, "/other", http.StatusFound) |
| 60 | }) |
| 61 | if _, err := f.RequestAccess(context.Background(), accessCommand()); err == nil || redirected.Load() != 0 { |
| 62 | t.Fatal("redirect followed", err) |
| 63 | } |
| 64 | } |
| 65 | func TestAccessMalformedResponseFinishesWithoutRepost(t *testing.T) { |
| 66 | var posts atomic.Int32 |
| 67 | f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| 68 | posts.Add(1) |
| 69 | w.WriteHeader(201) |
| 70 | fmt.Fprint(w, `{"id":"ar_one","state":"mystery"}`) |
| 71 | }) |
| 72 | ctx := context.Background() |
| 73 | s, err := OpenState(ctx, t.TempDir()) |
| 74 | if err != nil { |
| 75 | t.Fatal(err) |
| 76 | } |
| 77 | defer s.Close() |
| 78 | c := accessCommand() |
| 79 | s.AcceptAccess(ctx, "frame", c) |
| 80 | e := &AccessEngine{State: s, Forge: f} |
| 81 | for i := 0; i < 3; i++ { |
| 82 | if err := e.Step(ctx, c.CardID); err != nil { |
| 83 | t.Fatal(err) |
| 84 | } |
| 85 | } |
| 86 | var state string |
| 87 | s.db.QueryRow("SELECT state FROM access_requests").Scan(&state) |
| 88 | if state != "unconfirmed" || posts.Load() != 1 { |
| 89 | t.Fatal("malformed response not final and distinct", state, posts.Load()) |
| 90 | } |
| 91 | } |
| 92 | func TestAccessPermanentPollErrorsAndLocalExpiry(t *testing.T) { |
| 93 | for _, mode := range []string{"404", "401", "unknown", "expiry"} { |
| 94 | t.Run(mode, func(t *testing.T) { |
| 95 | var calls atomic.Int32 |
| 96 | f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| 97 | calls.Add(1) |
| 98 | switch mode { |
| 99 | case "404": |
| 100 | w.WriteHeader(404) |
| 101 | case "401": |
| 102 | w.WriteHeader(401) |
| 103 | case "expiry": |
| 104 | w.WriteHeader(503) |
| 105 | default: |
| 106 | v := accessResponse("ar_one", "mystery") |
| 107 | writeAccessInfo(w, v) |
| 108 | } |
| 109 | }) |
| 110 | ctx := context.Background() |
| 111 | s, err := OpenState(ctx, t.TempDir()) |
| 112 | if err != nil { |
| 113 | t.Fatal(err) |
| 114 | } |
| 115 | defer s.Close() |
| 116 | c := accessCommand() |
| 117 | s.AcceptAccess(ctx, "frame", c) |
| 118 | old := wire.AccessReport{CardID: c.CardID, Person: c.Person, RequestID: "ar_one", State: "pending", Expires: time.Now().Add(time.Hour).Unix()} |
| 119 | if mode == "expiry" { |
| 120 | old.Expires = time.Now().Add(-11 * time.Minute).Unix() |
| 121 | } |
| 122 | raw, _ := json.Marshal(old) |
| 123 | s.db.Exec("UPDATE access_requests SET state='pending',report=?", string(raw)) |
| 124 | e := &AccessEngine{State: s, Forge: f} |
| 125 | for i := 0; i < 6; i++ { |
| 126 | _ = e.Step(ctx, c.CardID) |
| 127 | } |
| 128 | var state string |
| 129 | s.db.QueryRow("SELECT state FROM access_requests").Scan(&state) |
| 130 | want := "uncheckable" |
| 131 | if mode == "404" { |
| 132 | want = "missing" |
| 133 | } |
| 134 | if mode == "expiry" { |
| 135 | want = "checking_expiry" |
| 136 | } |
| 137 | if state != want || mode != "expiry" && calls.Load() > 3 || mode == "expiry" && calls.Load() != 6 { |
| 138 | t.Fatal("poll did not finish", state, calls.Load()) |
| 139 | } |
| 140 | }) |
| 141 | } |
| 142 | } |
| 143 | func TestAccessReadGrantCannotWrite(t *testing.T) { |
| 144 | f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| 145 | if r.URL.Path == "/api/v1/repos" { |
| 146 | fmt.Fprint(w, `{"repos":[]}`) |
| 147 | return |
| 148 | } |
| 149 | fmt.Fprint(w, `{"ns":"carlos","name":"platform","tier":"private"}`) |
| 150 | }) |
| 151 | f.accessTargets = func(context.Context) ([]string, error) { return []string{"carlos/platform"}, nil } |
| 152 | ctx := context.Background() |
| 153 | repo := "amadan.net/carlos/platform" |
| 154 | if !slices.Contains(f.Reachable(ctx), repo) { |
| 155 | t.Fatal("read grant missing") |
| 156 | } |
| 157 | if remote, err := readRemote(ctx, f, repo); err != nil || remote.GitPassword == "" { |
| 158 | t.Fatal("read grant cannot fetch", err) |
| 159 | } |
| 160 | if _, err := f.Remote(ctx, repo, Push); err == nil { |
| 161 | t.Fatal("read grant got write credential") |
| 162 | } |
| 163 | if _, err := f.Merge(ctx, repo, "branch", forge.MergeRequest{}); !errors.Is(err, forge.ErrMergeRefused) { |
| 164 | t.Fatal("read grant reached merge", err) |
| 165 | } |
| 166 | if _, err := f.ciCredential(ctx, repo); !errors.Is(err, forge.ErrCIRead) { |
| 167 | t.Fatal("read grant got CI credential", err) |
| 168 | } |
| 169 | } |
| 170 | func TestAccessDowngradeRefusesBeforeQueue(t *testing.T) { |
| 171 | b := &bridge{speaks: wire.Protocol25, trip: func(context.Context, wire.ToolCall) wire.ToolResult { |
| 172 | t.Fatal("unsupported tool sent") |
| 173 | return wire.ToolResult{} |
| 174 | }} |
| 175 | got := b.roundTrip(context.Background(), wire.ToolCall{Name: wire.ToolRequestAccess}) |
| 176 | if !got.IsError || !strings.Contains(got.Code, "unsupported") { |
| 177 | t.Fatal(got) |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | type accessQueueForge struct{ filed chan string } |
| 182 | |
| 183 | func (f *accessQueueForge) RequestAccess(_ context.Context, c wire.AccessCommand) (wire.AccessReport, error) { |
| 184 | f.filed <- c.CardID |
| 185 | return wire.AccessReport{RequestID: c.CardID, State: "limited"}, nil |
| 186 | } |
| 187 | func (*accessQueueForge) PollAccess(ctx context.Context, _ string, _ wire.AccessCommand) (wire.AccessReport, error) { |
| 188 | <-ctx.Done() |
| 189 | return wire.AccessReport{}, ctx.Err() |
| 190 | } |
| 191 | func (*accessQueueForge) Recheck() {} |
| 192 | func (*accessQueueForge) Reachable(context.Context) []string { return nil } |
| 193 | func TestAccessSixthConfirmationDoesNotStarve(t *testing.T) { |
| 194 | ctx, cancel := context.WithCancel(context.Background()) |
| 195 | s, err := OpenState(ctx, t.TempDir()) |
| 196 | if err != nil { |
| 197 | t.Fatal(err) |
| 198 | } |
| 199 | defer s.Close() |
| 200 | f := &accessQueueForge{filed: make(chan string, 2)} |
| 201 | for i := 0; i < 5; i++ { |
| 202 | c := accessCommand() |
| 203 | c.CardID = fmt.Sprint("pending", i) |
| 204 | s.AcceptAccess(ctx, c.CardID, c) |
| 205 | raw, _ := json.Marshal(wire.AccessReport{RequestID: c.CardID, State: "pending", Expires: time.Now().Add(time.Hour).Unix()}) |
| 206 | s.db.Exec("UPDATE access_requests SET state='pending',report=? WHERE card_id=?", string(raw), c.CardID) |
| 207 | } |
| 208 | done := make(chan struct{}) |
| 209 | e := &AccessEngine{State: s, Forge: f} |
| 210 | go func() { e.Run(ctx); close(done) }() |
| 211 | defer func() { cancel(); <-done }() |
| 212 | time.Sleep(1200 * time.Millisecond) |
| 213 | for _, id := range []string{"z-first-confirmed", "a-second-confirmed"} { |
| 214 | c := accessCommand() |
| 215 | c.CardID = id |
| 216 | s.AcceptAccess(ctx, id, c) |
| 217 | } |
| 218 | for _, want := range []string{"z-first-confirmed", "a-second-confirmed"} { |
| 219 | select { |
| 220 | case got := <-f.filed: |
| 221 | if got != want { |
| 222 | t.Fatal("confirmation order", got, want) |
| 223 | } |
| 224 | case <-time.After(2500 * time.Millisecond): |
| 225 | t.Fatal("new confirmation starved behind polls") |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | func TestAccessToolsAndPromptFollowProtocol(t *testing.T) { |
| 231 | for _, proto := range []int{25, 26} { |
| 232 | c := coordBase{o: ClaudeOptions{Protocol: func() int { return proto }}, profile: profileFor(wire.LaneCoordinator)} |
| 233 | offered := slices.Contains(c.accessToolSet(true).names, wire.ToolRequestAccess) |
| 234 | prompted := strings.Contains(c.accessOpening(nil), "request_access") |
| 235 | if offered != (proto >= 26) || prompted != (proto >= 26) { |
| 236 | t.Fatal("wrong tool or prompt at protocol", proto, offered, prompted) |
| 237 | } |
| 238 | } |
| 239 | } |
| 240 | func TestAccessUnencodableCallIsRetired(t *testing.T) { |
| 241 | ctx := context.Background() |
| 242 | s, err := OpenState(ctx, t.TempDir()) |
| 243 | if err != nil { |
| 244 | t.Fatal(err) |
| 245 | } |
| 246 | defer s.Close() |
| 247 | call := wire.ToolCall{CallID: "call", TurnID: "finished-turn", Name: wire.ToolRequestAccess, Args: json.RawMessage(`{}`)} |
| 248 | if err := s.SendToolCall(ctx, call); err != nil { |
| 249 | t.Fatal(err) |
| 250 | } |
| 251 | frames, _, err := s.Unacked(ctx, 0) |
| 252 | if err != nil || len(frames) != 1 { |
| 253 | t.Fatal(err, frames) |
| 254 | } |
| 255 | l := &Link{State: s, proto: 25} |
| 256 | wait := l.waitTool(call.CallID) |
| 257 | if err := l.send(ctx, nil, frames[0]); err != nil { |
| 258 | t.Fatal(err) |
| 259 | } |
| 260 | select { |
| 261 | case res := <-wait: |
| 262 | if res.Code != "access_unsupported" { |
| 263 | t.Fatal(res) |
| 264 | } |
| 265 | default: |
| 266 | t.Fatal("no immediate unsupported result") |
| 267 | } |
| 268 | frames, _, err = s.Unacked(ctx, 0) |
| 269 | if err != nil || len(frames) != 0 { |
| 270 | t.Fatal("old call can replay after upgrade", frames, err) |
| 271 | } |
| 272 | } |
| 273 | func TestAccessWorkerCommandRefused(t *testing.T) { |
| 274 | ctx := context.Background() |
| 275 | s, err := OpenState(ctx, t.TempDir()) |
| 276 | if err != nil { |
| 277 | t.Fatal(err) |
| 278 | } |
| 279 | defer s.Close() |
| 280 | l := &Link{State: s, Role: wire.RoleWorker, Access: &AccessEngine{State: s}} |
| 281 | if err := l.acceptAccess(ctx, "frame", accessCommand()); err == nil { |
| 282 | t.Fatal("worker accepted access command") |
| 283 | } |
| 284 | var n int |
| 285 | s.db.QueryRow("SELECT count(*) FROM access_requests").Scan(&n) |
| 286 | if n != 0 { |
| 287 | t.Fatal("worker persisted command") |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | func TestAccessExistingScopeAndReasonMustMatch(t *testing.T) { |
| 292 | for _, field := range []string{"target", "reason"} { |
| 293 | t.Run(field, func(t *testing.T) { |
| 294 | f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| 295 | v := accessResponse("ar_one", "pending") |
| 296 | v.Existing = true |
| 297 | if field == "target" { |
| 298 | v.Target = "carlos" |
| 299 | v.Repo = "" |
| 300 | } else { |
| 301 | v.Reason = "A different request." |
| 302 | } |
| 303 | writeAccessInfo(w, v) |
| 304 | }) |
| 305 | if _, err := f.RequestAccess(context.Background(), accessCommand()); err == nil { |
| 306 | t.Fatal("different confirmed request reused", field) |
| 307 | } |
| 308 | }) |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | func TestAccessWithdrawnLeaseDoesNotPoisonStream(t *testing.T) { |
| 313 | ctx := context.Background() |
| 314 | s, err := OpenState(ctx, t.TempDir()) |
| 315 | if err != nil { |
| 316 | t.Fatal(err) |
| 317 | } |
| 318 | defer s.Close() |
| 319 | c := accessCommand() |
| 320 | s.AcceptAccess(ctx, "frame", c) |
| 321 | e := &AccessEngine{State: s, Authorize: func(context.Context, string) error { return ErrWithdrawn }} |
| 322 | if err := e.Step(ctx, c.CardID); err != nil { |
| 323 | t.Fatal(err) |
| 324 | } |
| 325 | frames, _, err := s.Unacked(ctx, 0) |
| 326 | if err != nil || len(frames) != 0 { |
| 327 | t.Fatal("demoted runner repeats a report it cannot submit", frames, err) |
| 328 | } |
| 329 | var state string |
| 330 | s.db.QueryRow("SELECT state FROM access_requests").Scan(&state) |
| 331 | if state != "authority" { |
| 332 | t.Fatal(state) |
| 333 | } |
| 334 | } |
| 335 | |