package thin import ( "context" "encoding/json" "errors" "fmt" "net/http" "slices" "strings" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/runner/forge" "amadan.net/oficina/equipo/internal/wire" ) func TestAccessContractRequiresConfirmedFields(t *testing.T) { for _, field := range []string{"target", "role", "reason", "approve_url", "expires", "state"} { t.Run(field, func(t *testing.T) { f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { v := accessResponse("ar_one", "pending") v.Existing = true raw, _ := json.Marshal(v) var body map[string]any json.Unmarshal(raw, &body) body["events"] = []any{} delete(body, field) json.NewEncoder(w).Encode(body) }) if _, err := f.RequestAccess(context.Background(), accessCommand()); err == nil { t.Fatal("incomplete existing response reused", field) } }) } } func TestAccessHostileApprovalURL(t *testing.T) { 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"} { t.Run(url, func(t *testing.T) { f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { v := accessResponse("ar_one", "pending") v.ApproveURL = url w.WriteHeader(201) writeAccessInfo(w, v) }) if _, err := f.RequestAccess(context.Background(), accessCommand()); err == nil { t.Fatal("hostile approval URL accepted") } }) } var redirected atomic.Int32 f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/other" { redirected.Add(1) writeAccess(w, "ar_one", "pending") return } http.Redirect(w, r, "/other", http.StatusFound) }) if _, err := f.RequestAccess(context.Background(), accessCommand()); err == nil || redirected.Load() != 0 { t.Fatal("redirect followed", err) } } func TestAccessMalformedResponseFinishesWithoutRepost(t *testing.T) { var posts atomic.Int32 f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { posts.Add(1) w.WriteHeader(201) fmt.Fprint(w, `{"id":"ar_one","state":"mystery"}`) }) ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() c := accessCommand() s.AcceptAccess(ctx, "frame", c) e := &AccessEngine{State: s, Forge: f} for i := 0; i < 3; i++ { if err := e.Step(ctx, c.CardID); err != nil { t.Fatal(err) } } var state string s.db.QueryRow("SELECT state FROM access_requests").Scan(&state) if state != "unconfirmed" || posts.Load() != 1 { t.Fatal("malformed response not final and distinct", state, posts.Load()) } } func TestAccessPermanentPollErrorsAndLocalExpiry(t *testing.T) { for _, mode := range []string{"404", "401", "unknown", "expiry"} { t.Run(mode, func(t *testing.T) { var calls atomic.Int32 f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { calls.Add(1) switch mode { case "404": w.WriteHeader(404) case "401": w.WriteHeader(401) case "expiry": w.WriteHeader(503) default: v := accessResponse("ar_one", "mystery") writeAccessInfo(w, v) } }) ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() c := accessCommand() s.AcceptAccess(ctx, "frame", c) old := wire.AccessReport{CardID: c.CardID, Person: c.Person, RequestID: "ar_one", State: "pending", Expires: time.Now().Add(time.Hour).Unix()} if mode == "expiry" { old.Expires = time.Now().Add(-11 * time.Minute).Unix() } raw, _ := json.Marshal(old) s.db.Exec("UPDATE access_requests SET state='pending',report=?", string(raw)) e := &AccessEngine{State: s, Forge: f} for i := 0; i < 6; i++ { _ = e.Step(ctx, c.CardID) } var state string s.db.QueryRow("SELECT state FROM access_requests").Scan(&state) want := "uncheckable" if mode == "404" { want = "missing" } if mode == "expiry" { want = "checking_expiry" } if state != want || mode != "expiry" && calls.Load() > 3 || mode == "expiry" && calls.Load() != 6 { t.Fatal("poll did not finish", state, calls.Load()) } }) } } func TestAccessReadGrantCannotWrite(t *testing.T) { f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/api/v1/repos" { fmt.Fprint(w, `{"repos":[]}`) return } fmt.Fprint(w, `{"ns":"carlos","name":"platform","tier":"private"}`) }) f.accessTargets = func(context.Context) ([]string, error) { return []string{"carlos/platform"}, nil } ctx := context.Background() repo := "amadan.net/carlos/platform" if !slices.Contains(f.Reachable(ctx), repo) { t.Fatal("read grant missing") } if remote, err := readRemote(ctx, f, repo); err != nil || remote.GitPassword == "" { t.Fatal("read grant cannot fetch", err) } if _, err := f.Remote(ctx, repo, Push); err == nil { t.Fatal("read grant got write credential") } if _, err := f.Merge(ctx, repo, "branch", forge.MergeRequest{}); !errors.Is(err, forge.ErrMergeRefused) { t.Fatal("read grant reached merge", err) } if _, err := f.ciCredential(ctx, repo); !errors.Is(err, forge.ErrCIRead) { t.Fatal("read grant got CI credential", err) } } func TestAccessDowngradeRefusesBeforeQueue(t *testing.T) { b := &bridge{speaks: wire.Protocol25, trip: func(context.Context, wire.ToolCall) wire.ToolResult { t.Fatal("unsupported tool sent") return wire.ToolResult{} }} got := b.roundTrip(context.Background(), wire.ToolCall{Name: wire.ToolRequestAccess}) if !got.IsError || !strings.Contains(got.Code, "unsupported") { t.Fatal(got) } } type accessQueueForge struct{ filed chan string } func (f *accessQueueForge) RequestAccess(_ context.Context, c wire.AccessCommand) (wire.AccessReport, error) { f.filed <- c.CardID return wire.AccessReport{RequestID: c.CardID, State: "limited"}, nil } func (*accessQueueForge) PollAccess(ctx context.Context, _ string, _ wire.AccessCommand) (wire.AccessReport, error) { <-ctx.Done() return wire.AccessReport{}, ctx.Err() } func (*accessQueueForge) Recheck() {} func (*accessQueueForge) Reachable(context.Context) []string { return nil } func TestAccessSixthConfirmationDoesNotStarve(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() f := &accessQueueForge{filed: make(chan string, 2)} for i := 0; i < 5; i++ { c := accessCommand() c.CardID = fmt.Sprint("pending", i) s.AcceptAccess(ctx, c.CardID, c) raw, _ := json.Marshal(wire.AccessReport{RequestID: c.CardID, State: "pending", Expires: time.Now().Add(time.Hour).Unix()}) s.db.Exec("UPDATE access_requests SET state='pending',report=? WHERE card_id=?", string(raw), c.CardID) } done := make(chan struct{}) e := &AccessEngine{State: s, Forge: f} go func() { e.Run(ctx); close(done) }() defer func() { cancel(); <-done }() time.Sleep(1200 * time.Millisecond) for _, id := range []string{"z-first-confirmed", "a-second-confirmed"} { c := accessCommand() c.CardID = id s.AcceptAccess(ctx, id, c) } for _, want := range []string{"z-first-confirmed", "a-second-confirmed"} { select { case got := <-f.filed: if got != want { t.Fatal("confirmation order", got, want) } case <-time.After(2500 * time.Millisecond): t.Fatal("new confirmation starved behind polls") } } } func TestAccessToolsAndPromptFollowProtocol(t *testing.T) { for _, proto := range []int{25, 26} { c := coordBase{o: ClaudeOptions{Protocol: func() int { return proto }}, profile: profileFor(wire.LaneCoordinator)} offered := slices.Contains(c.accessToolSet(true).names, wire.ToolRequestAccess) prompted := strings.Contains(c.accessOpening(nil), "request_access") if offered != (proto >= 26) || prompted != (proto >= 26) { t.Fatal("wrong tool or prompt at protocol", proto, offered, prompted) } } } func TestAccessUnencodableCallIsRetired(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() call := wire.ToolCall{CallID: "call", TurnID: "finished-turn", Name: wire.ToolRequestAccess, Args: json.RawMessage(`{}`)} if err := s.SendToolCall(ctx, call); err != nil { t.Fatal(err) } frames, _, err := s.Unacked(ctx, 0) if err != nil || len(frames) != 1 { t.Fatal(err, frames) } l := &Link{State: s, proto: 25} wait := l.waitTool(call.CallID) if err := l.send(ctx, nil, frames[0]); err != nil { t.Fatal(err) } select { case res := <-wait: if res.Code != "access_unsupported" { t.Fatal(res) } default: t.Fatal("no immediate unsupported result") } frames, _, err = s.Unacked(ctx, 0) if err != nil || len(frames) != 0 { t.Fatal("old call can replay after upgrade", frames, err) } } func TestAccessWorkerCommandRefused(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() l := &Link{State: s, Role: wire.RoleWorker, Access: &AccessEngine{State: s}} if err := l.acceptAccess(ctx, "frame", accessCommand()); err == nil { t.Fatal("worker accepted access command") } var n int s.db.QueryRow("SELECT count(*) FROM access_requests").Scan(&n) if n != 0 { t.Fatal("worker persisted command") } } func TestAccessExistingScopeAndReasonMustMatch(t *testing.T) { for _, field := range []string{"target", "reason"} { t.Run(field, func(t *testing.T) { f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { v := accessResponse("ar_one", "pending") v.Existing = true if field == "target" { v.Target = "carlos" v.Repo = "" } else { v.Reason = "A different request." } writeAccessInfo(w, v) }) if _, err := f.RequestAccess(context.Background(), accessCommand()); err == nil { t.Fatal("different confirmed request reused", field) } }) } } func TestAccessWithdrawnLeaseDoesNotPoisonStream(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() c := accessCommand() s.AcceptAccess(ctx, "frame", c) e := &AccessEngine{State: s, Authorize: func(context.Context, string) error { return ErrWithdrawn }} if err := e.Step(ctx, c.CardID); err != nil { t.Fatal(err) } frames, _, err := s.Unacked(ctx, 0) if err != nil || len(frames) != 0 { t.Fatal("demoted runner repeats a report it cannot submit", frames, err) } var state string s.db.QueryRow("SELECT state FROM access_requests").Scan(&state) if state != "authority" { t.Fatal(state) } }