Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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())
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/server/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
},
}

Expand Down
21 changes: 21 additions & 0 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion docs/management-api-v8.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
4 changes: 4 additions & 0 deletions docs/sdk-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
82 changes: 66 additions & 16 deletions internal/access/config_access/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}
}
Expand Down Expand Up @@ -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,
},
Expand All @@ -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
}
91 changes: 91 additions & 0 deletions internal/access/config_access/provider_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
Loading