package thintest import ( "bytes" "context" "crypto/ed25519" "crypto/rand" "encoding/base64" "io" "net/http" "os" "strconv" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/wire" ) // canaryToken is an obviously fake setup token: it is sealed in the test // and must never appear on the instance. const canaryToken = "sk-ant-oat01-CANARY-not-a-real-token-CANARY" // recorder keeps every response body the client read. type recorder struct { mu sync.Mutex seen bytes.Buffer } func (r *recorder) RoundTrip(req *http.Request) (*http.Response, error) { res, err := http.DefaultTransport.RoundTrip(req) if err != nil { return res, err } raw, err := io.ReadAll(res.Body) res.Body.Close() r.mu.Lock() r.seen.Write(raw) r.mu.Unlock() res.Body = io.NopCloser(bytes.NewReader(raw)) return res, err } func (r *recorder) String() string { r.mu.Lock() defer r.mu.Unlock() return r.seen.String() } // sealKeys is a runner's seal key pair from a fresh enrolment key. func sealKeys(t *testing.T) sealbox.Keys { t.Helper() _, private, err := ed25519.GenerateKey(rand.Reader) if err != nil { t.Fatal(err) } keys, err := sealbox.FromEd25519(private) if err != nil { t.Fatal(err) } return keys } // rawEvents reads the person's event stream from the start as it is // served, for a moment. func rawEvents(t *testing.T, r *rig) string { t.Helper() ctx, cancel := context.WithTimeout(r.ctx, 1500*time.Millisecond) defer cancel() req, _ := http.NewRequestWithContext(ctx, "GET", r.inst.URL+"/api/v1/events?after=0", nil) req.Header.Set("Authorization", "Bearer "+r.client.Token) req.Header.Set("Accept", "text/event-stream") res, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } defer res.Body.Close() raw, _ := io.ReadAll(res.Body) if !bytes.Contains(raw, []byte("event: connection")) { t.Fatalf("the stream served no connection events: %.400s", raw) } return string(raw) } // TestContractTokenConnection (Paul, 2026-11-09; spec ยง2.4): the runner's // seal key is published; a Claude token attempt shows the token card and // goes to the runner as connect (kind token); a sealed box whose clear // binding is not this attempt's is refused; one that is goes to the // runner as a durable secret frame and is blanked once acked. The // canary's plaintext appears nowhere on the instance (database and WAL // bytes, events, responses, pages, logs) and the box nowhere but the // mailbox until the ack. func TestContractTokenConnection(t *testing.T) { r := newRig(t) rec := &recorder{} r.client.HTTP.Transport = rec keys := sealKeys(t) runner := r.dial(0) hello := held() hello.Generation, hello.SealKey = runner.Welcome.Generation, keys.PublicString() if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil { t.Fatal(err) } r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) var runnerID string waitFor(t, "the seal key published", func() bool { list, err := r.client.Runners(r.ctx) if err != nil || len(list.Items) != 1 { return false } runnerID = list.Items[0].ID return list.Items[0].SealKey == keys.PublicString() }) if snap, err := r.client.Snapshot(r.ctx); err != nil || snap.Runner.SealKey != keys.PublicString() { t.Fatalf("snapshot runner %+v %v", snap.Runner, err) } if _, err := r.client.Connect(r.ctx, wire.Connect{Provider: "codex", Kind: wire.KindToken}); Status(err) != 422 { t.Fatalf("a Codex token attempt: %v", err) } attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude", Kind: wire.KindToken}) if err != nil || attempt.State != wire.ConnConnecting || attempt.Kind != wire.KindToken || attempt.Prompt == nil || attempt.Prompt.Kind != wire.PromptToken || attempt.Prompt.Code != "claude setup-token" || attempt.RunnerID != runnerID { t.Fatalf("token attempt %+v %v", attempt, err) } f, body, err := runner.Expect(r.ctx, wire.FrameConnect) if err != nil { t.Fatal(err) } if cmd := body.(*wire.ConnectCommand); cmd.Connection != attempt.ID || cmd.Kind != wire.KindToken || cmd.Provider != "claude" { t.Fatalf("connect frame %+v", cmd) } if err = runner.Send(r.ctx, "a-connect", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil { t.Fatal(err) } expires := time.Now().UTC().Add(wire.SealedTTL).Truncate(time.Second) sealed, err := sealbox.Seal(keys.PublicString(), wire.SealedPayload{Secret: canaryToken, RunnerID: runnerID, ConnectionID: attempt.ID, Provider: "claude", Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: expires}) if err != nil { t.Fatal(err) } for name, change := range map[string]func(*wire.Sealed){ "another runner": func(s *wire.Sealed) { s.RunnerID = "rn_other" }, "another connection": func(s *wire.Sealed) { s.ConnectionID = "cn_other" }, "another provider": func(s *wire.Sealed) { s.Provider = "codex" }, "another endpoint": func(s *wire.Sealed) { s.Endpoint = "https://api.anthropic.com" }, "attempt 2": func(s *wire.Sealed) { s.Attempt = 2 }, "expired": func(s *wire.Sealed) { s.ExpiresAt = time.Now().Add(-time.Second) }, "too far ahead": func(s *wire.Sealed) { s.ExpiresAt = time.Now().Add(wire.SealedTTL + 2*time.Minute) }, "too big": func(s *wire.Sealed) { s.Box = strings.Repeat("A", wire.MaxSealedBytes+4) }, "not base64": func(s *wire.Sealed) { s.Box = "not base64!" }, "too short to open": func(s *wire.Sealed) { s.Box = base64.StdEncoding.EncodeToString(make([]byte, 40)) }, } { bad := sealed change(&bad) if _, err := r.client.Secret(r.ctx, attempt.ID, bad); Status(err) != 422 { t.Fatalf("%s: %v", name, err) } } if _, err := r.client.Secret(r.ctx, "cn_nobody", sealed); Status(err) != 404 { t.Fatalf("an unknown attempt: %v", err) } var queued int if err = r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE kind = ?", wire.FrameSecret).Scan(&queued); err != nil || queued != 0 { t.Fatalf("a refused box was queued: %d %v", queued, err) } posted, err := r.client.Secret(r.ctx, attempt.ID, sealed) if err != nil || posted.ID != attempt.ID || posted.State != wire.ConnConnecting || posted.Prompt != nil { t.Fatalf("secret %+v %v", posted, err) } // One box per attempt: the runner would refuse a second anyway. if _, err := r.client.Secret(r.ctx, attempt.ID, sealed); Status(err) != 409 { t.Fatalf("a second box: %v", err) } f, body, err = runner.Expect(r.ctx, wire.FrameSecret) if err != nil { t.Fatal(err) } shape(t, "frames/secret.json", runner.Received[len(runner.Received)-1]) cmd := body.(*wire.SecretCommand) if cmd.Connection != attempt.ID || cmd.Person != Owner || cmd.Sealed.Box != sealed.Box || !cmd.Sealed.ExpiresAt.Equal(expires) { t.Fatalf("secret frame %+v", cmd) } if opened, err := keys.Open(cmd.Sealed, time.Now()); err != nil || opened.Secret != canaryToken { t.Fatalf("the runner could not open the box: %v", err) } stored := func() string { var b string if err := r.inst.DB.Writer().QueryRow("SELECT group_concat(body, '|') FROM runner_commands WHERE kind = ?", wire.FrameSecret).Scan(&b); err != nil { t.Fatal(err) } return b } if !strings.Contains(stored(), sealed.Box) { t.Fatal("the box is not in the mailbox before the ack") } if err = runner.Send(r.ctx, "a-secret", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil { t.Fatal(err) } waitFor(t, "the box blanked after the ack", func() bool { return !strings.Contains(stored(), sealed.Box) }) // The runner's word: healthy, and its hello with the token's expiry. tokenExpires := time.Now().UTC().Add(wire.TokenLifetime).Truncate(time.Second) 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 { t.Fatal(err) } // The expiry is an estimate: neither the token nor the CLI says it. hello.Connections = []wire.HeldConnection{{LocalID: "claude-1", Person: Owner, Provider: "claude", Kind: wire.KindToken, Label: Owner, State: wire.ConnHealthy, ExpiresAt: &tokenExpires, ExpiresEstimated: true}} if err = runner.Send(r.ctx, "h2", wire.FrameHello, hello); err != nil { t.Fatal(err) } r.wait("healthy with the token's expiry", func(c *Conversation) bool { v := c.Connections[attempt.ID] return v.State == wire.ConnHealthy && v.ExpiresAt != nil && v.ExpiresAt.Equal(tokenExpires) && v.ExpiresEstimated }) if got, err := r.client.Connection(r.ctx, attempt.ID); err != nil || got.ExpiresAt == nil || !got.ExpiresAt.Equal(tokenExpires) || !got.ExpiresEstimated || got.Kind != wire.KindToken { t.Fatalf("connection %+v %v", got, err) } if page := r.inst.Get(t, "/conversation/connections"); !strings.Contains(page, "Expires about "+tokenExpires.Format("2 Jan 2006")) { t.Fatal("the row does not say the expiry is an estimate") } // The health check's real request: its usage is recorded like any // other, once per check, as the person's on that connection. for i, check := range []string{"chk_1", "chk_2", "chk_2"} { in := int64(900 + i) usage := wire.UsageReport{CheckID: check, Rows: []wire.Usage{{Provider: "claude", Connection: "claude-1", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &in}}} if err = runner.Send(r.ctx, "r-check-"+strconv.Itoa(i), wire.FrameUsage, usage); err != nil { t.Fatal(err) } } waitFor(t, "the checks' usage", func() bool { var n, sum int64 var role, person string err := r.inst.DB.Writer().QueryRow("SELECT count(*), coalesce(sum(input_tokens),0), coalesce(max(role),''), coalesce(max(person),'') FROM chat_usage WHERE connection = 'claude-1' AND step_id LIKE 'chk_%'").Scan(&n, &sum, &role, &person) return err == nil && n == 2 && sum == 900+901 && role == "check" && person == Owner }) // The sweep: everything the instance serves, logs or keeps on disk. var sinks []string for _, path := range []string{"/conversation/connections", "/conversation", "/conversation/settings"} { sinks = append(sinks, r.inst.Get(t, path)) } if _, err := r.client.Connections(r.ctx); err != nil { t.Fatal(err) } if _, err := r.client.Snapshot(r.ctx); err != nil { t.Fatal(err) } if _, err := r.client.Runners(r.ctx); err != nil { t.Fatal(err) } served := append(sinks, rawEvents(t, r), rec.String(), r.inst.Logs()) var events, rows string _ = r.inst.DB.Writer().QueryRow("SELECT coalesce(group_concat(body, '|'), '') FROM chat_events").Scan(&events) _ = r.inst.DB.Writer().QueryRow("SELECT coalesce(group_concat(coalesce(prompt,'') || label || state || kind, '|'), '') FROM chat_connections").Scan(&rows) served = append(served, events, rows) canaries := []string{canaryToken, base64.StdEncoding.EncodeToString([]byte(canaryToken)), "CANARY"} for i, s := range served { for _, c := range canaries { if strings.Contains(s, c) { t.Fatalf("sink %d holds the canary %q", i, c) } } if strings.Contains(s, sealed.Box) || strings.Contains(s, sealed.Box[:24]) { t.Fatalf("sink %d holds the sealed box", i) } } // On disk only the ciphertext may remain (WAL residue), never the // plaintext. for _, suffix := range []string{"", "-wal", "-shm"} { raw, err := os.ReadFile(r.inst.Path + suffix) if err != nil { if os.IsNotExist(err) && suffix != "" { continue } t.Fatal(err) } for _, c := range canaries { if bytes.Contains(raw, []byte(c)) { t.Fatalf("database%s holds the canary %q", suffix, c) } } } } // TestContractTokenAttemptEnds: an attempt cancelled before its runner // took the box takes the box with it; a seal key that is not an X25519 // public key is never published. func TestContractTokenAttemptEnds(t *testing.T) { r := newRig(t) keys := sealKeys(t) hello := held() hello.SealKey = base64.StdEncoding.EncodeToString([]byte("not a key")) runner, err := DialRunnerHello(r.ctx, r.inst.URL, r.runner, hello) if err != nil { t.Fatal(err) } t.Cleanup(runner.Close) r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online }) if list, err := r.client.Runners(r.ctx); err != nil || len(list.Items) != 1 || list.Items[0].SealKey != "" { t.Fatalf("a malformed seal key was published: %+v %v", list, err) } attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude", Kind: wire.KindToken}) if err != nil { t.Fatal(err) } sealed, err := sealbox.Seal(keys.PublicString(), wire.SealedPayload{Secret: canaryToken, RunnerID: attempt.RunnerID, ConnectionID: attempt.ID, Provider: "claude", Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: time.Now().UTC().Add(5 * time.Minute)}) if err != nil { t.Fatal(err) } if _, err = r.client.Secret(r.ctx, attempt.ID, sealed); err != nil { t.Fatal(err) } if _, err = r.client.CancelConnection(r.ctx, attempt.ID); err != nil { t.Fatal(err) } var bodies string if err = r.inst.DB.Writer().QueryRow("SELECT group_concat(body, '|') || group_concat(acked_at IS NOT NULL, '') FROM runner_commands WHERE kind = ?", wire.FrameSecret).Scan(&bodies); err != nil { t.Fatal(err) } if strings.Contains(bodies, sealed.Box) || !strings.HasSuffix(bodies, "1") { t.Fatalf("the cancelled attempt's box stays in the mailbox: %.120s", bodies) } // A box for an attempt that ended is refused. if _, err = r.client.Secret(r.ctx, attempt.ID, sealed); Status(err) != 409 { t.Fatalf("a box for an ended attempt: %v", err) } } func waitFor(t *testing.T, what string, cond func() bool) { t.Helper() deadline := time.Now().Add(10 * time.Second) for !cond() { if time.Now().After(deadline) { t.Fatalf("timed out waiting for %s", what) } time.Sleep(25 * time.Millisecond) } } // Check again on a token connection that needs signing in again goes to // the runner as a durable check frame naming the connection; a // connection still connecting, or signed out, is refused. func TestContractCheckAgain(t *testing.T) { r := newRig(t) runner, err := DialRunnerHello(r.ctx, r.inst.URL, r.runner, held(wire.HeldConnection{LocalID: "claude-9", Person: Owner, Provider: "claude", Kind: wire.KindToken, Label: "tok@example.com", State: wire.ConnSignInAgain})) if err != nil { t.Fatal(err) } t.Cleanup(runner.Close) var id string r.wait("the token connection", func(c *Conversation) bool { for _, v := range c.Connections { if v.LocalID == "claude-9" { id = v.ID } } return id != "" }) if err = r.client.CheckConnection(r.ctx, id); err != nil { t.Fatal(err) } _, body, err := runner.Expect(r.ctx, wire.FrameCheck) if err != nil { t.Fatal(err) } if v := body.(*wire.CheckCommand); v.Connection != id || v.LocalID != "claude-9" || v.Person != Owner { t.Fatalf("check %+v", v) } attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude", Kind: wire.KindToken}) if err != nil { t.Fatal(err) } if err = r.client.CheckConnection(r.ctx, attempt.ID); Status(err) != 409 { t.Fatalf("check on an attempt: %v", err) } }