| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "net/http" |
| 8 | "slices" |
| 9 | "strings" |
| 10 | "sync/atomic" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | "github.com/coder/websocket" |
| 16 | ) |
| 17 | |
| 18 | func TestAccessUnknownProtocolQueuesDurably(t *testing.T) { |
| 19 | ctx := context.Background() |
| 20 | s, err := OpenState(ctx, t.TempDir()) |
| 21 | if err != nil { |
| 22 | t.Fatal(err) |
| 23 | } |
| 24 | defer s.Close() |
| 25 | l := &Link{State: s} |
| 26 | b := &bridge{Link: l, State: s} |
| 27 | call := wire.ToolCall{CallID: "offline", TurnID: "turn", Name: wire.ToolRequestAccess, Args: json.RawMessage(`{}`)} |
| 28 | cancelctx, cancel := context.WithCancel(ctx) |
| 29 | defer cancel() |
| 30 | result := make(chan wire.ToolResult, 1) |
| 31 | go func() { result <- b.roundTrip(cancelctx, call) }() |
| 32 | deadline := time.Now().Add(2 * time.Second) |
| 33 | for { |
| 34 | frames, _, err := s.Unacked(ctx, 0) |
| 35 | if err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | if len(frames) == 1 { |
| 39 | break |
| 40 | } |
| 41 | select { |
| 42 | case got := <-result: |
| 43 | t.Fatal("offline tool was not queued", got) |
| 44 | default: |
| 45 | } |
| 46 | if time.Now().After(deadline) { |
| 47 | t.Fatal("offline tool not durably queued") |
| 48 | } |
| 49 | time.Sleep(time.Millisecond) |
| 50 | } |
| 51 | cancel() |
| 52 | if got := <-result; got.Code == "access_unsupported" { |
| 53 | t.Fatal("disconnected request refused as old protocol") |
| 54 | } |
| 55 | c := coordBase{o: ClaudeOptions{Protocol: func() int { p, _ := l.Spoken(); return p }}, profile: profileFor(wire.LaneCoordinator)} |
| 56 | if !slices.Contains(c.accessToolSet(true).names, wire.ToolRequestAccess) || !strings.Contains(c.accessOpening(nil), "request_access") || strings.Contains(c.sessionAccount(), "legacy") { |
| 57 | t.Fatal("unknown protocol removes tools or changes session key") |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | func TestAccessDisconnectKeepsNegotiatedSession(t *testing.T) { |
| 62 | for _, proto := range []int{25, 26} { |
| 63 | t.Run(fmt.Sprint(proto), func(t *testing.T) { |
| 64 | ctx := context.Background() |
| 65 | s, err := OpenState(ctx, t.TempDir()) |
| 66 | if err != nil { |
| 67 | t.Fatal(err) |
| 68 | } |
| 69 | defer s.Close() |
| 70 | l := &Link{proto: proto, conn: &websocket.Conn{}} |
| 71 | c := coordBase{o: ClaudeOptions{Protocol: l.LastProtocol}, profile: profileFor(wire.LaneCoordinator)} |
| 72 | key := c.sessionAccount() |
| 73 | tools := slices.Clone(c.accessToolSet(true).names) |
| 74 | capability := c.accessProtocol() >= wire.ProtocolAccess |
| 75 | for _, provider := range []string{"claude", "codex"} { |
| 76 | if err := s.saveSession(ctx, "person", wire.LaneCoordinator, provider, key, "resume-id", "turn"); err != nil { |
| 77 | t.Fatal(err) |
| 78 | } |
| 79 | } |
| 80 | l.conn = nil |
| 81 | if c.accessProtocol() >= wire.ProtocolAccess != capability { |
| 82 | t.Fatal("disconnect rotates coordinator capability") |
| 83 | } |
| 84 | if c.sessionAccount() != key || !slices.Equal(tools, c.accessToolSet(true).names) { |
| 85 | t.Fatal("disconnect changes session key or tools") |
| 86 | } |
| 87 | _, refused := accessRefused(wire.ToolCall{Name: wire.ToolRequestAccess}, (&bridge{Link: l}).spoken()) |
| 88 | if refused != (proto < 26) { |
| 89 | t.Fatal("disconnected link forgot negotiation") |
| 90 | } |
| 91 | for _, provider := range []string{"claude", "codex"} { |
| 92 | if err := s.saveSession(ctx, "person", wire.LaneCoordinator, provider, c.sessionAccount(), "resume-id", "turn"); err != nil { |
| 93 | t.Fatal(err) |
| 94 | } |
| 95 | } |
| 96 | l.conn = &websocket.Conn{} |
| 97 | for _, provider := range []string{"claude", "codex"} { |
| 98 | row, ok, err := s.session(ctx, "person", wire.LaneCoordinator, provider) |
| 99 | if err != nil || !ok || row.Account != c.sessionAccount() || row.SessionID != "resume-id" { |
| 100 | t.Fatal("reconnect loses provider resume", provider, row, err) |
| 101 | } |
| 102 | } |
| 103 | if proto == 26 && strings.Contains(key, "legacy") { |
| 104 | t.Fatal("protocol 26 legacy key") |
| 105 | } |
| 106 | }) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | func TestAccessPostFinalOutcomes(t *testing.T) { |
| 111 | for _, status := range []int{404, 409} { |
| 112 | t.Run(fmt.Sprint(status), func(t *testing.T) { |
| 113 | var posts, lists, refresh atomic.Int32 |
| 114 | f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| 115 | if r.URL.Path == "/api/v1/repos" { |
| 116 | lists.Add(1) |
| 117 | fmt.Fprint(w, `{"repos":[]}`) |
| 118 | return |
| 119 | } |
| 120 | posts.Add(1) |
| 121 | w.WriteHeader(status) |
| 122 | }) |
| 123 | ctx := context.Background() |
| 124 | s, err := OpenState(ctx, t.TempDir()) |
| 125 | if err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | defer s.Close() |
| 129 | c := accessCommand() |
| 130 | if err := s.AcceptAccess(ctx, "frame", c); err != nil { |
| 131 | t.Fatal(err) |
| 132 | } |
| 133 | e := &AccessEngine{State: s, Forge: f, Refresh: func() { refresh.Add(1) }} |
| 134 | for i := 0; i < 3; i++ { |
| 135 | if err := e.Step(ctx, c.CardID); err != nil { |
| 136 | t.Fatal(err) |
| 137 | } |
| 138 | } |
| 139 | var state string |
| 140 | s.db.QueryRow("SELECT state FROM access_requests").Scan(&state) |
| 141 | want := "not_owned" |
| 142 | if status == 409 { |
| 143 | want = "already" |
| 144 | } |
| 145 | if state != want || !wire.AccessFinal(state) || posts.Load() != 1 { |
| 146 | t.Fatal("POST outcome is not distinct and final", state, posts.Load()) |
| 147 | } |
| 148 | if status == 409 && (refresh.Load() != 1 || lists.Load() != 1) { |
| 149 | t.Fatal("already-access did not refresh catalog", refresh.Load(), lists.Load()) |
| 150 | } |
| 151 | if status == 404 && refresh.Load() != 0 { |
| 152 | t.Fatal("not-owned refreshed catalog") |
| 153 | } |
| 154 | }) |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | func TestAccessExpiryClockMarginAndReconciliation(t *testing.T) { |
| 159 | for _, mode := range []string{"margin", "server_pending", "server_approved", "offline_then_approved", "server_expired"} { |
| 160 | t.Run(mode, func(t *testing.T) { |
| 161 | var gets, refresh atomic.Int32 |
| 162 | var online atomic.Bool |
| 163 | online.Store(mode != "margin" && mode != "offline_then_approved") |
| 164 | f := accessForge(t, func(w http.ResponseWriter, r *http.Request) { |
| 165 | if r.URL.Path == "/api/v1/repos" { |
| 166 | fmt.Fprint(w, `{"repos":[]}`) |
| 167 | return |
| 168 | } |
| 169 | gets.Add(1) |
| 170 | if !online.Load() { |
| 171 | w.WriteHeader(503) |
| 172 | return |
| 173 | } |
| 174 | state := "approved" |
| 175 | if mode == "server_pending" { |
| 176 | state = "pending" |
| 177 | } |
| 178 | if mode == "server_expired" { |
| 179 | state = "expired" |
| 180 | } |
| 181 | v := accessResponse("ar_one", state) |
| 182 | v.Created = time.Now().Add(-72 * time.Hour).Unix() |
| 183 | v.Expires = time.Now().Add(-20 * time.Minute).Unix() |
| 184 | writeAccessInfo(w, v) |
| 185 | }) |
| 186 | ctx := context.Background() |
| 187 | dir := t.TempDir() |
| 188 | s, err := OpenState(ctx, dir) |
| 189 | if err != nil { |
| 190 | t.Fatal(err) |
| 191 | } |
| 192 | defer func() { s.Close() }() |
| 193 | c := accessCommand() |
| 194 | s.AcceptAccess(ctx, "frame", c) |
| 195 | expires := time.Now().Add(-20 * time.Minute).Unix() |
| 196 | if mode == "margin" { |
| 197 | expires = time.Now().Add(-5 * time.Minute).Unix() |
| 198 | } |
| 199 | old := wire.AccessReport{CardID: c.CardID, Person: c.Person, RequestID: "ar_one", State: "pending", ApproveURL: "https://amadan.net/settings/agents/requests/ar_one", Expires: expires} |
| 200 | raw, _ := json.Marshal(old) |
| 201 | s.db.Exec("UPDATE access_requests SET state='pending',report=?", string(raw)) |
| 202 | e := &AccessEngine{State: s, Forge: f, Refresh: func() { refresh.Add(1) }} |
| 203 | _ = e.Step(ctx, c.CardID) |
| 204 | var report string |
| 205 | s.db.QueryRow("SELECT report FROM access_requests").Scan(&report) |
| 206 | var got wire.AccessReport |
| 207 | json.Unmarshal([]byte(report), &got) |
| 208 | want := "approved" |
| 209 | switch mode { |
| 210 | case "margin", "server_pending": |
| 211 | want = "pending" |
| 212 | case "offline_then_approved", "server_expired": |
| 213 | want = "expired" |
| 214 | } |
| 215 | if got.State != want || gets.Load() != 1 { |
| 216 | t.Fatal("clock overrode server or safety margin", got.State, want, gets.Load()) |
| 217 | } |
| 218 | if mode == "offline_then_approved" { |
| 219 | s.Close() |
| 220 | s, err = OpenState(ctx, dir) |
| 221 | if err != nil { |
| 222 | t.Fatal(err) |
| 223 | } |
| 224 | e.State = s |
| 225 | online.Store(true) |
| 226 | runctx, stop := context.WithCancel(ctx) |
| 227 | done := make(chan struct{}) |
| 228 | go func() { e.Run(runctx); close(done) }() |
| 229 | deadline := time.Now().Add(3 * time.Second) |
| 230 | for refresh.Load() == 0 && time.Now().Before(deadline) { |
| 231 | time.Sleep(10 * time.Millisecond) |
| 232 | } |
| 233 | stop() |
| 234 | <-done |
| 235 | |
| 236 | s.db.QueryRow("SELECT report FROM access_requests").Scan(&report) |
| 237 | json.Unmarshal([]byte(report), &got) |
| 238 | if got.State != "approved" || refresh.Load() != 1 { |
| 239 | t.Fatal("local expiry lost later approval after restart", got, refresh.Load()) |
| 240 | } |
| 241 | } |
| 242 | if mode == "server_expired" { |
| 243 | _ = e.Step(ctx, c.CardID) |
| 244 | if gets.Load() != 1 { |
| 245 | t.Fatal("server expiry is not final") |
| 246 | } |
| 247 | } |
| 248 | }) |
| 249 | } |
| 250 | } |
| 251 | |