| 1 | package wire_test |
| 2 | |
| 3 | import ( |
| 4 | "reflect" |
| 5 | "strings" |
| 6 | "testing" |
| 7 | |
| 8 | "amadan.net/oficina/equipo/internal/wire" |
| 9 | "amadan.net/oficina/equipo/internal/wire/wiretest" |
| 10 | ) |
| 11 | |
| 12 | // secretShaped are JSON field names a connection record may never carry |
| 13 | // (spec §7): the instance holds a record and never a secret. |
| 14 | var secretShaped = []string{"key", "token", "secret", "credential", "password", "path", "sealed", "oauth"} |
| 15 | |
| 16 | // fieldNames walks a type's JSON field names, nested structs and slices |
| 17 | // included. Usage's token counts are counts, not tokens: they are the |
| 18 | // one listed exception. |
| 19 | func fieldNames(t reflect.Type, seen map[reflect.Type]bool, out *[]string) { |
| 20 | for t.Kind() == reflect.Pointer || t.Kind() == reflect.Slice || t.Kind() == reflect.Map { |
| 21 | t = t.Elem() |
| 22 | } |
| 23 | if t.Kind() != reflect.Struct || seen[t] || t.PkgPath() != reflect.TypeOf(wire.Connection{}).PkgPath() { |
| 24 | return |
| 25 | } |
| 26 | seen[t] = true |
| 27 | for i := 0; i < t.NumField(); i++ { |
| 28 | f := t.Field(i) |
| 29 | name, _, _ := strings.Cut(f.Tag.Get("json"), ",") |
| 30 | *out = append(*out, t.Name()+"."+name) |
| 31 | fieldNames(f.Type, seen, out) |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | // TestConnectionTypesCarryNoSecrets is spec C7's guard: no connection |
| 36 | // resource, frame or the hello and reply that carry connection data has a |
| 37 | // secret-shaped field. Token counts in Usage are the only exception. |
| 38 | func TestConnectionTypesCarryNoSecrets(t *testing.T) { |
| 39 | var names []string |
| 40 | seen := map[reflect.Type]bool{} |
| 41 | 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{}} { |
| 42 | fieldNames(reflect.TypeOf(v), seen, &names) |
| 43 | } |
| 44 | // seal_key is the runner's public key (spec §2.4): public by design. |
| 45 | // An advice card’s key is its kind and subject (connectors spec §9). |
| 46 | // CopyFlag.key identifies an app string; CopyResult.tokens is its numeric usage. |
| 47 | // ChangedFile paths are validated repository-relative names, never account paths. |
| 48 | 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} |
| 49 | counter, _ := reflect.TypeOf(wire.CopyResult{}).FieldByName("Tokens") |
| 50 | if counter.Type.Kind() != reflect.Int64 { |
| 51 | t.Fatal("Copy token counter must remain numeric") |
| 52 | } |
| 53 | for _, n := range names { |
| 54 | _, field, _ := strings.Cut(n, ".") |
| 55 | for _, bad := range secretShaped { |
| 56 | if strings.Contains(strings.ToLower(field), bad) && !allowed[n] { |
| 57 | // Notebook entries and findings name repository files, not |
| 58 | // credentials; they ride in Snapshot through tasks. |
| 59 | if strings.HasPrefix(n, "NotebookEntry.") || strings.HasPrefix(n, "Finding.") || strings.HasPrefix(n, "Attachment.") { |
| 60 | continue |
| 61 | } |
| 62 | t.Errorf("%s looks like a secret (%q)", n, bad) |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | if len(names) < 40 { |
| 67 | t.Fatalf("walked only %d fields", len(names)) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // TestConnectionFixturesCarryNoSecrets: the recorded documents a native |
| 72 | // app replays hold no secret-shaped key either. |
| 73 | func TestConnectionFixturesCarryNoSecrets(t *testing.T) { |
| 74 | 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"} { |
| 75 | // seal_key is public (spec §2.4); api_key is a connection's kind |
| 76 | // and its card's, never a field (connectors spec §10). |
| 77 | raw := strings.ReplaceAll(strings.ToLower(string(wiretest.Fixture(name))), `"seal_key"`, "") |
| 78 | raw = strings.ReplaceAll(raw, `"kind":"api_key"`, `"kind":""`) |
| 79 | // token is a connection's kind (a pasted setup-token), never a field. |
| 80 | raw = strings.ReplaceAll(raw, `"kind":"token"`, `"kind":""`) |
| 81 | for _, bad := range []string{"token\"", "secret", "credential", "password", "sealed", "_key", "api_key", "access_token", "refresh"} { |
| 82 | if strings.Contains(raw, bad) { |
| 83 | t.Errorf("%s contains %q", name, bad) |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | // TestHousekeepingTypesCarryNoSecrets: the secret-shape guard covers the |
| 90 | // housekeeping resources, events and their fixtures (spec §6). The day's |
| 91 | // token budget is a count, the one listed exception. |
| 92 | func TestHousekeepingTypesCarryNoSecrets(t *testing.T) { |
| 93 | var names []string |
| 94 | seen := map[reflect.Type]bool{} |
| 95 | for _, v := range []any{wire.Housekeeping{}, wire.HousekeepingActions{}, wire.HousekeepingAction{}, wire.SetHousekeeping{}, wire.SetDetector{}, wire.HousekeepingSummary{}, wire.ActionConflict{}, wire.Card{}} { |
| 96 | fieldNames(reflect.TypeOf(v), seen, &names) |
| 97 | } |
| 98 | // copy_key names a copy string for the error, and an advice card's |
| 99 | // key its kind and subject: neither is a secret. |
| 100 | allowed := map[string]bool{"HousekeepingBudget.tokens": true, "ActionConflict.copy_key": true, "Advice.key": true} |
| 101 | for _, n := range names { |
| 102 | _, field, _ := strings.Cut(n, ".") |
| 103 | for _, bad := range secretShaped { |
| 104 | if strings.Contains(strings.ToLower(field), bad) && !allowed[n] { |
| 105 | t.Errorf("%s looks like a secret (%q)", n, bad) |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | if len(names) < 30 { |
| 110 | t.Fatalf("walked only %d fields", len(names)) |
| 111 | } |
| 112 | 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"} { |
| 113 | raw := strings.ReplaceAll(strings.ToLower(string(wiretest.Fixture(name))), "\"copy_key\"", "") |
| 114 | for _, bad := range []string{"token\"", "secret", "credential", "password", "sealed", "_key\"", "api_key", "access_token", "refresh"} { |
| 115 | if strings.Contains(raw, bad) { |
| 116 | t.Errorf("%s contains %q", name, bad) |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | // Sealed secrets go one way only: the runner never sends one back, and |
| 123 | // the instance's connection resources never carry one (spec §2.4). |
| 124 | func TestSealedOnlyTowardTheRunner(t *testing.T) { |
| 125 | var names []string |
| 126 | seen := map[reflect.Type]bool{} |
| 127 | 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{}} { |
| 128 | fieldNames(reflect.TypeOf(v), seen, &names) |
| 129 | } |
| 130 | for _, n := range names { |
| 131 | if l := strings.ToLower(n); strings.Contains(l, "sealed") || strings.Contains(l, "secret") || strings.HasSuffix(l, ".box") { |
| 132 | t.Errorf("%s carries a sealed secret back", n) |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | // TestMeteredConfirmations is §2.1's add-connection rule: a metered |
| 138 | // connection needs the provider-side limit confirmed; pay-as-you-go off |
| 139 | // makes an overflow subscription a subscription and means nothing for a |
| 140 | // provider billed per token. |
| 141 | func TestMeteredConfirmations(t *testing.T) { |
| 142 | tensorx := wire.APIKeyProviders[wire.ProviderTensorX] |
| 143 | plan := wire.APIKeyProvider{Name: "Plan", Harness: "fake", Upstream: "https://plan.example.com", Endpoint: "https://plan.example.com:443", Overflow: true, Currency: "USD"} |
| 144 | for _, c := range []struct { |
| 145 | p wire.APIKeyProvider |
| 146 | limit, paygOff bool |
| 147 | ok bool |
| 148 | billing string |
| 149 | }{ |
| 150 | {tensorx, false, false, false, wire.BillingMetered}, |
| 151 | {tensorx, true, false, true, wire.BillingMetered}, |
| 152 | {tensorx, true, true, false, wire.BillingMetered}, |
| 153 | {plan, false, false, false, wire.BillingMetered}, |
| 154 | {plan, true, false, true, wire.BillingMetered}, |
| 155 | {plan, false, true, true, wire.BillingSubscription}, |
| 156 | {plan, true, true, true, wire.BillingSubscription}, |
| 157 | } { |
| 158 | if err := c.p.CheckConfirmations(c.limit, c.paygOff); (err == nil) != c.ok { |
| 159 | t.Fatalf("%s limit=%v payg_off=%v: %v", c.p.Name, c.limit, c.paygOff, err) |
| 160 | } |
| 161 | if got := c.p.Billing(c.paygOff); got != c.billing { |
| 162 | t.Fatalf("%s payg_off=%v billed %s", c.p.Name, c.paygOff, got) |
| 163 | } |
| 164 | } |
| 165 | if tensorx.Upstream != "https://api.tensorx.ai" || tensorx.Endpoint != "https://api.tensorx.ai:443" || tensorx.Harness != wire.HarnessPi || !tensorx.PerToken { |
| 166 | t.Fatalf("tensorx %+v", tensorx) |
| 167 | } |
| 168 | for _, b := range []wire.Budget{{Day: 0, Month: 1}, {Day: 2, Month: 1}, {Day: 1, Month: wire.MaxBudgetMonth + 1}, {Day: -1, Month: 5}} { |
| 169 | if wire.ValidBudget(b) { |
| 170 | t.Fatalf("budget %+v accepted", b) |
| 171 | } |
| 172 | } |
| 173 | if !wire.ValidBudget(wire.Budget{Day: wire.DefaultBudgetDay, Month: wire.DefaultBudgetMonth}) { |
| 174 | t.Fatal("the default budget is refused") |
| 175 | } |
| 176 | } |
| 177 | |