oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package headless
2
3import (
4 "context"
5 "crypto/ed25519"
6 "crypto/rand"
7 "encoding/base64"
8 "encoding/json"
9 "math"
10 "os"
11 "path/filepath"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/fakeclaude"
17 "amadan.net/oficina/equipo/internal/runner/provider"
18 "amadan.net/oficina/equipo/internal/runner/thin"
19 "amadan.net/oficina/equipo/internal/runnerproto"
20 "amadan.net/oficina/equipo/internal/sealbox"
21 "amadan.net/oficina/equipo/internal/thintest"
22 "amadan.net/oficina/equipo/internal/wire"
23)
24
25// addToken gives the owner a token connection as the runner makes one
26// from a delivered secret: a home with the token file and the identity,
27// no CLI login, bound as kind token. It returns the token.
28func (r *localRunner) addToken(t *testing.T, id, email string) string {
29 t.Helper()
30 home := private(t, filepath.Join(r.root, "accounts", id))
31 token := fakeclaude.Token(email)
32 if err := os.WriteFile(filepath.Join(home, provider.TokenFile), []byte(token), 0600); err != nil {
33 t.Fatal(err)
34 }
35 identity := map[string]string{"account_id": email, "home_id": rand.Text(), "provider_version": fakeclaude.Version}
36 writeJSON(t, filepath.Join(home, "equipo-identity.json"), identity)
37 bs := append(r.bindings(t), map[string]any{"id": id, "local_id": id, "label": id, "person_id": thintest.Owner, "provider": "claude", "family": "claude", "model": "claude-opus-5-5", "account_id": email, "provider_home": home, "kind": "token", "expected_identity": identity})
38 writeJSON(t, r.cfg.AccountBindingsPath, bs)
39 // As the connect check would: a real request answered, recorded on the
40 // runner, so the token is a connection.
41 st, err := thin.OpenState(context.Background(), r.cfg.StateDir)
42 if err != nil {
43 t.Fatal(err)
44 }
45 (&thin.Conns{Runner: r.cfg, State: st}).Validated(id)
46 st.Close()
47 return token
48}
49
50// T1: a turn and an Engineering step on a token connection. The fake CLI
51// runs only with the token in CLAUDE_CODE_OAUTH_TOKEN (it refuses a turn
52// without it, and exits on a token in argv), and says so in its reply.
53// The runner's hello carries its seal key, the one its enrolment key
54// gives; nothing the runner sent the instance carries the token.
55func TestHeadlessTokenConnection(t *testing.T) {
56 env, inst, r := localEnv(t)
57 _, key, _ := ed25519.GenerateKey(rand.Reader)
58 if err := runnerproto.JournalCredentials(filepath.Join(r.cfg.StateDir, "machine-key.json"), base64.RawURLEncoding.EncodeToString(key)); err != nil {
59 t.Fatal(err)
60 }
61 keys, _ := sealbox.FromEd25519(key)
62 token := r.addToken(t, "claude-7", "tok@example.com")
63 r.only(t, "claude-7")
64 r.start(t)
65 s := open(t, env)
66 s.keep()
67 sent := s.send(t, "Hello on a token.")
68 m := replyOf(t, s, sent.Turn.ID)
69 if !strings.Contains(m.Text, "(signed in by token)") || s.conv.Turns[sent.Turn.ID].Connection != "claude-7" {
70 t.Fatalf("turn on the token connection: %q", m.Text)
71 }
72 text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. edit:README.md|teh panes|the panes"
73 sent = s.send(t, text)
74 id := s.taskOf(t, sent.Turn.ID)
75 step := s.step(t, id, 5*time.Minute, wire.StepDone, wire.StepFailed)
76 if step.State != wire.StepDone || !step.Pushed || step.Account != "claude-7" || !strings.Contains(step.Summary, "(signed in by token)") {
77 t.Fatalf("step on the token connection: %+v", step)
78 }
79 conns, err := env.Client.Connections(s.ctx)
80 if err != nil {
81 t.Fatal(err)
82 }
83 for _, c := range conns.Items {
84 if c.LocalID == "claude-7" && (c.Kind != wire.KindToken || c.State != wire.ConnHealthy) {
85 t.Fatalf("connection %+v", c)
86 }
87 }
88 var hello string
89 if err = inst.DB.Writer().QueryRow("SELECT hello FROM runner_sessions").Scan(&hello); err != nil {
90 t.Fatal(err)
91 }
92 var h wire.Hello
93 if err = json.Unmarshal([]byte(hello), &h); err != nil || h.SealKey != keys.PublicString() {
94 t.Fatalf("hello seal key %q, want %q", h.SealKey, keys.PublicString())
95 }
96 // Everything the instance stored, every table: no token.
97 db := inst.DB.Writer()
98 tables, err := db.Query("SELECT name FROM sqlite_master WHERE type='table'")
99 if err != nil {
100 t.Fatal(err)
101 }
102 var names []string
103 for tables.Next() {
104 var n string
105 _ = tables.Scan(&n)
106 names = append(names, n)
107 }
108 tables.Close()
109 for _, n := range names {
110 rows, err := db.Query(`SELECT * FROM "` + n + `"`)
111 if err != nil {
112 t.Fatal(err)
113 }
114 cols, _ := rows.Columns()
115 for rows.Next() {
116 vals := make([]any, len(cols))
117 ptrs := make([]any, len(cols))
118 for i := range vals {
119 ptrs[i] = &vals[i]
120 }
121 _ = rows.Scan(ptrs...)
122 for _, v := range vals {
123 var s string
124 switch x := v.(type) {
125 case string:
126 s = x
127 case []byte:
128 s = string(x)
129 }
130 if strings.Contains(s, token) {
131 rows.Close()
132 t.Fatalf("the token reached the instance's %s", n)
133 }
134 }
135 }
136 rows.Close()
137 }
138 if page := inst.Get(t, "/tasks/"+id); strings.Contains(page, token) {
139 t.Fatal("the token is on the task page")
140 }
141}
142
143// T2, end to end: the person adds Claude by token through the API as the
144// page does. The box is sealed to the seal key the instance publishes for
145// the runner, the runner opens it, the CLI's status probe passes, the row
146// is healthy with the token's expiry, and the next turn runs on it with
147// the token in CLAUDE_CODE_OAUTH_TOKEN. The token is nowhere on the
148// instance: its database file and WAL, its logs, its API and pages.
149func TestHeadlessTokenPasteEndToEnd(t *testing.T) {
150 env, inst, r := localEnv(t)
151 _, key, _ := ed25519.GenerateKey(rand.Reader)
152 if err := runnerproto.JournalCredentials(filepath.Join(r.cfg.StateDir, "machine-key.json"), base64.RawURLEncoding.EncodeToString(key)); err != nil {
153 t.Fatal(err)
154 }
155 r.only(t)
156 r.start(t)
157 s := open(t, env)
158 s.keep()
159 c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: wire.ProviderClaude, Kind: wire.KindToken})
160 if err != nil {
161 t.Fatal(err)
162 }
163 s.wait(t, "token card", time.Minute, func(cv *thintest.Conversation) bool {
164 v := cv.Connections[c.ID]
165 return v.Prompt != nil && v.Prompt.Kind == wire.PromptToken
166 })
167 snap, err := env.Client.Snapshot(s.ctx)
168 if err != nil || snap.Runner.SealKey == "" {
169 t.Fatalf("no seal key published: %v", err)
170 }
171 token := fakeclaude.Token("paste@example.com")
172 sealed, err := sealbox.Seal(snap.Runner.SealKey, wire.SealedPayload{Secret: token, RunnerID: snap.Runner.ID, ConnectionID: c.ID, Provider: wire.ProviderClaude, Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: time.Now().Add(wire.SealedTTL).UTC().Truncate(time.Second)})
173 if err != nil {
174 t.Fatal(err)
175 }
176 if _, err = env.Client.Secret(s.ctx, c.ID, sealed); err != nil {
177 v, _ := env.Client.Connection(s.ctx, c.ID)
178 t.Fatalf("%v: connection %+v", err, v)
179 }
180 var got wire.Connection
181 s.wait(t, "token healthy", time.Minute, func(cv *thintest.Conversation) bool {
182 got = cv.Connections[c.ID]
183 return got.State == wire.ConnHealthy
184 })
185 if got.ExpiresAt == nil || !got.ExpiresEstimated || time.Until(*got.ExpiresAt) < 360*24*time.Hour || got.LocalID == "" {
186 t.Fatalf("healthy token connection %+v", got)
187 }
188 // Healthy only after a real request through the contained launch;
189 // its usage is the person's, recorded like any other.
190 until(t, "the check's usage", func() bool {
191 var n int
192 err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role = 'check' AND connection = ? AND outcome = ? AND person = ?", got.LocalID, wire.OutcomeReplied, thintest.Owner).Scan(&n)
193 return err == nil && n == 1
194 })
195 // The same box again is refused by the instance or answered with
196 // nothing by the runner: the connection stays as it is.
197 _, _ = env.Client.Secret(s.ctx, c.ID, sealed)
198 sent := s.send(t, "Hello on the pasted token.")
199 m := replyOf(t, s, sent.Turn.ID)
200 if !strings.Contains(m.Text, "(signed in by token)") || s.conv.Turns[sent.Turn.ID].Connection != got.LocalID {
201 t.Fatalf("turn on the pasted token: %q", m.Text)
202 }
203 // Nothing on the instance holds the token: the database file and its
204 // WAL as bytes, the logs, the API and the page.
205 for _, f := range []string{inst.Path, inst.Path + "-wal"} {
206 raw, err := os.ReadFile(f)
207 if err != nil && !os.IsNotExist(err) {
208 t.Fatal(err)
209 }
210 if strings.Contains(string(raw), token) {
211 t.Fatalf("the token is in %s", filepath.Base(f))
212 }
213 }
214 if strings.Contains(inst.Logs(), token) {
215 t.Fatal("the token is in the instance's logs")
216 }
217 if page := inst.Get(t, "/conversation/connections"); strings.Contains(page, token) || !strings.Contains(page, "Expires about") {
218 t.Fatal("the token is on the page, or its expiry is not")
219 }
220 list, _ := env.Client.Connections(s.ctx)
221 raw, _ := json.Marshal(list)
222 if strings.Contains(string(raw), token) {
223 t.Fatal("the token is in the API")
224 }
225 // Signed out: the home and the token file go.
226 if _, err = env.Client.SignOut(s.ctx, c.ID); err != nil {
227 t.Fatal(err)
228 }
229 s.wait(t, "signed out", time.Minute, func(cv *thintest.Conversation) bool { return cv.Connections[c.ID].State == wire.ConnSignedOut })
230 if _, err := os.Stat(filepath.Join(r.root, "accounts", got.LocalID)); !os.IsNotExist(err) {
231 t.Fatalf("the token's home stayed: %v", err)
232 }
233}
234
235// A bad token pasted end to end. The CLI's status says signed in for any
236// token, so only the check's real request, through the contained launch,
237// finds it out: "This token was rejected", never healthy, the home and
238// the binding gone, and the refused request's usage recorded. The link
239// stays up: the instance takes every frame the runner sent.
240func TestHeadlessTokenRejected(t *testing.T) {
241 env, inst, r := localEnv(t)
242 _, key, _ := ed25519.GenerateKey(rand.Reader)
243 if err := runnerproto.JournalCredentials(filepath.Join(r.cfg.StateDir, "machine-key.json"), base64.RawURLEncoding.EncodeToString(key)); err != nil {
244 t.Fatal(err)
245 }
246 r.only(t)
247 homes := func() string {
248 entries, _ := os.ReadDir(filepath.Join(r.root, "accounts"))
249 var names []string
250 for _, e := range entries {
251 names = append(names, e.Name())
252 }
253 return strings.Join(names, ",")
254 }
255 before := homes()
256 r.start(t)
257 s := open(t, env)
258 s.keep()
259 c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: wire.ProviderClaude, Kind: wire.KindToken})
260 if err != nil {
261 t.Fatal(err)
262 }
263 s.wait(t, "token card", time.Minute, func(cv *thintest.Conversation) bool {
264 v := cv.Connections[c.ID]
265 return v.Prompt != nil && v.Prompt.Kind == wire.PromptToken
266 })
267 snap, err := env.Client.Snapshot(s.ctx)
268 if err != nil {
269 t.Fatal(err)
270 }
271 sealed, err := sealbox.Seal(snap.Runner.SealKey, wire.SealedPayload{Secret: "sk-ant-oat01-revoked-by-the-provider", RunnerID: snap.Runner.ID, ConnectionID: c.ID, Provider: wire.ProviderClaude, Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: time.Now().Add(wire.SealedTTL).UTC().Truncate(time.Second)})
272 if err != nil {
273 t.Fatal(err)
274 }
275 if _, err = env.Client.Secret(s.ctx, c.ID, sealed); err != nil {
276 t.Fatal(err)
277 }
278 var end wire.Connection
279 s.wait(t, "the attempt's end", time.Minute, func(cv *thintest.Conversation) bool {
280 end = cv.Connections[c.ID]
281 return end.State != wire.ConnConnecting
282 })
283 if end.State != wire.ConnError || end.Reason != "provider_refused" || end.LocalID != "" {
284 t.Fatalf("a bad token ended %+v", end)
285 }
286 if page := inst.Get(t, "/conversation/connections"); !strings.Contains(page, "This token was rejected. Run claude setup-token again.") {
287 t.Fatal("the row does not say the token was rejected")
288 }
289 until(t, "the home and binding gone", func() bool {
290 return homes() == before && len(r.bindings(t)) == 0
291 })
292 until(t, "the refused check's usage", func() bool {
293 var n int
294 err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role = 'check' AND outcome = ?", wire.OutcomeFailed).Scan(&n)
295 return err == nil && n == 1
296 })
297}
298
299// A token connection's check reads the provider's rate limits as a turn
300// does: a check that reports windows leaves the connection with that
301// headroom on the runner, and one refused on quota leaves it limited
302// until the reset the provider gave, on the runner and on the row. No
303// turn runs on either.
304func TestHeadlessTokenCheckHeadroom(t *testing.T) {
305 env, inst, r := localEnv(t)
306 r.addToken(t, "claude-7", "tok@example.com")
307 r.addToken(t, "claude-8", "spent-tok@example.com")
308 r.only(t, "claude-7", "claude-8")
309 r.start(t)
310 s := open(t, env)
311 s.keep()
312 ids := map[string]string{}
313 s.wait(t, "both rows", time.Minute, func(cv *thintest.Conversation) bool {
314 for _, c := range cv.Connections {
315 ids[c.LocalID] = c.ID
316 }
317 return ids["claude-7"] != "" && ids["claude-8"] != ""
318 })
319 for _, local := range []string{"claude-7", "claude-8"} {
320 if err := env.Client.CheckConnection(s.ctx, ids[local]); err != nil {
321 t.Fatal(err)
322 }
323 }
324 var spent wire.Connection
325 s.wait(t, "the refused check limits its row", 2*time.Minute, func(cv *thintest.Conversation) bool {
326 spent = cv.Connections[ids["claude-8"]]
327 return spent.State == wire.ConnLimited
328 })
329 if spent.Headroom == nil || spent.Headroom.ResetsAt == nil || time.Until(*spent.Headroom.ResetsAt) < 40*time.Hour {
330 t.Fatalf("the limited row has no reported reset: %+v", spent.Headroom)
331 }
332 until(t, "both checks' usage", func() bool {
333 var n int
334 err := inst.DB.Writer().QueryRow("SELECT count(DISTINCT connection) FROM chat_usage WHERE role = 'check'").Scan(&n)
335 return err == nil && n == 2
336 })
337 r.stop(t)
338 st, err := thin.OpenState(context.Background(), r.cfg.StateDir)
339 if err != nil {
340 t.Fatal(err)
341 }
342 defer st.Close()
343 held := map[string]wire.HeldConnection{}
344 for _, h := range (&thin.Conns{Runner: r.cfg, State: st}).Held() {
345 held[h.LocalID] = h
346 }
347 windows := func(h *wire.Headroom) map[string]float64 {
348 out := map[string]float64{}
349 if h != nil {
350 for _, w := range h.Windows {
351 out[w.Name] = math.Round(w.UsedPercent)
352 }
353 }
354 return out
355 }
356 if got := windows(held["claude-7"].Headroom); held["claude-7"].State != wire.ConnHealthy || len(got) != 2 || got["five_hour"] != 12 || got["seven_day"] != 25 {
357 t.Fatalf("the check's windows were not kept: %+v %v", held["claude-7"], got)
358 }
359 if h := held["claude-8"]; h.State != wire.ConnLimited || windows(h.Headroom)["seven_day"] != 100 {
360 t.Fatalf("the refused check did not limit the connection: %+v", h)
361 }
362 var turns int
363 if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role <> 'check'").Scan(&turns); err != nil || turns != 0 {
364 t.Fatalf("a turn ran: %d %v", turns, err)
365 }
366}
367
368// until polls cond (it reads files and rows, which send no events).
369func until(t *testing.T, what string, cond func() bool) {
370 t.Helper()
371 deadline := time.Now().Add(time.Minute)
372 for !cond() {
373 if time.Now().After(deadline) {
374 t.Fatalf("timed out waiting for %s", what)
375 }
376 time.Sleep(50 * time.Millisecond)
377 }
378}
379