package wire_test import ( "reflect" "strings" "testing" "amadan.net/oficina/equipo/internal/wire" "amadan.net/oficina/equipo/internal/wire/wiretest" ) // secretShaped are JSON field names a connection record may never carry // (spec §7): the instance holds a record and never a secret. var secretShaped = []string{"key", "token", "secret", "credential", "password", "path", "sealed", "oauth"} // fieldNames walks a type's JSON field names, nested structs and slices // included. Usage's token counts are counts, not tokens: they are the // one listed exception. func fieldNames(t reflect.Type, seen map[reflect.Type]bool, out *[]string) { for t.Kind() == reflect.Pointer || t.Kind() == reflect.Slice || t.Kind() == reflect.Map { t = t.Elem() } if t.Kind() != reflect.Struct || seen[t] || t.PkgPath() != reflect.TypeOf(wire.Connection{}).PkgPath() { return } seen[t] = true for i := 0; i < t.NumField(); i++ { f := t.Field(i) name, _, _ := strings.Cut(f.Tag.Get("json"), ",") *out = append(*out, t.Name()+"."+name) fieldNames(f.Type, seen, out) } } // TestConnectionTypesCarryNoSecrets is spec C7's guard: no connection // resource, frame or the hello and reply that carry connection data has a // secret-shaped field. Token counts in Usage are the only exception. func TestConnectionTypesCarryNoSecrets(t *testing.T) { var names []string seen := map[reflect.Type]bool{} for _, v := range []any{wire.Connection{}, wire.ConnectionList{}, wire.Connect{}, wire.ConnectCommand{}, wire.CancelConnectCommand{}, wire.ConnectionReport{}, wire.Hello{}, wire.Reply{}, wire.TurnReport{}, wire.Snapshot{}, wire.StepReport{}, wire.AnswerReport{}, wire.UsageReport{}, wire.DisconnectCommand{}, wire.Sync{}, wire.ModelCommand{}, wire.ModelsCommand{}, wire.ModelChoice{}, wire.ModelState{}, wire.ConnectionModel{}, wire.SetModels{}, wire.BudgetCommand{}, wire.ResumeSpendCommand{}, wire.SetBudget{}, wire.ResumeSpend{}, wire.ChooseModel{}, wire.Budget{}, wire.Spend{}, wire.DispatchCommand{}, wire.ReleaseCommand{}, wire.PriorityCommand{}, wire.SetPriority{}, wire.RunNow{}, wire.RunNowAccepted{}, wire.StepHold{}, wire.TaskPriority{}, wire.Preferences{}, wire.PreferenceCommand{}} { fieldNames(reflect.TypeOf(v), seen, &names) } // seal_key is the runner's public key (spec §2.4): public by design. // An advice card’s key is its kind and subject (connectors spec §9). // CopyFlag.key identifies an app string; CopyResult.tokens is its numeric usage. // ChangedFile paths are validated repository-relative names, never account paths. allowed := map[string]bool{"ChangedFile.path": true, "ChangedFile.old_path": true, "CopyFlag.key": true, "CopyResult.tokens": true, "Advice.key": true, "Hello.seal_key": true, "Runner.seal_key": true, "Usage.input_tokens": true, "Usage.output_tokens": true, "Usage.cached_input_tokens": true, "Usage.cache_write_tokens": true, "Usage.reasoning_output_tokens": true} counter, _ := reflect.TypeOf(wire.CopyResult{}).FieldByName("Tokens") if counter.Type.Kind() != reflect.Int64 { t.Fatal("Copy token counter must remain numeric") } for _, n := range names { _, field, _ := strings.Cut(n, ".") for _, bad := range secretShaped { if strings.Contains(strings.ToLower(field), bad) && !allowed[n] { // Notebook entries and findings name repository files, not // credentials; they ride in Snapshot through tasks. if strings.HasPrefix(n, "NotebookEntry.") || strings.HasPrefix(n, "Finding.") || strings.HasPrefix(n, "Attachment.") { continue } t.Errorf("%s looks like a secret (%q)", n, bad) } } } if len(names) < 40 { t.Fatalf("walked only %d fields", len(names)) } } // TestConnectionFixturesCarryNoSecrets: the recorded documents a native // app replays hold no secret-shaped key either. func TestConnectionFixturesCarryNoSecrets(t *testing.T) { for _, name := range []string{"api/connections.json", "api/connection-connecting-codex.json", "api/connection-signing-in-claude.json", "api/connect-request.json", "api/event-connection.json", "frames/connect.json", "frames/cancel_connect.json", "frames/connection.json", "frames/hello.json", "frames/reply-usage.json", "frames/usage.json", "frames/disconnect.json", "frames/sync.json", "frames/preference.json", "api/preferences.json", "api/event-preference.json", "api/connection-metered.json", "api/connection-choose-model.json", "api/connect-request-api-key.json", "api/budget.json", "api/resume-request.json", "api/model-request.json", "frames/budget.json", "frames/model.json", "frames/resume_spend.json", "frames/connect-api-key.json", "frames/usage-probe.json", "frames/hello-metered.json", "frames/release.json", "frames/priority.json", "frames/step-held.json", "frames/preference-until.json", "frames/dispatch-urgent.json", "api/task-held.json", "api/priority-request.json", "api/run-now-request.json", "api/run-now-accepted.json", "api/card-held.json", "frames/models.json", "frames/hello-models.json", "frames/usage-model-mismatch.json", "api/connection-choose-models.json", "api/connection-models.json", "api/models-request.json", "frames/hello-worker-conns.json"} { // seal_key is public (spec §2.4); api_key is a connection's kind // and its card's, never a field (connectors spec §10). raw := strings.ReplaceAll(strings.ToLower(string(wiretest.Fixture(name))), `"seal_key"`, "") raw = strings.ReplaceAll(raw, `"kind":"api_key"`, `"kind":""`) // token is a connection's kind (a pasted setup-token), never a field. raw = strings.ReplaceAll(raw, `"kind":"token"`, `"kind":""`) for _, bad := range []string{"token\"", "secret", "credential", "password", "sealed", "_key", "api_key", "access_token", "refresh"} { if strings.Contains(raw, bad) { t.Errorf("%s contains %q", name, bad) } } } } // TestHousekeepingTypesCarryNoSecrets: the secret-shape guard covers the // housekeeping resources, events and their fixtures (spec §6). The day's // token budget is a count, the one listed exception. func TestHousekeepingTypesCarryNoSecrets(t *testing.T) { var names []string seen := map[reflect.Type]bool{} for _, v := range []any{wire.Housekeeping{}, wire.HousekeepingActions{}, wire.HousekeepingAction{}, wire.SetHousekeeping{}, wire.SetDetector{}, wire.HousekeepingSummary{}, wire.ActionConflict{}, wire.Card{}} { fieldNames(reflect.TypeOf(v), seen, &names) } // copy_key names a copy string for the error, and an advice card's // key its kind and subject: neither is a secret. allowed := map[string]bool{"HousekeepingBudget.tokens": true, "ActionConflict.copy_key": true, "Advice.key": true} for _, n := range names { _, field, _ := strings.Cut(n, ".") for _, bad := range secretShaped { if strings.Contains(strings.ToLower(field), bad) && !allowed[n] { t.Errorf("%s looks like a secret (%q)", n, bad) } } } if len(names) < 30 { t.Fatalf("walked only %d fields", len(names)) } for _, name := range []string{"api/housekeeping.json", "api/housekeeping-paused.json", "api/housekeeping-quiet-request.json", "api/action-combined.json", "api/action-undone.json", "api/action-refused.json", "api/housekeeping-actions.json", "api/action-conflict.json", "api/event-housekeeping.json", "api/event-housekeeping-summary.json", "api/card-housekeeping.json", "api/card-digest.json"} { raw := strings.ReplaceAll(strings.ToLower(string(wiretest.Fixture(name))), "\"copy_key\"", "") for _, bad := range []string{"token\"", "secret", "credential", "password", "sealed", "_key\"", "api_key", "access_token", "refresh"} { if strings.Contains(raw, bad) { t.Errorf("%s contains %q", name, bad) } } } } // Sealed secrets go one way only: the runner never sends one back, and // the instance's connection resources never carry one (spec §2.4). func TestSealedOnlyTowardTheRunner(t *testing.T) { var names []string seen := map[reflect.Type]bool{} for _, v := range []any{wire.Hello{}, wire.Sync{}, wire.ConnectionReport{}, wire.Reply{}, wire.TurnReport{}, wire.StepReport{}, wire.AnswerReport{}, wire.UsageReport{}, wire.Connection{}, wire.ConnectionList{}, wire.Snapshot{}} { fieldNames(reflect.TypeOf(v), seen, &names) } for _, n := range names { if l := strings.ToLower(n); strings.Contains(l, "sealed") || strings.Contains(l, "secret") || strings.HasSuffix(l, ".box") { t.Errorf("%s carries a sealed secret back", n) } } } // TestMeteredConfirmations is §2.1's add-connection rule: a metered // connection needs the provider-side limit confirmed; pay-as-you-go off // makes an overflow subscription a subscription and means nothing for a // provider billed per token. func TestMeteredConfirmations(t *testing.T) { tensorx := wire.APIKeyProviders[wire.ProviderTensorX] plan := wire.APIKeyProvider{Name: "Plan", Harness: "fake", Upstream: "https://plan.example.com", Endpoint: "https://plan.example.com:443", Overflow: true, Currency: "USD"} for _, c := range []struct { p wire.APIKeyProvider limit, paygOff bool ok bool billing string }{ {tensorx, false, false, false, wire.BillingMetered}, {tensorx, true, false, true, wire.BillingMetered}, {tensorx, true, true, false, wire.BillingMetered}, {plan, false, false, false, wire.BillingMetered}, {plan, true, false, true, wire.BillingMetered}, {plan, false, true, true, wire.BillingSubscription}, {plan, true, true, true, wire.BillingSubscription}, } { if err := c.p.CheckConfirmations(c.limit, c.paygOff); (err == nil) != c.ok { t.Fatalf("%s limit=%v payg_off=%v: %v", c.p.Name, c.limit, c.paygOff, err) } if got := c.p.Billing(c.paygOff); got != c.billing { t.Fatalf("%s payg_off=%v billed %s", c.p.Name, c.paygOff, got) } } if tensorx.Upstream != "https://api.tensorx.ai" || tensorx.Endpoint != "https://api.tensorx.ai:443" || tensorx.Harness != wire.HarnessPi || !tensorx.PerToken { t.Fatalf("tensorx %+v", tensorx) } for _, b := range []wire.Budget{{Day: 0, Month: 1}, {Day: 2, Month: 1}, {Day: 1, Month: wire.MaxBudgetMonth + 1}, {Day: -1, Month: 5}} { if wire.ValidBudget(b) { t.Fatalf("budget %+v accepted", b) } } if !wire.ValidBudget(wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth}) { t.Fatal("the default budget is refused") } }