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 "context"
5 "net/http"
6 "net/url"
7 "strings"
8 "testing"
9 "time"
10
11 "amadan.net/oficina/equipo/internal/equipo"
12 "amadan.net/oficina/equipo/internal/sealbox"
13 "amadan.net/oficina/equipo/internal/wire"
14)
15
16// canaryKey is an obviously fake TensorX key: sealed in the test, never
17// seen by the instance.
18const canaryKey = "tx-CANARY-not-a-real-key-CANARY"
19
20// TestContractMeteredConnection (connectors spec S1, §§2.1 to 2.3, §10):
21// an API-key connection is refused without its confirmations or its
22// budget and on a runner before protocol 12; with them it goes to the
23// runner as connect (kind api_key, billing, budget); its key is sealed
24// to the runner and bound to TensorX's origin; the person picks the
25// model from the runner's list; the probe's usage is recorded with role
26// probe and its cost; hello brings the budget and spend; a budget change
27// is pending until the runner acks its frame; Resume is bound to the
28// pause it saw. The canary key appears nowhere the instance can read.
29func TestContractMeteredConnection(t *testing.T) {
30 budget := &wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth}
31 good := wire.Connect{Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, LimitConfirmed: true, Budget: budget}
32 // An older runner is refused a metered connection, not downgraded.
33 {
34 old := newRig(t)
35 runner := dialAt(t, old, wire.ProtocolPreviewHost)
36 hello := primaryAt(held(), wire.ProtocolPreviewHost)
37 hello.Generation, hello.SealKey = runner.Welcome.Generation, sealKeys(t).PublicString()
38 if err := runner.Send(old.ctx, "h1", wire.FrameHello, hello); err != nil {
39 t.Fatal(err)
40 }
41 old.wait("runner online", func(c *Conversation) bool { return c.Runner.Online })
42 if _, err := old.client.Connect(old.ctx, good); Status(err) != 409 {
43 t.Fatalf("a protocol 11 runner: %v", err)
44 }
45 ctx, cancel := context.WithTimeout(old.ctx, 300*time.Millisecond)
46 if f, _, _ := runner.Expect(ctx, wire.FrameConnect); f.Type == wire.FrameConnect {
47 t.Fatal("a protocol 11 runner was sent a connect")
48 }
49 cancel()
50 }
51 r := newRig(t)
52 keys := sealKeys(t)
53 runner := dialAt(t, r, wire.ProtocolMetered)
54 hello := primaryAt(held(), wire.ProtocolMetered)
55 hello.Generation, hello.SealKey = runner.Welcome.Generation, keys.PublicString()
56 if err := runner.Send(r.ctx, "h1", wire.FrameHello, hello); err != nil {
57 t.Fatal(err)
58 }
59 r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online })
60 var runnerID string
61 waitFor(t, "the runner listed", func() bool {
62 list, err := r.client.Runners(r.ctx)
63 if err != nil || len(list.Items) != 1 {
64 return false
65 }
66 runnerID = list.Items[0].ID
67 return true
68 })
69 for name, bad := range map[string]wire.Connect{
70 "no limit confirmation": {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, Budget: budget},
71 "pay-as-you-go off on a per-token provider": {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, LimitConfirmed: true, PaygOffConfirmed: true, Budget: budget},
72 "no budget": {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, LimitConfirmed: true},
73 "a day over a month": {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, LimitConfirmed: true, Budget: &wire.Budget{Day: 5, Month: 4}},
74 "an unknown provider": {Provider: "elsewhere", Kind: wire.KindAPIKey, LimitConfirmed: true, Budget: budget},
75 "a confirmation on a subscription": {Provider: "codex", Kind: wire.KindSubscription, LimitConfirmed: true},
76 } {
77 if _, err := r.client.Connect(r.ctx, bad); Status(err) != 422 {
78 t.Fatalf("%s: %v", name, err)
79 }
80 }
81 // The Add page: TensorX with its required confirmation, what it
82 // means, and the budget pre-filled; posted without the confirmation
83 // it is refused and says so.
84 pages := &toolRig{rig: r}
85 owner := r.inst.Cookie()
86 add := pages.get(owner, "/conversation/settings/connections/add", 200)
87 for _, want := range []string{`data-add-metered="tensorx"`, `name="limit_confirmed" value="1" required`, "This key has a spending limit at TensorX", "I can’t see this limit.", `name="budget_day" inputmode="decimal" value="1"`, `name="budget_month" inputmode="decimal" value="10"`} {
88 if !strings.Contains(add, want) {
89 t.Fatalf("the Add page lacks %s", want)
90 }
91 }
92 if status, loc := pages.post(owner, "/conversation/connections", url.Values{"provider": {"tensorx"}, "kind": {"api_key"}, "budget_day": {"1"}, "budget_month": {"10"}}); status != http.StatusSeeOther || loc != "/conversation/settings/connections/add?refused=confirm" {
93 t.Fatalf("unconfirmed add: %d %q", status, loc)
94 }
95 if page := pages.get(owner, "/conversation/settings/connections/add?refused=confirm", 200); !strings.Contains(page, "Confirm the spending limit and check both budget amounts before continuing.") {
96 t.Fatal("the refusal is not said")
97 }
98 attempt, err := r.client.Connect(r.ctx, good)
99 if err != nil || attempt.State != wire.ConnConnecting || attempt.Kind != wire.KindAPIKey || attempt.Prompt == nil || attempt.Prompt.Kind != wire.PromptAPIKey || attempt.Billing != wire.BillingMetered || attempt.Harness != wire.HarnessPi || attempt.Upstream != "https://api.tensorx.ai" || attempt.LimitConfirmedAt == nil || attempt.PaygOffConfirmedAt != nil {
100 t.Fatalf("attempt %+v %v", attempt, err)
101 }
102 f, body, err := runner.Expect(r.ctx, wire.FrameConnect)
103 if err != nil {
104 t.Fatal(err)
105 }
106 shape(t, "frames/connect-api-key.json", runner.Received[len(runner.Received)-1])
107 if cmd := body.(*wire.ConnectCommand); cmd.Connection != attempt.ID || cmd.Kind != wire.KindAPIKey || cmd.Provider != wire.ProviderTensorX || cmd.Billing != wire.BillingMetered || cmd.Budget == nil || cmd.Budget.Day != wire.DefaultBudgetDay || cmd.Budget.Currency != "USD" || cmd.Budget.Revision != 1 {
108 t.Fatalf("connect %+v", cmd)
109 }
110 runner.Send(r.ctx, "a-connect", wire.FrameAck, wire.Ack{ID: f.ID})
111 if card := pages.get(owner, "/conversation/settings/connections/add", 200); !strings.Contains(card, `data-kind="api_key" data-runner="`+runnerID+`" data-endpoint="https://api.tensorx.ai:443" data-seal-key="`) || !strings.Contains(card, "data-key-form") || !strings.Contains(card, "Paste your TensorX API key") {
112 t.Fatal("the key card is not sealed to the runner for TensorX's origin")
113 }
114
115 // The key, sealed to the runner and bound to TensorX's origin.
116 endpoint := wire.APIKeyProviders[wire.ProviderTensorX].Endpoint
117 expires := time.Now().UTC().Add(wire.SealedTTL).Truncate(time.Second)
118 sealed, err := sealbox.Seal(keys.PublicString(), wire.SealedPayload{Secret: canaryKey, RunnerID: runnerID, ConnectionID: attempt.ID, Provider: wire.ProviderTensorX, Endpoint: endpoint, Attempt: 1, ExpiresAt: expires})
119 if err != nil {
120 t.Fatal(err)
121 }
122 for name, change := range map[string]func(*wire.Sealed){
123 "Claude's endpoint": func(s *wire.Sealed) { s.Endpoint = wire.EndpointAnthropic },
124 "Claude": func(s *wire.Sealed) { s.Provider = wire.ProviderClaude },
125 "attempt 2": func(s *wire.Sealed) { s.Attempt = 2 },
126 } {
127 bad := sealed
128 change(&bad)
129 if _, err := r.client.Secret(r.ctx, attempt.ID, bad); Status(err) != 422 {
130 t.Fatalf("%s: %v", name, err)
131 }
132 }
133 if posted, err := r.client.Secret(r.ctx, attempt.ID, sealed); err != nil || posted.Prompt != nil {
134 t.Fatalf("secret %+v %v", posted, err)
135 }
136 f, body, err = runner.Expect(r.ctx, wire.FrameSecret)
137 if err != nil {
138 t.Fatal(err)
139 }
140 if opened, err := keys.Open(body.(*wire.SecretCommand).Sealed, time.Now()); err != nil || opened.Secret != canaryKey || opened.Endpoint != endpoint {
141 t.Fatalf("the runner could not open the box: %v", err)
142 }
143 runner.Send(r.ctx, "a-secret", wire.FrameAck, wire.Ack{ID: f.ID})
144
145 // The runner's model list; the person picks one of them.
146 if _, err := r.client.ChooseModel(r.ctx, attempt.ID, "z-ai/glm-5.3"); Status(err) != 409 {
147 t.Fatalf("a model before the list: %v", err)
148 }
149 runner.Send(r.ctx, "r-models", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: wire.ProviderTensorX, State: wire.ConnConnecting, Prompt: &wire.ConnectPrompt{Kind: wire.PromptModel, Models: []string{"moonshotai/kimi-k3.1-pro", "z-ai/glm-5.3"}}})
150 r.wait("the model card", func(c *Conversation) bool {
151 p := c.Connections[attempt.ID].Prompt
152 return p != nil && p.Kind == wire.PromptModel && len(p.Models) == 2
153 })
154 got, _ := r.client.Connection(r.ctx, attempt.ID)
155 shape(t, "api/connection-choose-model.json", got)
156 if card := pages.get(owner, "/conversation/settings/connections/add", 200); !strings.Contains(card, `action="/conversation/connections/`+attempt.ID+`/model"`) || !strings.Contains(card, `value="z-ai/glm-5.3"`) {
157 t.Fatal("the model card does not list the runner's models")
158 }
159 if _, err := r.client.ChooseModel(r.ctx, attempt.ID, "vendor/unlisted"); Status(err) != 422 {
160 t.Fatalf("an unlisted model: %v", err)
161 }
162 if picked, err := r.client.ChooseModel(r.ctx, attempt.ID, "z-ai/glm-5.3"); err != nil || picked.Model != "z-ai/glm-5.3" || len(picked.Prompt.Models) != 0 {
163 t.Fatalf("picked %+v %v", picked, err)
164 }
165 f, body, err = runner.Expect(r.ctx, wire.FrameModel)
166 if err != nil {
167 t.Fatal(err)
168 }
169 shape(t, "frames/model.json", runner.Received[len(runner.Received)-1])
170 if cmd := body.(*wire.ModelCommand); cmd.Connection != attempt.ID || cmd.Model != "z-ai/glm-5.3" || cmd.Person != Owner {
171 t.Fatalf("model %+v", cmd)
172 }
173 runner.Send(r.ctx, "a-model", wire.FrameAck, wire.Ack{ID: f.ID})
174
175 // The probe: healthy, its usage charged with role probe.
176 cost, in, out := int64(21), int64(9), int64(1)
177 probe := wire.UsageReport{ProbeID: "pr_" + attempt.ID, Rows: []wire.Usage{{Provider: wire.ProviderTensorX, Connection: "tensorx-1", Model: "z-ai/glm-5.3", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &in, OutputTokens: &out, CostMicros: &cost, Currency: "USD", PriceVersion: "tensorx-2026-11-12"}}}
178 for i := 0; i < 2; i++ {
179 // Resent: recorded once.
180 if err := runner.Send(r.ctx, "r-probe", wire.FrameUsage, probe); err != nil {
181 t.Fatal(err)
182 }
183 }
184 runner.Send(r.ctx, "r-healthy", wire.FrameConnection, wire.ConnectionReport{Connection: attempt.ID, Person: Owner, Provider: wire.ProviderTensorX, LocalID: "tensorx-1", State: wire.ConnHealthy})
185 metered := wire.HeldConnection{LocalID: "tensorx-1", Person: Owner, Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, State: wire.ConnHealthy, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Budget: &wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth, Currency: "USD", Revision: 1}, Spend: &wire.Spend{Day: 840_000, Month: 6_200_000, Currency: "USD"}}
186 hello.Connections = []wire.HeldConnection{metered}
187 runner.Send(r.ctx, "h3", wire.FrameHello, hello)
188 r.wait("healthy with its spend", func(c *Conversation) bool {
189 v := c.Connections[attempt.ID]
190 return v.State == wire.ConnHealthy && v.Spend != nil && v.Spend.Day == 840_000 && v.Model == "z-ai/glm-5.3"
191 })
192 // The spend line (spec §2.3).
193 list := pages.get(owner, "/conversation/settings/connections", 200)
194 for _, want := range []string{"$0.84 of $1 today · $6.20 of $10 this month", "Reported by Pi. Spending can exceed the budget by one step.", "z-ai/glm-5.3", `data-budget-form="` + attempt.ID + `"`} {
195 if !strings.Contains(list, want) {
196 t.Fatalf("the row lacks %q", want)
197 }
198 }
199 var rows int
200 var role string
201 var charged int64
202 if err := r.inst.DB.Writer().QueryRow("SELECT count(*), max(role), max(cost_micros) FROM chat_usage WHERE step_id = ?", "pr_"+attempt.ID).Scan(&rows, &role, &charged); err != nil || rows != 1 || role != wire.UsageProbe || charged != 21 {
203 t.Fatalf("probe usage: %d %s %d %v", rows, role, charged, err)
204 }
205
206 // A budget change: pending until the runner acks the frame.
207 if _, err := r.client.SetBudget(r.ctx, attempt.ID, wire.SetBudget{Day: 2_000_000, Month: 10_000_000, Revision: 0}); Status(err) != 409 {
208 t.Fatalf("a stale budget revision: %v", err)
209 }
210 if _, err := r.client.SetBudget(r.ctx, attempt.ID, wire.SetBudget{Day: 20_000_000, Month: 10_000_000, Revision: 1}); Status(err) != 422 {
211 t.Fatalf("a day over its month: %v", err)
212 }
213 changed, err := r.client.SetBudget(r.ctx, attempt.ID, wire.SetBudget{Day: 2_000_000, Month: 10_000_000, Revision: 1})
214 if err != nil || !changed.BudgetPending || changed.Budget.Revision != 2 || changed.Budget.Day != 2_000_000 {
215 t.Fatalf("budget %+v %v", changed, err)
216 }
217 shape(t, "api/connection-metered.json", changed)
218 if page := pages.get(owner, "/conversation/settings/connections", 200); !strings.Contains(page, "Applies when Headless runner confirms") {
219 t.Fatal("the pending budget is not said")
220 }
221 f, body, err = runner.Expect(r.ctx, wire.FrameBudget)
222 if err != nil {
223 t.Fatal(err)
224 }
225 shape(t, "frames/budget.json", runner.Received[len(runner.Received)-1])
226 if cmd := body.(*wire.BudgetCommand); cmd.LocalID != "tensorx-1" || cmd.Budget.Revision != 2 || cmd.Budget.Currency != "USD" {
227 t.Fatalf("budget frame %+v", cmd)
228 }
229 runner.Send(r.ctx, "a-budget", wire.FrameAck, wire.Ack{ID: f.ID})
230 r.wait("the budget applied", func(c *Conversation) bool {
231 v := c.Connections[attempt.ID]
232 return !v.BudgetPending && v.Budget != nil && v.Budget.Revision == 2
233 })
234
235 // Resume is bound to the pause the person saw.
236 if err := r.client.ResumeSpend(r.ctx, attempt.ID, 3); Status(err) != 409 {
237 t.Fatalf("a resume with nothing paused: %v", err)
238 }
239 metered.Spend = &wire.Spend{Day: 840_000, Month: 6_200_000, Currency: "USD", Unknown: true, PauseRevision: 3}
240 metered.Budget = &wire.Budget{Day: 2_000_000, Month: 10_000_000, Currency: "USD", Revision: 2}
241 hello.Connections = []wire.HeldConnection{metered}
242 runner.Send(r.ctx, "h4", wire.FrameHello, hello)
243 r.wait("spend unknown", func(c *Conversation) bool {
244 v := c.Connections[attempt.ID]
245 return v.Spend != nil && v.Spend.Unknown
246 })
247 if page := pages.get(owner, "/conversation/settings/connections", 200); !strings.Contains(page, "Paused: spend unknown. Check your spending at TensorX, then choose Resume") || !strings.Contains(page, `name="pause_revision" value="3"`) {
248 t.Fatal("spend unknown is not said with its Resume")
249 }
250 if err := r.client.ResumeSpend(r.ctx, attempt.ID, 2); Status(err) != 409 {
251 t.Fatalf("a stale resume: %v", err)
252 }
253 if err := r.client.ResumeSpend(r.ctx, attempt.ID, 3); err != nil {
254 t.Fatal(err)
255 }
256 _, body, err = runner.Expect(r.ctx, wire.FrameResumeSpend)
257 if err != nil {
258 t.Fatal(err)
259 }
260 shape(t, "frames/resume_spend.json", runner.Received[len(runner.Received)-1])
261 if cmd := body.(*wire.ResumeSpendCommand); cmd.PauseRevision != 3 || cmd.LocalID != "tensorx-1" {
262 t.Fatalf("resume frame %+v", cmd)
263 }
264
265 // Security round finding 8: a teammate's model pick, budget change
266 // or Resume on this connection finds nothing; once the owner is off
267 // the roster, theirs changes nothing either.
268 commands := func() int {
269 var n int
270 r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE person = ?", Owner).Scan(&n)
271 return n
272 }
273 before, rev := commands(), r.conv.Connections[attempt.ID].Revision
274 mate := personToolRig(t, pages, "mate@example.com", equipo.RoleOwner)
275 if _, err := mate.client.ChooseModel(r.ctx, attempt.ID, "z-ai/glm-5.3"); Status(err) != 404 {
276 t.Fatalf("a teammate's model pick: %v", err)
277 }
278 if _, err := mate.client.SetBudget(r.ctx, attempt.ID, wire.SetBudget{Day: 1, Month: 1, Revision: 2}); Status(err) != 404 {
279 t.Fatalf("a teammate's budget: %v", err)
280 }
281 if err := mate.client.ResumeSpend(r.ctx, attempt.ID, 3); Status(err) != 404 {
282 t.Fatalf("a teammate's resume: %v", err)
283 }
284 if _, err := r.inst.DB.Writer().Exec("UPDATE members SET active = 0 WHERE address = ?", Owner); err != nil {
285 t.Fatal(err)
286 }
287 if _, err := r.client.SetBudget(r.ctx, attempt.ID, wire.SetBudget{Day: 3_000_000, Month: 10_000_000, Revision: 2}); err == nil {
288 t.Fatal("a removed person's budget change went through")
289 }
290 if err := r.client.ResumeSpend(r.ctx, attempt.ID, 3); err == nil {
291 t.Fatal("a removed person's resume went through")
292 }
293 var after int64
294 r.inst.DB.Writer().QueryRow("SELECT revision FROM chat_connections WHERE id = ?", attempt.ID).Scan(&after)
295 if commands() != before || after != rev {
296 t.Fatalf("the owner's commands %d (was %d), revision %d (was %d)", commands(), before, after, rev)
297 }
298 if _, err := r.inst.DB.Writer().Exec("UPDATE members SET active = 1 WHERE address = ?", Owner); err != nil {
299 t.Fatal(err)
300 }
301
302 // The key is nowhere on the instance.
303 var found int
304 for _, q := range []string{"SELECT count(*) FROM runner_commands WHERE body LIKE ?", "SELECT count(*) FROM chat_connections WHERE coalesce(prompt,'') || coalesce(budget,'') || coalesce(spend,'') LIKE ?", "SELECT count(*) FROM chat_events WHERE body LIKE ?"} {
305 var n int
306 if err := r.inst.DB.Writer().QueryRow(q, "%"+canaryKey+"%").Scan(&n); err != nil && !strings.Contains(err.Error(), "no such") {
307 t.Fatal(err)
308 }
309 found += n
310 }
311 if found != 0 {
312 t.Fatalf("the key is on the instance (%d)", found)
313 }
314}
315
316// dialAt connects a fake runner whose first hello speaks protocol.
317func dialAt(t *testing.T, r *rig, protocol int) *FakeRunner {
318 t.Helper()
319 f, err := DialRunnerHello(r.ctx, r.inst.URL, r.runner, primaryAt(held(), protocol))
320 if err != nil {
321 t.Fatal(err)
322 }
323 t.Cleanup(f.Close)
324 return f
325}
326