oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thintest
2
3import (
4 "bytes"
5 "context"
6 "crypto/ed25519"
7 "crypto/rand"
8 "encoding/base64"
9 "io"
10 "net/http"
11 "os"
12 "strconv"
13 "strings"
14 "sync"
15 "testing"
16 "time"
17
18 "amadan.net/oficina/equipo/internal/sealbox"
19 "amadan.net/oficina/equipo/internal/wire"
20)
21
22// canaryToken is an obviously fake setup token: it is sealed in the test
23// and must never appear on the instance.
24const canaryToken = "sk-ant-oat01-CANARY-not-a-real-token-CANARY"
25
26// recorder keeps every response body the client read.
27type recorder struct {
28 mu sync.Mutex
29 seen bytes.Buffer
30}
31
32func (r *recorder) RoundTrip(req *http.Request) (*http.Response, error) {
33 res, err := http.DefaultTransport.RoundTrip(req)
34 if err != nil {
35 return res, err
36 }
37 raw, err := io.ReadAll(res.Body)
38 res.Body.Close()
39 r.mu.Lock()
40 r.seen.Write(raw)
41 r.mu.Unlock()
42 res.Body = io.NopCloser(bytes.NewReader(raw))
43 return res, err
44}
45
46func (r *recorder) String() string {
47 r.mu.Lock()
48 defer r.mu.Unlock()
49 return r.seen.String()
50}
51
52// sealKeys is a runner's seal key pair from a fresh enrolment key.
53func sealKeys(t *testing.T) sealbox.Keys {
54 t.Helper()
55 _, private, err := ed25519.GenerateKey(rand.Reader)
56 if err != nil {
57 t.Fatal(err)
58 }
59 keys, err := sealbox.FromEd25519(private)
60 if err != nil {
61 t.Fatal(err)
62 }
63 return keys
64}
65
66// rawEvents reads the person's event stream from the start as it is
67// served, for a moment.
68func rawEvents(t *testing.T, r *rig) string {
69 t.Helper()
70 ctx, cancel := context.WithTimeout(r.ctx, 1500*time.Millisecond)
71 defer cancel()
72 req, _ := http.NewRequestWithContext(ctx, "GET", r.inst.URL+"/api/v1/events?after=0", nil)
73 req.Header.Set("Authorization", "Bearer "+r.client.Token)
74 req.Header.Set("Accept", "text/event-stream")
75 res, err := http.DefaultClient.Do(req)
76 if err != nil {
77 t.Fatal(err)
78 }
79 defer res.Body.Close()
80 raw, _ := io.ReadAll(res.Body)
81 if !bytes.Contains(raw, []byte("event: connection")) {
82 t.Fatalf("the stream served no connection events: %.400s", raw)
83 }
84 return string(raw)
85}
86
87// TestContractTokenConnection (Paul, 2026-11-09; spec §2.4): the runner's
88// seal key is published; a Claude token attempt shows the token card and
89// goes to the runner as connect (kind token); a sealed box whose clear
90// binding is not this attempt's is refused; one that is goes to the
91// runner as a durable secret frame and is blanked once acked. The
92// canary's plaintext appears nowhere on the instance (database and WAL
93// bytes, events, responses, pages, logs) and the box nowhere but the
94// mailbox until the ack.
95func TestContractTokenConnection(t *testing.T) {
96 r := newRig(t)
97 rec := &recorder{}
98 r.client.HTTP.Transport = rec
99 keys := sealKeys(t)
100 runner := r.dial(0)
101 hello := held()
102 hello.Generation, hello.SealKey = runner.Welcome.Generation, keys.PublicString()
103 if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil {
104 t.Fatal(err)
105 }
106 r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online })
107 var runnerID string
108 waitFor(t, "the seal key published", func() bool {
109 list, err := r.client.Runners(r.ctx)
110 if err != nil || len(list.Items) != 1 {
111 return false
112 }
113 runnerID = list.Items[0].ID
114 return list.Items[0].SealKey == keys.PublicString()
115 })
116 if snap, err := r.client.Snapshot(r.ctx); err != nil || snap.Runner.SealKey != keys.PublicString() {
117 t.Fatalf("snapshot runner %+v %v", snap.Runner, err)
118 }
119
120 if _, err := r.client.Connect(r.ctx, wire.Connect{Provider: "codex", Kind: wire.KindToken}); Status(err) != 422 {
121 t.Fatalf("a Codex token attempt: %v", err)
122 }
123 attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude", Kind: wire.KindToken})
124 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 {
125 t.Fatalf("token attempt %+v %v", attempt, err)
126 }
127 f, body, err := runner.Expect(r.ctx, wire.FrameConnect)
128 if err != nil {
129 t.Fatal(err)
130 }
131 if cmd := body.(*wire.ConnectCommand); cmd.Connection != attempt.ID || cmd.Kind != wire.KindToken || cmd.Provider != "claude" {
132 t.Fatalf("connect frame %+v", cmd)
133 }
134 if err = runner.Send(r.ctx, "a-connect", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil {
135 t.Fatal(err)
136 }
137
138 expires := time.Now().UTC().Add(wire.SealedTTL).Truncate(time.Second)
139 sealed, err := sealbox.Seal(keys.PublicString(), wire.SealedPayload{Secret: canaryToken, RunnerID: runnerID, ConnectionID: attempt.ID, Provider: "claude", Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: expires})
140 if err != nil {
141 t.Fatal(err)
142 }
143 for name, change := range map[string]func(*wire.Sealed){
144 "another runner": func(s *wire.Sealed) { s.RunnerID = "rn_other" },
145 "another connection": func(s *wire.Sealed) { s.ConnectionID = "cn_other" },
146 "another provider": func(s *wire.Sealed) { s.Provider = "codex" },
147 "another endpoint": func(s *wire.Sealed) { s.Endpoint = "https://api.anthropic.com" },
148 "attempt 2": func(s *wire.Sealed) { s.Attempt = 2 },
149 "expired": func(s *wire.Sealed) { s.ExpiresAt = time.Now().Add(-time.Second) },
150 "too far ahead": func(s *wire.Sealed) { s.ExpiresAt = time.Now().Add(wire.SealedTTL + 2*time.Minute) },
151 "too big": func(s *wire.Sealed) { s.Box = strings.Repeat("A", wire.MaxSealedBytes+4) },
152 "not base64": func(s *wire.Sealed) { s.Box = "not base64!" },
153 "too short to open": func(s *wire.Sealed) { s.Box = base64.StdEncoding.EncodeToString(make([]byte, 40)) },
154 } {
155 bad := sealed
156 change(&bad)
157 if _, err := r.client.Secret(r.ctx, attempt.ID, bad); Status(err) != 422 {
158 t.Fatalf("%s: %v", name, err)
159 }
160 }
161 if _, err := r.client.Secret(r.ctx, "cn_nobody", sealed); Status(err) != 404 {
162 t.Fatalf("an unknown attempt: %v", err)
163 }
164 var queued int
165 if err = r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE kind = ?", wire.FrameSecret).Scan(&queued); err != nil || queued != 0 {
166 t.Fatalf("a refused box was queued: %d %v", queued, err)
167 }
168
169 posted, err := r.client.Secret(r.ctx, attempt.ID, sealed)
170 if err != nil || posted.ID != attempt.ID || posted.State != wire.ConnConnecting || posted.Prompt != nil {
171 t.Fatalf("secret %+v %v", posted, err)
172 }
173 // One box per attempt: the runner would refuse a second anyway.
174 if _, err := r.client.Secret(r.ctx, attempt.ID, sealed); Status(err) != 409 {
175 t.Fatalf("a second box: %v", err)
176 }
177 f, body, err = runner.Expect(r.ctx, wire.FrameSecret)
178 if err != nil {
179 t.Fatal(err)
180 }
181 shape(t, "frames/secret.json", runner.Received[len(runner.Received)-1])
182 cmd := body.(*wire.SecretCommand)
183 if cmd.Connection != attempt.ID || cmd.Person != Owner || cmd.Sealed.Box != sealed.Box || !cmd.Sealed.ExpiresAt.Equal(expires) {
184 t.Fatalf("secret frame %+v", cmd)
185 }
186 if opened, err := keys.Open(cmd.Sealed, time.Now()); err != nil || opened.Secret != canaryToken {
187 t.Fatalf("the runner could not open the box: %v", err)
188 }
189 stored := func() string {
190 var b string
191 if err := r.inst.DB.Writer().QueryRow("SELECT group_concat(body, '|') FROM runner_commands WHERE kind = ?", wire.FrameSecret).Scan(&b); err != nil {
192 t.Fatal(err)
193 }
194 return b
195 }
196 if !strings.Contains(stored(), sealed.Box) {
197 t.Fatal("the box is not in the mailbox before the ack")
198 }
199 if err = runner.Send(r.ctx, "a-secret", wire.FrameAck, wire.Ack{ID: f.ID}); err != nil {
200 t.Fatal(err)
201 }
202 waitFor(t, "the box blanked after the ack", func() bool { return !strings.Contains(stored(), sealed.Box) })
203
204 // The runner's word: healthy, and its hello with the token's expiry.
205 tokenExpires := time.Now().UTC().Add(wire.TokenLifetime).Truncate(time.Second)
206 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 {
207 t.Fatal(err)
208 }
209 // The expiry is an estimate: neither the token nor the CLI says it.
210 hello.Connections = []wire.HeldConnection{{LocalID: "claude-1", Person: Owner, Provider: "claude", Kind: wire.KindToken, Label: Owner, State: wire.ConnHealthy, ExpiresAt: &tokenExpires, ExpiresEstimated: true}}
211 if err = runner.Send(r.ctx, "h2", wire.FrameHello, hello); err != nil {
212 t.Fatal(err)
213 }
214 r.wait("healthy with the token's expiry", func(c *Conversation) bool {
215 v := c.Connections[attempt.ID]
216 return v.State == wire.ConnHealthy && v.ExpiresAt != nil && v.ExpiresAt.Equal(tokenExpires) && v.ExpiresEstimated
217 })
218 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 {
219 t.Fatalf("connection %+v %v", got, err)
220 }
221 if page := r.inst.Get(t, "/conversation/connections"); !strings.Contains(page, "Expires about "+tokenExpires.Format("2 Jan 2006")) {
222 t.Fatal("the row does not say the expiry is an estimate")
223 }
224
225 // The health check's real request: its usage is recorded like any
226 // other, once per check, as the person's on that connection.
227 for i, check := range []string{"chk_1", "chk_2", "chk_2"} {
228 in := int64(900 + i)
229 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}}}
230 if err = runner.Send(r.ctx, "r-check-"+strconv.Itoa(i), wire.FrameUsage, usage); err != nil {
231 t.Fatal(err)
232 }
233 }
234 waitFor(t, "the checks' usage", func() bool {
235 var n, sum int64
236 var role, person string
237 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)
238 return err == nil && n == 2 && sum == 900+901 && role == "check" && person == Owner
239 })
240
241 // The sweep: everything the instance serves, logs or keeps on disk.
242 var sinks []string
243 for _, path := range []string{"/conversation/connections", "/conversation", "/conversation/settings"} {
244 sinks = append(sinks, r.inst.Get(t, path))
245 }
246 if _, err := r.client.Connections(r.ctx); err != nil {
247 t.Fatal(err)
248 }
249 if _, err := r.client.Snapshot(r.ctx); err != nil {
250 t.Fatal(err)
251 }
252 if _, err := r.client.Runners(r.ctx); err != nil {
253 t.Fatal(err)
254 }
255 served := append(sinks, rawEvents(t, r), rec.String(), r.inst.Logs())
256 var events, rows string
257 _ = r.inst.DB.Writer().QueryRow("SELECT coalesce(group_concat(body, '|'), '') FROM chat_events").Scan(&events)
258 _ = r.inst.DB.Writer().QueryRow("SELECT coalesce(group_concat(coalesce(prompt,'') || label || state || kind, '|'), '') FROM chat_connections").Scan(&rows)
259 served = append(served, events, rows)
260 canaries := []string{canaryToken, base64.StdEncoding.EncodeToString([]byte(canaryToken)), "CANARY"}
261 for i, s := range served {
262 for _, c := range canaries {
263 if strings.Contains(s, c) {
264 t.Fatalf("sink %d holds the canary %q", i, c)
265 }
266 }
267 if strings.Contains(s, sealed.Box) || strings.Contains(s, sealed.Box[:24]) {
268 t.Fatalf("sink %d holds the sealed box", i)
269 }
270 }
271 // On disk only the ciphertext may remain (WAL residue), never the
272 // plaintext.
273 for _, suffix := range []string{"", "-wal", "-shm"} {
274 raw, err := os.ReadFile(r.inst.Path + suffix)
275 if err != nil {
276 if os.IsNotExist(err) && suffix != "" {
277 continue
278 }
279 t.Fatal(err)
280 }
281 for _, c := range canaries {
282 if bytes.Contains(raw, []byte(c)) {
283 t.Fatalf("database%s holds the canary %q", suffix, c)
284 }
285 }
286 }
287}
288
289// TestContractTokenAttemptEnds: an attempt cancelled before its runner
290// took the box takes the box with it; a seal key that is not an X25519
291// public key is never published.
292func TestContractTokenAttemptEnds(t *testing.T) {
293 r := newRig(t)
294 keys := sealKeys(t)
295 hello := held()
296 hello.SealKey = base64.StdEncoding.EncodeToString([]byte("not a key"))
297 runner, err := DialRunnerHello(r.ctx, r.inst.URL, r.runner, hello)
298 if err != nil {
299 t.Fatal(err)
300 }
301 t.Cleanup(runner.Close)
302 r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online })
303 if list, err := r.client.Runners(r.ctx); err != nil || len(list.Items) != 1 || list.Items[0].SealKey != "" {
304 t.Fatalf("a malformed seal key was published: %+v %v", list, err)
305 }
306 attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude", Kind: wire.KindToken})
307 if err != nil {
308 t.Fatal(err)
309 }
310 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)})
311 if err != nil {
312 t.Fatal(err)
313 }
314 if _, err = r.client.Secret(r.ctx, attempt.ID, sealed); err != nil {
315 t.Fatal(err)
316 }
317 if _, err = r.client.CancelConnection(r.ctx, attempt.ID); err != nil {
318 t.Fatal(err)
319 }
320 var bodies string
321 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 {
322 t.Fatal(err)
323 }
324 if strings.Contains(bodies, sealed.Box) || !strings.HasSuffix(bodies, "1") {
325 t.Fatalf("the cancelled attempt's box stays in the mailbox: %.120s", bodies)
326 }
327 // A box for an attempt that ended is refused.
328 if _, err = r.client.Secret(r.ctx, attempt.ID, sealed); Status(err) != 409 {
329 t.Fatalf("a box for an ended attempt: %v", err)
330 }
331}
332
333func waitFor(t *testing.T, what string, cond func() bool) {
334 t.Helper()
335 deadline := time.Now().Add(10 * time.Second)
336 for !cond() {
337 if time.Now().After(deadline) {
338 t.Fatalf("timed out waiting for %s", what)
339 }
340 time.Sleep(25 * time.Millisecond)
341 }
342}
343
344// Check again on a token connection that needs signing in again goes to
345// the runner as a durable check frame naming the connection; a
346// connection still connecting, or signed out, is refused.
347func TestContractCheckAgain(t *testing.T) {
348 r := newRig(t)
349 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}))
350 if err != nil {
351 t.Fatal(err)
352 }
353 t.Cleanup(runner.Close)
354 var id string
355 r.wait("the token connection", func(c *Conversation) bool {
356 for _, v := range c.Connections {
357 if v.LocalID == "claude-9" {
358 id = v.ID
359 }
360 }
361 return id != ""
362 })
363 if err = r.client.CheckConnection(r.ctx, id); err != nil {
364 t.Fatal(err)
365 }
366 _, body, err := runner.Expect(r.ctx, wire.FrameCheck)
367 if err != nil {
368 t.Fatal(err)
369 }
370 if v := body.(*wire.CheckCommand); v.Connection != id || v.LocalID != "claude-9" || v.Person != Owner {
371 t.Fatalf("check %+v", v)
372 }
373 attempt, err := r.client.Connect(r.ctx, wire.Connect{Provider: "claude", Kind: wire.KindToken})
374 if err != nil {
375 t.Fatal(err)
376 }
377 if err = r.client.CheckConnection(r.ctx, attempt.ID); Status(err) != 409 {
378 t.Fatalf("check on an attempt: %v", err)
379 }
380}
381