connections: token attempts and sealed secrets on the instance
A Claude connection from a pasted setup token (spec §2.4). The runner's
seal key from its hello is kept when it is an X25519 public key and
published on Runner.seal_key. POST /connections with kind token starts
a Claude attempt with the token card's prompt. POST
/connections/{id}/secret checks the clear binding names this attempt
(runner, connection, Claude, the Anthropic endpoint, attempt 1, an expiry
within the TTL) and the box's size, then queues a durable secret frame
to that runner only (never rebound). The ack blanks the box; a cancelled
or expired attempt drops it. The token's expiry from hello is stored and
shown on the connection. The canary contract test checks the plaintext
appears nowhere on the instance and the box nowhere outside the mailbox.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+483
−15
internal/equipo/chat/connections.go+98 −10internal/equipo/chat/http.go+18 −0internal/equipo/chat/runner.go+5 −0internal/equipo/chat/runners.go+9 −2internal/equipo/migrations/0056_thin_token_connections.sql+1 −0internal/equipo/migrations/schema.sql+1 −1internal/plan3test/person_api_contract_test.go+1 −1internal/thintest/client.go+5 −0internal/thintest/instance.go+24 −1internal/thintest/token_contract_test.go+321 −0
diff --git a/internal/equipo/chat/connections.go b/internal/equipo/chat/connections.go| index d15e45fa..36178583 100644 |
| --- a/internal/equipo/chat/connections.go |
| +++ b/internal/equipo/chat/connections.go |
| @@ -2,9 +2,11 @@ package chat |
| import ( |
| "context" |
| + "encoding/base64" |
| "encoding/json" |
| "errors" |
| "slices" |
| + "strings" |
| "time" |
| "amadan.net/oficina/equipo/internal/wire" |
| @@ -43,6 +45,8 @@ type connectionRecord struct { |
| Revision int64 |
| CreatedAt time.Time |
| UpdatedAt time.Time |
| + // ExpiresAt is when a pasted token expires, as the runner reports it. |
| + ExpiresAt *time.Time |
| } |
| func (connectionRecord) TableName() string { return "chat_connections" } |
| @@ -75,7 +79,7 @@ type usageRecord struct { |
| func (usageRecord) TableName() string { return "chat_usage" } |
| func connectionView(r connectionRecord) wire.Connection { |
| - v := wire.Connection{ID: r.ID, Revision: r.Revision, RunnerID: r.RunnerID, LocalID: r.LocalID, Provider: r.Provider, Kind: r.Kind, Label: r.Label, State: r.State, Reason: r.Reason, Plan: r.Plan, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt} |
| + v := wire.Connection{ID: r.ID, Revision: r.Revision, RunnerID: r.RunnerID, LocalID: r.LocalID, Provider: r.Provider, Kind: r.Kind, Label: r.Label, State: r.State, Reason: r.Reason, Plan: r.Plan, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt, ExpiresAt: r.ExpiresAt} |
| if r.Headroom != "" { |
| v.Headroom = &wire.Headroom{} |
| if json.Unmarshal([]byte(r.Headroom), v.Headroom) != nil { |
| @@ -111,7 +115,7 @@ func (t *txn) saveConnection(r *connectionRecord, fresh bool) error { |
| r.CreatedAt = r.UpdatedAt |
| err = t.db.Create(r).Error |
| } else { |
| - err = t.db.Model(&connectionRecord{}).Where("id = ?", r.ID).Select("local_id", "label", "state", "reason", "plan", "headroom", "prompt", "revision", "updated_at").Updates(r).Error |
| + err = t.db.Model(&connectionRecord{}).Where("id = ?", r.ID).Select("local_id", "label", "state", "reason", "plan", "headroom", "prompt", "revision", "updated_at", "expires_at").Updates(r).Error |
| } |
| if err != nil { |
| return err |
| @@ -166,21 +170,21 @@ func (t *txn) helloConnections(l Lease, held []wire.HeldConnection) error { |
| }) { |
| continue |
| } |
| - r := connectionRecord{ID: newID("cn_"), Person: person, RunnerID: runner, LocalID: h.LocalID, Provider: h.Provider, Kind: h.Kind, Label: h.Label, State: h.State, Plan: h.Plan, Headroom: headroom} |
| + r := connectionRecord{ID: newID("cn_"), Person: person, RunnerID: runner, LocalID: h.LocalID, Provider: h.Provider, Kind: h.Kind, Label: h.Label, State: h.State, Plan: h.Plan, Headroom: headroom, ExpiresAt: h.ExpiresAt} |
| if err := t.saveConnection(&r, true); err != nil { |
| return err |
| } |
| continue |
| } |
| r := rows[i] |
| - changed := r.State != h.State || r.Label != h.Label || r.Plan != h.Plan || r.Reason != "" |
| + changed := r.State != h.State || r.Label != h.Label || r.Plan != h.Plan || r.Reason != "" || !sameTime(r.ExpiresAt, h.ExpiresAt) |
| if !changed && r.Headroom == headroom { |
| continue |
| } |
| if !changed && t.now().Sub(r.UpdatedAt) < headroomEvery { |
| continue |
| } |
| - r.State, r.Label, r.Plan, r.Headroom, r.Reason, r.Prompt = h.State, h.Label, h.Plan, headroom, "", "" |
| + r.State, r.Label, r.Plan, r.Headroom, r.Reason, r.Prompt, r.ExpiresAt = h.State, h.Label, h.Plan, headroom, "", "", h.ExpiresAt |
| if err := t.saveConnection(&r, false); err != nil { |
| return err |
| } |
| @@ -238,6 +242,12 @@ func (t *txn) connectionReport(l Lease, v *wire.ConnectionReport) error { |
| if v.State != wire.ConnConnecting { |
| r.Prompt = "" |
| } |
| + if v.State == wire.ConnHealthy && r.Kind == wire.KindToken && r.ExpiresAt == nil { |
| + // A setup token lasts a year from when it was pasted; the runner's |
| + // hello says exactly when. |
| + at := t.now().Add(wire.TokenLifetime) |
| + r.ExpiresAt = &at |
| + } |
| if v.LocalID != "" && v.State != wire.ConnError { |
| // The hello may have recorded the new connection first. |
| if err := t.db.Where("person = ? AND runner_id = ? AND local_id = ? AND id <> ?", r.Person, r.RunnerID, v.LocalID, r.ID).Delete(&connectionRecord{}).Error; err != nil { |
| @@ -390,11 +400,13 @@ func (s *Store) Connection(ctx context.Context, person, id string) (out wire.Con |
| // a Codex account by device code; a Claude account by the CLI's own |
| // sign-in, finished at the runner's machine (loopback, no paste) or, when |
| // the person's browser is elsewhere, by `equipo-runner login claude` in |
| -// a terminal there. Nothing secret passes through the instance either way. |
| -// A second attempt for the same provider while one is connecting returns |
| -// that one. |
| +// a terminal there; or a Claude account from a pasted setup token (kind |
| +// token), sealed in the app to the runner (SendSecret). Nothing the |
| +// instance can read passes through it either way. A second attempt for |
| +// the same provider while one is connecting returns that one. |
| func (s *Store) StartConnection(ctx context.Context, person string, in wire.Connect) (out wire.Connection, err error) { |
| - if in.Provider != wire.ProviderClaude && in.Provider != wire.ProviderCodex || in.Kind != "" && in.Kind != wire.KindSubscription { |
| + token := in.Kind == wire.KindToken |
| + if in.Provider != wire.ProviderClaude && in.Provider != wire.ProviderCodex || in.Kind != "" && in.Kind != wire.KindSubscription && !token || token && (in.Provider != wire.ProviderClaude || in.SameMachine) { |
| return out, ErrInvalid |
| } |
| err = s.tx(ctx, func(t *txn) error { |
| @@ -422,7 +434,10 @@ func (s *Store) StartConnection(ctx context.Context, person string, in wire.Conn |
| return ErrRunnerOffline |
| } |
| r := connectionRecord{ID: newID("cn_"), Person: person, RunnerID: runner.ID, Provider: in.Provider, Kind: wire.KindSubscription, State: wire.ConnConnecting} |
| - if in.Provider == wire.ProviderClaude && !in.SameMachine { |
| + if token { |
| + // The token card: run the command anywhere, approve, paste. |
| + r.Kind, r.Prompt = wire.KindToken, asJSON(wire.ConnectPrompt{Kind: wire.PromptToken, Code: "claude setup-token"}) |
| + } else if in.Provider == wire.ProviderClaude && !in.SameMachine { |
| // The honest card: Claude's sign-in finishes on the runner's |
| // machine. The runner watches for the terminal login. |
| r.Prompt = asJSON(wire.ConnectPrompt{Kind: wire.PromptTerminal, Code: "equipo-runner login claude"}) |
| @@ -456,6 +471,9 @@ func (s *Store) CancelConnection(ctx context.Context, person, id string) (out wi |
| if err := t.saveConnection(&r, false); err != nil { |
| return err |
| } |
| + if err := t.dropSecret(r.ID); err != nil { |
| + return err |
| + } |
| out = connectionView(r) |
| return t.command(person, wire.FrameCancelConnect, wire.CancelConnectCommand{Connection: r.ID, Person: person}) |
| }) |
| @@ -489,6 +507,73 @@ func (s *Store) SignOut(ctx context.Context, person, id string) (out wire.Connec |
| return out, err |
| } |
| +// SendSecret queues the sealed secret for one of the person's token |
| +// attempts (spec §2.4) as a durable secret frame to the attempt's |
| +// runner. The instance cannot open the box; it checks the clear binding |
| +// beside it names this attempt (its runner, Claude's endpoint, attempt |
| +// 1, a short expiry) and that the box is a size a sealed token can be. |
| +// One box per attempt: the attempt's token prompt goes with it, so the |
| +// card waits for the runner. The box is in no event, response or log |
| +// line, and leaves the mailbox once the runner acks it. |
| +func (s *Store) SendSecret(ctx context.Context, person, id string, in wire.Sealed) (out wire.Connection, err error) { |
| + if !sealedShape(in, s.now()) { |
| + return out, ErrInvalid |
| + } |
| + err = s.tx(ctx, func(t *txn) error { |
| + if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| + return err |
| + } |
| + var r connectionRecord |
| + if err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| + return ErrNotFound |
| + } else if err != nil { |
| + return err |
| + } |
| + if in.RunnerID != r.RunnerID || in.ConnectionID != r.ID || in.Provider != r.Provider || r.Kind != wire.KindToken { |
| + return ErrInvalid |
| + } |
| + if r.State != wire.ConnConnecting || r.Prompt == "" { |
| + return ErrConflict |
| + } |
| + r.Prompt = "" |
| + if err := t.saveConnection(&r, false); err != nil { |
| + return err |
| + } |
| + out = connectionView(r) |
| + return t.commandTo(r.RunnerID, person, wire.FrameSecret, wire.SecretCommand{Connection: r.ID, Person: person, Sealed: in}) |
| + }) |
| + return out, err |
| +} |
| + |
| +// sealedShape checks what can be checked of a box without opening it. |
| +func sealedShape(in wire.Sealed, now time.Time) bool { |
| + if in.Provider != wire.ProviderClaude || in.Endpoint != wire.EndpointAnthropic || in.Attempt != 1 || len(in.Box) > wire.MaxSealedBytes { |
| + return false |
| + } |
| + // The runner allows a minute of clock skew past the TTL; so does this. |
| + if !in.ExpiresAt.After(now) || in.ExpiresAt.Sub(now) > wire.SealedTTL+time.Minute { |
| + return false |
| + } |
| + raw, err := base64.StdEncoding.DecodeString(in.Box) |
| + // An ephemeral public key and a MAC at least. |
| + return err == nil && len(raw) > 48 |
| +} |
| + |
| +// dropSecret takes an ended attempt's box out of the mailbox before its |
| +// runner took it. |
| +func (t *txn) dropSecret(connection string) error { |
| + like := `{"connection":"` + strings.ReplaceAll(connection, `"`, "") + `",%` |
| + return t.db.Model(&commandRecord{}).Where("kind = ? AND body LIKE ?", wire.FrameSecret, like).Updates(map[string]any{"body": "{}", "acked_at": t.now()}).Error |
| +} |
| + |
| +// sameTime reports whether two optional times are the same instant. |
| +func sameTime(a, b *time.Time) bool { |
| + if a == nil || b == nil { |
| + return a == b |
| + } |
| + return a.Equal(*b) |
| +} |
| + |
| // expireAttempts ends attempts that made no progress (a runner that went |
| // away mid-attempt reports nothing). |
| func (t *txn) expireAttempts() error { |
| @@ -501,6 +586,9 @@ func (t *txn) expireAttempts() error { |
| if err := t.saveConnection(&rows[i], false); err != nil { |
| return err |
| } |
| + if err := t.dropSecret(rows[i].ID); err != nil { |
| + return err |
| + } |
| } |
| return nil |
| } |
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go| index 57f4d5f1..f40f69d1 100644 |
| --- a/internal/equipo/chat/http.go |
| +++ b/internal/equipo/chat/http.go |
| @@ -93,6 +93,7 @@ func (h *HTTP) Mount(r chi.Router) { |
| r.Post("/connections", h.bearer(h.connect)) |
| r.Get("/connections/{id}", h.thinOr("GET /connections/{id}", thinConnection, h.bearer(h.connection))) |
| r.Post("/connections/{id}/cancel", h.bearer(h.cancelConnection)) |
| + r.Post("/connections/{id}/secret", h.bearer(h.secret)) |
| r.Delete("/connections/{id}", h.thinOr("DELETE /connections/{id}", thinConnection, h.bearer(h.signOut))) |
| r.Post("/connections/{id}/forget", h.bearer(h.forget)) |
| r.Get("/thinking", h.bearer(h.thinking)) |
| @@ -211,6 +212,23 @@ func (h *HTTP) setPreferences(w http.ResponseWriter, r *http.Request, p personap |
| writeJSON(w, 200, out) |
| } |
| +// secret is POST /api/v1/connections/{id}/secret: a token attempt's |
| +// sealed secret (wire.Sealed), 202 with the attempt waiting for its |
| +// runner. The box is never echoed. |
| +func (h *HTTP) secret(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| + var in wire.Sealed |
| + if err := readJSON(r, &in); err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + out, err := h.Store.SendSecret(r.Context(), p.Address, chi.URLParam(r, "id"), in) |
| + if err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + writeJSON(w, http.StatusAccepted, out) |
| +} |
| + |
| func (h *HTTP) cancelConnection(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| out, err := h.Store.CancelConnection(r.Context(), p.Address, chi.URLParam(r, "id")) |
| if err != nil { |
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go| index 4d74f5bd..ea2b06c8 100644 |
| --- a/internal/equipo/chat/runner.go |
| +++ b/internal/equipo/chat/runner.go |
| @@ -337,6 +337,11 @@ func (t *txn) ack(l Lease, id string) error { |
| if c.Kind == wire.FrameBlob { |
| return t.blobAcked(c.Body) |
| } |
| + if c.Kind == wire.FrameSecret { |
| + // The runner holds the secret now: the box leaves the mailbox |
| + // (only WAL and backup residue can remain, spec §2.4). |
| + return t.db.Model(&commandRecord{}).Where("seq = ?", c.Seq).Update("body", "{}").Error |
| + } |
| if c.Kind != wire.FrameMessage { |
| return nil |
| } |
diff --git a/internal/equipo/chat/runners.go b/internal/equipo/chat/runners.go| index f5e156c4..3922070c 100644 |
| --- a/internal/equipo/chat/runners.go |
| +++ b/internal/equipo/chat/runners.go |
| @@ -2,6 +2,7 @@ package chat |
| import ( |
| "context" |
| + "encoding/base64" |
| "encoding/json" |
| "errors" |
| "slices" |
| @@ -35,7 +36,8 @@ const orphanedBy = `SELECT id FROM runners WHERE person = ? AND revoked_at IS NO |
| // attemptKinds are commands that belong to one attempt on one runner: a |
| // dispatch whose ack was lost may already run there, so they never move. |
| -var attemptKinds = []string{wire.FrameDispatch, wire.FrameCancelStep, wire.FrameAsk, wire.FrameCancelAsk, wire.FrameBlob, wire.FrameSendPack, wire.FramePublish} |
| +// A sealed secret opens only with its own runner's key. |
| +var attemptKinds = []string{wire.FrameDispatch, wire.FrameCancelStep, wire.FrameAsk, wire.FrameCancelAsk, wire.FrameBlob, wire.FrameSendPack, wire.FramePublish, wire.FrameSecret} |
| // rebind gives the person's primary the conversation's commands no runner |
| // holds: those written while the person had no primary, and a revoked |
| @@ -215,6 +217,11 @@ func cleanHello(h wire.Hello) wire.Hello { |
| default: |
| h.Sandbox = "" |
| } |
| + // The seal key is published for the apps to seal to: only an X25519 |
| + // public key (32 bytes, standard base64) is kept. |
| + if raw, err := base64.StdEncoding.DecodeString(h.SealKey); err != nil || len(raw) != 32 { |
| + h.SealKey = "" |
| + } |
| return h |
| } |
| @@ -300,7 +307,7 @@ func (t *txn) runnerOnline(person, id string) (bool, error) { |
| // runnerView is the Runner resource. |
| func runnerView(r runnerInfo) wire.Runner { |
| - v := wire.Runner{ID: r.ID, Revision: r.Revision, Online: r.Online, Label: r.Label, Role: r.Role, Platform: r.Hello.Platform, Capabilities: r.Hello.Capabilities, Removing: r.Removing} |
| + v := wire.Runner{ID: r.ID, Revision: r.Revision, Online: r.Online, Label: r.Label, Role: r.Role, Platform: r.Hello.Platform, Capabilities: r.Hello.Capabilities, Removing: r.Removing, SealKey: r.Hello.SealKey} |
| if !r.SeenAt.IsZero() { |
| at := r.SeenAt |
| v.Since = &at |
diff --git a/internal/equipo/migrations/0056_thin_token_connections.sql b/internal/equipo/migrations/0056_thin_token_connections.sql| new file mode 100644 |
| index 00000000..97dca54a |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0056_thin_token_connections.sql |
| @@ -0,0 +1 @@ |
| +ALTER TABLE chat_connections ADD COLUMN expires_at datetime; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 47baae33..9590f2a8 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -607,7 +607,7 @@ CREATE TABLE chat_task_distinct (a text, b text, created_at datetime, PRIMARY KE |
| CREATE TABLE chat_questions (id text PRIMARY KEY, task_id text, asker text, idempotency_key text, step_id text, specialist text, chosen text, text text, state text, reason text, attempt integer, dispatched numeric, answer text, timing text, revision integer, created_at datetime, updated_at datetime); |
| CREATE INDEX chat_question_task ON chat_questions(task_id); |
| CREATE UNIQUE INDEX chat_question_key ON chat_questions(task_id, asker, idempotency_key); |
| -CREATE TABLE chat_connections (id text PRIMARY KEY, person text, runner_id text, local_id text, provider text, kind text, label text, state text, reason text, plan text, headroom text, prompt text, revision integer, created_at datetime, updated_at datetime); |
| +CREATE TABLE chat_connections (id text PRIMARY KEY, person text, runner_id text, local_id text, provider text, kind text, label text, state text, reason text, plan text, headroom text, prompt text, revision integer, created_at datetime, updated_at datetime, expires_at datetime); |
| CREATE INDEX chat_connection_person ON chat_connections(person); |
| CREATE TABLE chat_usage (id integer PRIMARY KEY, person text, connection text, provider text, model text, role text, task_id text, step_id text, turn_id text, attempt integer, outcome text, complete numeric, input_tokens integer, cached_input_tokens integer, cache_write_tokens integer, output_tokens integer, reasoning_output_tokens integer, recorded_at datetime); |
| CREATE INDEX chat_usage_person ON chat_usage(person, recorded_at); |
diff --git a/internal/plan3test/person_api_contract_test.go b/internal/plan3test/person_api_contract_test.go| index cb5c5f61..c46b9d6a 100644 |
| --- a/internal/plan3test/person_api_contract_test.go |
| +++ b/internal/plan3test/person_api_contract_test.go |
| @@ -56,7 +56,7 @@ func personAPIContractCoverage(t *testing.T) { |
| f := newFixture(t) |
| registered := map[string]bool{} |
| // Thin v1 conversation routes are contracted by internal/wire fixtures. |
| - thin := map[string]bool{"GET /messages": true, "POST /messages": true, "GET /turns/{id}": true, "POST /turns/{id}/cancel": true, "GET /snapshot": true, "GET /events": true, "DELETE /projects/{id}": true, "POST /cards/{id}/answer": true, "GET /notebook": true, "POST /notebook/reset": true, "POST /tasks/{id}/retry": true, "POST /tasks/{id}/recover": true, "POST /tasks/{id}/merge": true, "POST /tasks/{id}/duplicate": true, "POST /tasks/{id}/uncombine": true, "GET /thinking": true, "PUT /thinking": true, "POST /tasks/{id}/thread": true, "GET /steps/{id}/log": true, "POST /tasks/{id}/questions": true, "POST /questions/{id}/cancel": true, "POST /connections": true, "POST /connections/{id}/cancel": true, "POST /connections/{id}/forget": true, "GET /connections/preference": true, "PUT /connections/preference": true, "GET /housekeeping": true, "PUT /housekeeping": true, "PUT /housekeeping/detectors/{id}": true, "GET /housekeeping/actions": true, "POST /housekeeping/actions/{id}/undo": true, "POST /attachments": true, "GET /attachments/{id}": true, "GET /attachments/{id}/preview": true} |
| + thin := map[string]bool{"GET /messages": true, "POST /messages": true, "GET /turns/{id}": true, "POST /turns/{id}/cancel": true, "GET /snapshot": true, "GET /events": true, "DELETE /projects/{id}": true, "POST /cards/{id}/answer": true, "GET /notebook": true, "POST /notebook/reset": true, "POST /tasks/{id}/retry": true, "POST /tasks/{id}/recover": true, "POST /tasks/{id}/merge": true, "POST /tasks/{id}/duplicate": true, "POST /tasks/{id}/uncombine": true, "GET /thinking": true, "PUT /thinking": true, "POST /tasks/{id}/thread": true, "GET /steps/{id}/log": true, "POST /tasks/{id}/questions": true, "POST /questions/{id}/cancel": true, "POST /connections": true, "POST /connections/{id}/cancel": true, "POST /connections/{id}/secret": true, "POST /connections/{id}/forget": true, "GET /connections/preference": true, "PUT /connections/preference": true, "GET /housekeeping": true, "PUT /housekeeping": true, "PUT /housekeeping/detectors/{id}": true, "GET /housekeeping/actions": true, "POST /housekeeping/actions/{id}/undo": true, "POST /attachments": true, "GET /attachments/{id}": true, "GET /attachments/{id}/preview": true} |
| must(t, chi.Walk(f.Store.PersonAPIHandler().(chi.Routes), func(method, path string, _ http.Handler, _ ...func(http.Handler) http.Handler) error { |
| if thin[method+" "+path] { |
| return nil |
diff --git a/internal/thintest/client.go b/internal/thintest/client.go| index c1c029f6..2359efc9 100644 |
| --- a/internal/thintest/client.go |
| +++ b/internal/thintest/client.go |
| @@ -278,6 +278,11 @@ func (c *Client) CancelConnection(ctx context.Context, id string) (out wire.Conn |
| return out, c.do(ctx, "POST", "/api/v1/connections/"+id+"/cancel", nil, &out) |
| } |
| +// Secret posts a token attempt's sealed secret (202 with the attempt). |
| +func (c *Client) Secret(ctx context.Context, id string, in wire.Sealed) (out wire.Connection, err error) { |
| + return out, c.do(ctx, "POST", "/api/v1/connections/"+id+"/secret", in, &out) |
| +} |
| + |
| // Stream is one open SSE connection. |
| type Stream struct { |
| Events <-chan wire.Event |
diff --git a/internal/thintest/instance.go b/internal/thintest/instance.go| index 54b9db05..505c6378 100644 |
| --- a/internal/thintest/instance.go |
| +++ b/internal/thintest/instance.go |
| @@ -19,6 +19,7 @@ import ( |
| "os" |
| "path/filepath" |
| "strings" |
| + "sync" |
| "testing" |
| "time" |
| @@ -55,6 +56,27 @@ type Instance struct { |
| server *http.Server |
| cookie *http.Cookie |
| logger *slog.Logger |
| + logs *logBuffer |
| +} |
| + |
| +// logBuffer keeps every line the instance logged, so a test can show a |
| +// secret never reached one. |
| +type logBuffer struct { |
| + mu sync.Mutex |
| + buf bytes.Buffer |
| +} |
| + |
| +func (l *logBuffer) Write(p []byte) (int, error) { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + return l.buf.Write(p) |
| +} |
| + |
| +// Logs is everything the instance has logged so far, every level. |
| +func (i *Instance) Logs() string { |
| + i.logs.mu.Lock() |
| + defer i.logs.mu.Unlock() |
| + return i.logs.buf.String() |
| } |
| // StartInstance migrates a fresh database and serves it. |
| @@ -64,7 +86,8 @@ func StartInstance(t testing.TB) *Instance { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - i := &Instance{addr: l.Addr().String(), Path: schema.Path(t), logger: slog.New(slog.NewTextHandler(io.Discard, nil))} |
| + logs := &logBuffer{} |
| + i := &Instance{addr: l.Addr().String(), Path: schema.Path(t), logs: logs, logger: slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug}))} |
| i.URL = "http://" + i.addr |
| i.serve(t, l) |
| t.Cleanup(func() { i.Stop() }) |
diff --git a/internal/thintest/token_contract_test.go b/internal/thintest/token_contract_test.go| new file mode 100644 |
| index 00000000..c779d4ef |
| --- /dev/null |
| +++ b/internal/thintest/token_contract_test.go |
| @@ -0,0 +1,321 @@ |
| +package thintest |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "io" |
| + "net/http" |
| + "os" |
| + "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) |
| + } |
| + hello.Connections = []wire.HeldConnection{{LocalID: "claude-1", Person: Owner, Provider: "claude", Kind: wire.KindToken, Label: Owner, State: wire.ConnHealthy, ExpiresAt: &tokenExpires}} |
| + 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) |
| + }) |
| + if got, err := r.client.Connection(r.ctx, attempt.ID); err != nil || got.ExpiresAt == nil || !got.ExpiresAt.Equal(tokenExpires) || got.Kind != wire.KindToken { |
| + t.Fatalf("connection %+v %v", got, err) |
| + } |
| + |
| + // 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) |
| + } |
| +} |