package thin import ( "context" "encoding/json" "net/http" "net/http/httptest" "net/netip" "os" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/metered" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/wire" ) // fakeTensorX is an OpenAI-compatible provider on 127.0.0.1 standing in // for TensorX: one key it accepts, a model list, and one-token // completions it counts. No real provider is called. type fakeTensorX struct { *httptest.Server mu sync.Mutex key string probes []string usage string // answered, when set, is the model the provider says answered; // hold, when set, keeps a completion open until it is closed. answered string hold chan struct{} started chan struct{} // swap names, per model asked for, the model that answers instead; // gone, the models it does not have (404, model_not_found). swap map[string]string gone map[string]bool // list, when set, is the model list it answers. list string } func newFakeTensorX(t *testing.T, key string) *fakeTensorX { f := &fakeTensorX{key: key, usage: `{"prompt_tokens":9,"completion_tokens":1}`} f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { f.mu.Lock() key, usage := f.key, f.usage f.mu.Unlock() if r.Header.Get("Authorization") != "Bearer "+key { w.WriteHeader(http.StatusUnauthorized) return } switch r.Method + " " + r.URL.Path { case "GET /v1/models": f.mu.Lock() list := f.list f.mu.Unlock() if list == "" { list = `{"data":[{"id":"z-ai/glm-5.3"},{"id":"vendor/unpriced"}]}` } w.Write([]byte(list)) case "POST /v1/chat/completions": var in struct { Model string `json:"model"` MaxTokens int `json:"max_tokens"` } if json.NewDecoder(r.Body).Decode(&in) != nil || in.MaxTokens != 1 { w.WriteHeader(http.StatusBadRequest) return } f.mu.Lock() f.probes = append(f.probes, in.Model) model, hold, started := in.Model, f.hold, f.started if f.answered != "" { model = f.answered } if other, ok := f.swap[in.Model]; ok { model = other } gone := f.gone[in.Model] f.mu.Unlock() if gone { w.WriteHeader(http.StatusNotFound) w.Write([]byte(`{"error":{"code":"model_not_found"}}`)) return } if hold != nil { started <- struct{}{} <-hold } w.Write([]byte(`{"model":"` + model + `","choices":[{"message":{"content":"ok"}}],"usage":` + usage + `}`)) default: w.WriteHeader(http.StatusNotFound) } })) t.Cleanup(f.Close) if !strings.HasPrefix(f.URL, "http://127.0.0.1:") { t.Fatalf("fake provider not on loopback: %s", f.URL) } return f } func (f *fakeTensorX) set(key, usage string) { f.mu.Lock() defer f.mu.Unlock() if key != "" { f.key = key } if usage != "" { f.usage = usage } } func (f *fakeTensorX) probeCount() int { f.mu.Lock() defer f.mu.Unlock() return len(f.probes) } // meteredConnector is a connector with the metered guard, its API-key // providers pointed at fake. func (r *tokenRig) meteredConnector(fake *fakeTensorX) *Connector { if r.conns.Meter == nil { r.conns.Meter = &metered.Meter{DB: r.state.db} } c := r.connector() // The production transport, with the fake's loopback address allowed. c.http, c.origin = connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), func(string) string { return fake.URL } return c } func (r *tokenRig) startAPIKey(c *Connector, id string) string { r.t.Helper() cmd := wire.ConnectCommand{Connection: id, Person: connPerson, Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, Billing: wire.BillingMetered, Budget: &wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth, Currency: "USD", Revision: 1}} if err := c.Accept(r.ctx, "f-connect-"+id, cmd); err != nil { r.t.Fatal(err) } r.card(id, wire.PromptAPIKey) var home string _ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id=?", id).Scan(&home) if home == "" || filepath.Dir(home) != r.root || !strings.HasPrefix(filepath.Base(home), "tensorx-") { r.t.Fatalf("attempt home %q", home) } return home } func (r *tokenRig) card(id, kind string) wire.ConnectPrompt { r.t.Helper() var p wire.ConnectPrompt r.waitFor(func() bool { for _, v := range r.reports(id) { if v.State == wire.ConnConnecting && v.Prompt != nil && v.Prompt.Kind == kind { p = *v.Prompt return true } } return false }, "the "+kind+" card") return p } // sealedKey is a box for an API-key attempt, as the page seals it. func (r *tokenRig) sealedKey(id, key string, change func(*wire.SealedPayload)) wire.SecretCommand { r.t.Helper() p := wire.SealedPayload{Secret: key, RunnerID: tokenRunner, ConnectionID: id, Provider: wire.ProviderTensorX, Endpoint: wire.APIKeyProviders[wire.ProviderTensorX].Endpoint, Attempt: 1, ExpiresAt: time.Now().Add(5 * time.Minute).UTC()} if change != nil { change(&p) } s, err := sealbox.Seal(r.keys.PublicString(), p) if err != nil { r.t.Fatal(err) } return wire.SecretCommand{Connection: id, Person: connPerson, Sealed: s} } func (r *tokenRig) held(local string) (wire.HeldConnection, bool) { for _, h := range r.conns.Held() { if h.LocalID == local { return h, true } } return wire.HeldConnection{}, false } // eligibleChoices are a models card's models that can be allowed. func eligibleChoices(p wire.ConnectPrompt) []string { var out []string for _, c := range p.Choices { if c.Eligible { out = append(out, c.ID) } } return out } func (r *tokenRig) usageFrames() []wire.UsageReport { frames, _, err := r.state.Unacked(context.Background(), 0) if err != nil { r.t.Fatal(err) } var out []wire.UsageReport for _, f := range frames { var v wire.UsageReport if f.Type == wire.FrameUsage && json.Unmarshal(f.Data, &v) == nil { out = append(out, v) } } return out } // TestAPIKeyConnectionRoundTrip is S1's sealed API-key paste on the // runner: the box bound to TensorX's origin is delivered into the home // (0600); the runner reads the model list and offers the priced ones; // the picked model's one-token probe against the fake provider passes // the metered guard and is charged as a usage row with role probe; the // connection is then healthy in hello with its budget and spend; Check // again probes again and a refused key reads sign_in_again; a budget // frame applies above the revision held; sign-out deletes the home and // the record. The key is in no frame and no log line. func TestAPIKeyConnectionRoundTrip(t *testing.T) { const key = "tx-fake-key-fake-key" r := newTokenRig(t) fake := newFakeTensorX(t, key) c := r.meteredConnector(fake) home := r.startAPIKey(c, "cn_tx") local := filepath.Base(home) if !r.deliver(c, "f-secret-1", r.sealedKey("cn_tx", key, nil)) { t.Fatalf("secret refused: %v", r.errs) } // The models card (ยง16.1): every listed model, the priced and tiered // ones eligible. An older instance would be said the one-model pick // (Encode); its model frame is taken as a set of one. p := r.card("cn_tx", wire.PromptModels) if strings.Join(eligibleChoices(p), ",") != "z-ai/glm-5.3" || len(p.Choices) != 2 { t.Fatalf("offered %+v", p.Choices) } if fake.probeCount() != 0 { t.Fatal("probed before a model was picked") } // A model not offered changes nothing; the offered one runs the probe. if err := c.Model(r.ctx, "f-model-0", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "vendor/unpriced"}); err != nil { t.Fatal(err) } if err := c.Model(r.ctx, "f-model-1", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "z-ai/glm-5.3"}); err != nil { t.Fatal(err) } end := r.ended("cn_tx") if end.State != wire.ConnHealthy || end.LocalID != local || end.Provider != wire.ProviderTensorX { t.Fatalf("end %+v", end) } if fake.probeCount() != 1 { t.Fatalf("probes %d", fake.probeCount()) } raw, err := os.ReadFile(filepath.Join(home, ".oauth-token")) info, _ := os.Stat(filepath.Join(home, ".oauth-token")) if err != nil || string(raw) != key || info.Mode().Perm() != 0600 { t.Fatalf("key file: %v", err) } usage := r.usageFrames() if len(usage) != 1 || usage[0].ProbeID != "pr_cn_tx" || len(usage[0].Rows) != 1 { t.Fatalf("probe usage %+v", usage) } row := usage[0].Rows[0] // 9 input at 1.75 and 1 output at 4.50 per million: 16 + 5 micros. if row.CostMicros == nil || *row.CostMicros != 21 || row.PriceVersion != "tensorx-2026-11-12" || row.Connection != local || !row.Complete { t.Fatalf("probe row %+v", row) } h, ok := r.held(local) if !ok || h.Kind != wire.KindAPIKey || h.State != wire.ConnHealthy || h.Harness != wire.HarnessPi || h.Upstream != "https://api.tensorx.ai" || h.Billing != wire.BillingMetered || h.Model != "z-ai/glm-5.3" || h.Budget == nil || h.Budget.Day != wire.DefaultBudgetDay || h.Spend == nil || h.Spend.Day != 21 || h.Spend.Unknown || h.Spend.Running { t.Fatalf("held %+v %v", h, ok) } // Check again: another billable probe, charged. if err := c.Check(r.ctx, "f-check-1", wire.CheckCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}); err != nil { t.Fatal(err) } r.waitFor(func() bool { h, _ := r.held(local); return h.Spend != nil && h.Spend.Day == 42 }, "the second probe's charge") // The provider refuses the key now: sign_in_again, nothing charged. fake.set("rotated", "") if err := c.Check(r.ctx, "f-check-2", wire.CheckCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}); err != nil { t.Fatal(err) } r.waitFor(func() bool { h, _ := r.held(local); return h.State == wire.ConnSignInAgain }, "sign_in_again") if h, _ := r.held(local); h.Spend.Day != 42 || h.Spend.Unknown { t.Fatalf("a refused probe charged: %+v", h.Spend) } // Budget frames: applied above the revision held, else not. if err := c.Budget(r.ctx, "f-budget-1", wire.BudgetCommand{Connection: "cn_tx", Person: connPerson, LocalID: local, Budget: wire.Budget{Day: 2_000_000, Month: 20_000_000, Revision: 2}}); err != nil { t.Fatal(err) } if err := c.Budget(r.ctx, "f-budget-0", wire.BudgetCommand{Connection: "cn_tx", Person: connPerson, LocalID: local, Budget: wire.Budget{Day: 1, Month: 1, Revision: 1}}); err != nil { t.Fatal(err) } // Security round finding 4: a frame for another connection under the // same runner name changes nothing, and a frame already consumed is // not applied again whatever it now says. for frame, cmd := range map[string]wire.BudgetCommand{ "f-budget-other": {Connection: "cn_earlier", Person: connPerson, LocalID: local, Budget: wire.Budget{Day: 3, Month: 3, Revision: 7}}, "f-budget-1": {Connection: "cn_tx", Person: connPerson, LocalID: local, Budget: wire.Budget{Day: 4, Month: 4, Revision: 8}}, } { if err := c.Budget(r.ctx, frame, cmd); err != nil { t.Fatal(err) } } if h, _ := r.held(local); h.Budget.Day != 2_000_000 || h.Budget.Month != 20_000_000 || h.Budget.Revision != 2 { t.Fatalf("budget %+v", h.Budget) } // Nothing in the outbox or the log is the key. frames, _, _ := r.state.Unacked(context.Background(), 0) for _, f := range frames { if strings.Contains(string(f.Data), key) { t.Fatalf("%s frame carries the key", f.Type) } } if strings.Contains(r.logs.String(), key) { t.Fatal("the log carries the key") } // Sign out: the record, the home and the key go. if err := c.Disconnect(r.ctx, "f-disconnect", wire.DisconnectCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}); err != nil { t.Fatal(err) } r.waitFor(func() bool { for _, v := range r.reports("cn_tx") { if v.State == wire.ConnSignedOut { return true } } return false }, "signed out") if _, err := os.Lstat(home); !os.IsNotExist(err) { t.Fatalf("home left: %v", err) } if _, ok := r.held(local); ok { t.Fatal("still held") } // Security round finding 4: a later connection never takes the same // runner name, so no frame for this one can reach it. again := r.startAPIKey(c, "cn_tx2") if filepath.Base(again) == local || filepath.Base(home) == "tensorx-1" { t.Fatalf("the runner name %q was reused (%q)", filepath.Base(again), local) } } // TestAPIKeySignOutDuringAProbe (security round, finding 3): a sign-out // while a Check again's probe runs admits nothing more, waits for the // probe, commits its charge, and only then deletes the connection. func TestAPIKeySignOutDuringAProbe(t *testing.T) { const key = "tx-fake-key-fake-key" r := newTokenRig(t) fake := newFakeTensorX(t, key) c := r.meteredConnector(fake) home := r.startAPIKey(c, "cn_tx") local := filepath.Base(home) r.deliver(c, "f-secret-1", r.sealedKey("cn_tx", key, nil)) r.card("cn_tx", wire.PromptModels) c.Model(r.ctx, "f-model-1", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "z-ai/glm-5.3"}) if end := r.ended("cn_tx"); end.State != wire.ConnHealthy { t.Fatalf("end %+v", end) } fake.mu.Lock() fake.hold, fake.started = make(chan struct{}), make(chan struct{}, 8) fake.mu.Unlock() var release sync.Once t.Cleanup(func() { release.Do(func() { close(fake.hold) }) }) checked := make(chan error, 1) go func() { checked <- c.Check(r.ctx, "f-check-1", wire.CheckCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}) }() <-fake.started out := make(chan error, 1) go func() { out <- c.Disconnect(r.ctx, "f-disconnect", wire.DisconnectCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}) }() r.waitFor(func() bool { conn, ok, _ := metered.Get(r.ctx, r.state.db, local) return ok && conn.Retiring }, "the connection retiring") if a, err := r.conns.Meter.Admit(r.ctx, local, metered.Holder{Step: "s-late", Attempt: 1, Role: metered.RoleEngineering}, nil); err != nil || a.Admitted { t.Fatalf("admitted while signing out: %+v %v", a, err) } if _, ok, _ := metered.Get(r.ctx, r.state.db, local); !ok { t.Fatal("deleted while its probe ran") } release.Do(func() { close(fake.hold) }) if err := <-out; err != nil { t.Fatal(err) } <-checked r.waitFor(func() bool { _, ok, _ := metered.Get(r.ctx, r.state.db, local) return !ok }, "the connection removed") var charged int r.state.db.QueryRow("SELECT count(*) FROM budget_charge WHERE connection=? AND step LIKE 'pr_tensorx%'", local).Scan(&charged) probes := 0 for _, u := range r.usageFrames() { if strings.HasPrefix(u.ProbeID, "pr_"+local) { probes++ } } if charged != 1 || probes != 1 { t.Fatalf("the running probe's charge: %d rows, %d usage frames", charged, probes) } } // TestAPIKeyProbeAnsweredByAnotherModel (security round, finding 6): // a probe answered by another model proves nothing; its usage is that // model's, and an unpriced one leaves the spend unknown. func TestAPIKeyProbeAnsweredByAnotherModel(t *testing.T) { const key = "tx-fake-key-fake-key" r := newTokenRig(t) fake := newFakeTensorX(t, key) c := r.meteredConnector(fake) home := r.startAPIKey(c, "cn_tx") local := filepath.Base(home) r.deliver(c, "f-secret-1", r.sealedKey("cn_tx", key, nil)) r.card("cn_tx", wire.PromptModels) c.Model(r.ctx, "f-model-1", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "z-ai/glm-5.3"}) if end := r.ended("cn_tx"); end.State != wire.ConnHealthy { t.Fatalf("end %+v", end) } fake.mu.Lock() fake.answered = "vendor/unpriced" fake.mu.Unlock() if err := c.Check(r.ctx, "f-check-1", wire.CheckCommand{Connection: "cn_tx", Person: connPerson, LocalID: local}); err != nil { t.Fatal(err) } r.waitFor(func() bool { h, _ := r.held(local); return h.Spend != nil && h.Spend.Unknown }, "spend unknown") var row *wire.Usage for _, u := range r.usageFrames() { if strings.HasPrefix(u.ProbeID, "pr_"+local) { row = &u.Rows[0] } } if row == nil || row.Model != "vendor/unpriced" || row.CostMicros != nil { t.Fatalf("the probe's row %+v", row) } // A new attempt answered by another model is not made a connection. r2 := newTokenRig(t) fake2 := newFakeTensorX(t, key) fake2.answered = "z-ai/glm-5.3-flash" c2 := r2.meteredConnector(fake2) r2.startAPIKey(c2, "cn_tx") r2.deliver(c2, "f-secret-1", r2.sealedKey("cn_tx", key, nil)) r2.card("cn_tx", wire.PromptModels) c2.Model(r2.ctx, "f-model-1", wire.ModelCommand{Connection: "cn_tx", Person: connPerson, Model: "z-ai/glm-5.3"}) if end := r2.ended("cn_tx"); end.State == wire.ConnHealthy { t.Fatalf("made a connection on another model's answer: %+v", end) } } // TestAPIKeyBoxBoundToTheProvider: a box for an API-key attempt bound to // Claude's endpoint, or naming Claude, is refused and ends the attempt; // a key the provider refuses ends it key_refused, home and all. func TestAPIKeyBoxBoundToTheProvider(t *testing.T) { const key = "tx-fake-key-fake-key" r := newTokenRig(t) fake := newFakeTensorX(t, key) c := r.meteredConnector(fake) for i, change := range []func(*wire.SealedPayload){ func(p *wire.SealedPayload) { p.Endpoint = wire.EndpointAnthropic }, func(p *wire.SealedPayload) { p.Provider = wire.ProviderClaude }, } { id := "cn_bad" + string(rune('a'+i)) home := r.startAPIKey(c, id) r.deliver(c, "f-secret-"+id, r.sealedKey(id, key, change)) if end := r.ended(id); end.State != wire.ConnError || end.Reason != "provider_refused" { t.Fatalf("%s: %+v", id, end) } if _, err := os.Lstat(home); !os.IsNotExist(err) { t.Fatalf("%s: home left", id) } } home := r.startAPIKey(c, "cn_wrong") r.deliver(c, "f-secret-wrong", r.sealedKey("cn_wrong", "tx-not-the-key", nil)) if end := r.ended("cn_wrong"); end.State != wire.ConnError || end.Reason != "key_refused" { t.Fatalf("wrong key: %+v", end) } if _, err := os.Lstat(home); !os.IsNotExist(err) { t.Fatal("refused key's home left") } if fake.probeCount() != 0 || len(r.conns.Held()) != 0 { t.Fatal("a refused attempt probed or stayed") } } // OpenCode Go connects as TensorX does, at its own paths: the model list // at /inference/go/v1/models, the probe at /inference/go/openai/v1; only // models Go's price table knows are offered (not the free ones, nor // those Go serves on another API); the probe's row is priced by the // table although Go says cost 0 within its plan; the connection is run // by OpenCode, metered. func TestAPIKeyOpenCodeGoConnect(t *testing.T) { const key = "go-fake-key-fake-key" r := newTokenRig(t) var probes []string var mu sync.Mutex fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, q *http.Request) { if q.Header.Get("Authorization") != "Bearer "+key { w.WriteHeader(http.StatusUnauthorized) return } switch q.Method + " " + q.URL.Path { case "GET /inference/go/v1/models": w.Write([]byte(`{"data":[{"id":"glm-5.3"},{"id":"beam-free"},{"id":"qwen3.8-max"}]}`)) case "POST /inference/go/openai/v1/chat/completions": var in struct { Model string `json:"model"` MaxTokens int `json:"max_tokens"` } if json.NewDecoder(q.Body).Decode(&in) != nil || in.MaxTokens != 1 { w.WriteHeader(http.StatusBadRequest) return } mu.Lock() probes = append(probes, in.Model) mu.Unlock() w.Write([]byte(`{"model":"` + in.Model + `","choices":[{"message":{"content":"ok"}}],"usage":{"prompt_tokens":9,"completion_tokens":1,"cost":0,"opencode":{"billing_source":"go","allowance":0.00002}}}`)) default: w.WriteHeader(http.StatusNotFound) } })) t.Cleanup(fake.Close) r.conns.Meter = &metered.Meter{DB: r.state.db} c := r.connector() c.http, c.origin = connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), func(string) string { return fake.URL } cmd := wire.ConnectCommand{Connection: "cn_go", Person: connPerson, Provider: wire.ProviderOpenCodeGo, Kind: wire.KindAPIKey, Billing: wire.BillingMetered, Budget: &wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth, Currency: "USD", Revision: 1}} if err := c.Accept(r.ctx, "f-connect-cn_go", cmd); err != nil { t.Fatal(err) } r.card("cn_go", wire.PromptAPIKey) var home string _ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id=?", "cn_go").Scan(&home) local := filepath.Base(home) if !strings.HasPrefix(local, "opencode-go-") { t.Fatalf("home %q", home) } box := r.sealedKey("cn_go", key, func(p *wire.SealedPayload) { p.Provider, p.Endpoint = wire.ProviderOpenCodeGo, wire.APIKeyProviders[wire.ProviderOpenCodeGo].Endpoint }) if !r.deliver(c, "f-secret-go", box) { t.Fatalf("secret refused: %v", r.errs) } if p := r.card("cn_go", wire.PromptModels); strings.Join(eligibleChoices(p), ",") != "glm-5.3" { t.Fatalf("offered %v", p.Models) } if err := c.Model(r.ctx, "f-model-go", wire.ModelCommand{Connection: "cn_go", Person: connPerson, Model: "glm-5.3"}); err != nil { t.Fatal(err) } if end := r.ended("cn_go"); end.State != wire.ConnHealthy || end.Provider != wire.ProviderOpenCodeGo { t.Fatalf("end %+v", end) } usage := r.usageFrames() if len(usage) != 1 || len(usage[0].Rows) != 1 { t.Fatalf("probe usage %+v", usage) } row := usage[0].Rows[0] // 9 input at 1.40 and 1 output at 4.40 per million: 13 + 5 micros. if row.CostMicros == nil || *row.CostMicros != 18 || row.PriceVersion != "opencode-go-2026-11-12" || row.Provider != wire.ProviderOpenCodeGo { t.Fatalf("probe row %+v", row) } h, ok := r.held(local) if !ok || h.Harness != wire.HarnessOpenCode || h.Upstream != "https://opencode.ai" || h.Billing != wire.BillingMetered || h.Model != "glm-5.3" || h.Spend == nil || h.Spend.Day != 18 { t.Fatalf("held %+v %v", h, ok) } if b := r.conns.MeteredMine(r.ctx, connPerson); len(b) != 1 || b[0].Family != "glm" || harnessOf(b[0]) != wire.HarnessOpenCode { t.Fatalf("bindings %+v", b) } mu.Lock() defer mu.Unlock() if len(probes) != 1 || probes[0] != "glm-5.3" { t.Fatalf("probes %v", probes) } }