| 1 | package thintest |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/base64" |
| 6 | "html" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "os" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/sealbox" |
| 15 | "amadan.net/oficina/equipo/internal/wire" |
| 16 | ) |
| 17 | |
| 18 | // canaryCode is an obviously fake sign-in code. |
| 19 | const canaryCode = "CANARYCODE-not-a-real-code#CANARYSTATE" |
| 20 | |
| 21 | // signInLink is the authorize link a runner's setup-token printed (fake). |
| 22 | const signInLink = "https://claude.com/cai/oauth/authorize?code=true&client_id=fake&response_type=code&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&state=s1" |
| 23 | |
| 24 | // TestContractSignInCode (Paul, 2026-11-10): Claude with the browser |
| 25 | // elsewhere starts the runner's own setup-token (kind subscription, the |
| 26 | // card starting); the runner's link goes on the card with its attempt; |
| 27 | // a sealed code bound to the code endpoint and that attempt goes to the |
| 28 | // runner as a durable secret frame, one per card, the card waiting; a |
| 29 | // wrong code's new card takes the next; healthy turns the record into a |
| 30 | // token connection. A box the card did not ask for is refused. The |
| 31 | // code's plaintext and the box appear nowhere on the instance. |
| 32 | func TestContractSignInCode(t *testing.T) { |
| 33 | r := newRig(t) |
| 34 | rec := &recorder{} |
| 35 | r.client.HTTP.Transport = rec |
| 36 | keys := sealKeys(t) |
| 37 | runner := r.dial(0) |
| 38 | hello := held() |
| 39 | hello.Generation, hello.SealKey = runner.Welcome.Generation, keys.PublicString() |
| 40 | if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil { |
| 41 | t.Fatal(err) |
| 42 | } |
| 43 | r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) |
| 44 | var runnerID string |
| 45 | waitFor(t, "the seal key published", func() bool { |
| 46 | list, err := r.client.Runners(r.ctx) |
| 47 | if err != nil || len(list.Items) != 1 { |
| 48 | return false |
| 49 | } |
| 50 | runnerID = list.Items[0].ID |
| 51 | return list.Items[0].SealKey == keys.PublicString() |
| 52 | }) |
| 53 | |
| 54 | attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude"}) |
| 55 | if err != nil || attempt.Kind != wire.KindSubscription || attempt.Prompt == nil || attempt.Prompt.Kind != wire.PromptAuthorize || attempt.Prompt.URL != "" || attempt.Prompt.Attempt != 0 { |
| 56 | t.Fatalf("sign-in attempt %+v %v", attempt, err) |
| 57 | } |
| 58 | f, body, err := runner.Expect(r.ctx, wire.FrameConnect) |
| 59 | if err != nil { |
| 60 | t.Fatal(err) |
| 61 | } |
| 62 | if cmd := body.(*wire.ConnectCommand); cmd.Kind != wire.KindSubscription || cmd.SameMachine || cmd.Provider != "claude" { |
| 63 | t.Fatalf("connect frame %+v", cmd) |
| 64 | } |
| 65 | _ = runner.Send(r.ctx, "a-connect", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 66 | seal := func(code string, n int64, endpoint string) wire.Sealed { |
| 67 | t.Helper() |
| 68 | s, err := sealbox.Seal(keys.PublicString(), wire.SealedPayload{Secret: code, RunnerID: runnerID, ConnectionID: attempt.ID, Provider: "claude", Endpoint: endpoint, Attempt: n, ExpiresAt: time.Now().UTC().Add(wire.SealedTTL).Truncate(time.Second)}) |
| 69 | if err != nil { |
| 70 | t.Fatal(err) |
| 71 | } |
| 72 | return s |
| 73 | } |
| 74 | // No link yet: nothing to answer. |
| 75 | if _, err = r.client.Secret(r.ctx, attempt.ID, seal(canaryCode, 1, wire.EndpointClaudeCode)); Status(err) != 409 { |
| 76 | t.Fatalf("a code before the link: %v", err) |
| 77 | } |
| 78 | if err = runner.Send(r.ctx, "r-link", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: "claude", State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptAuthorize, URL: signInLink, Attempt: 1}}); err != nil { |
| 79 | t.Fatal(err) |
| 80 | } |
| 81 | r.wait("the link on the card", func(c *Conversation) bool { |
| 82 | p := c.Connections[attempt.ID].Prompt |
| 83 | return p != nil && p.URL == signInLink && p.Attempt == 1 |
| 84 | }) |
| 85 | page := html.UnescapeString(r.inst.Get(t, "/conversation/settings/connections/add")) |
| 86 | for _, want := range []string{"Open Anthropic", "Copy link", "Paste the code Anthropic shows you", `data-attempt="1"`, `data-endpoint="` + wire.EndpointClaudeCode + `"`, `data-seal-key="` + keys.PublicString() + `"`, "Paste a token you already have"} { |
| 87 | if !strings.Contains(page, want) { |
| 88 | t.Fatalf("the card lacks %q", want) |
| 89 | } |
| 90 | } |
| 91 | if strings.Contains(page, "That code did not work.") { |
| 92 | t.Fatal("a first card says the code was wrong") |
| 93 | } |
| 94 | for name, box := range map[string]wire.Sealed{ |
| 95 | "attempt 0": seal(canaryCode, 0, wire.EndpointClaudeCode), |
| 96 | "past the last": seal(canaryCode, wire.MaxCodeAttempts+1, wire.EndpointClaudeCode), |
| 97 | "a token's binding": seal(canaryCode, 1, wire.EndpointAnthropic), |
| 98 | "another endpoint": seal(canaryCode, 1, "https://platform.claude.com/oauth/other"), |
| 99 | } { |
| 100 | if _, err := r.client.Secret(r.ctx, attempt.ID, box); Status(err) != 422 { |
| 101 | t.Fatalf("%s: %v", name, err) |
| 102 | } |
| 103 | } |
| 104 | if _, err := r.client.Secret(r.ctx, attempt.ID, seal(canaryCode, 2, wire.EndpointClaudeCode)); Status(err) != 409 { |
| 105 | t.Fatalf("an attempt the card did not ask for: %v", err) |
| 106 | } |
| 107 | first := seal(canaryCode, 1, wire.EndpointClaudeCode) |
| 108 | posted, err := r.client.Secret(r.ctx, attempt.ID, first) |
| 109 | if err != nil || posted.Prompt == nil || posted.Prompt.Kind != wire.PromptAuthorize || posted.Prompt.URL != "" || posted.Prompt.Attempt != 1 { |
| 110 | t.Fatalf("code %+v %v", posted, err) |
| 111 | } |
| 112 | if _, err := r.client.Secret(r.ctx, attempt.ID, first); Status(err) != 409 { |
| 113 | t.Fatalf("a second box for one card: %v", err) |
| 114 | } |
| 115 | if page := r.inst.Get(t, "/conversation/settings/connections/add"); !strings.Contains(page, "Your runner is finishing the sign-in") || strings.Contains(page, "Open Anthropic") { |
| 116 | t.Fatal("the card does not wait for the runner") |
| 117 | } |
| 118 | f, body, err = runner.Expect(r.ctx, wire.FrameSecret) |
| 119 | if err != nil { |
| 120 | t.Fatal(err) |
| 121 | } |
| 122 | cmd := body.(*wire.SecretCommand) |
| 123 | if opened, err := keys.Open(cmd.Sealed, time.Now()); err != nil || opened.Secret != canaryCode || opened.Endpoint != wire.EndpointClaudeCode || opened.Attempt != 1 { |
| 124 | t.Fatalf("the runner's box: %v", err) |
| 125 | } |
| 126 | _ = runner.Send(r.ctx, "a-secret", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 127 | |
| 128 | // A wrong code: the runner's next card says so and takes attempt 2. |
| 129 | if err = runner.Send(r.ctx, "r-wrong", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: "claude", State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptAuthorize, URL: signInLink, Attempt: 2, WrongCode: true}}); err != nil { |
| 130 | t.Fatal(err) |
| 131 | } |
| 132 | r.wait("the wrong-code card", func(c *Conversation) bool { |
| 133 | p := c.Connections[attempt.ID].Prompt |
| 134 | return p != nil && p.Attempt == 2 && p.WrongCode && p.URL != "" |
| 135 | }) |
| 136 | if got, err := r.client.Connection(r.ctx, attempt.ID); err != nil { |
| 137 | t.Fatal(err) |
| 138 | } else { |
| 139 | shape(t, "api/connection-signing-in-claude.json", got) |
| 140 | } |
| 141 | if page := r.inst.Get(t, "/conversation/settings/connections/add"); !strings.Contains(page, "That code did not work. Open Anthropic again and paste the new code.") || !strings.Contains(page, `data-attempt="2"`) { |
| 142 | t.Fatal("the card does not say the code was wrong") |
| 143 | } |
| 144 | second := seal(canaryCode, 2, wire.EndpointClaudeCode) |
| 145 | shape(t, "api/connection-code.json", second) |
| 146 | if _, err = r.client.Secret(r.ctx, attempt.ID, second); err != nil { |
| 147 | t.Fatal(err) |
| 148 | } |
| 149 | f, _, err = runner.Expect(r.ctx, wire.FrameSecret) |
| 150 | if err != nil { |
| 151 | t.Fatal(err) |
| 152 | } |
| 153 | _ = runner.Send(r.ctx, "a-secret-2", wire.FrameAck, wire.Ack{ID: f.ID}) |
| 154 | |
| 155 | // Healthy: a token connection now, its expiry an estimate. |
| 156 | if err = runner.Send(r.ctx, "r-healthy", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, LocalID: "claude-1", Provider: "claude", State: wire.ConnHealthy, Label: Owner}); err != nil { |
| 157 | t.Fatal(err) |
| 158 | } |
| 159 | r.wait("healthy", func(c *Conversation) bool { return c.Connections[attempt.ID].State == wire.ConnHealthy }) |
| 160 | if got, err := r.client.Connection(r.ctx, attempt.ID); err != nil || got.Kind != wire.KindToken || got.ExpiresAt == nil || !got.ExpiresEstimated || got.Prompt != nil { |
| 161 | t.Fatalf("connection %+v %v", got, err) |
| 162 | } |
| 163 | |
| 164 | // A sign-in that ends refused says so plainly: not "This token was |
| 165 | // rejected", and it stays a subscription attempt. |
| 166 | other, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude"}) |
| 167 | if err != nil { |
| 168 | t.Fatal(err) |
| 169 | } |
| 170 | if err = runner.Send(r.ctx, "r-refused", wire.FrameConnection, wire.ConnectionReport{Connection: other.ID, Person: Owner, Provider: "claude", State: wire.ConnError, Reason: "provider_refused"}); err != nil { |
| 171 | t.Fatal(err) |
| 172 | } |
| 173 | r.wait("refused", func(c *Conversation) bool { return c.Connections[other.ID].State == wire.ConnError }) |
| 174 | if got, _ := r.client.Connection(r.ctx, other.ID); got.Kind != wire.KindSubscription { |
| 175 | t.Fatalf("ended %+v", got) |
| 176 | } |
| 177 | if page := r.inst.Get(t, "/conversation/settings/connections/add"); !strings.Contains(page, "The provider did not complete the sign-in.") || strings.Contains(page, "This token was rejected") { |
| 178 | t.Fatal("the ended sign-in's note") |
| 179 | } |
| 180 | |
| 181 | // The sweep: pages, API responses, events, logs, rows, database and |
| 182 | // WAL bytes. |
| 183 | var sinks []string |
| 184 | for _, path := range []string{"/conversation/settings/connections", "/conversation/settings/connections/add", "/conversation"} { |
| 185 | sinks = append(sinks, r.inst.Get(t, path)) |
| 186 | } |
| 187 | if _, err := r.client.Connections(r.ctx); err != nil { |
| 188 | t.Fatal(err) |
| 189 | } |
| 190 | var events, rows string |
| 191 | _ = r.inst.DB.Writer().QueryRow("SELECT coalesce(group_concat(body, '|'), '') FROM chat_events").Scan(&events) |
| 192 | _ = r.inst.DB.Writer().QueryRow("SELECT coalesce(group_concat(coalesce(prompt,'') || label || state || kind, '|'), '') FROM chat_connections").Scan(&rows) |
| 193 | sinks = append(sinks, rawEvents(t, r), rec.String(), r.inst.Logs(), events, rows) |
| 194 | canaries := []string{canaryCode, "CANARYCODE", "CANARYSTATE", base64.StdEncoding.EncodeToString([]byte(canaryCode))} |
| 195 | for i, s := range sinks { |
| 196 | for _, c := range canaries { |
| 197 | if strings.Contains(s, c) { |
| 198 | t.Fatalf("sink %d holds the code %q", i, c) |
| 199 | } |
| 200 | } |
| 201 | for _, box := range []wire.Sealed{first, second} { |
| 202 | if strings.Contains(s, box.Box[:24]) { |
| 203 | t.Fatalf("sink %d holds a sealed box", i) |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | for _, suffix := range []string{"", "-wal", "-shm"} { |
| 208 | raw, err := os.ReadFile(r.inst.Path + suffix) |
| 209 | if err != nil { |
| 210 | if os.IsNotExist(err) && suffix != "" { |
| 211 | continue |
| 212 | } |
| 213 | t.Fatal(err) |
| 214 | } |
| 215 | for _, c := range canaries { |
| 216 | if bytes.Contains(raw, []byte(c)) { |
| 217 | t.Fatalf("database%s holds the code %q", suffix, c) |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | // Recovering a Claude token connection is the sign-in by a link first, |
| 224 | // as on the Add page: the rejected row's Sign in again and the renewal |
| 225 | // line's Sign in again post no token kind, and start a sign-in attempt |
| 226 | // whose card offers the paste second. A rejected row says only that the |
| 227 | // token was rejected (its button says what to do). |
| 228 | func TestContractTokenRecoverySignsIn(t *testing.T) { |
| 229 | r := newRig(t) |
| 230 | soon := time.Now().UTC().Add(10 * 24 * time.Hour) |
| 231 | runner, err := DialRunnerHello(r.ctx, r.inst.URL, r.runner, held( |
| 232 | wire.HeldConnection{LocalID: "claude-8", Person: Owner, Provider: "claude", Kind: wire.KindToken, Label: "old@example.com", State: wire.ConnSignInAgain}, |
| 233 | wire.HeldConnection{LocalID: "claude-9", Person: Owner, Provider: "claude", Kind: wire.KindToken, Label: "soon@example.com", State: wire.ConnHealthy, ExpiresAt: &soon, ExpiresEstimated: true}, |
| 234 | )) |
| 235 | if err != nil { |
| 236 | t.Fatal(err) |
| 237 | } |
| 238 | t.Cleanup(runner.Close) |
| 239 | r.wait("the token connections", func(c *Conversation) bool { return len(c.Connections) == 2 }) |
| 240 | page := r.inst.Get(t, "/conversation/settings/connections") |
| 241 | rows := strings.Split(page, "<article equipo-conn-row")[1:] |
| 242 | if len(rows) != 2 { |
| 243 | t.Fatalf("%d rows", len(rows)) |
| 244 | } |
| 245 | for _, row := range rows { |
| 246 | if strings.Contains(row, `name="kind" value="token"`) { |
| 247 | t.Fatalf("a row recovers by pasting a token: %.600s", row) |
| 248 | } |
| 249 | if strings.Contains(row, "Paste a new token") || strings.Contains(row, "Run claude setup-token") { |
| 250 | t.Fatalf("a row asks for a pasted token: %.600s", row) |
| 251 | } |
| 252 | } |
| 253 | if !strings.Contains(rows[0], "data-recover") || !strings.Contains(rows[0], "This token was rejected.") || !strings.Contains(rows[1], "data-token-renew") || !strings.Contains(rows[1], "data-renew") { |
| 254 | t.Fatal("the rows lack their recovery") |
| 255 | } |
| 256 | // What the row's form posts: provider only. |
| 257 | owner := r.inst.Cookie() |
| 258 | status, _ := (&toolRig{rig: r}).post(owner, "/conversation/connections", url.Values{"provider": {"claude"}}) |
| 259 | if status != http.StatusSeeOther { |
| 260 | t.Fatalf("post %d", status) |
| 261 | } |
| 262 | _, body, err := runner.Expect(r.ctx, wire.FrameConnect) |
| 263 | if err != nil { |
| 264 | t.Fatal(err) |
| 265 | } |
| 266 | if cmd := body.(*wire.ConnectCommand); cmd.Kind != wire.KindSubscription || cmd.Provider != "claude" { |
| 267 | t.Fatalf("connect %+v", cmd) |
| 268 | } |
| 269 | if add := r.inst.Get(t, "/conversation/settings/connections/add"); !strings.Contains(add, `data-kind`) && !strings.Contains(add, "data-loading") { |
| 270 | t.Fatal("no sign-in card") |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | // "I am at this machine" is gone: the API refuses same_machine for |
| 275 | // Claude (and Codex, which never used it). |
| 276 | func TestContractSameMachineRefused(t *testing.T) { |
| 277 | r := newRig(t) |
| 278 | runner := r.dial(0) |
| 279 | r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) |
| 280 | for _, p := range []string{"claude", "codex"} { |
| 281 | if _, err := r.client.Connect(r.ctx, wire.Connect{Provider: p, SameMachine: true}); Status(err) != 422 { |
| 282 | t.Fatalf("%s at this machine: %v", p, err) |
| 283 | } |
| 284 | } |
| 285 | _ = runner |
| 286 | } |
| 287 | |