diff --git a/cmd/server/main.go b/cmd/server/main.go index 372b9013419..07226f2cf32 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -63,7 +63,7 @@ func shouldEnableExampleAPIKeySafeMode(cfg *config.Config, commandMode, tuiMode, if tuiMode && !standalone { return false } - return safemode.HasExampleAPIKeys(cfg.APIKeys) + return safemode.HasExampleAPIKeys(cfg.APIKeyStrings()) } // main is the entry point of the application. @@ -633,7 +633,7 @@ func run() (exitStatus int) { exampleAPIKeySafeMode := shouldEnableExampleAPIKeySafeMode(cfg, commandMode, tuiMode, standalone, cloudConfigMissing, homeMode) serverOptions := []api.ServerOption(nil) if exampleAPIKeySafeMode { - matches := safemode.ExampleAPIKeys(cfg.APIKeys) + matches := safemode.ExampleAPIKeys(cfg.APIKeyStrings()) log.WithField("api_keys", strings.Join(matches, ",")).Error("unsafe example API key configured; proxy API endpoints disabled until api-keys is updated") serverOptions = append(serverOptions, api.WithExampleAPIKeySafeMode()) } diff --git a/cmd/server/main_test.go b/cmd/server/main_test.go index 413e838a4b7..7bb2b76876d 100644 --- a/cmd/server/main_test.go +++ b/cmd/server/main_test.go @@ -36,12 +36,12 @@ func TestArgvEnablesBoolFlag(t *testing.T) { func TestShouldEnableExampleAPIKeySafeMode(t *testing.T) { cfgWithExampleKey := &config.Config{ SDKConfig: config.SDKConfig{ - APIKeys: []string{"real-key", " your-api-key-1 "}, + APIKeys: config.APIKeyEntries("real-key", " your-api-key-1 "), }, } cfgWithRealKey := &config.Config{ SDKConfig: config.SDKConfig{ - APIKeys: []string{"real-key"}, + APIKeys: config.APIKeyEntries("real-key"), }, } diff --git a/config.example.yaml b/config.example.yaml index 69aed36f620..f56211b434a 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -142,6 +142,27 @@ access: - "your-api-key-1" - "your-api-key-2" - "your-api-key-3" + # A key can be bound to specific credentials with the mapping form. Requests that + # authenticate with a bound key are only ever served by the listed credentials + # (selection, retries, failover, session affinity and websocket continuity all stay + # inside the set), and /v1/models, /v1beta/models and the Claude models list only show + # the models those credentials serve. Plain-string keys stay unrestricted. + # + # Each `auths` item is a credential ID or an auth file name, matched exactly (case + # sensitive, no basename matching). Credentials declared in this file (for example + # codex-api-key entries) have generated IDs and are matched by ID only. An empty + # `auths` list is rejected, unknown fields (anything but `key` and `auths`) are rejected, + # and a key listed twice is a config error, so a binding is never dropped silently. + # The spawn_agent model list and /v1/analytics/codex/turn-costs are scoped to the + # key's credentials too. + # A bound key that matches no credential gets no models and no successful requests. + # Bound keys are not supported in Home mode: they are refused there instead of + # silently ignoring the binding. + # + # - key: "personal-key" + # auths: ["codex-personal.json", "claude-personal.json"] + # - key: "work-key" + # auths: ["codex-work.json"] # Optional credential concurrency and observation contracts. diff --git a/docs/management-api-v8.md b/docs/management-api-v8.md index 672435c1c7e..fa4618af33f 100644 --- a/docs/management-api-v8.md +++ b/docs/management-api-v8.md @@ -73,7 +73,7 @@ the corresponding group value. Legacy field names are rejected by v8 writes. | Example path | Value or purpose | | --- | --- | -| `/config/access/api-keys` | Client authentication keys, for example `["client-key"]`. | +| `/config/access/api-keys` | Client authentication keys. Each entry is a plain string or a `{"key": "...", "auths": ["file.json"]}` object that binds the key to credentials, for example `["client-key", {"key": "personal", "auths": ["codex-personal.json"]}]`. | | `/config/api-keys` | All upstream provider groups. | | `/config/api-keys/codex` | Codex upstream groups. | | `/config/client/codex/optimize-multi-agent-v2` | Boolean, default `false`; applies to Codex clients across OAuth and API-key routes. | diff --git a/docs/sdk-access.md b/docs/sdk-access.md index 343c851b4fc..c59e62e740f 100644 --- a/docs/sdk-access.md +++ b/docs/sdk-access.md @@ -82,6 +82,10 @@ import ( The blank identifier import ensures `init` runs so `sdkaccess.RegisterProvider` executes before you call `RegisteredProviders()` (or before `cliproxy.NewBuilder().Build()`). +### Restricting a principal to credentials + +`Result.AllowedAuths` optionally lists credential IDs or auth file names. When it is non-empty, requests authenticated by that result are only served by the listed credentials, and model listings only show the models they serve. The built-in `config-api-key` provider fills it from `access.api-keys` entries written as `{key, auths}`. Leave it empty for an unrestricted principal. A non-empty list that names no usable credential (for example only blank items) stays restricted and serves nothing. + ### Metadata and auditing `Result.Metadata` carries provider-specific context. The built-in `config-api-key` provider, for example, stores the credential source (`authorization`, `x-goog-api-key`, `x-api-key`, `query-key`, `query-auth-token`). Populate this map in custom providers to enrich logs and downstream auditing. diff --git a/internal/access/config_access/provider.go b/internal/access/config_access/provider.go index b6d371ae154..8b2deaf2b05 100644 --- a/internal/access/config_access/provider.go +++ b/internal/access/config_access/provider.go @@ -30,17 +30,19 @@ func Register(cfg *sdkconfig.SDKConfig) { type provider struct { name string - keys map[string]struct{} + // keys maps each accepted key to the credentials it is bound to. A nil + // value means the key is unrestricted. + keys map[string][]string } -func newProvider(name string, keys []string) *provider { +func newProvider(name string, keys []sdkconfig.APIKeyEntry) *provider { providerName := strings.TrimSpace(name) if providerName == "" { providerName = sdkaccess.DefaultAccessProviderName } - keySet := make(map[string]struct{}, len(keys)) - for _, key := range keys { - keySet[key] = struct{}{} + keySet := make(map[string][]string, len(keys)) + for _, entry := range keys { + keySet[entry.Key] = entry.Auths } return &provider{name: providerName, keys: keySet} } @@ -89,10 +91,11 @@ func (p *provider) Authenticate(_ context.Context, r *http.Request) (*sdkaccess. if candidate.value == "" { continue } - if _, ok := p.keys[candidate.value]; ok { + if auths, ok := p.keys[candidate.value]; ok { return &sdkaccess.Result{ - Provider: p.Identifier(), - Principal: candidate.value, + Provider: p.Identifier(), + Principal: candidate.value, + AllowedAuths: append([]string(nil), auths...), Metadata: map[string]string{ "source": candidate.source, }, @@ -117,25 +120,72 @@ func extractBearerToken(header string) string { return strings.TrimSpace(parts[1]) } -func normalizeKeys(keys []string) []string { +// blockedAuthRef is a restriction item that matches no credential. A bound key +// whose usable refs are all gone keeps this single item so it stays bound to +// nothing instead of becoming unrestricted. +const blockedAuthRef = " " + +// normalizeKeys trims keys and drops blanks. A duplicated key is rejected at +// config load; if one still reaches this point it fails closed: the copies are +// intersected, and any bound copy outweighs an unrestricted one. A bound entry +// is never turned into an unrestricted one. +func normalizeKeys(keys []sdkconfig.APIKeyEntry) []sdkconfig.APIKeyEntry { if len(keys) == 0 { return nil } - normalized := make([]string, 0, len(keys)) - seen := make(map[string]struct{}, len(keys)) - for _, key := range keys { - trimmedKey := strings.TrimSpace(key) + normalized := make([]sdkconfig.APIKeyEntry, 0, len(keys)) + index := make(map[string]int, len(keys)) + for _, entry := range keys { + trimmedKey := strings.TrimSpace(entry.Key) if trimmedKey == "" { continue } - if _, exists := seen[trimmedKey]; exists { + var auths []string + if entry.Auths != nil { + auths = make([]string, 0, len(entry.Auths)) + for _, ref := range entry.Auths { + if trimmedRef := strings.TrimSpace(ref); trimmedRef != "" { + auths = append(auths, trimmedRef) + } + } + if len(auths) == 0 { + auths = []string{blockedAuthRef} + } + } + if at, exists := index[trimmedKey]; exists { + normalized[at].Auths = intersectAuths(normalized[at].Auths, auths) continue } - seen[trimmedKey] = struct{}{} - normalized = append(normalized, trimmedKey) + index[trimmedKey] = len(normalized) + normalized = append(normalized, sdkconfig.APIKeyEntry{Key: trimmedKey, Auths: auths}) } if len(normalized) == 0 { return nil } return normalized } + +// intersectAuths combines the restrictions of two copies of one key. A nil list +// is unrestricted, so the other list wins; two lists keep only the shared refs. +func intersectAuths(a, b []string) []string { + if a == nil { + return b + } + if b == nil { + return a + } + in := make(map[string]struct{}, len(b)) + for _, ref := range b { + in[ref] = struct{}{} + } + var out []string + for _, ref := range a { + if _, ok := in[ref]; ok && ref != blockedAuthRef { + out = append(out, ref) + } + } + if len(out) == 0 { + return []string{blockedAuthRef} + } + return out +} diff --git a/internal/access/config_access/provider_test.go b/internal/access/config_access/provider_test.go new file mode 100644 index 00000000000..fb73fc63aaf --- /dev/null +++ b/internal/access/config_access/provider_test.go @@ -0,0 +1,91 @@ +package configaccess + +import ( + "context" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func authenticate(t *testing.T, p *provider, key string) ([]string, bool) { + t.Helper() + req := httptest.NewRequest("GET", "/v1/models", nil) + req.Header.Set("Authorization", "Bearer "+key) + result, authErr := p.Authenticate(context.Background(), req) + if authErr != nil { + return nil, false + } + return result.AllowedAuths, true +} + +func TestProviderReturnsAllowedAuthsForBoundKey(t *testing.T) { + p := newProvider("", normalizeKeys([]sdkconfig.APIKeyEntry{ + {Key: "plain"}, + {Key: " personal ", Auths: []string{" codex-personal.json ", "", "claude-personal.json"}}, + })) + if auths, ok := authenticate(t, p, "plain"); !ok || len(auths) != 0 { + t.Fatalf("plain key: auths=%v ok=%v, want unrestricted", auths, ok) + } + auths, ok := authenticate(t, p, "personal") + if !ok { + t.Fatal("bound key rejected") + } + if want := []string{"codex-personal.json", "claude-personal.json"}; !reflect.DeepEqual(auths, want) { + t.Fatalf("auths = %v, want %v", auths, want) + } + if _, ok = authenticate(t, p, "unknown"); ok { + t.Fatal("unknown key accepted") + } +} + +func TestProviderDuplicateKeyFailsClosed(t *testing.T) { + for name, tc := range map[string]struct { + keys []sdkconfig.APIKeyEntry + want []string + }{ + "plain before bound": {[]sdkconfig.APIKeyEntry{{Key: "dup"}, {Key: "dup", Auths: []string{"a.json"}}}, []string{"a.json"}}, + "bound before plain": {[]sdkconfig.APIKeyEntry{{Key: "dup", Auths: []string{"a.json"}}, {Key: "dup"}}, []string{"a.json"}}, + "two bound overlap": {[]sdkconfig.APIKeyEntry{{Key: "dup", Auths: []string{"a.json", "b.json"}}, {Key: "dup", Auths: []string{"b.json", "c.json"}}}, []string{"b.json"}}, + "two bound disjoint": {[]sdkconfig.APIKeyEntry{{Key: "dup", Auths: []string{"a.json"}}, {Key: "dup", Auths: []string{"b.json"}}}, []string{blockedAuthRef}}, + } { + t.Run(name, func(t *testing.T) { + p := newProvider("", normalizeKeys(tc.keys)) + auths, ok := authenticate(t, p, "dup") + if !ok || !reflect.DeepEqual(auths, tc.want) { + t.Fatalf("auths=%v ok=%v, want %v", auths, ok, tc.want) + } + }) + } +} + +func TestProviderBoundEntryWithOnlyBlankRefsStaysBound(t *testing.T) { + p := newProvider("", normalizeKeys([]sdkconfig.APIKeyEntry{{Key: "k", Auths: []string{"", " "}}})) + auths, ok := authenticate(t, p, "k") + if !ok || len(auths) == 0 { + t.Fatalf("auths=%v ok=%v, want a non-empty restriction that matches nothing", auths, ok) + } + for _, ref := range auths { + if strings.TrimSpace(ref) != "" { + t.Fatalf("restriction %v must not name any credential", auths) + } + } +} + +func TestProviderAllowedAuthsAcceptedFromEveryKeySource(t *testing.T) { + p := newProvider("", normalizeKeys([]sdkconfig.APIKeyEntry{{Key: "k", Auths: []string{"a.json"}}})) + for name, set := range map[string]func(r *http.Request){ + "x-api-key": func(r *http.Request) { r.Header.Set("X-Api-Key", "k") }, + "x-goog-api-key": func(r *http.Request) { r.Header.Set("X-Goog-Api-Key", "k") }, + } { + req := httptest.NewRequest("GET", "/v1/models", nil) + set(req) + result, authErr := p.Authenticate(context.Background(), req) + if authErr != nil || !reflect.DeepEqual(result.AllowedAuths, []string{"a.json"}) { + t.Fatalf("%s: result=%v err=%v", name, result, authErr) + } + } +} diff --git a/internal/api/handlers/management/config_lists.go b/internal/api/handlers/management/config_lists.go index 22206a14ab7..dbc03730a9b 100644 --- a/internal/api/handlers/management/config_lists.go +++ b/internal/api/handlers/management/config_lists.go @@ -2,6 +2,7 @@ package management import ( "bytes" + "errors" "fmt" "strings" @@ -157,15 +158,140 @@ func (h *Handler) deleteFromStringList(c *gin.Context, targetOf func() *[]string // api-keys func (h *Handler) GetAPIKeys(c *gin.Context) { c.JSON(200, gin.H{"api-keys": h.cfg.APIKeys}) } func (h *Handler) PutAPIKeys(c *gin.Context) { - h.putStringList(c, func(v []string) { - h.cfg.APIKeys = append([]string(nil), v...) - }, nil) + data, err := c.GetRawData() + if err != nil { + c.JSON(400, gin.H{"error": "failed to read body"}) + return + } + items, err := parseAPIKeyItems(data) + if err != nil { + c.JSON(400, gin.H{"error": err.Error()}) + return + } + h.mu.Lock() + defer h.mu.Unlock() + // A plain string keeps the binding the key already has, so a list of bare keys can + // never widen a bound key. An object states its binding explicitly. + bindings := make(map[string][]string, len(h.cfg.APIKeys)) + for _, entry := range h.cfg.APIKeys { + if entry.Bound() { + bindings[strings.TrimSpace(entry.Key)] = entry.Auths + } + } + var next config.SDKConfig + next.APIKeys = make([]config.APIKeyEntry, 0, len(items)) + for _, item := range items { + entry := item.entry + if item.plain { + entry.Auths = bindings[strings.TrimSpace(entry.Key)] + } + next.APIKeys = append(next.APIKeys, entry) + } + if rejectInvalidAPIKeys(c, &next) { + return + } + h.cfg.APIKeys = next.APIKeys + h.persistLocked(c) +} + +type apiKeyItem struct { + entry config.APIKeyEntry + plain bool +} + +// parseAPIKeyItems reads the body GetAPIKeys writes: a bare array, {"items": [...]} or the {"api-keys": [...]} object GetAPIKeys +// returns, +// whose elements are plain key strings or {key, auths} objects. +func parseAPIKeyItems(data []byte) ([]apiKeyItem, error) { + var raws []json.RawMessage + if err := json.Unmarshal(data, &raws); err != nil { + // Pointers tell an absent field (invalid) from a present empty array (clear the list). + var obj struct { + Items *[]json.RawMessage `json:"items"` + APIKeys *[]json.RawMessage `json:"api-keys"` + } + if err2 := json.Unmarshal(data, &obj); err2 != nil { + return nil, errors.New("invalid body") + } + switch { + case obj.Items != nil: + raws = *obj.Items + case obj.APIKeys != nil: + raws = *obj.APIKeys + default: + return nil, errors.New("invalid body") + } + } + items := make([]apiKeyItem, 0, len(raws)) + for i, raw := range raws { + var entry config.APIKeyEntry + if err := json.Unmarshal(raw, &entry); err != nil { + return nil, fmt.Errorf("api-keys[%d]: %w", i, err) + } + items = append(items, apiKeyItem{entry: entry, plain: strings.HasPrefix(strings.TrimSpace(string(raw)), `"`)}) + } + return items, nil } + +// PatchAPIKeys renames or appends one key. A rename keeps the credential binding of +// the key it renames, so editing a key never widens it to every credential. func (h *Handler) PatchAPIKeys(c *gin.Context) { - h.patchStringList(c, func() *[]string { return &h.cfg.APIKeys }, func() {}) + var body struct { + Old *string `json:"old"` + New *string `json:"new"` + Index *int `json:"index"` + Value *string `json:"value"` + } + if err := c.ShouldBindJSON(&body); err != nil { + c.JSON(400, gin.H{"error": "invalid body"}) + return + } + h.mu.Lock() + defer h.mu.Unlock() + entries := append([]config.APIKeyEntry(nil), h.cfg.APIKeys...) + switch { + case body.Index != nil && body.Value != nil && *body.Index >= 0 && *body.Index < len(entries): + entries[*body.Index].Key = *body.Value + case body.Old != nil && body.New != nil: + renamed := false + for i := range entries { + if entries[i].Key == *body.Old { + entries[i].Key = *body.New + renamed = true + break + } + } + if !renamed { + entries = append(entries, config.APIKeyEntry{Key: *body.New}) + } + default: + c.JSON(400, gin.H{"error": "missing fields"}) + return + } + var next config.SDKConfig + next.APIKeys = entries + if rejectInvalidAPIKeys(c, &next) { + return + } + h.cfg.APIKeys = entries + h.persistLocked(c) } + +// DeleteAPIKeys removes one key and keeps the binding of every key that stays. func (h *Handler) DeleteAPIKeys(c *gin.Context) { - h.deleteFromStringList(c, func() *[]string { return &h.cfg.APIKeys }, func() {}) + // The key list is read by the getter below, which runs under the handler mutex. + var keys []string + h.deleteFromStringList(c, func() *[]string { keys = h.cfg.APIKeyStrings(); return &keys }, func() { h.cfg.SetAPIKeyStrings(keys) }) +} + +// rejectInvalidAPIKeys answers 400 when the proposed key list is not a valid config, +// for example because it lists a key twice. +func rejectInvalidAPIKeys(c *gin.Context, proposed *config.SDKConfig) bool { + if err := proposed.ValidateAPIKeys(); err != nil { + c.JSON(400, gin.H{"error": err.Error()}) + return true + } + return false } // gemini-api-key: []GeminiKey diff --git a/internal/api/handlers/management/config_lists_api_keys_test.go b/internal/api/handlers/management/config_lists_api_keys_test.go new file mode 100644 index 00000000000..2cbbcb208c9 --- /dev/null +++ b/internal/api/handlers/management/config_lists_api_keys_test.go @@ -0,0 +1,185 @@ +package management + +import ( + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync" + "testing" + + "github.com/MoeForge/moego/json" + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func apiKeysHandler(t *testing.T, entries ...config.APIKeyEntry) *Handler { + t.Helper() + return &Handler{ + cfg: &config.Config{SDKConfig: sdkconfig.SDKConfig{APIKeys: entries}}, + configFilePath: writeTestConfigFile(t), + } +} + +func callAPIKeys(t *testing.T, call func(*gin.Context), method, target, body string) *httptest.ResponseRecorder { + t.Helper() + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(method, target, strings.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + call(c) + return rec +} + +func TestPatchAPIKeysRenameKeepsBinding(t *testing.T) { + for name, body := range map[string]string{ + "by index": `{"index":1,"value":"renamed"}`, + "by old / new": `{"old":"personal","new":"renamed"}`, + } { + t.Run(name, func(t *testing.T) { + h := apiKeysHandler(t, config.APIKeyEntry{Key: "plain"}, config.APIKeyEntry{Key: "personal", Auths: []string{"a.json"}}) + rec := callAPIKeys(t, h.PatchAPIKeys, http.MethodPatch, "/v0/management/api-keys", body) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String()) + } + want := []config.APIKeyEntry{{Key: "plain"}, {Key: "renamed", Auths: []string{"a.json"}}} + if !reflect.DeepEqual(h.cfg.APIKeys, want) { + t.Fatalf("APIKeys = %#v, want %#v", h.cfg.APIKeys, want) + } + }) + } +} + +func TestPatchAPIKeysAppendsUnboundAndRejectsDuplicates(t *testing.T) { + h := apiKeysHandler(t, config.APIKeyEntry{Key: "personal", Auths: []string{"a.json"}}) + if rec := callAPIKeys(t, h.PatchAPIKeys, http.MethodPatch, "/", `{"old":"missing","new":"fresh"}`); rec.Code != http.StatusOK { + t.Fatalf("append status = %d", rec.Code) + } + if got := h.cfg.APIKeys; len(got) != 2 || got[1].Key != "fresh" || got[1].Bound() { + t.Fatalf("APIKeys = %#v", got) + } + before := append([]config.APIKeyEntry(nil), h.cfg.APIKeys...) + if rec := callAPIKeys(t, h.PatchAPIKeys, http.MethodPatch, "/", `{"old":"fresh","new":"personal"}`); rec.Code != http.StatusBadRequest { + t.Fatalf("duplicate rename status = %d, want 400", rec.Code) + } + if !reflect.DeepEqual(h.cfg.APIKeys, before) { + t.Fatalf("a rejected patch changed the keys: %#v", h.cfg.APIKeys) + } +} + +func TestPutAPIKeysKeepsBindingsAndRejectsDuplicates(t *testing.T) { + h := apiKeysHandler(t, config.APIKeyEntry{Key: "personal", Auths: []string{"a.json"}}) + if rec := callAPIKeys(t, h.PutAPIKeys, http.MethodPut, "/", `["personal","other"]`); rec.Code != http.StatusOK { + t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String()) + } + want := []config.APIKeyEntry{{Key: "personal", Auths: []string{"a.json"}}, {Key: "other"}} + if !reflect.DeepEqual(h.cfg.APIKeys, want) { + t.Fatalf("APIKeys = %#v, want %#v", h.cfg.APIKeys, want) + } + if rec := callAPIKeys(t, h.PutAPIKeys, http.MethodPut, "/", `["dup","dup"]`); rec.Code != http.StatusBadRequest { + t.Fatalf("duplicate PUT status = %d, want 400", rec.Code) + } + if !reflect.DeepEqual(h.cfg.APIKeys, want) { + t.Fatalf("a rejected PUT changed the keys: %#v", h.cfg.APIKeys) + } +} + +func TestPutAPIKeysAcceptsWhatGetEmits(t *testing.T) { + entries := []config.APIKeyEntry{ + {Key: "plain"}, + {Key: "personal", Auths: []string{"a.json", "b.json"}}, + {Key: "work", Auths: []string{"c.json"}}, + } + h := apiKeysHandler(t, entries...) + got := callAPIKeys(t, h.GetAPIKeys, http.MethodGet, "/v0/management/api-keys", "") + if got.Code != http.StatusOK { + t.Fatalf("GET status = %d", got.Code) + } + var emitted struct { + APIKeys json.RawMessage `json:"api-keys"` + } + if err := json.Unmarshal(got.Body.Bytes(), &emitted); err != nil { + t.Fatal(err) + } + bodies := map[string]string{ + "GET body as is": got.Body.String(), + "bare array": string(emitted.APIKeys), + "items wrapper": `{"items":` + string(emitted.APIKeys) + `}`, + "api-keys wrapper": `{"api-keys":` + string(emitted.APIKeys) + `}`, + } + for name, body := range bodies { + t.Run(name, func(t *testing.T) { + target := apiKeysHandler(t, entries...) + if rec := callAPIKeys(t, target.PutAPIKeys, http.MethodPut, "/v0/management/api-keys", body); rec.Code != http.StatusOK { + t.Fatalf("PUT status = %d body=%s", rec.Code, rec.Body.String()) + } + if !reflect.DeepEqual(target.cfg.APIKeys, entries) { + t.Fatalf("round trip changed the keys: %#v, want %#v", target.cfg.APIKeys, entries) + } + }) + } +} + +func TestPutAPIKeysTakesExplicitBindingsAndValidatesThem(t *testing.T) { + h := apiKeysHandler(t, config.APIKeyEntry{Key: "old", Auths: []string{"a.json"}}) + body := `["plain",{"key":"bound","auths":["x.json"]},{"key":"old","auths":["b.json"]}]` + if rec := callAPIKeys(t, h.PutAPIKeys, http.MethodPut, "/", body); rec.Code != http.StatusOK { + t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String()) + } + want := []config.APIKeyEntry{{Key: "plain"}, {Key: "bound", Auths: []string{"x.json"}}, {Key: "old", Auths: []string{"b.json"}}} + if !reflect.DeepEqual(h.cfg.APIKeys, want) { + t.Fatalf("APIKeys = %#v, want %#v", h.cfg.APIKeys, want) + } + for name, bad := range map[string]string{ + "duplicate across forms": `["k",{"key":"k","auths":["a.json"]}]`, + "unknown field": `[{"key":"k","auth":["a.json"]}]`, + "empty auths": `[{"key":"k","auths":[]}]`, + "blank auth item": `[{"key":"k","auths":[" "]}]`, + } { + if rec := callAPIKeys(t, h.PutAPIKeys, http.MethodPut, "/", bad); rec.Code != http.StatusBadRequest { + t.Fatalf("%s: status = %d, want 400 body=%s", name, rec.Code, rec.Body.String()) + } + if !reflect.DeepEqual(h.cfg.APIKeys, want) { + t.Fatalf("%s: a rejected PUT changed the keys: %#v", name, h.cfg.APIKeys) + } + } +} + +func TestPutAPIKeysAcceptsPresentEmptyWrapperAndRejectsMissingField(t *testing.T) { + for _, body := range []string{`{"items":[]}`, `{"api-keys":[]}`, `[]`} { + h := apiKeysHandler(t, config.APIKeyEntry{Key: "plain"}) + if rec := callAPIKeys(t, h.PutAPIKeys, http.MethodPut, "/v0/management/api-keys", body); rec.Code != http.StatusOK { + t.Fatalf("PUT %s status = %d body=%s", body, rec.Code, rec.Body.String()) + } + if len(h.cfg.APIKeys) != 0 { + t.Fatalf("PUT %s left %#v, want the list cleared", body, h.cfg.APIKeys) + } + } + for _, body := range []string{`{}`, `{"other":[]}`, `{"items":null}`, `"x"`} { + h := apiKeysHandler(t, config.APIKeyEntry{Key: "plain"}) + if rec := callAPIKeys(t, h.PutAPIKeys, http.MethodPut, "/v0/management/api-keys", body); rec.Code != http.StatusBadRequest { + t.Fatalf("PUT %s status = %d, want 400", body, rec.Code) + } + if len(h.cfg.APIKeys) != 1 { + t.Fatalf("a rejected PUT %s changed the list: %#v", body, h.cfg.APIKeys) + } + } +} + +func TestDeleteAPIKeysRacesSafelyWithPut(t *testing.T) { + h := apiKeysHandler(t, config.APIKeyEntry{Key: "a"}, config.APIKeyEntry{Key: "b", Auths: []string{"x.json"}}) + var wg sync.WaitGroup + for range 8 { + wg.Add(2) + go func() { + defer wg.Done() + callAPIKeys(t, h.DeleteAPIKeys, http.MethodDelete, "/v0/management/api-keys?value=a", "") + }() + go func() { + defer wg.Done() + callAPIKeys(t, h.PutAPIKeys, http.MethodPut, "/v0/management/api-keys", `["a",{"key":"b","auths":["x.json"]}]`) + }() + } + wg.Wait() +} diff --git a/internal/api/handlers/management/config_v8_etag_test.go b/internal/api/handlers/management/config_v8_etag_test.go index dd00d18b5cd..5c47d5ce751 100644 --- a/internal/api/handlers/management/config_v8_etag_test.go +++ b/internal/api/handlers/management/config_v8_etag_test.go @@ -112,7 +112,7 @@ func TestConfigV8ETagIfMatch(t *testing.T) { if err != nil { t.Fatal(err) } - if len(loaded.APIKeys) != 1 || loaded.APIKeys[0] != "other-key" { + if len(loaded.APIKeys) != 1 || loaded.APIKeys[0].Key != "other-key" { t.Fatalf("stale PUT resurrected revoked key: %v", loaded.APIKeys) } diff --git a/internal/api/handlers/management/config_v8_test.go b/internal/api/handlers/management/config_v8_test.go index 0ea7821ab67..b486be4e1d9 100644 --- a/internal/api/handlers/management/config_v8_test.go +++ b/internal/api/handlers/management/config_v8_test.go @@ -422,7 +422,7 @@ func TestConfigV8DeleteLastField(t *testing.T) { if err != nil { t.Fatal(err) } - if !tc.check(cfg) || cfg.Port != 8317 || len(cfg.APIKeys) != 1 || cfg.APIKeys[0] != "client" { + if !tc.check(cfg) || cfg.Port != 8317 || len(cfg.APIKeys) != 1 || cfg.APIKeys[0].Key != "client" { t.Fatal("delete did not restore defaults or changed unrelated settings") } if !reflect.DeepEqual(h.cfg.OAuthOnlyFields, cfg.OAuthOnlyFields) { diff --git a/internal/api/server_api_key_binding_test.go b/internal/api/server_api_key_binding_test.go new file mode 100644 index 00000000000..14e5b5e911d --- /dev/null +++ b/internal/api/server_api_key_binding_test.go @@ -0,0 +1,136 @@ +package api + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/MoeForge/moego/json" + proxyconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/turncost" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestServerModelListIsFilteredPerBoundKey(t *testing.T) { + cfg := &proxyconfig.Config{SDKConfig: sdkconfig.SDKConfig{APIKeys: []proxyconfig.APIKeyEntry{ + {Key: "plain-key"}, + {Key: "personal-key", Auths: []string{"binding-personal.json"}}, + {Key: "work-key", Auths: []string{"binding-work-id"}}, + {Key: "dangling-key", Auths: []string{"missing.json"}}, + }}} + server := newTestServerWithConfig(t, cfg) + modelRegistry := registry.GetGlobalRegistry() + for id, model := range map[string]string{"binding-personal-id": "binding-personal-model", "binding-work-id": "binding-work-model"} { + modelRegistry.RegisterClient(id, "codex", []*registry.ModelInfo{{ID: model, Object: "model"}}) + t.Cleanup(func() { modelRegistry.UnregisterClient(id) }) + } + for id, file := range map[string]string{"binding-personal-id": "binding-personal.json", "binding-work-id": "binding-work.json"} { + if _, err := server.handlers.AuthManager.Register(auth.WithSkipPersist(context.Background()), &auth.Auth{ + ID: id, FileName: file, Provider: "codex", Status: auth.StatusActive, + }); err != nil { + t.Fatal(err) + } + } + + list := func(key string) map[string]bool { + t.Helper() + req := httptest.NewRequest(http.MethodGet, "/v1/models", nil) + req.Header.Set("Authorization", "Bearer "+key) + rr := httptest.NewRecorder() + server.engine.ServeHTTP(rr, req) + if rr.Code != http.StatusOK { + t.Fatalf("%s: status = %d body=%s", key, rr.Code, rr.Body.String()) + } + var body struct { + Data []map[string]any `json:"data"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + ids := map[string]bool{} + for _, model := range body.Data { + if id, ok := model["id"].(string); ok { + ids[id] = true + } + } + return ids + } + + if got := list("plain-key"); !got["binding-personal-model"] || !got["binding-work-model"] { + t.Fatalf("plain key must see every model, got %v", got) + } + if got := list("personal-key"); !got["binding-personal-model"] || got["binding-work-model"] { + t.Fatalf("personal key (file name) listing = %v", got) + } + if got := list("work-key"); !got["binding-work-model"] || got["binding-personal-model"] { + t.Fatalf("work key (ID) listing = %v", got) + } + if got := list("dangling-key"); len(got) != 0 { + t.Fatalf("a key bound to a missing credential must list nothing, got %v", got) + } +} + +func TestTurnCostsEndpointIsScopedToBoundKey(t *testing.T) { + cfg := &proxyconfig.Config{SDKConfig: sdkconfig.SDKConfig{APIKeys: []proxyconfig.APIKeyEntry{ + {Key: "plain-key"}, + {Key: "personal-key", Auths: []string{"turn-personal.json"}}, + {Key: "dangling-key", Auths: []string{"turn-missing.json"}}, + }}} + cfg.CodexTurnCosts.Enabled = true + cfg.CodexTurnCosts.UpstreamEstimates = false + server := newTestServerWithConfig(t, cfg) + for id, file := range map[string]string{"turn-personal-id": "turn-personal.json", "turn-work-id": "turn-work.json"} { + if _, err := server.handlers.AuthManager.Register(auth.WithSkipPersist(context.Background()), &auth.Auth{ + ID: id, FileName: file, Provider: "codex", Status: auth.StatusActive, + }); err != nil { + t.Fatal(err) + } + } + record := func(authID, turnID, responseID string) { + turncost.Default().HandleUsage(context.Background(), coreusage.Record{ + Provider: "codex", Model: "gpt-5.1-codex", TurnID: turnID, AuthID: authID, + Detail: coreusage.Detail{ResponseID: responseID, InputTokens: 1000}, + }) + } + record("turn-personal-id", "scoped-turn-personal", "r1") + record("turn-work-id", "scoped-turn-work", "r2") + + status := func(key string) map[string]string { + t.Helper() + req := httptest.NewRequest(http.MethodPost, "/v1/analytics/codex/turn-costs", strings.NewReader(`{"turn_ids":["scoped-turn-personal","scoped-turn-work"]}`)) + req.Header.Set("Authorization", "Bearer "+key) + rr := httptest.NewRecorder() + server.engine.ServeHTTP(rr, req) + if rr.Code != http.StatusOK { + t.Fatalf("%s: status = %d body=%s", key, rr.Code, rr.Body.String()) + } + var body struct { + Turns []struct { + TurnID string `json:"turn_id"` + Status string `json:"status"` + } `json:"turns"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + out := map[string]string{} + for _, turn := range body.Turns { + out[turn.TurnID] = turn.Status + } + return out + } + if got := status("plain-key"); got["scoped-turn-personal"] != "priced" || got["scoped-turn-work"] != "priced" { + t.Fatalf("plain key = %v, want both priced", got) + } + if got := status("personal-key"); got["scoped-turn-personal"] != "priced" || got["scoped-turn-work"] != "pending" { + t.Fatalf("personal key = %v, want only its own turn priced", got) + } + if got := status("dangling-key"); got["scoped-turn-personal"] != "pending" || got["scoped-turn-work"] != "pending" { + t.Fatalf("dangling key = %v, want nothing priced", got) + } +} diff --git a/internal/api/server_claude_tool_search_test.go b/internal/api/server_claude_tool_search_test.go index 3a6d3f150ff..0a6c34ee4d9 100644 --- a/internal/api/server_claude_tool_search_test.go +++ b/internal/api/server_claude_tool_search_test.go @@ -20,7 +20,7 @@ func setClaudeToolSearchForTest(t *testing.T, enabled bool) { // startup and on every config reload. func TestServerAppliesClaudeToolSearchSwitch(t *testing.T) { setClaudeToolSearchForTest(t, false) - cfg := &proxyconfig.Config{SDKConfig: sdkconfig.SDKConfig{APIKeys: []string{"test-key"}}} + cfg := &proxyconfig.Config{SDKConfig: sdkconfig.SDKConfig{APIKeys: proxyconfig.APIKeyEntries("test-key")}} cfg.Claude.ToolSearch = true server := newTestServerWithConfig(t, cfg) if !responsesclaude.ClientToolSearchEnabled() { diff --git a/internal/api/server_codex_turn_costs_test.go b/internal/api/server_codex_turn_costs_test.go index 81aa6d0232c..74423c057c8 100644 --- a/internal/api/server_codex_turn_costs_test.go +++ b/internal/api/server_codex_turn_costs_test.go @@ -23,7 +23,7 @@ func postTurnCosts(t *testing.T, server *Server, authorization string) *httptest } func TestCodexTurnCostsRouteRequiresAPIKey(t *testing.T) { - cfg := &proxyconfig.Config{SDKConfig: sdkconfig.SDKConfig{APIKeys: []string{"test-key"}}} + cfg := &proxyconfig.Config{SDKConfig: sdkconfig.SDKConfig{APIKeys: proxyconfig.APIKeyEntries("test-key")}} cfg.CodexTurnCosts.Enabled = true server := newTestServerWithConfig(t, cfg) @@ -37,7 +37,7 @@ func TestCodexTurnCostsRouteRequiresAPIKey(t *testing.T) { } func TestCodexTurnCostsRouteDisabledReturnsNotFound(t *testing.T) { - cfg := &proxyconfig.Config{SDKConfig: sdkconfig.SDKConfig{APIKeys: []string{"test-key"}}} + cfg := &proxyconfig.Config{SDKConfig: sdkconfig.SDKConfig{APIKeys: proxyconfig.APIKeyEntries("test-key")}} server := newTestServerWithConfig(t, cfg) if rr := postTurnCosts(t, server, "Bearer test-key"); rr.Code != http.StatusNotFound { diff --git a/internal/api/server_middleware.go b/internal/api/server_middleware.go index 302df321d7b..d2448c10260 100644 --- a/internal/api/server_middleware.go +++ b/internal/api/server_middleware.go @@ -360,7 +360,7 @@ func (s *Server) homeHeartbeatMiddleware() gin.HandlerFunc { } func (s *Server) exampleAPIKeySafeModeRequired(cfg *config.Config) bool { - return s != nil && s.exampleAPIKeySafeModeEnabled && cfg != nil && safemode.HasExampleAPIKeys(cfg.APIKeys) + return s != nil && s.exampleAPIKeySafeModeEnabled && cfg != nil && safemode.HasExampleAPIKeys(cfg.APIKeyStrings()) } func (s *Server) exampleAPIKeySafeModeMiddleware() gin.HandlerFunc { @@ -397,7 +397,7 @@ func (s *Server) serveExampleAPIKeyWarningPage(c *gin.Context) { cfg := s.getConfig() var keys []string if cfg != nil { - keys = safemode.ExampleAPIKeys(cfg.APIKeys) + keys = safemode.ExampleAPIKeys(cfg.APIKeyStrings()) } c.Header("Content-Type", "text/html; charset=utf-8") c.Header("Cache-Control", "no-store") @@ -522,6 +522,9 @@ func accessAuthMiddleware(manager *sdkaccess.Manager, realtimeError bool) gin.Ha if len(result.Metadata) > 0 { c.Set("accessMetadata", result.Metadata) } + if len(result.AllowedAuths) > 0 { + c.Set(sdkaccess.AllowedAuthsContextKey, result.AllowedAuths) + } reqCtx := coreusage.WithAPIKey(c.Request.Context(), result.Principal) reqCtx = coreusage.WithAccessProvider(reqCtx, result.Provider) reqCtx = coreusage.WithIsNativeKey(reqCtx, coreusage.IsNativeAccessProvider(result.Provider)) @@ -590,6 +593,9 @@ func realtimeAuthMiddleware(manager *sdkaccess.Manager, handler *codexlive.Handl } c.Set("userApiKey", principal) c.Set("accessProvider", provider) + if len(authorization.IssuerAllowedAuths) > 0 { + c.Set(sdkaccess.AllowedAuthsContextKey, authorization.IssuerAllowedAuths) + } reqCtx := coreusage.WithAPIKey(c.Request.Context(), principal) reqCtx = coreusage.WithAccessProvider(reqCtx, provider) reqCtx = coreusage.WithIsNativeKey(reqCtx, coreusage.IsNativeAccessProvider(provider)) diff --git a/internal/api/server_muse_code_test.go b/internal/api/server_muse_code_test.go index 5f46a07c388..9fed508b392 100644 --- a/internal/api/server_muse_code_test.go +++ b/internal/api/server_muse_code_test.go @@ -440,7 +440,7 @@ func TestMuseCodeModelsSupportsHomeModeOAuthSettingsHotReloadAndPluginIntercepto // 1. Real server.engine rejects Home request with 503 when Home heartbeat is absent, without leaking local models. cfgNoHome := &proxyconfig.Config{ - SDKConfig: sdkconfig.SDKConfig{APIKeys: []string{"test-key"}}, + SDKConfig: sdkconfig.SDKConfig{APIKeys: proxyconfig.APIKeyEntries("test-key")}, Home: proxyconfig.HomeConfig{Enabled: true}, } serverNoHome := newTestServerWithConfig(t, cfgNoHome) @@ -527,7 +527,7 @@ func TestMuseCodeModelsSupportsHomeModeOAuthSettingsHotReloadAndPluginIntercepto home.SetCurrent(homeClient) cfgWithHome := &proxyconfig.Config{ - SDKConfig: sdkconfig.SDKConfig{APIKeys: []string{"test-key"}}, + SDKConfig: sdkconfig.SDKConfig{APIKeys: proxyconfig.APIKeyEntries("test-key")}, Home: proxyconfig.HomeConfig{Enabled: true}, OAuthSettings: map[string][]proxyconfig.OAuthModelSetting{ "codex": { @@ -742,7 +742,7 @@ func TestMuseCodeRoutesEnforceAuthSafeModeAndDisallowedPaths(t *testing.T) { // 2. Example API key safe mode blocks /muse-code/models with 403. safeCfg := &proxyconfig.Config{ SDKConfig: sdkconfig.SDKConfig{ - APIKeys: []string{"your-api-key-1"}, + APIKeys: proxyconfig.APIKeyEntries("your-api-key-1"), }, } safeServer := newTestServerWithConfig(t, safeCfg, WithExampleAPIKeySafeMode()) diff --git a/internal/api/server_realtime_binding_test.go b/internal/api/server_realtime_binding_test.go new file mode 100644 index 00000000000..7930f9770b0 --- /dev/null +++ b/internal/api/server_realtime_binding_test.go @@ -0,0 +1,152 @@ +package api + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/MoeForge/moego/json" + proxyconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +// recordingCodexExecutor records which credential serves each upstream realtime call. +type recordingCodexExecutor struct { + mu sync.Mutex + selected []string +} + +func (*recordingCodexExecutor) Identifier() string { return "codex" } +func (*recordingCodexExecutor) Execute(context.Context, *auth.Auth, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, error) { + return coreexecutor.Response{}, nil +} +func (*recordingCodexExecutor) ExecuteStream(context.Context, *auth.Auth, coreexecutor.Request, coreexecutor.Options) (*coreexecutor.StreamResult, error) { + return nil, nil +} +func (*recordingCodexExecutor) Refresh(_ context.Context, credential *auth.Auth) (*auth.Auth, error) { + return credential, nil +} +func (*recordingCodexExecutor) CountTokens(context.Context, *auth.Auth, coreexecutor.Request, coreexecutor.Options) (coreexecutor.Response, error) { + return coreexecutor.Response{}, nil +} +func (*recordingCodexExecutor) PrepareRequest(req *http.Request, credential *auth.Auth) error { + token, _ := credential.Metadata["access_token"].(string) + req.Header.Set("Authorization", "Bearer "+token) + return nil +} +func (e *recordingCodexExecutor) HttpRequest(_ context.Context, credential *auth.Auth, req *http.Request) (*http.Response, error) { + if req.Body != nil { + _, _ = io.Copy(io.Discard, req.Body) + } + e.mu.Lock() + e.selected = append(e.selected, credential.ID) + e.mu.Unlock() + return &http.Response{ + StatusCode: http.StatusCreated, + Header: http.Header{"Content-Type": []string{"application/sdp"}, "Location": []string{"/v1/realtime/calls/call-binding"}}, + Body: io.NopCloser(strings.NewReader("v=0\r\n")), + }, nil +} + +func (e *recordingCodexExecutor) servedBy() []string { + e.mu.Lock() + defer e.mu.Unlock() + return append([]string(nil), e.selected...) +} + +// TestRealtimeClientSecretKeepsTheIssuerBinding mints realtime client secrets through +// the real routes and middleware, then opens calls with them. A secret minted by a key +// bound to credential A must only ever be served by A, even though B is registered too. +func TestRealtimeClientSecretKeepsTheIssuerBinding(t *testing.T) { + cfg := &proxyconfig.Config{SDKConfig: sdkconfig.SDKConfig{APIKeys: []proxyconfig.APIKeyEntry{ + {Key: "plain-key"}, + {Key: "key-a", Auths: []string{"rt-a.json"}}, + {Key: "key-nothing", Auths: []string{"rt-missing.json"}}, + }}} + server := newTestServerWithConfig(t, cfg) + executor := &recordingCodexExecutor{} + manager := server.handlers.AuthManager + manager.RegisterExecutor(executor) + for id, file := range map[string]string{"rt-a": "rt-a.json", "rt-b": "rt-b.json"} { + if _, err := manager.Register(auth.WithSkipPersist(context.Background()), &auth.Auth{ + ID: id, FileName: file, Provider: "codex", Status: auth.StatusActive, + Metadata: map[string]any{"access_token": "token-" + id}, + }); err != nil { + t.Fatal(err) + } + } + + mint := func(key string) string { + t.Helper() + req := httptest.NewRequest(http.MethodPost, "/v1/realtime/client_secrets", strings.NewReader(`{"session":{"type":"realtime","model":"gpt-realtime"}}`)) + req.Header.Set("Authorization", "Bearer "+key) + rr := httptest.NewRecorder() + server.engine.ServeHTTP(rr, req) + if rr.Code != http.StatusOK { + t.Fatalf("mint with %s: status = %d body=%s", key, rr.Code, rr.Body.String()) + } + var body struct { + Value string `json:"value"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil || body.Value == "" { + t.Fatalf("mint with %s: body=%s err=%v", key, rr.Body.String(), err) + } + return body.Value + } + call := func(secret string) int { + t.Helper() + req := httptest.NewRequest(http.MethodPost, "/v1/realtime/calls", strings.NewReader("v=0\r\n")) + req.Header.Set("Authorization", "Bearer "+secret) + req.Header.Set("Content-Type", "application/sdp") + rr := httptest.NewRecorder() + server.engine.ServeHTTP(rr, req) + return rr.Code + } + + boundSecret := mint("key-a") + for i := 0; i < 8; i++ { + if code := call(boundSecret); code != http.StatusCreated { + t.Fatalf("bound call %d: status = %d", i, code) + } + } + for _, id := range executor.servedBy() { + if id != "rt-a" { + t.Fatalf("a secret minted by a key bound to rt-a was served by %q", id) + } + } + if got := len(executor.servedBy()); got != 8 { + t.Fatalf("served calls = %d, want 8", got) + } + + // A key bound to nothing mints a secret that can never be served. + before := len(executor.servedBy()) + nothingSecret := mint("key-nothing") + if code := call(nothingSecret); code == http.StatusCreated { + t.Fatalf("a secret minted by a key bound to a missing credential was served") + } + if got := len(executor.servedBy()); got != before { + t.Fatalf("a key bound to nothing reached an upstream credential") + } + + // Control: an unrestricted key's secret still rotates over both credentials, so the + // bound result above comes from the restriction and not from a missing credential. + plainSecret := mint("plain-key") + seen := map[string]bool{} + for i := 0; i < 8; i++ { + if code := call(plainSecret); code != http.StatusCreated { + t.Fatalf("plain call %d: status = %d", i, code) + } + } + for _, id := range executor.servedBy()[before:] { + seen[id] = true + } + if !seen["rt-a"] || !seen["rt-b"] { + t.Fatalf("unrestricted secret served by %v, want both credentials", seen) + } +} diff --git a/internal/api/server_reload.go b/internal/api/server_reload.go index f458ace001b..fc6fc1fced2 100644 --- a/internal/api/server_reload.go +++ b/internal/api/server_reload.go @@ -29,7 +29,7 @@ func (s *Server) applyAccessConfig(oldCfg, newCfg *config.Config) bool { return false } if s.tunnelHub != nil { - s.tunnelHub.UpdateAllowedAPIKeys(newCfg.APIKeys) + s.tunnelHub.UpdateAllowedAPIKeys(newCfg.APIKeyStrings()) } if s.accessManager == nil { return false diff --git a/internal/api/server_routes.go b/internal/api/server_routes.go index d552de3f22c..f6241a2ef28 100644 --- a/internal/api/server_routes.go +++ b/internal/api/server_routes.go @@ -28,6 +28,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" responsesclaude "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/claude/openai/responses" "github.com/router-for-me/CLIProxyAPI/v8/internal/turncost" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers/claude" "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers/gemini" @@ -92,7 +93,7 @@ func (s *Server) setupRoutes() { v1.POST("/responses", openaiResponsesHandlers.Responses) v1.POST("/responses/compact", openaiResponsesHandlers.Compact) v1.POST("/alpha/search", s.codexAlphaSearch) - v1.POST("/analytics/codex/turn-costs", turncost.Default().Handler) + v1.POST("/analytics/codex/turn-costs", turncost.Default().HandlerScoped(s.turnCostScope)) v1.POST("/live", s.codexLiveHandler.Handle) v1.GET("/live/:call_id", s.codexLiveHandler.HandleSideband) } @@ -723,7 +724,7 @@ func (s *Server) handleGrokModels(c *gin.Context) { } models = grokModelsFromHomeEntries(entries) } else { - models = grokModelsFromRegistryInfos(registry.GetGlobalRegistry().GetAvailableModelInfos()) + models = grokModelsFromRegistryInfos(s.availableModelInfosForRequest(c)) } s.writeModelListResponse(c, "openai", grokbuild.BuildResponse(models)) } @@ -1192,10 +1193,28 @@ func (s *Server) handleHomeGeminiModel(c *gin.Context) { }) } +// availableModelInfosForRequest lists model metadata visible to the request's client key. +func (s *Server) availableModelInfosForRequest(c *gin.Context) []*registry.ModelInfo { + modelRegistry := registry.GetGlobalRegistry() + refs := sdkaccess.AllowedAuthsFromGin(c) + if len(refs) == 0 { + return modelRegistry.GetAvailableModelInfos() + } + if s == nil || s.handlers == nil || s.handlers.AuthManager == nil { + return nil + } + return modelRegistry.GetAvailableModelInfosForClients(s.handlers.AuthManager.AllowedAuthIDs(refs)) +} + func (s *Server) loadHomeModelEntries(c *gin.Context) ([]homeModelEntry, bool) { if s == nil || c == nil || c.Request == nil { return nil, false } + if len(sdkaccess.AllowedAuthsFromGin(c)) > 0 { + // Home chooses credentials itself and cannot honor a key binding, so a + // bound key sees no models, matching the dispatch refusal. + return nil, true + } client := home.Current() if client == nil { c.JSON(http.StatusServiceUnavailable, handlers.ErrorResponse{ @@ -1614,3 +1633,17 @@ func homeModelInt64Value(model map[string]any, keys ...string) int64 { } return 0 } + +// turnCostScope limits the turn-cost endpoint to turns served by the credentials a bound +// client key may use. Turns outside the binding read as pending, and Home mode, which +// cannot enforce a binding, exposes none of them. +func (s *Server) turnCostScope(c *gin.Context) turncost.Scope { + refs := sdkaccess.AllowedAuthsFromGin(c) + if len(refs) == 0 { + return nil + } + if s == nil || s.handlers == nil || s.handlers.AuthManager == nil || s.handlers.AuthManager.HomeEnabled() { + return turncost.AuthIDScope(nil) + } + return turncost.AuthIDScope(s.handlers.AuthManager.AllowedAuthIDs(refs)) +} diff --git a/internal/api/server_test.go b/internal/api/server_test.go index 77d3dc47453..22c3b3f3d82 100644 --- a/internal/api/server_test.go +++ b/internal/api/server_test.go @@ -616,7 +616,7 @@ func newTestServerWithOptions(t *testing.T, opts ...ServerOption) *Server { t.Helper() cfg := &proxyconfig.Config{ SDKConfig: sdkconfig.SDKConfig{ - APIKeys: []string{"test-key"}, + APIKeys: proxyconfig.APIKeyEntries("test-key"), }, } return newTestServerWithConfig(t, cfg, opts...) @@ -1849,7 +1849,7 @@ func TestExampleAPIKeySafeModeShowsWarningAndKeepsManagement(t *testing.T) { server := newTestServerWithOptions(t, WithExampleAPIKeySafeMode()) cfg := *server.cfg - cfg.APIKeys = []string{"your-api-key-1"} + cfg.APIKeys = proxyconfig.APIKeyEntries("your-api-key-1") server.UpdateClients(&cfg) t.Run("root warning page includes management link", func(t *testing.T) { @@ -1945,7 +1945,7 @@ func TestExampleAPIKeySafeModeShowsWarningAndKeepsManagement(t *testing.T) { t.Run("safe mode clears after key update", func(t *testing.T) { nextCfg := cfg - nextCfg.APIKeys = []string{"real-key"} + nextCfg.APIKeys = proxyconfig.APIKeyEntries("real-key") server.UpdateClients(&nextCfg) req := httptest.NewRequest(http.MethodGet, "/v1/models", nil) @@ -2172,7 +2172,7 @@ func TestModelsWithClientVersionReturnsCodexCatalog(t *testing.T) { modelRegistry.UnregisterClient(clientID) }) - cfg := &proxyconfig.Config{SDKConfig: sdkconfig.SDKConfig{APIKeys: []string{"test-key"}}} + cfg := &proxyconfig.Config{SDKConfig: sdkconfig.SDKConfig{APIKeys: proxyconfig.APIKeyEntries("test-key")}} cfg.Client.Codex.EnableApplyPatch = true server := newTestServerWithConfig(t, cfg) server.handlers.AuthManager.RegisterExecutor(executor.NewCodexAutoExecutor(&proxyconfig.Config{})) diff --git a/internal/api/server_tunnel_test.go b/internal/api/server_tunnel_test.go index 91c25164c67..1f140fb8509 100644 --- a/internal/api/server_tunnel_test.go +++ b/internal/api/server_tunnel_test.go @@ -122,7 +122,7 @@ func readServerTunnelBinary(t *testing.T, conn *websocket.Conn) wstunnel.DataFra func TestServerWebsocketTunnel_EndToEndAndTenantIsolation(t *testing.T) { cfg := &config.Config{ SDKConfig: config.SDKConfig{ - APIKeys: []string{"tenant-a", "tenant-b"}, + APIKeys: config.APIKeyEntries("tenant-a", "tenant-b"), }, } apiSrv := newTestTunnelAPIServer(t, cfg) @@ -206,7 +206,7 @@ func TestServerWebsocketTunnel_EndToEndAndTenantIsolation(t *testing.T) { func TestServerWebsocketTunnel_NonGetMethodsReturn405AndPreserveCORSOptions(t *testing.T) { cfg := &config.Config{ SDKConfig: config.SDKConfig{ - APIKeys: []string{"method-key"}, + APIKeys: config.APIKeyEntries("method-key"), }, } apiSrv := newTestTunnelAPIServer(t, cfg) @@ -284,7 +284,7 @@ func TestServerWebsocketTunnel_RejectsWhenAPIKeysEmptyOrSafeMode(t *testing.T) { t.Run("example api-key safe mode blocks /v1/tunnel with 403", func(t *testing.T) { cfg := &config.Config{ SDKConfig: config.SDKConfig{ - APIKeys: []string{"your-api-key-1"}, + APIKeys: config.APIKeyEntries("your-api-key-1"), }, } apiSrv := newTestTunnelAPIServer(t, cfg, WithExampleAPIKeySafeMode()) @@ -327,7 +327,7 @@ func TestServerWebsocketTunnel_ServiceUnavailableResponseBodies(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { cfg := &config.Config{ - SDKConfig: config.SDKConfig{APIKeys: []string{"key"}}, + SDKConfig: config.SDKConfig{APIKeys: config.APIKeyEntries("key")}, Home: config.HomeConfig{Enabled: tc.homeEnabled}, } apiSrv := newTestTunnelAPIServer(t, cfg) @@ -356,7 +356,7 @@ func TestServerWebsocketTunnel_ServiceUnavailableResponseBodies(t *testing.T) { func TestServerWebsocketTunnel_HotReloadRevokesRemovedKeyOnly(t *testing.T) { cfg := &config.Config{ SDKConfig: config.SDKConfig{ - APIKeys: []string{"key-keep", "key-revoke"}, + APIKeys: config.APIKeyEntries("key-keep", "key-revoke"), }, } apiSrv := newTestTunnelAPIServer(t, cfg) @@ -375,7 +375,7 @@ func TestServerWebsocketTunnel_HotReloadRevokesRemovedKeyOnly(t *testing.T) { updatedCfg := &config.Config{ SDKConfig: config.SDKConfig{ - APIKeys: []string{"key-keep"}, + APIKeys: config.APIKeyEntries("key-keep"), }, } apiSrv.UpdateClients(updatedCfg) @@ -410,7 +410,7 @@ func TestServerWebsocketTunnel_ServerStopClosesConnections(t *testing.T) { Host: "127.0.0.1", Port: port, SDKConfig: config.SDKConfig{ - APIKeys: []string{"stop-key"}, + APIKeys: config.APIKeyEntries("stop-key"), }, } apiSrv := newTestTunnelAPIServer(t, cfg) diff --git a/internal/api/server_tunnel_transport_test.go b/internal/api/server_tunnel_transport_test.go index 6efb36f2775..28d59252251 100644 --- a/internal/api/server_tunnel_transport_test.go +++ b/internal/api/server_tunnel_transport_test.go @@ -116,7 +116,7 @@ func TestServerWebsocketTunnel_TLSWithoutALPNClosesRawTransport(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { apiSrv := newTestTunnelAPIServer(t, &config.Config{ - SDKConfig: config.SDKConfig{APIKeys: []string{"key"}}, + SDKConfig: config.SDKConfig{APIKeys: config.APIKeyEntries("key")}, }) baseListener, errListen := net.Listen("tcp", "127.0.0.1:0") if errListen != nil { diff --git a/internal/api/server_websocket_route_test.go b/internal/api/server_websocket_route_test.go index 392c153b211..a9a1d128fbd 100644 --- a/internal/api/server_websocket_route_test.go +++ b/internal/api/server_websocket_route_test.go @@ -15,7 +15,7 @@ func TestAttachWebsocketRouteDisabledInHomeMode(t *testing.T) { for _, wsAuth := range []bool{false, true} { t.Run(fmt.Sprintf("home=%t/ws-auth=%t", homeEnabled, wsAuth), func(t *testing.T) { cfg := &config.Config{ - SDKConfig: config.SDKConfig{APIKeys: []string{"test-key"}}, + SDKConfig: config.SDKConfig{APIKeys: config.APIKeyEntries("test-key")}, Home: config.HomeConfig{Enabled: homeEnabled}, WebsocketAuth: wsAuth, } diff --git a/internal/client/codex/live/allowed_auths_test.go b/internal/client/codex/live/allowed_auths_test.go new file mode 100644 index 00000000000..fab9887e0ba --- /dev/null +++ b/internal/client/codex/live/allowed_auths_test.go @@ -0,0 +1,148 @@ +package live + +import ( + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +func registerBindingCredentials(t *testing.T) *auth.Manager { + t.Helper() + manager := auth.NewManager(nil, nil, nil) + manager.RegisterExecutor(&captureExecutor{}) + for _, id := range []string{"bound-a", "bound-b"} { + registerCredential(t, manager, &auth.Auth{ + ID: id, + Provider: "codex", + Status: auth.StatusActive, + Metadata: map[string]any{"access_token": "token-" + id}, + }) + } + return manager +} + +// restrictTo mimics the access middleware: the authenticated key's credential +// restriction lives on the gin context and nowhere else. +func restrictTo(refs ...string) gin.HandlerFunc { + return func(c *gin.Context) { + c.Set(sdkaccess.AllowedAuthsContextKey, refs) + c.Next() + } +} + +func TestHandleDirectWebsocketHonorsTheKeyBinding(t *testing.T) { + gin.SetMode(gin.TestMode) + tokens := make(chan string, 32) + upstreamServer := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} + connection, errUpgrade := upgrader.Upgrade(writer, request, nil) + if errUpgrade != nil { + return + } + defer func() { _ = connection.Close() }() + tokens <- request.Header.Get("Authorization") + _ = connection.WriteMessage(websocket.TextMessage, []byte(`{"type":"session.created"}`)) + })) + defer upstreamServer.Close() + + manager := registerBindingCredentials(t) + handler := NewHandler(manager, nil) + handler.sidebandAPIBaseURL = "ws" + strings.TrimPrefix(upstreamServer.URL, "http") + "/v1" + router := gin.New() + router.GET("/v1/realtime", restrictTo("bound-a"), handler.HandleRealtimeWebsocket) + downstream := httptest.NewServer(router) + defer downstream.Close() + + wsURL := "ws" + strings.TrimPrefix(downstream.URL, "http") + "/v1/realtime?model=gpt-realtime" + const dials = 6 + for i := 0; i < dials; i++ { + connection, response, errDial := websocket.DefaultDialer.Dial(wsURL, nil) + if errDial != nil { + t.Fatalf("dial %d: %v", i, errDial) + } + if response != nil && response.Body != nil { + _ = response.Body.Close() + } + _, _, _ = connection.ReadMessage() + _ = connection.Close() + } + for i := 0; i < dials; i++ { + select { + case got := <-tokens: + if got != "Bearer token-bound-a" { + t.Fatalf("websocket %d was served with %q, want only bound-a", i, got) + } + case <-time.After(2 * time.Second): + t.Fatalf("upstream saw %d of %d websockets", i, dials) + } + } +} + +func TestHandleSidebandHonorsTheKeyBinding(t *testing.T) { + gin.SetMode(gin.TestMode) + var upstreamDials atomic.Int32 + tokens := make(chan string, 8) + upstreamServer := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} + connection, errUpgrade := upgrader.Upgrade(writer, request, nil) + if errUpgrade != nil { + return + } + defer func() { _ = connection.Close() }() + upstreamDials.Add(1) + tokens <- request.Header.Get("Authorization") + _ = connection.WriteMessage(websocket.TextMessage, []byte("hello")) + })) + defer upstreamServer.Close() + + manager := registerBindingCredentials(t) + handler := NewHandler(manager, nil) + handler.sidebandAPIBaseURL = "ws" + strings.TrimPrefix(upstreamServer.URL, "http") + "/v1" + router := gin.New() + router.GET("/v1/realtime/calls/:call_id", restrictTo("bound-a"), handler.HandleSideband) + downstream := httptest.NewServer(router) + defer downstream.Close() + base := "ws" + strings.TrimPrefix(downstream.URL, "http") + "/v1/realtime/calls/" + + // A call pinned to a credential outside the key's set must not be joined. + handler.sessions.put("call-outside", liveSession{authID: "bound-b", model: defaultLiveModel}) + connection, response, errDial := websocket.DefaultDialer.Dial(base+"call-outside", nil) + if errDial == nil { + _ = connection.Close() + t.Fatal("a bound key joined a call pinned to a credential outside its set") + } + if response != nil && response.Body != nil { + _ = response.Body.Close() + } + if got := upstreamDials.Load(); got != 0 { + t.Fatalf("upstream was dialed %d times for an out-of-set credential", got) + } + + // Control: a call pinned to the key's own credential is joined. + handler.sessions.put("call-inside", liveSession{authID: "bound-a", model: defaultLiveModel}) + connection, response, errDial = websocket.DefaultDialer.Dial(base+"call-inside", nil) + if errDial != nil { + t.Fatalf("dial in-set call: %v", errDial) + } + if response != nil && response.Body != nil { + _ = response.Body.Close() + } + _, _, _ = connection.ReadMessage() + _ = connection.Close() + select { + case got := <-tokens: + if got != "Bearer token-bound-a" { + t.Fatalf("sideband was served with %q, want bound-a", got) + } + case <-time.After(2 * time.Second): + t.Fatal("in-set sideband never reached upstream") + } +} diff --git a/internal/client/codex/live/client_secret.go b/internal/client/codex/live/client_secret.go index 1313960ce73..b0dcb2162f4 100644 --- a/internal/client/codex/live/client_secret.go +++ b/internal/client/codex/live/client_secret.go @@ -14,6 +14,7 @@ import ( "github.com/MoeForge/moego/json" "github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" ) const ( @@ -39,7 +40,10 @@ type ClientSecretAuthorization struct { Principal string IssuerPrincipal string IssuerProvider string - Session json.RawMessage + // IssuerAllowedAuths carries the credential restriction of the key that + // minted the secret, so the secret cannot reach other credentials. + IssuerAllowedAuths []string + Session json.RawMessage } type clientSecretEntry struct { @@ -74,7 +78,7 @@ func newClientSecretStore() *clientSecretStore { } } -func (s *clientSecretStore) create(session json.RawMessage, lifetime time.Duration, issuerPrincipal, issuerProvider string) (string, ClientSecretAuthorization, time.Time, error) { +func (s *clientSecretStore) create(session json.RawMessage, lifetime time.Duration, issuerPrincipal, issuerProvider string, issuerAllowedAuths []string) (string, ClientSecretAuthorization, time.Time, error) { if s == nil { return "", ClientSecretAuthorization{}, time.Time{}, errors.New("Realtime client secret store unavailable") } @@ -87,10 +91,11 @@ func (s *clientSecretStore) create(session json.RawMessage, lifetime time.Durati return "", ClientSecretAuthorization{}, time.Time{}, errSessionID } authorization := ClientSecretAuthorization{ - Principal: sessionID, - IssuerPrincipal: strings.TrimSpace(issuerPrincipal), - IssuerProvider: strings.TrimSpace(issuerProvider), - Session: append(json.RawMessage(nil), session...), + Principal: sessionID, + IssuerPrincipal: strings.TrimSpace(issuerPrincipal), + IssuerProvider: strings.TrimSpace(issuerProvider), + IssuerAllowedAuths: append([]string(nil), issuerAllowedAuths...), + Session: append(json.RawMessage(nil), session...), } now := s.currentTime() expiresAt := now.Add(lifetime) @@ -270,7 +275,11 @@ func (h *Handler) createClientSecret(c *gin.Context, session json.RawMessage, ex issuerProvider, _ := c.Get("accessProvider") issuerPrincipalValue, _ := issuerPrincipal.(string) issuerProviderValue, _ := issuerProvider.(string) - token, authorization, expiresAt, errCreate := h.clientSecrets.create(upstreamSession, lifetime, issuerPrincipalValue, issuerProviderValue) + var issuerAllowedAuths []string + if value, ok := c.Get(sdkaccess.AllowedAuthsContextKey); ok { + issuerAllowedAuths, _ = value.([]string) + } + token, authorization, expiresAt, errCreate := h.clientSecrets.create(upstreamSession, lifetime, issuerPrincipalValue, issuerProviderValue, issuerAllowedAuths) if errCreate != nil { if errors.Is(errCreate, errClientSecretCapacity) { c.Header("Retry-After", "1") diff --git a/internal/client/codex/live/client_secret_test.go b/internal/client/codex/live/client_secret_test.go index f38512f1b10..7a6d999c3e6 100644 --- a/internal/client/codex/live/client_secret_test.go +++ b/internal/client/codex/live/client_secret_test.go @@ -119,7 +119,7 @@ func TestClientSecretStoreRejectsExpiredToken(t *testing.T) { store := newClientSecretStore() now := time.Unix(1700000000, 0) store.now = func() time.Time { return now } - token, _, _, errCreate := store.create(json.RawMessage(`{"type":"realtime","model":"gpt-live-1-codex"}`), time.Minute, "issuer", "test") + token, _, _, errCreate := store.create(json.RawMessage(`{"type":"realtime","model":"gpt-live-1-codex"}`), time.Minute, "issuer", "test", nil) if errCreate != nil { t.Fatalf("create() error = %v", errCreate) } @@ -260,3 +260,24 @@ func TestApplyClientSecretCallSession(t *testing.T) { t.Fatalf("payload = %+v", payload) } } + +func TestClientSecretCarriesIssuerCredentialRestriction(t *testing.T) { + store := newClientSecretStore() + session := json.RawMessage(`{"type":"realtime","model":"gpt-live-1-codex"}`) + token, _, _, errCreate := store.create(session, time.Minute, "issuer", "test", []string{"personal.json"}) + if errCreate != nil { + t.Fatal(errCreate) + } + authorization, errAuth := store.authenticate(token) + if errAuth != nil { + t.Fatal(errAuth) + } + if got := authorization.IssuerAllowedAuths; len(got) != 1 || got[0] != "personal.json" { + t.Fatalf("IssuerAllowedAuths = %v, want [personal.json]", got) + } + unbound, _, _, _ := store.create(session, time.Minute, "issuer", "test", nil) + authorization, _ = store.authenticate(unbound) + if len(authorization.IssuerAllowedAuths) != 0 { + t.Fatalf("unbound issuer must stay unrestricted, got %v", authorization.IssuerAllowedAuths) + } +} diff --git a/internal/client/codex/optimize-multi-agent-v2/optimize_multi_agent_v2.go b/internal/client/codex/optimize-multi-agent-v2/optimize_multi_agent_v2.go index b51ec111f16..615b3ae0119 100644 --- a/internal/client/codex/optimize-multi-agent-v2/optimize_multi_agent_v2.go +++ b/internal/client/codex/optimize-multi-agent-v2/optimize_multi_agent_v2.go @@ -17,6 +17,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/home" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" "github.com/router-for-me/CLIProxyAPI/v8/internal/util" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) @@ -183,7 +184,37 @@ func prepareCodexMultiAgentV2ToolsDoc(doc *ojson.Doc, ctx context.Context, heade models, formattedMarkdown = codexSpawnAgentModelsAndMarkdownForRequest(ctx, headers, homeEnabled) } - return rewriteCodexCollaborationToolsDoc(doc, messageToolPaths, toolPaths, models, formattedMarkdown), true + stripped := false + if len(toolPaths) > 0 && formattedMarkdown == "" { + // A bound key with no usable model must not keep the model list the client wrote + // into the description: it can name credentials the key may not use. + if _, restricted := codexAllowedClients(ctx); restricted { + stripped = stripCodexSpawnAgentModels(doc, toolPaths) + } + } + return rewriteCodexCollaborationToolsDoc(doc, messageToolPaths, toolPaths, models, formattedMarkdown) || stripped, true +} + +// stripCodexSpawnAgentModels removes the "Available model overrides" section from every +// spawn_agent description and keeps the rest of the description. +func stripCodexSpawnAgentModels(doc *ojson.Doc, toolPaths []string) bool { + changed := false + for _, toolPath := range toolPaths { + descriptionPath := toolPath + ".description" + description := doc.Get(descriptionPath) + if description.Type != ojson.String { + continue + } + cleaned, _ := removeCodexSpawnAgentModelSections(description.String()) + if cleaned == description.String() { + continue + } + if errSet := doc.Set(descriptionPath, cleaned); errSet != nil { + return changed + } + changed = true + } + return changed } // OptimizeCodexMultiAgentV2Request rewrites an eligible spawn_agent request and @@ -360,7 +391,45 @@ func loadCodexCatalogTemplates() (map[string]map[string]any, map[string]any, uin return templates, defaultTemplate, revision, nil } +// codexAllowedClients returns the credentials a restricted client key may use, and whether +// the request is restricted at all. +func codexAllowedClients(ctx context.Context) (map[string]struct{}, bool) { + if ctx == nil { + return nil, false + } + ginCtx, ok := ctx.Value("gin").(*gin.Context) + if !ok || ginCtx == nil { + return nil, false + } + ids, restricted := sdkaccess.AllowedAuthIDsFromGin(ginCtx) + if !restricted { + return nil, false + } + set := make(map[string]struct{}, len(ids)) + for _, id := range ids { + set[id] = struct{}{} + } + return set, true +} + func codexSpawnAgentModelsAndMarkdownForRequest(ctx context.Context, headers http.Header, homeEnabled bool) ([]codexSpawnAgentModel, string) { + if allowed, restricted := codexAllowedClients(ctx); restricted { + // A key bound to credentials may only be offered the models those credentials + // serve. The shared cache holds the global list, so it is bypassed, and Home + // mode (which cannot enforce a binding) offers none. + templates, defaultTemplate, _, errLoad := loadCodexCatalogTemplates() + if errLoad != nil || defaultTemplate == nil { + return nil, "" + } + availableModels := []map[string]any{} + if !homeEnabled { + availableModels = registry.GetGlobalRegistry().GetAvailableModelsForClients("openai", allowed) + } + models := codexSpawnAgentModelsFromTemplates(availableModels, templates, defaultTemplate, func(modelID string) *registry.ModelInfo { + return registry.LookupModelInfo(modelID) + }) + return models, formatCodexSpawnAgentModels(models) + } if homeEnabled { availableModels := codexHomeAvailableModels(ctx, headers) templates, defaultTemplate, _, errLoad := loadCodexCatalogTemplates() diff --git a/internal/client/codex/optimize-multi-agent-v2/optimize_multi_agent_v2_test.go b/internal/client/codex/optimize-multi-agent-v2/optimize_multi_agent_v2_test.go index ff4c72e69f1..f0f593b3f13 100644 --- a/internal/client/codex/optimize-multi-agent-v2/optimize_multi_agent_v2_test.go +++ b/internal/client/codex/optimize-multi-agent-v2/optimize_multi_agent_v2_test.go @@ -12,6 +12,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" _ "github.com/router-for-me/CLIProxyAPI/v8/internal/translator" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" ) @@ -1231,3 +1232,75 @@ func BenchmarkOptimizeCodexMultiAgentV2Request(b *testing.B) { OptimizeCodexMultiAgentV2Request(ctx, headers, payload, cfg) } } + +func TestCodexSpawnAgentModelsAreScopedToBoundKey(t *testing.T) { + modelRegistry := registry.GetGlobalRegistry() + for id, model := range map[string]string{"bound-spawn-client-a": "bound-spawn-model-a", "bound-spawn-client-b": "bound-spawn-model-b"} { + modelRegistry.RegisterClient(id, "openai", []*registry.ModelInfo{{ID: model, DisplayName: model}}) + t.Cleanup(func() { modelRegistry.UnregisterClient(id) }) + } + requestCtx := func(refs []string, ids []string) context.Context { + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + if refs != nil { + ginCtx.Set(sdkaccess.AllowedAuthsContextKey, refs) + } + if ids != nil { + ginCtx.Set(sdkaccess.AllowedAuthIDsContextKey, ids) + } + return context.WithValue(context.Background(), "gin", ginCtx) + } + + // Warm the shared cache with the global list, which a bound key must never be served. + if all := formatCodexSpawnAgentModelsForRequest(context.Background(), nil, false); !strings.Contains(all, "bound-spawn-model-a") || !strings.Contains(all, "bound-spawn-model-b") { + t.Fatalf("unrestricted list = %s", all) + } + bound := formatCodexSpawnAgentModelsForRequest(requestCtx([]string{"a.json"}, []string{"bound-spawn-client-a"}), nil, false) + if !strings.Contains(bound, "bound-spawn-model-a") || strings.Contains(bound, "bound-spawn-model-b") { + t.Fatalf("bound list = %s, want only model a", bound) + } + // Restricted but nothing resolved, or IDs never published, must offer nothing. + for name, ctx := range map[string]context.Context{ + "no credentials resolved": requestCtx([]string{"missing.json"}, []string{}), + "ids never published": requestCtx([]string{"a.json"}, nil), + } { + if got := formatCodexSpawnAgentModelsForRequest(ctx, nil, false); strings.Contains(got, "bound-spawn-model") { + t.Fatalf("%s: list = %s, want no bound-spawn models", name, got) + } + } + // Home mode cannot enforce a binding. + if got := formatCodexSpawnAgentModelsForRequest(requestCtx([]string{"a.json"}, []string{"bound-spawn-client-a"}), nil, true); strings.Contains(got, "bound-spawn-model") { + t.Fatalf("home list = %s, want none", got) + } + // The bound request must not poison the cache for unrestricted callers. + if all := formatCodexSpawnAgentModelsForRequest(context.Background(), nil, false); !strings.Contains(all, "bound-spawn-model-b") { + t.Fatalf("unrestricted list after a bound request = %s", all) + } +} + +func TestPrepareCodexMultiAgentV2ToolsDropsModelListForBoundKeyWithNoModels(t *testing.T) { + payload := []byte(`{"tools":[{"type":"namespace","name":"collaboration","tools":[` + + `{"type":"function","name":"spawn_agent","description":"Intro line.\n` + codexSpawnAgentModelsHeading + `\n- ` + "`excluded-model`" + `: not yours.\nSpawns an agent.","parameters":{"type":"object"}}]}]}`) + headers := http.Header{"User-Agent": []string{"codex_cli_rs/0.144.1"}} + bound := func(ids []string) context.Context { + ginCtx, _ := gin.CreateTestContext(httptest.NewRecorder()) + ginCtx.Set(sdkaccess.AllowedAuthsContextKey, []string{"nothing.json"}) + ginCtx.Set(sdkaccess.AllowedAuthIDsContextKey, ids) + return context.WithValue(context.Background(), "gin", ginCtx) + } + for name, ctx := range map[string]context.Context{ + "no credentials resolved": bound([]string{}), + "ids never published": bound(nil), + } { + got, prepared := PrepareCodexMultiAgentV2Tools(ctx, headers, payload, true, false) + if !prepared { + t.Fatalf("%s: request was not prepared", name) + } + description := ojson.GetBytesNoCopy(got, "tools.0.tools.0.description").String() + if strings.Contains(description, "excluded-model") || strings.Contains(description, codexSpawnAgentModelsHeading) { + t.Fatalf("%s: description still lists models: %q", name, description) + } + if !strings.Contains(description, "Intro line.") || !strings.Contains(description, "Spawns an agent.") { + t.Fatalf("%s: description lost its remaining text: %q", name, description) + } + } +} diff --git a/internal/client/musecode/models.go b/internal/client/musecode/models.go index b09ff16b0d3..8b2ec84012c 100644 --- a/internal/client/musecode/models.go +++ b/internal/client/musecode/models.go @@ -10,6 +10,7 @@ import ( "github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" ) // HomeModelsLoader loads scoped models when Home mode is active. @@ -207,7 +208,11 @@ func (h *Handler) HandleModels(c *gin.Context) { return } } else { - inputs = ModelInputsFromGlobalRegistry(registry.GetGlobalRegistry()) + if refs := sdkaccess.AllowedAuthsFromGin(c); len(refs) > 0 { + inputs = h.modelInputsForAllowedAuths(refs) + } else { + inputs = ModelInputsFromGlobalRegistry(registry.GetGlobalRegistry()) + } } payload := BuildModelsResponse(inputs) @@ -243,26 +248,7 @@ func ModelInputsFromGlobalRegistry(reg *registry.ModelRegistry) []ModelInput { if pInfo == nil { continue } - routes = append(routes, ModelRoute{ - Provider: provider, - MetadataModelID: pInfo.MetadataModelID, - Created: pInfo.Created, - OwnedBy: pInfo.OwnedBy, - Type: pInfo.Type, - DisplayName: pInfo.DisplayName, - Description: pInfo.Description, - ContextLength: pInfo.ContextLength, - MaxContextLength: pInfo.MaxContextLength, - MaxCompletionTokens: pInfo.MaxCompletionTokens, - InputTokenLimit: pInfo.InputTokenLimit, - OutputTokenLimit: pInfo.OutputTokenLimit, - Thinking: pInfo.Thinking, - ExplicitThinking: pInfo.ExplicitThinking, - SupportedInputModalities: append([]string(nil), pInfo.SupportedInputModalities...), - ExplicitInputModalities: pInfo.ExplicitInputModalities, - SupportedOutputModalities: append([]string(nil), pInfo.SupportedOutputModalities...), - HasOutputModalities: len(pInfo.SupportedOutputModalities) > 0, - }) + routes = append(routes, modelRouteFromInfo(provider, pInfo)) } if len(routes) > 0 { inputs[i].Routes = routes @@ -271,6 +257,57 @@ func ModelInputsFromGlobalRegistry(reg *registry.ModelRegistry) []ModelInput { return inputs } +func modelRouteFromInfo(provider string, pInfo *registry.ModelInfo) ModelRoute { + return ModelRoute{ + Provider: provider, + MetadataModelID: pInfo.MetadataModelID, + Created: pInfo.Created, + OwnedBy: pInfo.OwnedBy, + Type: pInfo.Type, + DisplayName: pInfo.DisplayName, + Description: pInfo.Description, + ContextLength: pInfo.ContextLength, + MaxContextLength: pInfo.MaxContextLength, + MaxCompletionTokens: pInfo.MaxCompletionTokens, + InputTokenLimit: pInfo.InputTokenLimit, + OutputTokenLimit: pInfo.OutputTokenLimit, + Thinking: pInfo.Thinking, + ExplicitThinking: pInfo.ExplicitThinking, + SupportedInputModalities: append([]string(nil), pInfo.SupportedInputModalities...), + ExplicitInputModalities: pInfo.ExplicitInputModalities, + SupportedOutputModalities: append([]string(nil), pInfo.SupportedOutputModalities...), + HasOutputModalities: len(pInfo.SupportedOutputModalities) > 0, + } +} + +// ModelInputsForClients is ModelInputsFromGlobalRegistry limited to the given clients: +// models, metadata and provider routes all come from those clients, so a credential +// outside the set never shapes the capabilities a bound key sees. +func ModelInputsForClients(reg *registry.ModelRegistry, clientIDs map[string]struct{}) []ModelInput { + if reg == nil { + return nil + } + inputs := ModelInputsFromRegistry(reg.GetAvailableModelInfosForClients(clientIDs)) + byProvider := reg.GetAvailableModelInfosByProviderForClients(clientIDs) + for i := range inputs { + infos := byProvider[inputs[i].ID] + if len(infos) == 0 { + continue + } + providers := make([]string, 0, len(infos)) + for provider := range infos { + providers = append(providers, provider) + } + sort.Strings(providers) + routes := make([]ModelRoute, 0, len(providers)) + for _, provider := range providers { + routes = append(routes, modelRouteFromInfo(provider, infos[provider])) + } + inputs[i].Routes = routes + } + return inputs +} + // ModelInputsFromRegistry converts registry ModelInfo records into ModelInput entries. func ModelInputsFromRegistry(infos []*registry.ModelInfo) []ModelInput { if len(infos) == 0 { @@ -1230,3 +1267,12 @@ func minPositive(a, b int) int { return a } } + +// modelInputsForAllowedAuths builds the catalog from the credentials a bound client key +// may use only; models, capabilities and routes of every other credential stay out. +func (h *Handler) modelInputsForAllowedAuths(refs []string) []ModelInput { + if h == nil || h.authManager == nil { + return nil + } + return ModelInputsForClients(registry.GetGlobalRegistry(), h.authManager.AllowedAuthIDs(refs)) +} diff --git a/internal/client/musecode/models_test.go b/internal/client/musecode/models_test.go index 55fa3a33496..f86c553ce8e 100644 --- a/internal/client/musecode/models_test.go +++ b/internal/client/musecode/models_test.go @@ -646,3 +646,36 @@ func TestHandleModelsHomeModeHookAndFallback(t *testing.T) { t.Fatalf("expected claude-opus-4-6 enriched with static reasoning metadata") } } + +func TestModelInputsForClientsScopeRoutesAndCapabilitiesToAllowedClients(t *testing.T) { + reg := registry.GetGlobalRegistry() + const modelID = "scoped-routes-model" + reg.RegisterClient("scoped-routes-personal", "codex", []*registry.ModelInfo{{ID: modelID, Created: 1, ContextLength: 100, MaxCompletionTokens: 10}}) + reg.RegisterClient("scoped-routes-work", "claude", []*registry.ModelInfo{{ID: modelID, Created: 1, ContextLength: 900, MaxCompletionTokens: 90}}) + t.Cleanup(func() { + reg.UnregisterClient("scoped-routes-personal") + reg.UnregisterClient("scoped-routes-work") + }) + + inputs := ModelInputsForClients(reg, map[string]struct{}{"scoped-routes-personal": {}}) + var got *ModelInput + for i := range inputs { + if inputs[i].ID == modelID { + got = &inputs[i] + } + } + if got == nil { + t.Fatalf("the allowed credential's model is missing from %d inputs", len(inputs)) + } + if len(got.Routes) != 1 || got.Routes[0].Provider != "codex" || got.Routes[0].ContextLength != 100 { + t.Fatalf("routes = %+v, want only the allowed codex route", got.Routes) + } + if got.ContextLength != 100 || got.MaxCompletionTokens != 10 { + t.Fatalf("capabilities = %d/%d, want the allowed credential's 100/10", got.ContextLength, got.MaxCompletionTokens) + } + for _, input := range ModelInputsForClients(reg, map[string]struct{}{"nobody": {}}) { + if input.ID == modelID { + t.Fatal("a client set that serves nothing listed the model") + } + } +} diff --git a/internal/config/api_key_entry.go b/internal/config/api_key_entry.go new file mode 100644 index 00000000000..261d07ab039 --- /dev/null +++ b/internal/config/api_key_entry.go @@ -0,0 +1,207 @@ +package config + +import ( + "fmt" + "strings" + + "github.com/MoeForge/moego/json" + "gopkg.in/yaml.v3" +) + +// APIKeyEntry is one client API key accepted by this proxy. +// +// In YAML an entry is either a plain string (an unrestricted key) or a mapping +// with a "key" and an optional "auths" list that binds the key to specific +// credentials. A bound key can only be served by the listed credentials and +// only sees the models those credentials serve. +type APIKeyEntry struct { + // Key is the client API key presented by callers. + Key string `yaml:"key" json:"key"` + + // Auths lists the credentials the key is bound to. Each item matches either + // the credential ID or the credential file name (for example + // "team/work.json"). An empty list means the key is not bound. + Auths []string `yaml:"auths,omitempty" json:"auths,omitempty"` +} + +// Bound reports whether the entry restricts the key to specific credentials. +func (e APIKeyEntry) Bound() bool { return len(e.Auths) > 0 } + +// APIKeyEntries converts plain keys into unrestricted entries. +func APIKeyEntries(keys ...string) []APIKeyEntry { + out := make([]APIKeyEntry, 0, len(keys)) + for _, key := range keys { + out = append(out, APIKeyEntry{Key: key}) + } + return out +} + +// APIKeyStrings returns the plain key values of the configured client API keys. +func (c *SDKConfig) APIKeyStrings() []string { + if c == nil || len(c.APIKeys) == 0 { + return nil + } + out := make([]string, 0, len(c.APIKeys)) + for _, entry := range c.APIKeys { + out = append(out, entry.Key) + } + return out +} + +// SetAPIKeyStrings replaces the configured keys with keys, keeping the +// credential binding of any key that was already configured. +func (c *SDKConfig) SetAPIKeyStrings(keys []string) { + bindings := make(map[string][]string, len(c.APIKeys)) + for _, entry := range c.APIKeys { + if entry.Bound() { + bindings[strings.TrimSpace(entry.Key)] = entry.Auths + } + } + next := make([]APIKeyEntry, 0, len(keys)) + for _, key := range keys { + next = append(next, APIKeyEntry{Key: key, Auths: bindings[strings.TrimSpace(key)]}) + } + c.APIKeys = next +} + +// UnmarshalYAML accepts a plain string or a {key, auths} mapping. +func (e *APIKeyEntry) UnmarshalYAML(node *yaml.Node) error { + switch node.Kind { + case yaml.ScalarNode: + var key string + if err := node.Decode(&key); err != nil { + return err + } + *e = APIKeyEntry{Key: key} + return nil + case yaml.MappingNode: + type plain APIKeyEntry + var decoded plain + if err := node.Decode(&decoded); err != nil { + return err + } + entry := APIKeyEntry(decoded) + if err := entry.validate(node.Content, node.Line); err != nil { + return err + } + *e = entry + return nil + default: + return fmt.Errorf("line %d: api-keys entries must be a string or a mapping with key and auths", node.Line) + } +} + +func (e APIKeyEntry) validate(content []*yaml.Node, line int) error { + authsPresent := false + for i := 0; i+1 < len(content); i += 2 { + switch content[i].Value { + case "key": + case "auths": + authsPresent = true + default: + return fmt.Errorf("line %d: api-keys entry has unknown field %q; only key and auths are allowed", content[i].Line, content[i].Value) + } + } + if err := e.check(authsPresent); err != nil { + return fmt.Errorf("line %d: %w", line, err) + } + return nil +} + +// check rejects an entry that would silently widen access: a blank key, or an +// auths list that is present but empty or holds a blank item. +func (e APIKeyEntry) check(authsPresent bool) error { + if strings.TrimSpace(e.Key) == "" { + return fmt.Errorf("api-keys entry requires a non-empty key") + } + if authsPresent && len(e.Auths) == 0 { + return fmt.Errorf("api-keys entry has an empty auths list; remove auths to leave the key unrestricted") + } + for _, ref := range e.Auths { + if strings.TrimSpace(ref) == "" { + return fmt.Errorf("api-keys entry has an empty auths item") + } + } + return nil +} + +// MarshalYAML writes unbound keys as plain strings so existing files keep their shape. +func (e APIKeyEntry) MarshalYAML() (any, error) { + if !e.Bound() { + return e.Key, nil + } + type plain APIKeyEntry + return plain(e), nil +} + +// UnmarshalJSON accepts a plain string or a {key, auths} object. +func (e *APIKeyEntry) UnmarshalJSON(data []byte) error { + trimmed := strings.TrimSpace(string(data)) + if strings.HasPrefix(trimmed, "\"") { + var key string + if err := json.Unmarshal(data, &key); err != nil { + return err + } + *e = APIKeyEntry{Key: key} + return nil + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return err + } + for name := range fields { + if name != "key" && name != "auths" { + return fmt.Errorf("api-keys entry has unknown field %q; only key and auths are allowed", name) + } + } + type plain APIKeyEntry + var decoded plain + if err := json.Unmarshal(data, &decoded); err != nil { + return err + } + _, authsPresent := fields["auths"] + entry := APIKeyEntry(decoded) + if err := entry.check(authsPresent); err != nil { + return err + } + *e = entry + return nil +} + +// MarshalJSON mirrors MarshalYAML. +func (e APIKeyEntry) MarshalJSON() ([]byte, error) { + if !e.Bound() { + return json.Marshal(e.Key) + } + type plain APIKeyEntry + return json.Marshal(plain(e)) +} + +// ValidateAPIKeys rejects client API keys that cannot be served safely. An entry +// whose auths list is empty or holds a blank item would lose its restriction when +// written out, and a key listed twice is ambiguous because the copies may carry different credential +// bindings, so it is a configuration error instead of "first one wins". +func (c *SDKConfig) ValidateAPIKeys() error { + if c == nil { + return nil + } + seen := make(map[string]struct{}, len(c.APIKeys)) + for index, entry := range c.APIKeys { + trimmed := strings.TrimSpace(entry.Key) + if trimmed == "" { + continue + } + // A present but empty auths list reads as unrestricted once it is written out + // (omitempty drops it), so it must not exist in an accepted config. + if entry.Auths != nil { + if err := entry.check(true); err != nil { + return fmt.Errorf("api-keys[%d]: %w", index, err) + } + } + if _, exists := seen[trimmed]; exists { + return fmt.Errorf("api-keys[%d] duplicates an earlier api-keys entry; list each key once", index) + } + seen[trimmed] = struct{}{} + } + return nil +} diff --git a/internal/config/api_key_entry_test.go b/internal/config/api_key_entry_test.go new file mode 100644 index 00000000000..466a00f5147 --- /dev/null +++ b/internal/config/api_key_entry_test.go @@ -0,0 +1,230 @@ +package config + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/MoeForge/moego/json" + "gopkg.in/yaml.v3" +) + +func TestAPIKeyEntryYAMLAcceptsBothForms(t *testing.T) { + var cfg SDKConfig + data := "api-keys:\n - legacy-plain-key\n - key: personal-key\n auths: [codex-personal.json, claude-personal.json]\n - key: mapping-without-auths\n" + if err := yaml.Unmarshal([]byte(data), &cfg); err != nil { + t.Fatal(err) + } + want := []APIKeyEntry{ + {Key: "legacy-plain-key"}, + {Key: "personal-key", Auths: []string{"codex-personal.json", "claude-personal.json"}}, + {Key: "mapping-without-auths"}, + } + if !reflect.DeepEqual(cfg.APIKeys, want) { + t.Fatalf("APIKeys = %#v, want %#v", cfg.APIKeys, want) + } + if cfg.APIKeys[0].Bound() || !cfg.APIKeys[1].Bound() || cfg.APIKeys[2].Bound() { + t.Fatal("Bound() mismatch") + } +} + +func TestAPIKeyEntryYAMLRejectsInvalid(t *testing.T) { + for name, data := range map[string]string{ + "empty auths": "api-keys:\n - key: k\n auths: []\n", + "missing key": "api-keys:\n - auths: [a.json]\n", + "blank key": "api-keys:\n - key: \" \"\n auths: [a.json]\n", + "blank auth": "api-keys:\n - key: k\n auths: [\"\"]\n", + "sequence": "api-keys:\n - [a, b]\n", + } { + t.Run(name, func(t *testing.T) { + var cfg SDKConfig + if err := yaml.Unmarshal([]byte(data), &cfg); err == nil { + t.Fatalf("expected an error, got %#v", cfg.APIKeys) + } + }) + } +} + +func TestAPIKeyEntryYAMLMarshalKeepsUnboundAsScalar(t *testing.T) { + out, err := yaml.Marshal(SDKConfig{APIKeys: []APIKeyEntry{{Key: "plain"}, {Key: "bound", Auths: []string{"a.json"}}}}) + if err != nil { + t.Fatal(err) + } + text := string(out) + if !strings.Contains(text, "- plain\n") || !strings.Contains(text, "key: bound") || !strings.Contains(text, "- a.json") { + t.Fatalf("unexpected YAML:\n%s", text) + } +} + +func TestAPIKeyEntryJSONBothForms(t *testing.T) { + var entries []APIKeyEntry + if err := json.Unmarshal([]byte(`["plain",{"key":"bound","auths":["a.json"]}]`), &entries); err != nil { + t.Fatal(err) + } + want := []APIKeyEntry{{Key: "plain"}, {Key: "bound", Auths: []string{"a.json"}}} + if !reflect.DeepEqual(entries, want) { + t.Fatalf("entries = %#v, want %#v", entries, want) + } + out, err := json.Marshal(entries) + if err != nil { + t.Fatal(err) + } + if string(out) != `["plain",{"key":"bound","auths":["a.json"]}]` { + t.Fatalf("marshal = %s", out) + } + if err := json.Unmarshal([]byte(`[{"auths":["a.json"]}]`), &entries); err == nil { + t.Fatal("missing key must be rejected") + } +} + +func TestSetAPIKeyStringsPreservesBindingsByKey(t *testing.T) { + cfg := SDKConfig{APIKeys: []APIKeyEntry{{Key: "plain"}, {Key: "bound", Auths: []string{"a.json"}}}} + cfg.SetAPIKeyStrings([]string{"bound", "new"}) + want := []APIKeyEntry{{Key: "bound", Auths: []string{"a.json"}}, {Key: "new"}} + if !reflect.DeepEqual(cfg.APIKeys, want) { + t.Fatalf("APIKeys = %#v, want %#v", cfg.APIKeys, want) + } + if got := cfg.APIKeyStrings(); !reflect.DeepEqual(got, []string{"bound", "new"}) { + t.Fatalf("APIKeyStrings = %v", got) + } +} + +func TestAPIKeyBindingSurvivesLoadAndSaveRoundTrip(t *testing.T) { + for name, data := range map[string]string{ + "legacy": "api-keys:\n - legacy-plain-key\n - key: personal-key\n auths: [codex-personal.json]\n", + "v8": "access:\n api-keys:\n - legacy-plain-key\n - key: personal-key\n auths: [codex-personal.json]\n", + } { + t.Run(name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(path, []byte(data), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := LoadConfig(path) + if err != nil { + t.Fatal(err) + } + want := []APIKeyEntry{{Key: "legacy-plain-key"}, {Key: "personal-key", Auths: []string{"codex-personal.json"}}} + if !reflect.DeepEqual(cfg.APIKeys, want) { + t.Fatalf("loaded %#v, want %#v", cfg.APIKeys, want) + } + cfg.APIKeys = append(cfg.APIKeys, APIKeyEntry{Key: "work-key", Auths: []string{"claude-work.json"}}) + if err = SaveConfigPreserveComments(path, cfg); err != nil { + t.Fatal(err) + } + reloaded, err := LoadConfig(path) + if err != nil { + t.Fatal(err) + } + want = append(want, APIKeyEntry{Key: "work-key", Auths: []string{"claude-work.json"}}) + if !reflect.DeepEqual(reloaded.APIKeys, want) { + t.Fatalf("reloaded %#v, want %#v", reloaded.APIKeys, want) + } + }) + } +} + +func TestAPIKeyEntryRejectsUnknownFieldsInYAMLAndJSON(t *testing.T) { + for name, data := range map[string]string{ + "auth typo": "{\"key\":\"k\",\"auth\":[\"a.json\"]}", + "auths suffix": "{\"key\":\"k\",\"auths_\":[\"a.json\"]}", + "extra beside ok": "{\"key\":\"k\",\"auths\":[\"a.json\"],\"note\":\"x\"}", + "wrong case": "{\"Key\":\"k\"}", + } { + t.Run("json "+name, func(t *testing.T) { + var e APIKeyEntry + if err := json.Unmarshal([]byte(data), &e); err == nil { + t.Fatalf("accepted %s as %#v", data, e) + } + }) + } + for name, data := range map[string]string{ + "auth typo": "api-keys:\n - key: k\n auth: [a.json]\n", + "auths suffix": "api-keys:\n - key: k\n auths_: [a.json]\n", + "extra": "api-keys:\n - key: k\n auths: [a.json]\n note: x\n", + } { + t.Run("yaml "+name, func(t *testing.T) { + var cfg SDKConfig + err := yaml.Unmarshal([]byte(data), &cfg) + if err == nil || !strings.Contains(err.Error(), "unknown field") { + t.Fatalf("err = %v, want an unknown field error", err) + } + }) + } +} + +func TestAPIKeyEntryJSONRejectsEmptyOrBlankAuths(t *testing.T) { + for name, data := range map[string]string{ + "empty list": `{"key":"k","auths":[]}`, + "null": `{"key":"k","auths":null}`, + "blank item": `{"key":"k","auths":[" "]}`, + "mixed": `{"key":"k","auths":["a.json",""]}`, + "blank key": `{"key":" ","auths":["a.json"]}`, + } { + t.Run(name, func(t *testing.T) { + var e APIKeyEntry + if err := json.Unmarshal([]byte(data), &e); err == nil { + t.Fatalf("accepted %s as %#v", data, e) + } + }) + } + var ok APIKeyEntry + if err := json.Unmarshal([]byte(`{"key":"k"}`), &ok); err != nil || ok.Bound() { + t.Fatalf("mapping without auths: %#v, %v", ok, err) + } +} + +func TestValidateAPIKeysRejectsDuplicates(t *testing.T) { + for name, keys := range map[string][]APIKeyEntry{ + "plain then bound": {{Key: "k"}, {Key: "k", Auths: []string{"a.json"}}}, + "bound then plain": {{Key: "k", Auths: []string{"a.json"}}, {Key: "k"}}, + "padded copy": {{Key: "k"}, {Key: " k "}}, + } { + cfg := SDKConfig{APIKeys: keys} + if err := cfg.ValidateAPIKeys(); err == nil { + t.Fatalf("%s: duplicate accepted", name) + } + } + ok := SDKConfig{APIKeys: []APIKeyEntry{{Key: "a"}, {Key: "b", Auths: []string{"x.json"}}}} + if err := ok.ValidateAPIKeys(); err != nil { + t.Fatal(err) + } +} + +func TestValidateAPIKeysRejectsEmptyAuthsThatWouldBecomeUnrestricted(t *testing.T) { + for name, entry := range map[string]APIKeyEntry{ + "empty non-nil list": {Key: "k", Auths: []string{}}, + "blank item": {Key: "k", Auths: []string{"a.json", " "}}, + } { + cfg := SDKConfig{APIKeys: []APIKeyEntry{entry}} + if err := cfg.ValidateAPIKeys(); err == nil { + t.Fatalf("%s: accepted, but it serializes as an unrestricted key", name) + } + } + // Nil auths is the plain unrestricted key and stays valid. + plain := SDKConfig{APIKeys: []APIKeyEntry{{Key: "k"}}} + if err := plain.ValidateAPIKeys(); err != nil { + t.Fatal(err) + } +} + +func TestLoadConfigRejectsDuplicateAPIKeys(t *testing.T) { + for name, data := range map[string]string{ + "legacy": "api-keys:\n - k\n - key: k\n auths: [a.json]\n", + "v8": "access:\n api-keys:\n - key: k\n auths: [a.json]\n - k\n", + } { + t.Run(name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(path, []byte(data), 0o600); err != nil { + t.Fatal(err) + } + if _, err := LoadConfig(path); err == nil { + t.Fatal("duplicate api-keys loaded") + } + if _, err := ParseConfigBytes([]byte(data)); err == nil { + t.Fatal("duplicate api-keys parsed") + } + }) + } +} diff --git a/internal/config/clone_test.go b/internal/config/clone_test.go index 4dcc5971f8a..b6136834a01 100644 --- a/internal/config/clone_test.go +++ b/internal/config/clone_test.go @@ -67,8 +67,8 @@ func TestCloneForRuntimeDeepCopiesConfig(t *testing.T) { if clone.Home.Host != "home.local" { t.Fatalf("clone.Home.Host = %q, want home.local", clone.Home.Host) } - if clone.APIKeys[0] != "client-key" { - t.Fatalf("clone.APIKeys[0] = %q, want client-key", clone.APIKeys[0]) + if clone.APIKeys[0].Key != "client-key" { + t.Fatalf("clone.APIKeys[0] = %q, want client-key", clone.APIKeys[0].Key) } if clone.OAuthExcludedModels["codex"][0] != "hidden-model" { t.Fatalf("clone.OAuthExcludedModels[codex][0] = %q, want hidden-model", clone.OAuthExcludedModels["codex"][0]) @@ -86,7 +86,7 @@ func TestCloneForRuntimeDeepCopiesConfig(t *testing.T) { t.Fatalf("clone payload object key = %#v, want value", got) } - clone.APIKeys[0] = "clone-client-key" + clone.APIKeys[0].Key = "clone-client-key" clone.OAuthExcludedModels["codex"][0] = "clone-hidden-model" clone.OAuthModelAlias["codex"][0].Alias = "clone-client-model" clone.OpenAICompatibility[0].Models[0].Thinking.Levels[0] = "clone-low" @@ -95,8 +95,8 @@ func TestCloneForRuntimeDeepCopiesConfig(t *testing.T) { setPluginRawScalar(t, &plugin.Raw, "mode", "third") clone.Plugins.Configs["sample"] = plugin - if cfg.APIKeys[0] != "mutated-client-key" { - t.Fatalf("cfg.APIKeys[0] = %q, want mutated-client-key", cfg.APIKeys[0]) + if cfg.APIKeys[0].Key != "mutated-client-key" { + t.Fatalf("cfg.APIKeys[0] = %q, want mutated-client-key", cfg.APIKeys[0].Key) } if cfg.OAuthExcludedModels["codex"][0] != "mutated-hidden-model" { t.Fatalf("cfg.OAuthExcludedModels[codex][0] = %q, want mutated-hidden-model", cfg.OAuthExcludedModels["codex"][0]) @@ -130,7 +130,7 @@ func sampleCloneRuntimeConfig() *Config { return &Config{ SDKConfig: SDKConfig{ - APIKeys: []string{"client-key"}, + APIKeys: APIKeyEntries("client-key"), Streaming: StreamingConfig{ KeepAliveSeconds: 3, BootstrapRetries: 2, @@ -249,7 +249,7 @@ func sampleCloneRuntimeConfig() *Config { func mutateOriginalConfig(cfg *Config) { cfg.Home.Host = "mutated-home.local" - cfg.APIKeys[0] = "mutated-client-key" + cfg.APIKeys[0].Key = "mutated-client-key" cfg.OAuthExcludedModels["codex"][0] = "mutated-hidden-model" cfg.OAuthModelAlias["codex"][0].Alias = "mutated-client-model" cfg.OpenAICompatibility[0].Models[0].Thinking.Levels[0] = "mutated-low" diff --git a/internal/config/config_v8_test.go b/internal/config/config_v8_test.go index dc29445e374..783574b74ce 100644 --- a/internal/config/config_v8_test.go +++ b/internal/config/config_v8_test.go @@ -815,7 +815,7 @@ func TestV8LegacyClientKeysDoNotOverwriteUpstreamGroups(t *testing.T) { if err != nil { t.Fatal(err) } - cfg.APIKeys = []string{"client-key"} + cfg.APIKeys = APIKeyEntries("client-key") if err = SaveConfigPreserveComments(path, cfg); err != nil { t.Fatal(err) } @@ -823,7 +823,7 @@ func TestV8LegacyClientKeysDoNotOverwriteUpstreamGroups(t *testing.T) { if err != nil { t.Fatal(err) } - if len(cfg.APIKeys) != 1 || cfg.APIKeys[0] != "client-key" || len(cfg.CodexKey) != 1 { + if len(cfg.APIKeys) != 1 || cfg.APIKeys[0].Key != "client-key" || len(cfg.CodexKey) != 1 { t.Fatal("client/upstream key collision lost credentials") } } diff --git a/internal/config/parse.go b/internal/config/parse.go index 21b2f1e85cd..044a6104152 100644 --- a/internal/config/parse.go +++ b/internal/config/parse.go @@ -105,6 +105,9 @@ func validateStartupConfig(data []byte, optional bool) (*startupConfig, error) { if errValidate := cfg.ValidateCredentialWeights(); errValidate != nil { return nil, errValidate } + if errValidate := cfg.ValidateAPIKeys(); errValidate != nil { + return nil, errValidate + } if errValidate := cfg.Codex.LiveMediaRelay.Validate(); errValidate != nil { return nil, errValidate } diff --git a/internal/config/sdk_config.go b/internal/config/sdk_config.go index c5b13aedc76..0c78f27dd36 100644 --- a/internal/config/sdk_config.go +++ b/internal/config/sdk_config.go @@ -97,7 +97,8 @@ type SDKConfig struct { ClaudeCode ClaudeCodeConfig `yaml:"claude-code" json:"claude-code"` // APIKeys is a list of keys for authenticating clients to this proxy server. - APIKeys []string `yaml:"api-keys" json:"api-keys"` + // An entry is a plain key or a key bound to specific credentials (see APIKeyEntry). + APIKeys []APIKeyEntry `yaml:"api-keys" json:"api-keys"` // PassthroughHeaders controls whether upstream response headers are forwarded to downstream clients. // Default is false (disabled). diff --git a/internal/registry/model_registry.go b/internal/registry/model_registry.go index 84ec75baf54..613ddd828f1 100644 --- a/internal/registry/model_registry.go +++ b/internal/registry/model_registry.go @@ -1604,6 +1604,161 @@ func (r *ModelRegistry) GetAvailableModels(handlerType string) []map[string]any return models } +// availableRegistrationsForClientsLocked returns the registrations that are available when +// only the given clients are considered. The caller must hold r.mutex. +func (r *ModelRegistry) availableRegistrationsForClientsLocked(clientIDs map[string]struct{}, now time.Time) []*ModelRegistration { + counts := make(map[string]int) + for clientID := range clientIDs { + seen := make(map[string]struct{}, len(r.clientModels[clientID])) + for _, modelID := range r.clientModels[clientID] { + if _, dup := seen[modelID]; dup { + continue + } + seen[modelID] = struct{}{} + counts[modelID]++ + } + } + out := make([]*ModelRegistration, 0, len(counts)) + for modelID, count := range counts { + registration := r.models[modelID] + if registration == nil { + continue + } + info, infoByProvider := r.scopedModelInfoLocked(modelID, clientIDs) + if info == nil { + // No selected client kept its own metadata; the global entry is the only description. + info = registration.Info + } + scoped := &ModelRegistration{ + Info: info, + InfoByProvider: infoByProvider, + Count: count, + LastUpdated: registration.LastUpdated, + QuotaExceededClients: filterClientMap(registration.QuotaExceededClients, clientIDs), + SuspendedClients: filterClientMap(registration.SuspendedClients, clientIDs), + SuspendedClientDeadlines: filterClientMap(registration.SuspendedClientDeadlines, clientIDs), + } + if available, _ := modelRegistrationAvailability(scoped, now); available { + out = append(out, scoped) + } + } + return out +} + +// scopedModelInfoLocked builds a model's metadata from the selected clients only, so a +// credential outside the set never shapes what a bound key sees (capabilities, limits, +// web-search support). The merge is deterministic: the lowest client ID that serves the +// model supplies Info, and the lowest client ID per provider supplies InfoByProvider. +// SupportsWebSearch is true when any selected client advertises it. The caller must hold r.mutex. +func (r *ModelRegistry) scopedModelInfoLocked(modelID string, clientIDs map[string]struct{}) (*ModelInfo, map[string]*ModelInfo) { + ids := make([]string, 0, len(clientIDs)) + for clientID := range clientIDs { + if r.clientModelInfos[clientID][modelID] != nil { + ids = append(ids, clientID) + } + } + if len(ids) == 0 { + return nil, nil + } + sort.Strings(ids) + var info *ModelInfo + byProvider := make(map[string]*ModelInfo) + webSearch := false + providerSearch := make(map[string]bool) + for _, clientID := range ids { + clientInfo := r.clientModelInfos[clientID][modelID] + if info == nil { + info = cloneModelInfo(clientInfo) + } + webSearch = webSearch || clientInfo.SupportsWebSearch + if provider := r.clientProviders[clientID]; provider != "" { + if byProvider[provider] == nil { + byProvider[provider] = cloneModelInfo(clientInfo) + } + providerSearch[provider] = providerSearch[provider] || clientInfo.SupportsWebSearch + } + } + info.SupportsWebSearch = webSearch + for provider, providerInfo := range byProvider { + providerInfo.SupportsWebSearch = providerSearch[provider] + } + return info, byProvider +} + +// GetAvailableModelsForClients returns the available models that at least one of the +// given clients serves, computed only from those clients. It is not cached because the +// client set varies per API key. An empty set returns no models. +func (r *ModelRegistry) GetAvailableModelsForClients(handlerType string, clientIDs map[string]struct{}) []map[string]any { + now := r.now() + r.mutex.RLock() + defer r.mutex.RUnlock() + + registrations := r.availableRegistrationsForClientsLocked(clientIDs, now) + models := make([]map[string]any, 0, len(registrations)) + for _, registration := range registrations { + if model := r.convertModelToMap(registration.Info, handlerType); model != nil { + models = append(models, model) + } + } + return models +} + +// GetAvailableModelInfosForClients is GetAvailableModelInfos limited to the given clients. +func (r *ModelRegistry) GetAvailableModelInfosForClients(clientIDs map[string]struct{}) []*ModelInfo { + now := r.now() + r.mutex.RLock() + defer r.mutex.RUnlock() + + registrations := r.availableRegistrationsForClientsLocked(clientIDs, now) + result := make([]*ModelInfo, 0, len(registrations)) + for _, registration := range registrations { + if registration.Info != nil { + result = append(result, cloneModelInfo(registration.Info)) + } + } + sort.Slice(result, func(i, j int) bool { + return strings.TrimSpace(result[i].ID) < strings.TrimSpace(result[j].ID) + }) + return result +} + +// GetAvailableModelInfosByProviderForClients returns, per available model, the per-provider +// metadata built from the given clients only (model ID -> provider -> info). +func (r *ModelRegistry) GetAvailableModelInfosByProviderForClients(clientIDs map[string]struct{}) map[string]map[string]*ModelInfo { + now := r.now() + r.mutex.RLock() + defer r.mutex.RUnlock() + + registrations := r.availableRegistrationsForClientsLocked(clientIDs, now) + out := make(map[string]map[string]*ModelInfo, len(registrations)) + for _, registration := range registrations { + if registration.Info == nil || len(registration.InfoByProvider) == 0 { + continue + } + providers := make(map[string]*ModelInfo, len(registration.InfoByProvider)) + for provider, info := range registration.InfoByProvider { + if info != nil { + providers[provider] = cloneModelInfo(info) + } + } + out[registration.Info.ID] = providers + } + return out +} + +func filterClientMap[V any](in map[string]V, keep map[string]struct{}) map[string]V { + if len(in) == 0 { + return nil + } + out := make(map[string]V, len(in)) + for clientID, value := range in { + if _, ok := keep[clientID]; ok { + out[clientID] = value + } + } + return out +} + // isQuotaSuspension reports whether a suspension is a quota cooldown. A model in a // quota cooldown stays listed: the limit is temporary, and a request meanwhile gets a // 429 with its retry time instead of an unknown model. A credential-wide quota diff --git a/internal/registry/model_registry_clients_test.go b/internal/registry/model_registry_clients_test.go new file mode 100644 index 00000000000..eba2f1385ea --- /dev/null +++ b/internal/registry/model_registry_clients_test.go @@ -0,0 +1,81 @@ +package registry + +import "testing" + +func modelIDsOf(models []map[string]any) map[string]bool { + ids := map[string]bool{} + for _, model := range models { + if id, ok := model["id"].(string); ok { + ids[id] = true + } + } + return ids +} + +func TestGetAvailableModelsForClientsLimitsToGivenClients(t *testing.T) { + r := newTestModelRegistry() + r.RegisterClient("personal", "codex", []*ModelInfo{{ID: "shared", Created: 1}, {ID: "personal-only", Created: 1}}) + r.RegisterClient("work", "codex", []*ModelInfo{{ID: "shared", Created: 1}, {ID: "work-only", Created: 1}}) + + got := modelIDsOf(r.GetAvailableModelsForClients("openai", map[string]struct{}{"personal": {}})) + if !got["shared"] || !got["personal-only"] || got["work-only"] || len(got) != 2 { + t.Fatalf("personal listing = %v", got) + } + if got = modelIDsOf(r.GetAvailableModelsForClients("openai", map[string]struct{}{"personal": {}, "work": {}})); len(got) != 3 { + t.Fatalf("combined listing = %v", got) + } + if got = modelIDsOf(r.GetAvailableModelsForClients("openai", nil)); len(got) != 0 { + t.Fatalf("empty client set must list nothing, got %v", got) + } + if all := modelIDsOf(r.GetAvailableModels("openai")); len(all) != 3 { + t.Fatalf("global listing changed: %v", all) + } +} + +func TestGetAvailableModelsForClientsScopesSuspensionAndQuotaToAllowedClients(t *testing.T) { + r := newTestModelRegistry() + r.RegisterClient("personal", "codex", []*ModelInfo{{ID: "shared", Created: 1}}) + r.RegisterClient("work", "codex", []*ModelInfo{{ID: "shared", Created: 1}}) + + // The unrelated client being suspended must not hide the model from the allowed client. + r.SuspendClientModel("work", "shared", "test") + if got := modelIDsOf(r.GetAvailableModelsForClients("openai", map[string]struct{}{"personal": {}})); !got["shared"] { + t.Fatalf("suspension of an unrelated client hid the model: %v", got) + } + + // The allowed client being suspended hides it even though another client still serves it. + r.ResumeClientModel("work", "shared") + r.SuspendClientModel("personal", "shared", "test") + if got := modelIDsOf(r.GetAvailableModelsForClients("openai", map[string]struct{}{"personal": {}})); got["shared"] { + t.Fatalf("suspended allowed client still lists the model: %v", got) + } + if got := modelIDsOf(r.GetAvailableModels("openai")); !got["shared"] { + t.Fatalf("global listing should still include the model: %v", got) + } +} + +func TestScopedModelInfoComesFromSelectedClientsOnly(t *testing.T) { + r := newTestModelRegistry() + r.RegisterClient("a-personal", "codex", []*ModelInfo{{ID: "shared", Created: 1, ContextLength: 100}}) + r.RegisterClient("b-work", "claude", []*ModelInfo{{ID: "shared", Created: 1, ContextLength: 900, SupportsWebSearch: true}}) + + r.mutex.RLock() + defer r.mutex.RUnlock() + info, byProvider := r.scopedModelInfoLocked("shared", map[string]struct{}{"a-personal": {}}) + if info == nil || info.ContextLength != 100 || info.SupportsWebSearch { + t.Fatalf("scoped info = %+v, want the personal credential's metadata only", info) + } + if len(byProvider) != 1 || byProvider["codex"] == nil || byProvider["claude"] != nil { + t.Fatalf("scoped InfoByProvider = %v, want codex only", byProvider) + } + info, byProvider = r.scopedModelInfoLocked("shared", map[string]struct{}{"a-personal": {}, "b-work": {}}) + if info.ContextLength != 100 || !info.SupportsWebSearch || len(byProvider) != 2 { + t.Fatalf("combined scoped info = %+v providers=%v, want lowest client's info and OR of web search", info, byProvider) + } + // The scoped registrations used for listings carry the scoped metadata too. + for _, reg := range r.availableRegistrationsForClientsLocked(map[string]struct{}{"a-personal": {}}, r.now()) { + if reg.Info.ContextLength != 100 || reg.InfoByProvider["claude"] != nil { + t.Fatalf("scoped registration leaked global metadata: %+v %v", reg.Info, reg.InfoByProvider) + } + } +} diff --git a/internal/tui/client.go b/internal/tui/client.go index 149c41fa181..d8072474145 100644 --- a/internal/tui/client.go +++ b/internal/tui/client.go @@ -692,7 +692,8 @@ func (c *Client) GetLogs(after int64, limit int) ([]string, int64, error) { func (c *Client) GetAPIKeys() ([]string, error) { value, code, err := c.v8ConfigGet("access/api-keys") if err == nil { - return stringSlice(value) + keys, _, errKeys := apiKeyItems(value) + return keys, errKeys } if err == errV8ConfigNodeMissing { return nil, nil @@ -702,7 +703,8 @@ func (c *Client) GetAPIKeys() ([]string, error) { if errGet != nil { return nil, errGet } - return stringSlice(wrapper["api-keys"]) + keys, _, errKeys := apiKeyItems(wrapper["api-keys"]) + return keys, errKeys } return nil, err } @@ -712,8 +714,16 @@ func (c *Client) GetAPIKeys() ([]string, error) { // write is rejected with 412 if another client saved after the read. A 405/501 // write status means this specific route is unimplemented and falls back to // the supplied v0 operation; 412 and other statuses are surfaced. -func (c *Client) replaceAPIKeys(keys []string, etag string, v0 func() error) error { - body, _ := json.Marshal(keys) +func (c *Client) replaceAPIKeys(keys []string, bindings map[string]any, etag string, v0 func() error) error { + entries := make([]any, 0, len(keys)) + for _, key := range keys { + if binding, ok := bindings[key]; ok { + entries = append(entries, binding) + continue + } + entries = append(entries, key) + } + body, _ := json.Marshal(entries) headers := http.Header{} if etag != "" { headers.Set("If-Match", etag) @@ -734,17 +744,17 @@ func (c *Client) replaceAPIKeys(keys []string, etag string, v0 func() error) err // mutateAPIKeys reads the current access.api-keys list, applies mutator, and // writes it back conditionally so concurrent edits are not silently lost. // It falls back to the v0 contract only when v8 is unsupported. -func (c *Client) mutateAPIKeys(mutator func(keys []string) ([]string, error), v0 func() error) error { - keys, etag, code, err := c.apiKeysV8() +func (c *Client) mutateAPIKeys(mutator func(keys []string, bindings map[string]any) ([]string, error), v0 func() error) error { + keys, bindings, etag, code, err := c.apiKeysV8() if err == nil { if etag == "" { return fmt.Errorf("cannot modify api-keys: server returned no config version (ETag); refusing unconditional replace") } - next, errMut := mutator(keys) + next, errMut := mutator(keys, bindings) if errMut != nil { return errMut } - return c.replaceAPIKeys(next, etag, v0) + return c.replaceAPIKeys(next, bindings, etag, v0) } if isRouteUnsupported(code) { return v0() @@ -755,7 +765,7 @@ func (c *Client) mutateAPIKeys(mutator func(keys []string) ([]string, error), v0 // AddAPIKey adds a new API key. On v8 it appends to access.api-keys; on v0 it // falls back to the legacy patch contract. func (c *Client) AddAPIKey(key string) error { - return c.mutateAPIKeys(func(keys []string) ([]string, error) { + return c.mutateAPIKeys(func(keys []string, _ map[string]any) ([]string, error) { return append(keys, key), nil }, func() error { body := map[string]any{"old": nil, "new": key} @@ -770,13 +780,23 @@ func (c *Client) AddAPIKey(key string) error { // longer has that value at this position the write is refused instead of // silently editing a shifted entry. func (c *Client) EditAPIKey(index int, newValue string, expected ...string) error { - return c.mutateAPIKeys(func(keys []string) ([]string, error) { + return c.mutateAPIKeys(func(keys []string, bindings map[string]any) ([]string, error) { if index < 0 || index >= len(keys) { return nil, fmt.Errorf("index %d out of range", index) } if len(expected) > 0 && keys[index] != expected[0] { return nil, fmt.Errorf("api-keys changed since selection (entry at index %d no longer matches); please refresh", index) } + // A renamed key keeps its credential binding. + if binding, ok := bindings[keys[index]].(map[string]any); ok { + renamed := make(map[string]any, len(binding)) + for field, value := range binding { + renamed[field] = value + } + renamed["key"] = newValue + delete(bindings, keys[index]) + bindings[newValue] = renamed + } keys[index] = newValue return keys, nil }, func() error { @@ -791,7 +811,7 @@ func (c *Client) EditAPIKey(index int, newValue string, expected ...string) erro // value shown to the user, so a concurrent reorder/delete is refused rather // than removing the wrong entry. func (c *Client) DeleteAPIKey(index int, expected ...string) error { - return c.mutateAPIKeys(func(keys []string) ([]string, error) { + return c.mutateAPIKeys(func(keys []string, _ map[string]any) ([]string, error) { if index < 0 || index >= len(keys) { return nil, fmt.Errorf("index %d out of range", index) } @@ -815,28 +835,60 @@ func (c *Client) DeleteAPIKey(index int, expected ...string) error { // config snapshot it came from, so a subsequent replace is conditional on that // same version. Reading the root document (rather than the child node) keeps // the list value and its version consistent even when the node is absent. -func (c *Client) apiKeysV8() ([]string, string, int, error) { +func (c *Client) apiKeysV8() ([]string, map[string]any, string, int, error) { data, code, hdr, err := c.doRequest("GET", "/v8/management/config", nil) etag := "" if hdr != nil { etag = hdr.Get("ETag") } if err != nil { - return nil, "", code, err + return nil, nil, "", code, err } if code >= 400 { - return nil, "", code, fmt.Errorf("HTTP %d: %s", code, strings.TrimSpace(string(data))) + return nil, nil, "", code, fmt.Errorf("HTTP %d: %s", code, strings.TrimSpace(string(data))) } var doc map[string]any if err := json.Unmarshal(data, &doc); err != nil { - return nil, "", code, err + return nil, nil, "", code, err } var node any if access, ok := doc["access"].(map[string]any); ok { node = access["api-keys"] } - keys, err := stringSlice(node) - return keys, etag, code, err + keys, bindings, err := apiKeyItems(node) + return keys, bindings, etag, code, err +} + +// apiKeyItems reads an api-keys list whose entries are plain strings or {key, auths} +// mappings. It returns the key values and the mapping entries by key, so a write can +// keep the credential binding of keys it did not remove. +func apiKeyItems(v any) ([]string, map[string]any, error) { + if v == nil { + return nil, nil, nil + } + raw, err := json.Marshal(v) + if err != nil { + return nil, nil, err + } + var items []any + if err := json.Unmarshal(raw, &items); err != nil { + return nil, nil, err + } + keys := make([]string, 0, len(items)) + bindings := make(map[string]any) + for _, item := range items { + switch entry := item.(type) { + case string: + keys = append(keys, entry) + case map[string]any: + key, _ := entry["key"].(string) + keys = append(keys, key) + bindings[key] = entry + default: + return nil, nil, fmt.Errorf("unsupported api-keys entry type %T", item) + } + } + return keys, bindings, nil } func stringSlice(v any) ([]string, error) { diff --git a/internal/tui/client_api_keys_binding_test.go b/internal/tui/client_api_keys_binding_test.go new file mode 100644 index 00000000000..a9de4fae00c --- /dev/null +++ b/internal/tui/client_api_keys_binding_test.go @@ -0,0 +1,83 @@ +package tui + +import ( + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/MoeForge/moego/json" +) + +// bindingServer serves a mixed api-keys list and records the last PUT body. +func bindingServer(t *testing.T, initial string, put *string) *Client { + t.Helper() + mux := http.NewServeMux() + mux.HandleFunc("/v8/management/config/access/api-keys", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPut { + body, _ := io.ReadAll(r.Body) + *put = string(body) + w.WriteHeader(http.StatusOK) + return + } + w.Header().Set("ETag", `"v1"`) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(initial)) + }) + mux.HandleFunc("/v8/management/config", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("ETag", `"v1"`) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"access":{"api-keys":` + initial + `}}`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + return NewClientWithBaseURL(srv.URL, "secret") +} + +const mixedAPIKeys = `["plain",{"key":"personal","auths":["codex-personal.json"]}]` + +func TestClientGetAPIKeysReadsBoundEntries(t *testing.T) { + var put string + keys, err := bindingServer(t, mixedAPIKeys, &put).GetAPIKeys() + if err != nil || len(keys) != 2 || keys[0] != "plain" || keys[1] != "personal" { + t.Fatalf("keys=%v err=%v", keys, err) + } +} + +func TestClientAPIKeyMutationsKeepBindings(t *testing.T) { + assertPut := func(t *testing.T, put, want string) { + t.Helper() + var got, expect any + if err := json.Unmarshal([]byte(put), &got); err != nil { + t.Fatalf("PUT body %q: %v", put, err) + } + _ = json.Unmarshal([]byte(want), &expect) + gotJSON, _ := json.Marshal(got) + expectJSON, _ := json.Marshal(expect) + if string(gotJSON) != string(expectJSON) { + t.Fatalf("PUT body = %s, want %s", gotJSON, expectJSON) + } + } + + t.Run("add", func(t *testing.T) { + var put string + if err := bindingServer(t, mixedAPIKeys, &put).AddAPIKey("new"); err != nil { + t.Fatal(err) + } + assertPut(t, put, `["plain",{"key":"personal","auths":["codex-personal.json"]},"new"]`) + }) + t.Run("edit moves the binding to the new key", func(t *testing.T) { + var put string + if err := bindingServer(t, mixedAPIKeys, &put).EditAPIKey(1, "renamed", "personal"); err != nil { + t.Fatal(err) + } + assertPut(t, put, `["plain",{"key":"renamed","auths":["codex-personal.json"]}]`) + }) + t.Run("delete another key keeps the binding", func(t *testing.T) { + var put string + if err := bindingServer(t, mixedAPIKeys, &put).DeleteAPIKey(0, "plain"); err != nil { + t.Fatal(err) + } + assertPut(t, put, `[{"key":"personal","auths":["codex-personal.json"]}]`) + }) +} diff --git a/internal/turncost/handler.go b/internal/turncost/handler.go index fd57653bc00..9e552945abe 100644 --- a/internal/turncost/handler.go +++ b/internal/turncost/handler.go @@ -22,7 +22,21 @@ type queryResponse struct { // Handler serves POST /v1/analytics/codex/turn-costs. When the feature is disabled it // answers 404, which makes Codex stop polling. -func (s *Service) Handler(c *gin.Context) { +func (s *Service) Handler(c *gin.Context) { s.serve(c, nil) } + +// HandlerScoped is Handler with a per-request visibility rule. scopeFor returns the +// scope of the authenticated caller, or nil when the caller may read every turn. +func (s *Service) HandlerScoped(scopeFor func(*gin.Context) Scope) gin.HandlerFunc { + return func(c *gin.Context) { + var scope Scope + if scopeFor != nil { + scope = scopeFor(c) + } + s.serve(c, scope) + } +} + +func (s *Service) serve(c *gin.Context, scope Scope) { if !s.Enabled() { c.AbortWithStatus(http.StatusNotFound) return @@ -37,5 +51,5 @@ func (s *Service) Handler(c *gin.Context) { if len(ids) > maxQueryTurns { ids = ids[:maxQueryTurns] } - c.JSON(http.StatusOK, queryResponse{Turns: s.Query(c.Request.Context(), ids)}) + c.JSON(http.StatusOK, queryResponse{Turns: s.QueryScoped(c.Request.Context(), ids, scope)}) } diff --git a/internal/turncost/service.go b/internal/turncost/service.go index da82df354e7..0d4eb903460 100644 --- a/internal/turncost/service.go +++ b/internal/turncost/service.go @@ -139,6 +139,29 @@ func (s *Service) HandleUsage(_ context.Context, record coreusage.Record) { // unknown, expired, or has a response without a known model price is reported as pending, // which Codex retries a few times before it stops asking about that turn. func (s *Service) Query(ctx context.Context, turnIDs []string) []TurnCost { + return s.QueryScoped(ctx, turnIDs, nil) +} + +// Scope decides whether a caller may see a recorded turn. A turn it rejects is reported +// as pending, exactly like an unknown one, and is never priced upstream. +type Scope func(Turn) bool + +// AuthIDScope admits only turns served by a single credential that is in the allowed set. +// The store keeps one credential per turn and a MixedAuth flag, so a turn served by +// several credentials, or by none that was recorded, cannot be proven to belong to the +// caller and is rejected. +func AuthIDScope(allowed map[string]struct{}) Scope { + return func(turn Turn) bool { + if turn.MixedAuth || turn.AuthID == "" { + return false + } + _, ok := allowed[turn.AuthID] + return ok + } +} + +// QueryScoped is Query limited to the turns the scope admits. A nil scope admits all. +func (s *Service) QueryScoped(ctx context.Context, turnIDs []string, scope Scope) []TurnCost { prices := s.prices.Load() var upstream map[string]TurnCost var source AuthSource @@ -147,7 +170,7 @@ func (s *Service) Query(ctx context.Context, turnIDs []string) []TurnCost { } turns := make(map[string]Turn, len(turnIDs)) for _, id := range turnIDs { - if turn, ok := s.store.Get(id); ok { + if turn, ok := s.store.Get(id); ok && (scope == nil || scope(turn)) { turns[id] = turn } } diff --git a/internal/turncost/upstream_test.go b/internal/turncost/upstream_test.go index cfb0295ad32..4e0fb62eed1 100644 --- a/internal/turncost/upstream_test.go +++ b/internal/turncost/upstream_test.go @@ -353,3 +353,44 @@ func itoa(v int) string { b, _ := json.Marshal(v) return string(b) } + +func TestQueryScopedHidesTurnsOutsideTheAllowedCredentials(t *testing.T) { + u := newFakeUpstream(t, func(call upstreamCall, w http.ResponseWriter) { + writeJSON(w, `{"threads":[{"thread_id":"th-a","turns":[{"turn_id":"turn-a","model":"gpt-5.6","estimated_usage_usd_micros":1000,"settled_response_ids":["ra"]}]},{"thread_id":"th-b","turns":[{"turn_id":"turn-b","model":"gpt-5.6","estimated_usage_usd_micros":2000,"settled_response_ids":["rb"]}]}]}`) + }) + s := upstreamService(t, u, codexAuth("auth-a", "tok-a", "acct-a"), codexAuth("auth-b", "tok-b", "acct-b")) + s.HandleUsage(context.Background(), record("auth-a", "th-a", "turn-a", "ra", 1_000_000)) + s.HandleUsage(context.Background(), record("auth-b", "th-b", "turn-b", "rb", 1_000_000)) + // A turn that auth-a and auth-b both served cannot be attributed to auth-a alone. + s.HandleUsage(context.Background(), record("auth-a", "th-m", "turn-mixed", "rm1", 1_000_000)) + s.HandleUsage(context.Background(), record("auth-b", "th-m", "turn-mixed", "rm2", 1_000_000)) + // A turn with no recorded credential cannot be attributed to the caller. + s.HandleUsage(context.Background(), record("", "th-n", "turn-anon", "rn", 1_000_000)) + + scope := AuthIDScope(map[string]struct{}{"auth-a": {}}) + got := s.QueryScoped(context.Background(), []string{"turn-a", "turn-b", "turn-mixed", "turn-anon"}, scope) + if got[0].Status != statusPriced { + t.Fatalf("turn-a = %+v, want priced", got[0]) + } + for _, c := range got[1:] { + if c.Status != statusPending || c.TotalUSD != "" { + t.Fatalf("%s = %+v, want pending without any cost", c.TurnID, c) + } + } + for _, call := range u.recorded() { + if call.token != "Bearer tok-a" { + t.Fatalf("upstream call used %q, only the allowed credential may be used", call.token) + } + for _, thread := range call.body.Threads { + if thread.ThreadID != "th-a" { + t.Fatalf("upstream asked about thread %q outside the scope", thread.ThreadID) + } + } + } + if got := s.QueryScoped(context.Background(), []string{"turn-a"}, AuthIDScope(nil)); got[0].Status != statusPending { + t.Fatalf("empty scope = %+v, want pending", got[0]) + } + if got := s.Query(context.Background(), []string{"turn-b"}); got[0].Status != statusPriced { + t.Fatalf("unscoped Query = %+v, want priced", got[0]) + } +} diff --git a/internal/watcher/diff/config_diff.go b/internal/watcher/diff/config_diff.go index 8be3a45fce4..3c97639b230 100644 --- a/internal/watcher/diff/config_diff.go +++ b/internal/watcher/diff/config_diff.go @@ -228,7 +228,7 @@ func BuildConfigChangeDetails(oldCfg, newCfg *config.Config) []string { // API keys (redacted) and counts if len(oldCfg.APIKeys) != len(newCfg.APIKeys) { changes = append(changes, fmt.Sprintf("api-keys count: %d -> %d", len(oldCfg.APIKeys), len(newCfg.APIKeys))) - } else if !reflect.DeepEqual(trimStrings(oldCfg.APIKeys), trimStrings(newCfg.APIKeys)) { + } else if !apiKeyEntriesEqual(oldCfg.APIKeys, newCfg.APIKeys) { changes = append(changes, "api-keys: values updated (count unchanged, redacted)") } if len(oldCfg.GeminiKey) != len(newCfg.GeminiKey) { @@ -601,6 +601,21 @@ func BuildConfigChangeDetails(oldCfg, newCfg *config.Config) []string { return changes } +func apiKeyEntriesEqual(a, b []config.APIKeyEntry) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if strings.TrimSpace(a[i].Key) != strings.TrimSpace(b[i].Key) { + return false + } + if !reflect.DeepEqual(trimStrings(a[i].Auths), trimStrings(b[i].Auths)) { + return false + } + } + return true +} + func trimStrings(in []string) []string { out := make([]string, len(in)) for i := range in { diff --git a/internal/watcher/diff/config_diff_test.go b/internal/watcher/diff/config_diff_test.go index 17037d53e55..5b32c8dd313 100644 --- a/internal/watcher/diff/config_diff_test.go +++ b/internal/watcher/diff/config_diff_test.go @@ -361,7 +361,7 @@ func TestBuildConfigChangeDetails_NilSafe(t *testing.T) { func TestBuildConfigChangeDetails_SecretsAndCounts(t *testing.T) { oldCfg := &config.Config{ SDKConfig: sdkconfig.SDKConfig{ - APIKeys: []string{"a"}, + APIKeys: config.APIKeyEntries("a"), }, RemoteManagement: config.RemoteManagement{ SecretKey: "", @@ -369,7 +369,7 @@ func TestBuildConfigChangeDetails_SecretsAndCounts(t *testing.T) { } newCfg := &config.Config{ SDKConfig: sdkconfig.SDKConfig{ - APIKeys: []string{"a", "b", "c"}, + APIKeys: config.APIKeyEntries("a", "b", "c"), }, RemoteManagement: config.RemoteManagement{ SecretKey: "new-secret", @@ -442,7 +442,7 @@ func TestBuildConfigChangeDetails_FlagsAndKeys(t *testing.T) { SDKConfig: sdkconfig.SDKConfig{ RequestLog: false, ProxyURL: "http://old-proxy", - APIKeys: []string{"key-1"}, + APIKeys: config.APIKeyEntries("key-1"), ForceModelPrefix: false, NonStreamKeepAliveInterval: 0, }, @@ -487,7 +487,7 @@ func TestBuildConfigChangeDetails_FlagsAndKeys(t *testing.T) { SDKConfig: sdkconfig.SDKConfig{ RequestLog: true, ProxyURL: "http://new-proxy", - APIKeys: []string{" key-1 ", "key-2"}, + APIKeys: config.APIKeyEntries(" key-1 ", "key-2"), ForceModelPrefix: true, NonStreamKeepAliveInterval: 5, DisableImageGeneration: config.DisableImageGenerationAll, @@ -569,7 +569,7 @@ func TestBuildConfigChangeDetails_AllBranches(t *testing.T) { SDKConfig: sdkconfig.SDKConfig{ RequestLog: false, ProxyURL: "http://old-proxy", - APIKeys: []string{" keyA "}, + APIKeys: config.APIKeyEntries(" keyA "), }, OAuthExcludedModels: map[string][]string{"p1": {"a"}}, OpenAICompatibility: []config.OpenAICompatibility{ @@ -618,7 +618,7 @@ func TestBuildConfigChangeDetails_AllBranches(t *testing.T) { SDKConfig: sdkconfig.SDKConfig{ RequestLog: true, ProxyURL: "http://new-proxy", - APIKeys: []string{"keyB"}, + APIKeys: config.APIKeyEntries("keyB"), DisableImageGeneration: config.DisableImageGenerationAll, }, OAuthExcludedModels: map[string][]string{"p1": {"b", "c"}, "p2": {"d"}}, diff --git a/sdk/access/allowed_auths.go b/sdk/access/allowed_auths.go new file mode 100644 index 00000000000..976277a3489 --- /dev/null +++ b/sdk/access/allowed_auths.go @@ -0,0 +1,44 @@ +package access + +import "github.com/gin-gonic/gin" + +// AllowedAuthsContextKey is the gin context key under which the credential +// restriction of the authenticated principal ([]string) is stored. +const AllowedAuthsContextKey = "accessAllowedAuths" + +// AllowedAuthsFromGin returns the credential restriction recorded for the +// authenticated request, or nil when the principal is unrestricted. +func AllowedAuthsFromGin(c *gin.Context) []string { + if c == nil { + return nil + } + value, exists := c.Get(AllowedAuthsContextKey) + if !exists { + return nil + } + refs, _ := value.([]string) + if len(refs) == 0 { + return nil + } + return append([]string(nil), refs...) +} + +// AllowedAuthIDsContextKey is the gin context key under which the credential IDs a +// restricted principal may use ([]string) are published for code that has no +// credential manager. It is derived from the restriction, never configured. +const AllowedAuthIDsContextKey = "accessAllowedAuthIDs" + +// AllowedAuthIDsFromGin reports whether the authenticated request is restricted and, if +// so, the IDs of the credentials it may use. A restricted request whose IDs were never +// published gets an empty list, so a consumer that checks the list fails closed. +func AllowedAuthIDsFromGin(c *gin.Context) (ids []string, restricted bool) { + if len(AllowedAuthsFromGin(c)) == 0 { + return nil, false + } + value, exists := c.Get(AllowedAuthIDsContextKey) + if !exists { + return []string{}, true + } + published, _ := value.([]string) + return append([]string{}, published...), true +} diff --git a/sdk/access/registry.go b/sdk/access/registry.go index e257f27658d..2f27c6bf418 100644 --- a/sdk/access/registry.go +++ b/sdk/access/registry.go @@ -17,7 +17,10 @@ type Provider interface { type Result struct { Provider string Principal string - Metadata map[string]string + // AllowedAuths restricts the request to the listed credentials (credential + // IDs or file names). Empty means the principal is not restricted. + AllowedAuths []string + Metadata map[string]string } var ( diff --git a/sdk/api/handlers/claude/code_handlers.go b/sdk/api/handlers/claude/code_handlers.go index e836bb7327e..205e62a4ce6 100644 --- a/sdk/api/handlers/claude/code_handlers.go +++ b/sdk/api/handlers/claude/code_handlers.go @@ -58,6 +58,11 @@ func (h *ClaudeCodeAPIHandler) HandlerType() string { return Claude } +// ModelsForRequest returns the models visible to the request's client key. +func (h *ClaudeCodeAPIHandler) ModelsForRequest(c *gin.Context) []map[string]any { + return h.AvailableModelsForRequest(c, "claude") +} + // Models returns a list of models supported by this handler. func (h *ClaudeCodeAPIHandler) Models() []map[string]any { // Get dynamic models from the global registry @@ -161,7 +166,7 @@ func rewriteClaudeDDModelInBody(rawJSON []byte) []byte { func (h *ClaudeCodeAPIHandler) ClaudeModels(c *gin.Context) { cfg := h.CurrentConfig() disableCloaking := cfg != nil && cfg.ClaudeCode.DisableCloakingModelList - h.WriteModelListResponse(c, h.HandlerType(), claudemodels.BuildResponse(h.Models(), disableCloaking)) + h.WriteModelListResponse(c, h.HandlerType(), claudemodels.BuildResponse(h.ModelsForRequest(c), disableCloaking)) } // handleNonStreamingResponse handles non-streaming content generation requests for Claude models. diff --git a/sdk/api/handlers/gemini/gemini_handlers.go b/sdk/api/handlers/gemini/gemini_handlers.go index d48c826b8ba..2cf39762f60 100644 --- a/sdk/api/handlers/gemini/gemini_handlers.go +++ b/sdk/api/handlers/gemini/gemini_handlers.go @@ -39,6 +39,11 @@ func (h *GeminiAPIHandler) HandlerType() string { return Gemini } +// ModelsForRequest returns the models visible to the request's client key. +func (h *GeminiAPIHandler) ModelsForRequest(c *gin.Context) []map[string]any { + return h.AvailableModelsForRequest(c, "gemini") +} + // Models returns the Gemini-compatible model metadata supported by this handler. func (h *GeminiAPIHandler) Models() []map[string]any { // Get dynamic models from the global registry @@ -49,7 +54,7 @@ func (h *GeminiAPIHandler) Models() []map[string]any { // GeminiModels handles the Gemini models listing endpoint. // It returns a JSON response containing available Gemini models and their specifications. func (h *GeminiAPIHandler) GeminiModels(c *gin.Context) { - rawModels := h.Models() + rawModels := h.ModelsForRequest(c) normalizedModels := make([]map[string]any, 0, len(rawModels)) defaultMethods := []string{"generateContent"} for _, model := range rawModels { @@ -96,7 +101,7 @@ func (h *GeminiAPIHandler) GeminiGetHandler(c *gin.Context) { action := strings.TrimPrefix(request.Action, "/") // Get dynamic models from the global registry and find the matching one - availableModels := h.Models() + availableModels := h.ModelsForRequest(c) var targetModel map[string]any for _, model := range availableModels { diff --git a/sdk/api/handlers/handlers.go b/sdk/api/handlers/handlers.go index 537c445b526..152651058d8 100644 --- a/sdk/api/handlers/handlers.go +++ b/sdk/api/handlers/handlers.go @@ -21,6 +21,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" "github.com/router-for-me/CLIProxyAPI/v8/internal/thinking" "github.com/router-for-me/CLIProxyAPI/v8/internal/util" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" coresession "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/session" @@ -380,9 +381,27 @@ func requestExecutionMetadata(ctx context.Context) map[string]any { if disallowFreeAuthFromContext(ctx) { meta[coreexecutor.DisallowFreeAuthMetadataKey] = true } + if allowedAuths := AllowedAuthsFromContext(ctx); len(allowedAuths) > 0 { + meta[coreexecutor.AllowedAuthsMetadataKey] = allowedAuths + } return meta } +// AllowedAuthsFromContext returns the credential restriction of the authenticated +// client key carried by the gin context in ctx. Empty means unrestricted. +func AllowedAuthsFromContext(ctx context.Context) []string { + if ctx == nil { + return nil + } + ginCtx, ok := ctx.Value("gin").(*gin.Context) + if !ok || ginCtx == nil { + return nil + } + return allowedAuthsFromGin(ginCtx) +} + +func allowedAuthsFromGin(c *gin.Context) []string { return sdkaccess.AllowedAuthsFromGin(c) } + func requestClientIP(request *http.Request) string { if request == nil { return "" @@ -754,6 +773,7 @@ func (h *BaseAPIHandler) GetContextWithCancel(handler interfaces.APIHandler, c * } }() } + h.PublishAllowedAuthIDs(c) newCtx = context.WithValue(newCtx, "gin", c) newCtx = coreusage.CaptureIdentity(newCtx) newCtx = coreauth.WithCodexClientRequest(newCtx, coreauth.IsCodexClientRequest(newCtx)) diff --git a/sdk/api/handlers/handlers_allowed_auth_ids_test.go b/sdk/api/handlers/handlers_allowed_auth_ids_test.go new file mode 100644 index 00000000000..925cbf3b4d1 --- /dev/null +++ b/sdk/api/handlers/handlers_allowed_auth_ids_test.go @@ -0,0 +1,60 @@ +package handlers + +import ( + "context" + "net/http/httptest" + "sort" + "testing" + + "github.com/gin-gonic/gin" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +func TestPublishAllowedAuthIDsResolvesRefsAndFailsClosed(t *testing.T) { + gin.SetMode(gin.TestMode) + manager := coreauth.NewManager(nil, nil, nil) + for id, file := range map[string]string{"publish-a": "publish-a.json", "publish-b": "publish-b.json"} { + if _, err := manager.Register(coreauth.WithSkipPersist(context.Background()), &coreauth.Auth{ID: id, FileName: file, Provider: "codex", Status: coreauth.StatusActive}); err != nil { + t.Fatal(err) + } + } + h := NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager) + + newCtx := func(refs []string) *gin.Context { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + if refs != nil { + c.Set(sdkaccess.AllowedAuthsContextKey, refs) + } + return c + } + + c := newCtx([]string{"publish-a.json", "publish-b"}) + h.PublishAllowedAuthIDs(c) + ids, restricted := sdkaccess.AllowedAuthIDsFromGin(c) + sort.Strings(ids) + if !restricted || len(ids) != 2 || ids[0] != "publish-a" || ids[1] != "publish-b" { + t.Fatalf("ids = %v restricted = %v", ids, restricted) + } + + c = newCtx([]string{"missing.json"}) + h.PublishAllowedAuthIDs(c) + if ids, restricted = sdkaccess.AllowedAuthIDsFromGin(c); !restricted || len(ids) != 0 { + t.Fatalf("dangling ref: ids = %v restricted = %v, want restricted and empty", ids, restricted) + } + + // A restricted request whose IDs were never published must read as "nothing allowed". + if ids, restricted = sdkaccess.AllowedAuthIDsFromGin(newCtx([]string{"publish-a.json"})); !restricted || len(ids) != 0 { + t.Fatalf("unpublished: ids = %v restricted = %v", ids, restricted) + } + + // A later unrestricted turn on the same connection clears the earlier IDs. + c = newCtx([]string{"publish-a.json"}) + h.PublishAllowedAuthIDs(c) + c.Set(sdkaccess.AllowedAuthsContextKey, nil) + h.PublishAllowedAuthIDs(c) + if _, restricted = sdkaccess.AllowedAuthIDsFromGin(c); restricted { + t.Fatal("an unrestricted turn must not stay restricted") + } +} diff --git a/sdk/api/handlers/handlers_allowed_models.go b/sdk/api/handlers/handlers_allowed_models.go new file mode 100644 index 00000000000..47b6d57aa40 --- /dev/null +++ b/sdk/api/handlers/handlers_allowed_models.go @@ -0,0 +1,45 @@ +package handlers + +import ( + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" +) + +// AvailableModelsForRequest lists the models for handlerType that the request's client +// key may use. Unrestricted keys see the global list; a key bound to credentials only +// sees models served by those credentials. Home mode cannot enforce a binding, so a +// bound key sees no models there, matching the dispatch refusal. +func (h *BaseAPIHandler) AvailableModelsForRequest(c *gin.Context, handlerType string) []map[string]any { + modelRegistry := registry.GetGlobalRegistry() + refs := allowedAuthsFromGin(c) + if len(refs) == 0 { + return modelRegistry.GetAvailableModels(handlerType) + } + if h == nil || h.AuthManager == nil || h.AuthManager.HomeEnabled() { + return []map[string]any{} + } + return modelRegistry.GetAvailableModelsForClients(handlerType, h.AuthManager.AllowedAuthIDs(refs)) +} + +// PublishAllowedAuthIDs records on c the credential IDs the request's client key may use, +// so code that only sees the request context (for example the spawn_agent model list) +// can scope itself without a credential manager. Home mode cannot enforce a binding, so +// a bound key gets no credentials there. +func (h *BaseAPIHandler) PublishAllowedAuthIDs(c *gin.Context) { + if c == nil { + return + } + refs := allowedAuthsFromGin(c) + if len(refs) == 0 { + c.Set(sdkaccess.AllowedAuthIDsContextKey, nil) + return + } + ids := []string{} + if h != nil && h.AuthManager != nil && !h.AuthManager.HomeEnabled() { + for id := range h.AuthManager.AllowedAuthIDs(refs) { + ids = append(ids, id) + } + } + c.Set(sdkaccess.AllowedAuthIDsContextKey, ids) +} diff --git a/sdk/api/handlers/handlers_metadata_test.go b/sdk/api/handlers/handlers_metadata_test.go index bf5d47aaa7a..3a060ad157e 100644 --- a/sdk/api/handlers/handlers_metadata_test.go +++ b/sdk/api/handlers/handlers_metadata_test.go @@ -438,3 +438,24 @@ func TestHomeUpdatedAPIKeyOverridesParentWithAPIKeyAfterCapture(t *testing.T) { t.Fatalf("coreusage.APIKeyFromContext = %q, want %q", got, "home-dispatched-key-b") } } + +func TestRequestExecutionMetadataCarriesAllowedAuths(t *testing.T) { + gin.SetMode(gin.TestMode) + newCtx := func(allowed []string) context.Context { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + if allowed != nil { + c.Set("accessAllowedAuths", allowed) + } + return context.WithValue(context.Background(), "gin", c) + } + + meta := requestExecutionMetadata(newCtx([]string{"personal.json", "claude-personal.json"})) + got, _ := meta[coreexecutor.AllowedAuthsMetadataKey].([]string) + if len(got) != 2 || got[0] != "personal.json" || got[1] != "claude-personal.json" { + t.Fatalf("allowed auths metadata = %v", meta[coreexecutor.AllowedAuthsMetadataKey]) + } + if _, ok := requestExecutionMetadata(newCtx(nil))[coreexecutor.AllowedAuthsMetadataKey]; ok { + t.Fatal("unbound request must not carry allowed auths") + } +} diff --git a/sdk/api/handlers/openai/codex_client_models.go b/sdk/api/handlers/openai/codex_client_models.go index 2b2e21859e3..edbba165d17 100644 --- a/sdk/api/handlers/openai/codex_client_models.go +++ b/sdk/api/handlers/openai/codex_client_models.go @@ -7,6 +7,10 @@ import ( ) func (h *OpenAIAPIHandler) codexClientModelsResponse(clientVersion ...string) map[string]any { + return h.codexClientModelsResponseFor(h.Models(), clientVersion...) +} + +func (h *OpenAIAPIHandler) codexClientModelsResponseFor(models []map[string]any, clientVersion ...string) map[string]any { version := "" if len(clientVersion) > 0 { version = clientVersion[0] @@ -26,7 +30,7 @@ func (h *OpenAIAPIHandler) codexClientModelsResponse(clientVersion ...string) ma toolSearchCapabilityForModel = h.SupportsNativeToolSearchModel } modelRegistry := registry.GetGlobalRegistry() - return codexmodels.BuildResponseForClientWithToolCapabilities(h.Models(), modelRegistry.GetModelProviders, modelRegistry.GetResponsesWebSearchCapability, applyPatchCapabilityForModel, toolSearchCapabilityForModel, optimizeMultiAgentV2, version) + return codexmodels.BuildResponseForClientWithToolCapabilities(models, modelRegistry.GetModelProviders, modelRegistry.GetResponsesWebSearchCapability, applyPatchCapabilityForModel, toolSearchCapabilityForModel, optimizeMultiAgentV2, version) } // CodexClientModelsResponse builds a Codex client model response. diff --git a/sdk/api/handlers/openai/openai_handlers.go b/sdk/api/handlers/openai/openai_handlers.go index 4c85565ead6..a579e6dcbf7 100644 --- a/sdk/api/handlers/openai/openai_handlers.go +++ b/sdk/api/handlers/openai/openai_handlers.go @@ -52,6 +52,11 @@ func (h *OpenAIAPIHandler) HandlerType() string { return OpenAI } +// ModelsForRequest returns the models visible to the request's client key. +func (h *OpenAIAPIHandler) ModelsForRequest(c *gin.Context) []map[string]any { + return h.AvailableModelsForRequest(c, "openai") +} + // Models returns the OpenAI-compatible model metadata supported by this handler. func (h *OpenAIAPIHandler) Models() []map[string]any { // Get dynamic models from the global registry @@ -65,7 +70,7 @@ func (h *OpenAIAPIHandler) Models() []map[string]any { func (h *OpenAIAPIHandler) OpenAIModels(c *gin.Context) { if _, ok := c.Request.URL.Query()["client_version"]; ok { clientVersion := c.Query("client_version") - body, errMarshal := codexmodels.MarshalCompact(h.codexClientModelsResponse(clientVersion)) + body, errMarshal := codexmodels.MarshalCompact(h.codexClientModelsResponseFor(h.ModelsForRequest(c), clientVersion)) if errMarshal != nil { c.JSON(http.StatusInternalServerError, handlers.ErrorResponse{ Error: handlers.ErrorDetail{ @@ -80,7 +85,7 @@ func (h *OpenAIAPIHandler) OpenAIModels(c *gin.Context) { } // Get all available models - allModels := h.Models() + allModels := h.ModelsForRequest(c) // Filter to only include the 4 required fields: id, object, created, owned_by filteredModels := make([]map[string]any, len(allModels)) diff --git a/sdk/api/handlers/openai/openai_models_allowed_auths_test.go b/sdk/api/handlers/openai/openai_models_allowed_auths_test.go new file mode 100644 index 00000000000..b14af7324fc --- /dev/null +++ b/sdk/api/handlers/openai/openai_models_allowed_auths_test.go @@ -0,0 +1,111 @@ +package openai + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/MoeForge/moego/json" + "github.com/gin-gonic/gin" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +func registerBoundModelFixture(t *testing.T) *auth.Manager { + t.Helper() + manager := auth.NewManager(nil, nil, nil) + modelRegistry := registry.GetGlobalRegistry() + for id, model := range map[string]string{"bound-models-personal": "bound-personal-model", "bound-models-work": "bound-work-model"} { + modelRegistry.RegisterClient(id, "codex", []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { modelRegistry.UnregisterClient(id) }) + if _, err := manager.Register(auth.WithSkipPersist(context.Background()), &auth.Auth{ + ID: id, FileName: id + ".json", Provider: "codex", Status: auth.StatusActive, + }); err != nil { + t.Fatal(err) + } + } + return manager +} + +func listModelIDs(models []map[string]any) map[string]bool { + ids := map[string]bool{} + for _, model := range models { + if id, ok := model["id"].(string); ok { + ids[id] = true + } + } + return ids +} + +func ginWithAllowed(allowed []string) *gin.Context { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) + if allowed != nil { + c.Set(sdkaccess.AllowedAuthsContextKey, allowed) + } + return c +} + +func TestModelsForRequestListsOnlyBoundCredentialModels(t *testing.T) { + manager := registerBoundModelFixture(t) + handler := NewOpenAIAPIHandler(handlers.NewBaseAPIHandlers(&config.SDKConfig{}, manager)) + + bound := listModelIDs(handler.ModelsForRequest(ginWithAllowed([]string{"bound-models-personal.json"}))) + if !bound["bound-personal-model"] || bound["bound-work-model"] || len(bound) != 1 { + t.Fatalf("bound listing = %v, want only bound-personal-model", bound) + } + + byID := listModelIDs(handler.ModelsForRequest(ginWithAllowed([]string{"bound-models-work"}))) + if !byID["bound-work-model"] || byID["bound-personal-model"] { + t.Fatalf("ID-bound listing = %v", byID) + } + + unbound := listModelIDs(handler.ModelsForRequest(ginWithAllowed(nil))) + if !unbound["bound-personal-model"] || !unbound["bound-work-model"] { + t.Fatalf("unbound listing = %v, want both models", unbound) + } + + none := handler.ModelsForRequest(ginWithAllowed([]string{"does-not-exist.json"})) + if len(none) != 0 { + t.Fatalf("binding to a missing credential must list nothing, got %v", none) + } +} + +func TestOpenAIModelsEndpointFiltersPerKey(t *testing.T) { + manager := registerBoundModelFixture(t) + handler := NewOpenAIAPIHandler(handlers.NewBaseAPIHandlers(&config.SDKConfig{}, manager)) + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil) + c.Set(sdkaccess.AllowedAuthsContextKey, []string{"bound-models-personal.json"}) + handler.OpenAIModels(c) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String()) + } + var body struct { + Data []map[string]any `json:"data"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + ids := listModelIDs(body.Data) + if !ids["bound-personal-model"] || ids["bound-work-model"] || len(ids) != 1 { + t.Fatalf("endpoint listing = %v, want only bound-personal-model", ids) + } +} + +func TestModelsForRequestHomeModeFailsClosed(t *testing.T) { + manager := registerBoundModelFixture(t) + manager.SetConfig(&config.Config{Home: config.HomeConfig{Enabled: true}}) + handler := NewOpenAIAPIHandler(handlers.NewBaseAPIHandlers(&config.SDKConfig{}, manager)) + if got := handler.ModelsForRequest(ginWithAllowed([]string{"bound-models-personal.json"})); len(got) != 0 { + t.Fatalf("bound key in home mode listed %v", got) + } +} diff --git a/sdk/api/handlers/openai/openai_responses_handlers.go b/sdk/api/handlers/openai/openai_responses_handlers.go index 5a21893fb8d..93971e3001f 100644 --- a/sdk/api/handlers/openai/openai_responses_handlers.go +++ b/sdk/api/handlers/openai/openai_responses_handlers.go @@ -885,6 +885,11 @@ func (h *OpenAIResponsesAPIHandler) HandlerType() string { return OpenaiResponse } +// ModelsForRequest returns the models visible to the request's client key. +func (h *OpenAIResponsesAPIHandler) ModelsForRequest(c *gin.Context) []map[string]any { + return h.AvailableModelsForRequest(c, "openai") +} + // Models returns the OpenAIResponses-compatible model metadata supported by this handler. func (h *OpenAIResponsesAPIHandler) Models() []map[string]any { // Get dynamic models from the global registry @@ -898,7 +903,7 @@ func (h *OpenAIResponsesAPIHandler) Models() []map[string]any { func (h *OpenAIResponsesAPIHandler) OpenAIResponsesModels(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "object": "list", - "data": h.Models(), + "data": h.ModelsForRequest(c), }) } @@ -915,6 +920,7 @@ func (h *OpenAIResponsesAPIHandler) prepareCodexMultiAgentV2ToolsDoc(c *gin.Cont if c != nil && c.Request != nil { requestCtx = c.Request.Context() } + h.PublishAllowedAuthIDs(c) requestCtx = context.WithValue(requestCtx, "gin", c) var requestHeaders http.Header diff --git a/sdk/api/handlers/openai/openai_responses_websocket.go b/sdk/api/handlers/openai/openai_responses_websocket.go index cdb7084ea40..cf02abc2802 100644 --- a/sdk/api/handlers/openai/openai_responses_websocket.go +++ b/sdk/api/handlers/openai/openai_responses_websocket.go @@ -22,6 +22,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" "github.com/router-for-me/CLIProxyAPI/v8/internal/util" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" @@ -386,15 +387,25 @@ func truncateWebsocketCloseReason(reason string, maxBytes int) string { } func (h *OpenAIResponsesAPIHandler) authenticateResponsesWebsocketTurn(c *gin.Context, baseReq *http.Request, payload []byte, requestModelName string, updateRequestContext bool) (string, *interfaces.ErrorMessage) { + result, errAuth := h.authenticateResponsesWebsocketTurnResult(c, baseReq, payload, requestModelName, updateRequestContext) + if errAuth != nil || result == nil { + return "", errAuth + } + return result.Principal, nil +} + +// authenticateResponsesWebsocketTurnResult authenticates one frame and returns the full +// access result, so a caller can compare the credential binding the frame resolves to. +func (h *OpenAIResponsesAPIHandler) authenticateResponsesWebsocketTurnResult(c *gin.Context, baseReq *http.Request, payload []byte, requestModelName string, updateRequestContext bool) (*sdkaccess.Result, *interfaces.ErrorMessage) { if h == nil || h.AccessManager == nil { - return "", nil + return nil, nil } sourceReq := baseReq if sourceReq == nil && c != nil { sourceReq = c.Request } if sourceReq == nil { - return "", nil + return nil, nil } authBody := payload if requestModelName != "" && json.Valid(payload) && strings.TrimSpace(ojson.GetBytesNoCopy(payload, "model").String()) == "" { @@ -423,13 +434,13 @@ func (h *OpenAIResponsesAPIHandler) authenticateResponsesWebsocketTurn(c *gin.Co if msg == "" { msg = authErr.Error() } - return "", &interfaces.ErrorMessage{ + return nil, &interfaces.ErrorMessage{ StatusCode: authErr.HTTPStatusCode(), Error: errors.New(msg), } } if result == nil { - return "", nil + return nil, nil } if c != nil && updateRequestContext { c.Set("userApiKey", result.Principal) @@ -439,6 +450,11 @@ func (h *OpenAIResponsesAPIHandler) authenticateResponsesWebsocketTurn(c *gin.Co } else { c.Set("accessMetadata", nil) } + if len(result.AllowedAuths) > 0 { + c.Set(sdkaccess.AllowedAuthsContextKey, result.AllowedAuths) + } else { + c.Set(sdkaccess.AllowedAuthsContextKey, nil) + } if c.Request != nil { reqCtx := usage.WithAPIKey(c.Request.Context(), result.Principal) reqCtx = usage.WithAccessProvider(reqCtx, result.Provider) @@ -446,7 +462,7 @@ func (h *OpenAIResponsesAPIHandler) authenticateResponsesWebsocketTurn(c *gin.Co c.Request = c.Request.WithContext(reqCtx) } } - return result.Principal, nil + return result, nil } // ResponsesWebsocket handles websocket requests for /v1/responses. @@ -1043,14 +1059,25 @@ func (h *OpenAIResponsesAPIHandler) ResponsesWebsocket(c *gin.Context) { return ok && current != nil && !current.Disabled && current.Status != coreauth.StatusDisabled }) boundPrincipal := usage.APIKeyFromContext(cliCtx) + // Snapshot on the turn goroutine; the authorizer runs on the executor goroutine and + // must not read the gin context, which this goroutine rewrites per turn. + boundAllowedAuths := append([]string(nil), sdkaccess.AllowedAuthsFromGin(c)...) cliCtx = cliproxyexecutor.WithWebsocketTurnAuthorizer(cliCtx, func(turnPayload []byte) ([]byte, error) { - principal, errAuth := h.authenticateResponsesWebsocketTurn(c, upgradeRequest, turnPayload, modelName, false) - if errAuth == nil && principal != "" && principal != boundPrincipal { + result, errAuth := h.authenticateResponsesWebsocketTurnResult(c, upgradeRequest, turnPayload, modelName, false) + if errAuth == nil && result != nil && result.Principal != "" && result.Principal != boundPrincipal { errAuth = &interfaces.ErrorMessage{ StatusCode: http.StatusUnauthorized, Error: errors.New("client credential changed during the websocket stream; reconnect"), } } + // The in-flight stream was dispatched under boundAllowedAuths. A frame whose + // binding changed (key rebound mid-socket) must not ride the stale restriction. + if errAuth == nil && result != nil && !sameAllowedAuths(result.AllowedAuths, boundAllowedAuths) { + errAuth = &interfaces.ErrorMessage{ + StatusCode: http.StatusUnauthorized, + Error: errors.New("client credential binding changed during the websocket stream; reconnect"), + } + } if errAuth == nil { return nil, nil } @@ -1433,3 +1460,22 @@ func writeResponsesWebsocketPreviousResponseNotFound(writer *responsesWebsocketW } return writeResponsesWebsocketPayload(writer, wsTimelineLog, errorPayload, time.Now()) } + +// sameAllowedAuths reports whether two credential restrictions are the same set. Nil and +// empty both mean unrestricted. +func sameAllowedAuths(a, b []string) bool { + if len(a) != len(b) { + return false + } + seen := make(map[string]int, len(a)) + for _, v := range a { + seen[v]++ + } + for _, v := range b { + seen[v]-- + if seen[v] < 0 { + return false + } + } + return true +} diff --git a/sdk/api/handlers/openai/openai_responses_websocket_binding_test.go b/sdk/api/handlers/openai/openai_responses_websocket_binding_test.go new file mode 100644 index 00000000000..69e74a86942 --- /dev/null +++ b/sdk/api/handlers/openai/openai_responses_websocket_binding_test.go @@ -0,0 +1,80 @@ +package openai + +import ( + "context" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "github.com/gin-gonic/gin" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +type reboundWebsocketAccessProvider struct { + allowed atomic.Value +} + +func (p *reboundWebsocketAccessProvider) Identifier() string { return "rebound" } + +func (p *reboundWebsocketAccessProvider) Authenticate(_ context.Context, _ *http.Request) (*sdkaccess.Result, *sdkaccess.AuthError) { + allowed, _ := p.allowed.Load().([]string) + return &sdkaccess.Result{Principal: "key-1", Provider: p.Identifier(), AllowedAuths: allowed}, nil +} + +func TestWebsocketTurnResultExposesCurrentBindingWithoutTouchingContext(t *testing.T) { + provider := &reboundWebsocketAccessProvider{} + provider.allowed.Store([]string{"cred-a.json"}) + access := sdkaccess.NewManager() + access.SetProviders([]sdkaccess.Provider{provider}) + h := NewOpenAIResponsesAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, nil)) + h.AccessManager = access + + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodGet, "/ping", nil) + c.Set(sdkaccess.AllowedAuthsContextKey, []string{"cred-a.json"}) + turn := httptest.NewRequest(http.MethodGet, "/v1/responses", nil) + + result, errAuth := h.authenticateResponsesWebsocketTurnResult(c, turn, []byte(`{}`), "gpt-5.5", false) + if errAuth != nil || result == nil { + t.Fatalf("turn auth: result=%v err=%v", result, errAuth) + } + if !sameAllowedAuths(result.AllowedAuths, []string{"cred-a.json"}) { + t.Fatalf("binding = %v, want cred-a.json", result.AllowedAuths) + } + + provider.allowed.Store([]string{"cred-b.json"}) + result, errAuth = h.authenticateResponsesWebsocketTurnResult(c, turn, []byte(`{}`), "gpt-5.5", false) + if errAuth != nil || result == nil { + t.Fatalf("turn auth after rebind: result=%v err=%v", result, errAuth) + } + if sameAllowedAuths(result.AllowedAuths, []string{"cred-a.json"}) { + t.Fatalf("rebound frame still reports the stale binding %v", result.AllowedAuths) + } + if got := sdkaccess.AllowedAuthsFromGin(c); len(got) != 1 || got[0] != "cred-a.json" { + t.Fatalf("a follow-up frame rewrote the shared gin restriction: %v", got) + } +} + +func TestSameAllowedAuths(t *testing.T) { + cases := []struct { + name string + a, b []string + want bool + }{ + {"both unrestricted", nil, []string{}, true}, + {"same order", []string{"a", "b"}, []string{"a", "b"}, true}, + {"different order", []string{"a", "b"}, []string{"b", "a"}, true}, + {"unrestricted vs bound", nil, []string{"a"}, false}, + {"bound vs unrestricted", []string{"a"}, nil, false}, + {"different member", []string{"a"}, []string{"b"}, false}, + {"duplicate vs distinct", []string{"a", "a"}, []string{"a", "b"}, false}, + } + for _, tc := range cases { + if got := sameAllowedAuths(tc.a, tc.b); got != tc.want { + t.Errorf("%s: sameAllowedAuths(%v, %v) = %v, want %v", tc.name, tc.a, tc.b, got, tc.want) + } + } +} diff --git a/sdk/api/handlers/openai/openai_videos_handlers.go b/sdk/api/handlers/openai/openai_videos_handlers.go index 673f2a98388..fc24d77a765 100644 --- a/sdk/api/handlers/openai/openai_videos_handlers.go +++ b/sdk/api/handlers/openai/openai_videos_handlers.go @@ -19,6 +19,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/interfaces" "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" "github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" log "github.com/sirupsen/logrus" @@ -980,6 +981,9 @@ func (h *OpenAIAPIHandler) videoContentDownloadAuth(c *gin.Context) *coreauth.Au if !ok { return nil } + if !coreauth.AuthAllowedByRefs(auth, sdkaccess.AllowedAuthsFromGin(c)) { + return nil + } return auth } diff --git a/sdk/cliproxy/auth/conductor_allowed_auths_test.go b/sdk/cliproxy/auth/conductor_allowed_auths_test.go new file mode 100644 index 00000000000..75e62ca2f60 --- /dev/null +++ b/sdk/cliproxy/auth/conductor_allowed_auths_test.go @@ -0,0 +1,383 @@ +package auth + +import ( + "context" + "errors" + "fmt" + "net/http" + "reflect" + "strings" + "testing" + + "github.com/gin-gonic/gin" + internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executionregistry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +type allowedAuthsFixture struct { + manager *Manager + executor *afterAuthTestExecutor + provider string + model string +} + +// newAllowedAuthsFixture registers cred-a (best priority), cred-b and cred-c, each with a file name. +func newAllowedAuthsFixture(t *testing.T, selector Selector) *allowedAuthsFixture { + t.Helper() + name := strings.ToLower(strings.ReplaceAll(t.Name(), "/", "-")) + provider := "allowed-auths-" + name + model := "allowed-auths-model-" + name + executor := &afterAuthTestExecutor{id: provider, failByAuth: map[string]error{}} + manager := NewManager(nil, selector, nil) + manager.SetRetryConfig(3, 0, 10) + manager.RegisterExecutor(executor) + for i, id := range []string{"cred-a", "cred-b", "cred-c"} { + registry.GetGlobalRegistry().RegisterClient(id, provider, []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(id) }) + _, errReg := manager.Register(WithSkipPersist(context.Background()), &Auth{ + ID: id, FileName: id + ".json", Provider: provider, Status: StatusActive, + Attributes: map[string]string{"priority": fmt.Sprint(10 - i)}, + }) + if errReg != nil { + t.Fatal(errReg) + } + } + return &allowedAuthsFixture{manager: manager, executor: executor, provider: provider, model: model} +} + +func (f *allowedAuthsFixture) run(mode string, allowed any) ([]byte, error) { + opts := cliproxyexecutor.Options{} + if allowed != nil { + opts.Metadata = map[string]any{cliproxyexecutor.AllowedAuthsMetadataKey: allowed} + } + return invokeAfterAuthMode(f.manager, f.provider, f.model, mode, opts) +} + +var errUpstream500 = &Error{Code: "upstream", Message: "boom", Retryable: true, HTTPStatus: http.StatusInternalServerError} + +func TestAllowedAuthsRestrictSelectionAcrossModesAndSelectors(t *testing.T) { + selectors := map[string]func() Selector{ + "fill-first": func() Selector { return &FillFirstSelector{} }, + "round-robin": func() Selector { return &RoundRobinSelector{} }, + } + for selName, newSelector := range selectors { + for _, mode := range []string{"execute", "count", "stream"} { + t.Run(selName+"/"+mode, func(t *testing.T) { + f := newAllowedAuthsFixture(t, newSelector()) + for range 4 { + payload, err := f.run(mode, []string{"cred-b.json"}) + if err != nil { + t.Fatal(err) + } + if len(payload) == 0 || string(payload[len(payload)-6:]) != "cred-b" { + t.Fatalf("payload %q was not served by cred-b", payload) + } + } + for _, id := range f.executor.Calls() { + if id != "cred-b" { + t.Fatalf("credential %s used outside the allowed set: %v", id, f.executor.Calls()) + } + } + }) + } + } +} + +func TestAllowedAuthsMatchByIDAndFileName(t *testing.T) { + f := newAllowedAuthsFixture(t, &FillFirstSelector{}) + if _, err := f.run("execute", []string{"cred-c"}); err != nil { + t.Fatal(err) + } + if _, err := f.run("execute", []string{"cred-b.json", "unknown"}); err != nil { + t.Fatal(err) + } + if got, want := f.executor.Calls(), []string{"cred-c", "cred-b"}; !reflect.DeepEqual(got, want) { + t.Fatalf("calls = %v, want %v", got, want) + } + // Matching is exact: no case folding and no basename matching. + for _, ref := range []string{"CRED-B.JSON", "cred-b", "dir/cred-b.json"} { + if ref == "cred-b" { + continue // matches the ID, so it is a valid reference. + } + if _, err := f.run("execute", []string{ref}); err == nil { + t.Fatalf("reference %q must not match", ref) + } + } +} + +func TestAllowedAuthsFailoverNeverLeavesTheAllowedSet(t *testing.T) { + for _, mode := range []string{"execute", "count", "stream"} { + t.Run(mode, func(t *testing.T) { + f := newAllowedAuthsFixture(t, &FillFirstSelector{}) + f.executor.failByAuth["cred-b"] = errUpstream500 + payload, err := f.run(mode, []string{"cred-b.json", "cred-c.json"}) + if err != nil || string(payload[len(payload)-6:]) != "cred-c" { + t.Fatalf("payload=%q err=%v, want failover to cred-c", payload, err) + } + + f = newAllowedAuthsFixture(t, &FillFirstSelector{}) + f.executor.failByAuth["cred-b"] = errUpstream500 + f.executor.failByAuth["cred-c"] = errUpstream500 + if _, err = f.run(mode, []string{"cred-b.json", "cred-c.json"}); err == nil { + t.Fatal("expected an error once every allowed credential failed") + } + for _, id := range f.executor.Calls() { + if id == "cred-a" { + t.Fatalf("failover escaped to cred-a: %v", f.executor.Calls()) + } + } + }) + } +} + +func TestAllowedAuthsEmptyIntersectionFailsInsteadOfFallingBack(t *testing.T) { + f := newAllowedAuthsFixture(t, &FillFirstSelector{}) + if _, err := f.run("execute", []string{"not-a-credential.json"}); err == nil { + t.Fatal("expected an error when no credential matches the binding") + } + if calls := f.executor.Calls(); len(calls) != 0 { + t.Fatalf("a credential was used: %v", calls) + } +} + +func TestAllowedAuthsUnparsableRestrictionFailsClosed(t *testing.T) { + f := newAllowedAuthsFixture(t, &FillFirstSelector{}) + for name, restriction := range map[string]any{"non-string item": []any{1}, "wrong type": 7, "blank items": []string{" "}} { + if _, err := f.run("execute", restriction); err == nil { + t.Fatalf("%s: expected an error", name) + } + } + if calls := f.executor.Calls(); len(calls) != 0 { + t.Fatalf("a credential was used: %v", calls) + } +} + +func TestUnboundRequestsAreUnchanged(t *testing.T) { + f := newAllowedAuthsFixture(t, &FillFirstSelector{}) + for _, restriction := range []any{nil, []string{}, []any{}} { + if _, err := f.run("execute", restriction); err != nil { + t.Fatal(err) + } + } + if got, want := f.executor.Calls(), []string{"cred-a", "cred-a", "cred-a"}; !reflect.DeepEqual(got, want) { + t.Fatalf("calls = %v, want %v", got, want) + } +} + +func TestAllowedAuthsPinnedOutsideTheSetIsRejected(t *testing.T) { + f := newAllowedAuthsFixture(t, &FillFirstSelector{}) + opts := cliproxyexecutor.Options{Metadata: map[string]any{ + cliproxyexecutor.PinnedAuthMetadataKey: "cred-a", + cliproxyexecutor.AllowedAuthsMetadataKey: []string{"cred-b.json"}, + }} + _, _, err := f.manager.pickNextLegacy(context.Background(), f.provider, f.model, opts, nil) + var authErr *Error + if !errors.As(err, &authErr) || authErr.Code != "auth_not_found" { + t.Fatalf("err = %v, want auth_not_found", err) + } + opts.Metadata[cliproxyexecutor.PinnedAuthMetadataKey] = "cred-b" + if auth, _, errPick := f.manager.pickNextLegacy(context.Background(), f.provider, f.model, opts, nil); errPick != nil || auth.ID != "cred-b" { + t.Fatalf("pinned allowed credential: auth=%v err=%v", auth, errPick) + } +} + +func TestAllowedAuthsSessionAffinityOwnerOutsideTheSetIsNotUsed(t *testing.T) { + sticky := NewSessionAffinitySelector(&FillFirstSelector{}) + t.Cleanup(sticky.Stop) + f := newAllowedAuthsFixture(t, sticky) + headers := http.Header{"Session_id": {"bound-session"}} + run := func(allowed []string) string { + opts := cliproxyexecutor.Options{Headers: headers} + if allowed != nil { + opts.Metadata = map[string]any{cliproxyexecutor.AllowedAuthsMetadataKey: allowed} + } + payload, err := invokeAfterAuthMode(f.manager, f.provider, f.model, "execute", opts) + if err != nil { + t.Fatal(err) + } + return string(payload[len(payload)-6:]) + } + if got := run(nil); got != "cred-a" { + t.Fatalf("unrestricted session served by %s, want cred-a", got) + } + // The same session now arrives with a key bound elsewhere: the sticky owner must not leak. + for range 3 { + if got := run([]string{"cred-b.json"}); got != "cred-b" { + t.Fatalf("bound session served by %s, want cred-b", got) + } + } +} + +func TestAllowedAuthsFallbackReadsGinContext(t *testing.T) { + f := newAllowedAuthsFixture(t, &FillFirstSelector{}) + gc, _ := gin.CreateTestContext(nil) + gc.Set(sdkaccess.AllowedAuthsContextKey, []string{"cred-c.json"}) + ctx := context.WithValue(context.Background(), "gin", gc) + resp, err := f.manager.Execute(ctx, []string{f.provider}, cliproxyexecutor.Request{Model: f.model}, cliproxyexecutor.Options{}) + if err != nil || string(resp.Payload) != "ok:cred-c" { + t.Fatalf("payload=%q err=%v, want cred-c", resp.Payload, err) + } + gc.Set(sdkaccess.AllowedAuthsContextKey, "unreadable") + if _, err = f.manager.Execute(ctx, []string{f.provider}, cliproxyexecutor.Request{Model: f.model}, cliproxyexecutor.Options{}); err == nil { + t.Fatal("an unreadable gin restriction must fail closed") + } +} + +func TestAllowedAuthsTypedNilGinContextIsUnrestrictedAndDoesNotPanic(t *testing.T) { + f := newAllowedAuthsFixture(t, &FillFirstSelector{}) + ctx := context.WithValue(context.Background(), "gin", (*gin.Context)(nil)) + resp, err := f.manager.Execute(ctx, []string{f.provider}, cliproxyexecutor.Request{Model: f.model}, cliproxyexecutor.Options{}) + if err != nil || len(resp.Payload) == 0 { + t.Fatalf("typed-nil gin context: payload=%q err=%v, want unrestricted success", resp.Payload, err) + } +} + +// The Codex alpha-search and realtime paths select a credential directly, with nothing but +// the gin request in ctx. The key's restriction must still bound that selection. +func TestAllowedAuthsGinOnlyContextBoundsDirectSelection(t *testing.T) { + manager := NewManager(nil, &RoundRobinSelector{}, nil) + manager.executors["codex"] = schedulerTestExecutor{} + for _, id := range []string{"alpha-a", "alpha-b"} { + if _, errRegister := manager.Register(WithSkipPersist(context.Background()), &Auth{ + ID: id, FileName: id + ".json", Provider: "codex", Status: StatusActive, + Attributes: map[string]string{AttributeAPIKey: id, AttributeCodexAlphaSearch: "true", "base_url": "https://codex.example.com"}, + }); errRegister != nil { + t.Fatalf("Register(%s) error = %v", id, errRegister) + } + } + ginCtx := func(restriction any) context.Context { + gc, _ := gin.CreateTestContext(nil) + if restriction != nil { + gc.Set(sdkaccess.AllowedAuthsContextKey, restriction) + } + return context.WithValue(context.Background(), "gin", gc) + } + pick := func(ctx context.Context) (string, error) { + selected, err := manager.SelectAuthWithCredentialPolicy(ctx, "codex", "", CredentialPolicyCodexAlphaSearchV1, cliproxyexecutor.Options{}) + if err != nil { + return "", err + } + return selected.ID, nil + } + + bound := ginCtx([]string{"alpha-b.json"}) + for i := range 6 { + if got, err := pick(bound); err != nil || got != "alpha-b" { + t.Fatalf("pick %d = %q, %v; want alpha-b only", i, got, err) + } + } + // Control: without a restriction the same pool rotates over both credentials. + seen := map[string]bool{} + open := ginCtx(nil) + for range 6 { + got, err := pick(open) + if err != nil { + t.Fatal(err) + } + seen[got] = true + } + if !seen["alpha-a"] || !seen["alpha-b"] { + t.Fatalf("unrestricted pool served by %v, want both", seen) + } + if got, err := pick(ginCtx([]string{"missing.json"})); err == nil { + t.Fatalf("a key bound to a missing credential selected %q", got) + } + if got, err := pick(ginCtx("unreadable")); err == nil { + t.Fatalf("an unreadable restriction selected %q", got) + } +} + +func TestAuthAllowedByRefs(t *testing.T) { + auth := &Auth{ID: "id-1", FileName: "team/work.json"} + for refs, want := range map[string]bool{"": true, "id-1": true, "team/work.json": true, " team/work.json ": true, "work.json": false, "other": false} { + var list []string + if refs != "" { + list = []string{refs} + } + if got := AuthAllowedByRefs(auth, list); got != want { + t.Fatalf("AuthAllowedByRefs(%q) = %t, want %t", refs, got, want) + } + } + if AuthAllowedByRefs(nil, []string{"x"}) { + t.Fatal("nil auth must not be allowed") + } +} + +func TestHomeModeRefusesBoundKeys(t *testing.T) { + provider := "home-bound-key" + model := "home-bound-model" + executor := &afterAuthTestExecutor{id: provider} + manager := NewManager(nil, &FillFirstSelector{}, nil) + manager.SetConfig(&internalconfig.Config{Home: internalconfig.HomeConfig{Enabled: true}}) + manager.RegisterExecutor(executor) + dispatcher := &retryContractHomeDispatcher{authIDs: []string{"cred-a"}} + manager.PublishHomeDispatch(dispatcher, executionregistry.New(), 1) + + opts := cliproxyexecutor.Options{Metadata: map[string]any{cliproxyexecutor.AllowedAuthsMetadataKey: []string{"cred-a.json"}}} + _, err := invokeAfterAuthMode(manager, provider, model, "execute", opts) + var authErr *Error + if !errors.As(err, &authErr) || authErr.Code != "api_key_auth_binding_unsupported" || authErr.HTTPStatus != http.StatusForbidden { + t.Fatalf("err = %v, want api_key_auth_binding_unsupported", err) + } + if calls := executor.Calls(); len(calls) != 0 { + t.Fatalf("a credential was used: %v", calls) + } +} + +// A session binding made by any key, bound or not, is only a preference: a request from +// another key bound to a different set must never follow it out of that set. +func TestAllowedAuthsSessionAffinityBindingFromAnyKeyNeverLeaksIntoABoundSet(t *testing.T) { + creators := map[string][]string{ + "unrestricted key": nil, + "key bound elsewhere": {"cred-c.json"}, + "key bound to a subset": {"cred-a.json", "cred-c.json"}, + } + for name, creatorAllowed := range creators { + for _, mode := range []string{"execute", "count", "stream"} { + t.Run(name+"/"+mode, func(t *testing.T) { + sticky := NewSessionAffinitySelector(&FillFirstSelector{}) + t.Cleanup(sticky.Stop) + f := newAllowedAuthsFixture(t, sticky) + headers := http.Header{"Session_id": {"shared-session"}} + run := func(allowed []string) (string, error) { + opts := cliproxyexecutor.Options{Headers: headers} + if allowed != nil { + opts.Metadata = map[string]any{cliproxyexecutor.AllowedAuthsMetadataKey: allowed} + } + payload, err := invokeAfterAuthMode(f.manager, f.provider, f.model, mode, opts) + if err != nil { + return "", err + } + return string(payload[len(payload)-6:]), nil + } + owner, err := run(creatorAllowed) + if err != nil { + t.Fatal(err) + } + if owner == "cred-b" { + t.Fatalf("creator %s was served by cred-b, the fixture needs the owner outside {cred-b}", name) + } + for range 3 { + got, err := run([]string{"cred-b.json"}) + if err != nil || got != "cred-b" { + t.Fatalf("bound request served by %q (err=%v), want cred-b", got, err) + } + } + // The binding the bound key made must not drag the creator's own traffic out + // of the creator's set either. + if creatorAllowed != nil { + got, err := run(creatorAllowed) + if err != nil { + t.Fatal(err) + } + if got == "cred-b" { + t.Fatalf("creator restricted to %v was served by cred-b", creatorAllowed) + } + } + }) + } + } +} diff --git a/sdk/cliproxy/auth/conductor_execution.go b/sdk/cliproxy/auth/conductor_execution.go index 3295f4b53a3..3ba6e10b242 100644 --- a/sdk/cliproxy/auth/conductor_execution.go +++ b/sdk/cliproxy/auth/conductor_execution.go @@ -22,9 +22,11 @@ import ( "github.com/MoeForge/moego/json" "github.com/MoeForge/moego/ojson" + "github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v8/internal/logging" "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" "github.com/router-for-me/CLIProxyAPI/v8/internal/util" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" cliproxysession "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/session" coreusage "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/usage" @@ -3293,6 +3295,112 @@ func disallowFreeAuthFromMetadata(meta map[string]any) bool { } } +// allowedAuthsFromMetadata parses the client-key credential restriction. It returns nil +// when the request is unrestricted. A restriction that cannot be parsed fails closed by +// returning an empty, non-nil set. +func allowedAuthsFromMetadata(meta map[string]any) map[string]struct{} { + if len(meta) == 0 { + return nil + } + raw, ok := meta[cliproxyexecutor.AllowedAuthsMetadataKey] + if !ok || raw == nil { + return nil + } + var refs []string + switch val := raw.(type) { + case []string: + refs = val + case []any: + for _, item := range val { + ref, isString := item.(string) + if !isString { + return map[string]struct{}{} + } + refs = append(refs, ref) + } + default: + return map[string]struct{}{} + } + set := make(map[string]struct{}, len(refs)) + for _, ref := range refs { + if trimmed := strings.TrimSpace(ref); trimmed != "" { + set[trimmed] = struct{}{} + } + } + if len(set) == 0 && len(refs) == 0 { + return nil + } + return set +} + +// allowedAuthsForRequest returns the client-key credential restriction of a request. It +// reads the execution metadata first and falls back to the authenticated request carried +// by ctx, so selections made outside the regular handler path stay restricted too. +func allowedAuthsForRequest(ctx context.Context, meta map[string]any) map[string]struct{} { + if set := allowedAuthsFromMetadata(meta); set != nil { + return set + } + if ctx == nil { + return nil + } + carrier := ctx.Value("gin") + if concrete, isGin := carrier.(*gin.Context); isGin && concrete == nil { + // A typed nil is non-nil as an interface and would panic inside Get. + return nil + } + ginCtx, ok := carrier.(interface{ Get(string) (any, bool) }) + if !ok || ginCtx == nil { + return nil + } + value, exists := ginCtx.Get(sdkaccess.AllowedAuthsContextKey) + if !exists { + return nil + } + if value == nil { + return nil + } + refs, isRefs := value.([]string) + if !isRefs { + // An unreadable restriction must not widen access. + return map[string]struct{}{} + } + if len(refs) == 0 { + return nil + } + return allowedAuthsFromMetadata(map[string]any{cliproxyexecutor.AllowedAuthsMetadataKey: refs}) +} + +// AuthAllowedByRefs reports whether the credential is permitted by a client-key restriction +// given as credential IDs or file names. An empty restriction permits every credential. +func AuthAllowedByRefs(auth *Auth, refs []string) bool { + if len(refs) == 0 { + return true + } + set := make(map[string]struct{}, len(refs)) + for _, ref := range refs { + if trimmed := strings.TrimSpace(ref); trimmed != "" { + set[trimmed] = struct{}{} + } + } + return authMatchesAllowedSet(set, auth) +} + +// authMatchesAllowedSet reports whether the credential ID or file name is in the set. +func authMatchesAllowedSet(set map[string]struct{}, auth *Auth) bool { + if auth == nil { + return false + } + if _, ok := set[auth.ID]; ok { + return true + } + if name := strings.TrimSpace(auth.FileName); name != "" { + if _, ok := set[name]; ok { + return true + } + } + return false +} + func isFreeCodexAuth(auth *Auth) bool { if auth == nil || auth.Attributes == nil { return false diff --git a/sdk/cliproxy/auth/conductor_home.go b/sdk/cliproxy/auth/conductor_home.go index d70b5276da9..d8b6e5c32d6 100644 --- a/sdk/cliproxy/auth/conductor_home.go +++ b/sdk/cliproxy/auth/conductor_home.go @@ -1015,6 +1015,15 @@ func (m *Manager) pickHomeDispatchSelection(ctx context.Context, model string, o if m == nil { return nil, &Error{Code: "auth_not_found", Message: "no auth available"} } + if allowedAuthsForRequest(ctx, opts.Metadata) != nil { + // Home chooses the credential on its own side and cannot enforce a + // per-key credential binding, so a bound key must not be dispatched. + return nil, &Error{ + Code: "api_key_auth_binding_unsupported", + Message: "api key credential binding is not supported in home mode", + HTTPStatus: http.StatusForbidden, + } + } if ctx == nil { ctx = context.Background() } diff --git a/sdk/cliproxy/auth/conductor_selection.go b/sdk/cliproxy/auth/conductor_selection.go index a32845142d5..9d3cbd4568d 100644 --- a/sdk/cliproxy/auth/conductor_selection.go +++ b/sdk/cliproxy/auth/conductor_selection.go @@ -102,6 +102,9 @@ type authSelectionEligibility struct { requiredKind string credentialPolicy string disallowFreeAuth bool + // allowedAuths restricts selection to credentials whose ID or file name is in + // the set. A nil set means no restriction; a non-nil empty set allows nothing. + allowedAuths map[string]struct{} } func withRequiredAuthKind(ctx context.Context, requiredKind string) context.Context { @@ -121,7 +124,10 @@ func credentialPolicyFromContext(ctx context.Context) string { } func authSelectionEligibilityForRequest(ctx context.Context, opts cliproxyexecutor.Options) authSelectionEligibility { - eligibility := authSelectionEligibility{disallowFreeAuth: disallowFreeAuthFromMetadata(opts.Metadata)} + eligibility := authSelectionEligibility{ + disallowFreeAuth: disallowFreeAuthFromMetadata(opts.Metadata), + allowedAuths: allowedAuthsForRequest(ctx, opts.Metadata), + } if ctx != nil { eligibility.requiredKind, _ = ctx.Value(requiredAuthKindContextKey{}).(string) eligibility.credentialPolicy, _ = ctx.Value(credentialPolicyContextKey{}).(string) @@ -139,6 +145,9 @@ func (e authSelectionEligibility) allows(auth *Auth) bool { if e.credentialPolicy != "" && !credentialPolicyAllows(e.credentialPolicy, auth) { return false } + if e.allowedAuths != nil && !authMatchesAllowedSet(e.allowedAuths, auth) { + return false + } return !e.disallowFreeAuth || !isFreeCodexAuth(auth) } @@ -2085,6 +2094,29 @@ func (m *Manager) List() []*Auth { return list } +// AllowedAuthIDs resolves client-key credential references (credential IDs or file names) +// to the IDs of the credentials currently registered. The result is never nil. +func (m *Manager) AllowedAuthIDs(refs []string) map[string]struct{} { + set := make(map[string]struct{}, len(refs)) + for _, ref := range refs { + if trimmed := strings.TrimSpace(ref); trimmed != "" { + set[trimmed] = struct{}{} + } + } + ids := make(map[string]struct{}) + if m == nil || len(set) == 0 { + return ids + } + m.mu.RLock() + defer m.mu.RUnlock() + for id, auth := range m.auths { + if authMatchesAllowedSet(set, auth) { + ids[id] = struct{}{} + } + } + return ids +} + // IDsByProvider returns matching credential IDs without cloning unrelated auth state. func (m *Manager) IDsByProvider(provider string) []string { m.mu.RLock() diff --git a/sdk/cliproxy/builder.go b/sdk/cliproxy/builder.go index 2f74cd1aac9..2b9a9850b87 100644 --- a/sdk/cliproxy/builder.go +++ b/sdk/cliproxy/builder.go @@ -252,6 +252,9 @@ func (b *Builder) Build() (*Service, error) { if errValidate := b.cfg.ValidateCredentialWeights(); errValidate != nil { return nil, fmt.Errorf("cliproxy: validate credential weights: %w", errValidate) } + if errValidate := b.cfg.ValidateAPIKeys(); errValidate != nil { + return nil, fmt.Errorf("cliproxy: validate api-keys: %w", errValidate) + } b.cfg.NormalizePluginsConfig() if errResolvePluginsDir := b.cfg.ResolvePluginsDir(); errResolvePluginsDir != nil && b.cfg.Plugins.Enabled { return nil, fmt.Errorf("cliproxy: %w", errResolvePluginsDir) diff --git a/sdk/cliproxy/executor/types.go b/sdk/cliproxy/executor/types.go index 04cd2a6a47d..c0c49f23473 100644 --- a/sdk/cliproxy/executor/types.go +++ b/sdk/cliproxy/executor/types.go @@ -24,6 +24,10 @@ const TraceIDMetadataKey = "trace_id" // DisallowFreeAuthMetadataKey instructs auth selection to skip known free-tier credentials. const DisallowFreeAuthMetadataKey = "disallow_free_auth" +// AllowedAuthsMetadataKey restricts auth selection to the listed credentials. Each item +// matches a credential ID or file name. Missing or empty means no restriction. +const AllowedAuthsMetadataKey = "allowed_auths" + // AuthSelectionModelMetadataKey overrides the model used only for auth selection. const AuthSelectionModelMetadataKey = "auth_selection_model" diff --git a/sdk/cliproxy/service_config.go b/sdk/cliproxy/service_config.go index 880f2603579..1781a26546f 100644 --- a/sdk/cliproxy/service_config.go +++ b/sdk/cliproxy/service_config.go @@ -164,6 +164,10 @@ func (s *Service) commitConfigUpdate(newCfg *config.Config) configCommit { log.WithError(errValidate).Warn("rejected config update with invalid credential weights") return configCommit{} } + if errValidate := newCfg.ValidateAPIKeys(); errValidate != nil { + log.WithError(errValidate).Warn("rejected config update with invalid api-keys") + return configCommit{} + } if errValidate := newCfg.Models.Validate(); errValidate != nil { log.WithError(errValidate).Warn("rejected invalid model catalog sources") diff --git a/sdk/cliproxy/service_config_api_keys_test.go b/sdk/cliproxy/service_config_api_keys_test.go new file mode 100644 index 00000000000..ddcbe62d724 --- /dev/null +++ b/sdk/cliproxy/service_config_api_keys_test.go @@ -0,0 +1,23 @@ +package cliproxy + +import ( + "testing" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +// A hot reload that lists one client key twice must be refused, so the running +// configuration keeps its unambiguous key bindings. +func TestConfigUpdateRejectsDuplicateAPIKeys(t *testing.T) { + oldCfg := &config.Config{SDKConfig: config.SDKConfig{APIKeys: []config.APIKeyEntry{{Key: "k", Auths: []string{"a.json"}}}}} + service := &Service{cfg: oldCfg, coreManager: coreauth.NewManager(nil, nil, nil)} + + dup := &config.Config{SDKConfig: config.SDKConfig{APIKeys: []config.APIKeyEntry{{Key: "k"}, {Key: "k", Auths: []string{"a.json"}}}}} + if commit := service.commitConfigUpdate(dup); commit.cfg != nil { + t.Fatal("a config with a duplicated api key was committed") + } + if service.cfg != oldCfg { + t.Fatal("the running config changed after a rejected update") + } +} diff --git a/sdk/config/config.go b/sdk/config/config.go index 11d965d551e..668d3812426 100644 --- a/sdk/config/config.go +++ b/sdk/config/config.go @@ -8,6 +8,8 @@ import internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" type SDKConfig = internalconfig.SDKConfig +type APIKeyEntry = internalconfig.APIKeyEntry + type Config = internalconfig.Config type ModelCatalogs = internalconfig.ModelCatalogs