diff --git a/internal/admin/server.go b/internal/admin/server.go index 6b83706..615f1fc 100644 --- a/internal/admin/server.go +++ b/internal/admin/server.go @@ -142,9 +142,10 @@ type ConfigView struct { GoKeys []SecretView `json:"go_keys"` Anonymous bool `json:"anonymous"` Warp config.WarpConfig `json:"warp"` - Proxies []SecretView `json:"proxies"` - ProxyFile string `json:"proxyfile"` - Upstream config.UpstreamConfig `json:"upstream"` + Proxies []SecretView `json:"proxies"` + ProxyFile string `json:"proxyfile"` + ProxyBindings map[string]string `json:"proxy_bindings,omitempty"` + Upstream config.UpstreamConfig `json:"upstream"` Retry config.RetryConfig `json:"retry"` Models config.ModelsConfig `json:"models"` Performance config.PerformanceConfig `json:"performance"` @@ -190,9 +191,10 @@ type ConfigUpdate struct { GoKeys []SecretInput `json:"go_keys"` Anonymous bool `json:"anonymous"` Warp config.WarpConfig `json:"warp"` - Proxies []SecretInput `json:"proxies"` - ProxyFile string `json:"proxyfile"` - Upstream config.UpstreamConfig `json:"upstream"` + Proxies []SecretInput `json:"proxies"` + ProxyFile string `json:"proxyfile"` + ProxyBindings map[string]string `json:"proxy_bindings,omitempty"` + Upstream config.UpstreamConfig `json:"upstream"` Retry config.RetryConfig `json:"retry"` Models config.ModelsConfig `json:"models"` Performance config.PerformanceConfig `json:"performance"` @@ -245,10 +247,15 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { if update.Reasoning != nil { reasoning = *update.Reasoning } + proxyBindings := current.ProxyBindings + if update.ProxyBindings != nil { + proxyBindings = update.ProxyBindings + } candidate := config.Config{ ServerKeyMetadata: current.ServerKeyMetadata, Rotation: current.Rotation, Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Warp: update.Warp, Proxies: proxies, ProxyFile: update.ProxyFile, + ProxyBindings: proxyBindings, Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer, Reasoning: reasoning, WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes}, @@ -391,7 +398,7 @@ func (a *Server) configView() ConfigView { effective, restart := a.manager.RestartStatus() return ConfigView{ Listen: cfg.Listen, ServerKeys: maskSecrets(cfg.ServerKeys, false), ZenKeys: maskSecrets(cfg.ZenKeys, false), GoKeys: maskSecrets(cfg.GoKeys, false), Anonymous: cfg.Anonymous, Warp: cfg.Warp, - Proxies: maskSecrets(cfg.Proxies, true), ProxyFile: cfg.ProxyFile, Upstream: cfg.Upstream, Retry: cfg.Retry, Models: cfg.Models, + Proxies: maskSecrets(cfg.Proxies, true), ProxyFile: cfg.ProxyFile, ProxyBindings: cfg.ProxyBindings, Upstream: cfg.Upstream, Retry: cfg.Retry, Models: cfg.Models, Performance: cfg.Performance, Logging: cfg.Logging, Prefer: cfg.Prefer, Reasoning: cfg.Reasoning, WebUI: WebUIView{Enabled: cfg.WebUI.Enabled, Listen: cfg.WebUI.Listen, Username: cfg.WebUI.Username, SessionTTLMinutes: cfg.WebUI.SessionTTLMinutes}, Effective: EffectiveView{Listen: effective.API, WebUIListen: effective.WebUI, WebUIEnabled: effective.WebUIEnabled}, diff --git a/internal/config/binding_test.go b/internal/config/binding_test.go new file mode 100644 index 0000000..5a7c0c9 --- /dev/null +++ b/internal/config/binding_test.go @@ -0,0 +1,185 @@ +package config + +import ( + "encoding/json" + "strings" + "testing" +) + +func sampleConfig() Config { + return Config{ + Listen: "127.0.0.1:8080", + ServerKeys: []string{"sk-local-test-key-1"}, + ZenKeys: []string{"zen-cred-alpha-12345", "zen-cred-beta-67890"}, + GoKeys: []string{"go-cred-gamma-11111"}, + Proxies: []string{"http://127.0.0.1:18090", "http://127.0.0.1:18091", "direct"}, + Upstream: UpstreamConfig{ + Zen: "https://opencode.ai/zen", + Go: "https://opencode.ai/go", + Anonymous: "https://opencode.ai/inference", + }, + Retry: RetryConfig{ + MaxAttempts: 3, + TimeoutSeconds: 30, + }, + Models: ModelsConfig{ + RefreshSeconds: 300, + }, + Performance: PerformanceConfig{ + MaxIdleConns: 10, + MaxIdleConnsPerHost: 5, + IdleConnTimeoutSeconds: 30, + ConnectTimeoutSeconds: 5, + FailureCooldownSeconds: 15, + }, + Logging: LoggingConfig{ + Level: "info", + RingSize: 1000, + }, + Prefer: TierGo, + } +} + +func TestNormalizeProxyBindings_Valid(t *testing.T) { + cfg := sampleConfig() + zenAlphaFP := Fingerprint(cfg.ZenKeys[0]) + cfg.ProxyBindings = map[string]string{ + zenAlphaFP: "http://127.0.0.1:18090", + // Key by raw value, should be canonicalized to its fingerprint + "zen-cred-beta-67890": "http://127.0.0.1:18091", + // Go key bound to direct + "go-cred-gamma-11111": "direct", + } + + norm, err := Normalize("", cfg) + if err != nil { + t.Fatalf("Normalize failed: %v", err) + } + + zenBetaFP := Fingerprint("zen-cred-beta-67890") + goGammaFP := Fingerprint("go-cred-gamma-11111") + + if got := norm.ProxyBindings[zenAlphaFP]; got != "http://127.0.0.1:18090" { + t.Errorf("zenAlpha proxy: got %q, want %q", got, "http://127.0.0.1:18090") + } + if got := norm.ProxyBindings[zenBetaFP]; got != "http://127.0.0.1:18091" { + t.Errorf("zenBeta proxy: got %q, want %q", got, "http://127.0.0.1:18091") + } + if got := norm.ProxyBindings[goGammaFP]; got != "direct" { + t.Errorf("goGamma proxy: got %q, want %q", got, "direct") + } + // Raw key string must not be kept in the map + if _, exists := norm.ProxyBindings["zen-cred-beta-67890"]; exists { + t.Errorf("raw secret key was kept in ProxyBindings map") + } +} + +func TestNormalizeProxyBindings_UnknownKeyRejected(t *testing.T) { + cfg := sampleConfig() + cfg.ProxyBindings = map[string]string{ + "unknown-secret-key": "http://127.0.0.1:18090", + } + + _, err := Normalize("", cfg) + if err == nil { + t.Fatalf("expected error for unknown key, got nil") + } + if !strings.Contains(err.Error(), "proxy_bindings contains reference to unknown key") { + t.Errorf("unexpected error message: %v", err) + } +} + +func TestNormalizeProxyBindings_UnknownProxyRejected(t *testing.T) { + cfg := sampleConfig() + cfg.ProxyBindings = map[string]string{ + "zen-cred-alpha-12345": "http://192.0.2.1:9999", + } + + _, err := Normalize("", cfg) + if err == nil { + t.Fatalf("expected error for unknown proxy, got nil") + } + if !strings.Contains(err.Error(), "proxy_bindings references unknown proxy") { + t.Errorf("unexpected error message: %v", err) + } +} + +func TestNormalizeProxyBindings_SecretNotExposedInJSON(t *testing.T) { + cfg := sampleConfig() + cfg.ProxyBindings = map[string]string{ + "zen-cred-alpha-12345": "http://127.0.0.1:18090", + } + norm, err := Normalize("", cfg) + if err != nil { + t.Fatalf("Normalize failed: %v", err) + } + + data, err := json.Marshal(norm) + if err != nil { + t.Fatalf("Marshal failed: %v", err) + } + jsonStr := string(data) + if strings.Contains(jsonStr, "zen-cred-alpha-12345") { + // Only zen_keys array should contain the secret, proxy_bindings must not! + type configCheck struct { + ProxyBindings map[string]string `json:"proxy_bindings"` + } + var check configCheck + if err := json.Unmarshal(data, &check); err != nil { + t.Fatalf("Unmarshal check failed: %v", err) + } + for k := range check.ProxyBindings { + if strings.Contains(k, "zen-cred") { + t.Errorf("raw secret leaked into serialized proxy_bindings key: %q", k) + } + } + } +} + +func TestNormalizeProxyBindings_ReorderingKeysPreservesBindings(t *testing.T) { + cfg := sampleConfig() + cfg.ProxyBindings = map[string]string{ + "zen-cred-alpha-12345": "http://127.0.0.1:18090", + "zen-cred-beta-67890": "http://127.0.0.1:18091", + } + + norm1, err := Normalize("", cfg) + if err != nil { + t.Fatalf("Normalize 1 failed: %v", err) + } + + // Reverse zen keys order + cfgReordered := sampleConfig() + cfgReordered.ZenKeys = []string{"zen-cred-beta-67890", "zen-cred-alpha-12345"} + cfgReordered.ProxyBindings = norm1.ProxyBindings + + norm2, err := Normalize("", cfgReordered) + if err != nil { + t.Fatalf("Normalize 2 failed: %v", err) + } + + fpAlpha := Fingerprint("zen-cred-alpha-12345") + fpBeta := Fingerprint("zen-cred-beta-67890") + + if norm2.ProxyBindings[fpAlpha] != norm1.ProxyBindings[fpAlpha] { + t.Errorf("alpha binding shifted after key reordering") + } + if norm2.ProxyBindings[fpBeta] != norm1.ProxyBindings[fpBeta] { + t.Errorf("beta binding shifted after key reordering") + } +} + +func TestClone_PreservesProxyBindings(t *testing.T) { + cfg := sampleConfig() + cfg.ProxyBindings = map[string]string{ + "fp-1": "http://127.0.0.1:18090", + } + cloned := Clone(cfg) + if cloned.ProxyBindings["fp-1"] != "http://127.0.0.1:18090" { + t.Errorf("Clone lost proxy bindings") + } + cloned.ProxyBindings["fp-2"] = "direct" + if _, exists := cfg.ProxyBindings["fp-2"]; exists { + t.Errorf("mutation of cloned map leaked to original") + } +} diff --git a/internal/config/config.go b/internal/config/config.go index afe5125..2a14eaa 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -36,6 +36,7 @@ type Config struct { Warp WarpConfig `json:"warp"` Proxies []string `json:"proxies"` ProxyFile string `json:"proxyfile"` + ProxyBindings map[string]string `json:"proxy_bindings,omitempty"` Upstream UpstreamConfig `json:"upstream"` Retry RetryConfig `json:"retry"` Models ModelsConfig `json:"models"` @@ -436,6 +437,9 @@ func Normalize(path string, cfg Config) (Config, error) { if err := normalizeReasoning(&cfg); err != nil { return Config{}, err } + if err := normalizeProxyBindings(&cfg); err != nil { + return Config{}, err + } return cfg, nil } @@ -566,5 +570,64 @@ func Clone(cfg Config) Config { } cfg.Reasoning.EffortByModel = efforts } + if cfg.ProxyBindings != nil { + bindings := make(map[string]string, len(cfg.ProxyBindings)) + for k, v := range cfg.ProxyBindings { + bindings[k] = v + } + cfg.ProxyBindings = bindings + } return cfg } + +// normalizeProxyBindings validates and canonicalizes explicit per-key proxy +// bindings. Keys are mapped to their 16-hex fingerprint so secrets are never +// stored twice, and target proxies must match a valid runtime proxy (or "direct"). +// Bound credentials fail closed: when their assigned proxy becomes unavailable, +// they do not migrate to another route. +// +// NOTE: Binding to a proxy route with a #pool fragment or an external rotator +// does not guarantee a static public egress IP; it pins traffic to that proxy transport. +func normalizeProxyBindings(cfg *Config) error { + if len(cfg.ProxyBindings) == 0 { + return nil + } + keyMap := make(map[string]string, len(cfg.ZenKeys)+len(cfg.GoKeys)) + for _, k := range cfg.ZenKeys { + fp := Fingerprint(k) + keyMap[k] = fp + keyMap[fp] = fp + } + for _, k := range cfg.GoKeys { + fp := Fingerprint(k) + keyMap[k] = fp + keyMap[fp] = fp + } + + knownProxies := make(map[string]string) + for _, raw := range cfg.RuntimeProxies() { + clean, _ := ParseProxyEntry(raw) + knownProxies[raw] = raw + knownProxies[clean] = raw + if clean == "direct" { + knownProxies["direct"] = "direct" + } + } + + normalized := make(map[string]string, len(cfg.ProxyBindings)) + for keyRef, proxyRef := range cfg.ProxyBindings { + trimmedKey := strings.TrimSpace(keyRef) + trimmedProxy := strings.TrimSpace(proxyRef) + fp, ok := keyMap[trimmedKey] + if !ok { + return fmt.Errorf("proxy_bindings contains reference to unknown key %q", MaskValue(trimmedKey)) + } + canonicalProxy, ok := knownProxies[trimmedProxy] + if !ok { + return fmt.Errorf("proxy_bindings references unknown proxy %q", RedactURL(trimmedProxy)) + } + normalized[fp] = canonicalProxy + } + cfg.ProxyBindings = normalized + return nil +} diff --git a/internal/gateway/binding_test.go b/internal/gateway/binding_test.go new file mode 100644 index 0000000..ba97df7 --- /dev/null +++ b/internal/gateway/binding_test.go @@ -0,0 +1,286 @@ +package gateway + +import ( + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "opencode2api/internal/config" +) + +func TestNodePool_PerKeyBinding(t *testing.T) { + transports := &proxyTransports{ + items: []*proxyTransport{ + {index: 0, name: "http://127.0.0.1:18090"}, + {index: 1, name: "http://127.0.0.1:18091"}, + {index: 2, name: "http://127.0.0.1:18092"}, + }, + } + for _, tr := range transports.items { + tr.healthy.Store(true) + } + + keys := []string{"key-alpha-12345", "key-beta-67890", "key-gamma-99999"} + alphaFP := config.Fingerprint(keys[0]) + + // Explicitly bind alpha to proxy 1 (index 1) and gamma to proxy 0 (index 0). + // beta is left unbound. + bindings := map[string]string{ + alphaFP: "http://127.0.0.1:18091", + keys[2]: "http://127.0.0.1:18090", // raw key lookup works too + } + + pool, err := nodePool(keys, transports, 15*time.Second, bindings) + if err != nil { + t.Fatalf("nodePool failed: %v", err) + } + + nodeAlpha := pool.nodes[0] + nodeBeta := pool.nodes[1] + nodeGamma := pool.nodes[2] + + if !nodeAlpha.bound || nodeAlpha.proxyIndex.Load() != 1 { + t.Errorf("nodeAlpha: want bound=true proxyIndex=1, got bound=%v proxyIndex=%d", nodeAlpha.bound, nodeAlpha.proxyIndex.Load()) + } + if nodeBeta.bound || nodeBeta.proxyIndex.Load() != 1 { // 1 % 3 = 1 + t.Errorf("nodeBeta: want bound=false proxyIndex=1, got bound=%v proxyIndex=%d", nodeBeta.bound, nodeBeta.proxyIndex.Load()) + } + if !nodeGamma.bound || nodeGamma.proxyIndex.Load() != 0 { + t.Errorf("nodeGamma: want bound=true proxyIndex=0, got bound=%v proxyIndex=%d", nodeGamma.bound, nodeGamma.proxyIndex.Load()) + } + + // Now fail proxy 1. + // nodeAlpha is bound to proxy 1 -> MUST NOT MOVE (fail-closed). + // nodeBeta is unbound on proxy 1 -> MUST MOVE to another healthy proxy (e.g. index 0 or 2). + moved := pool.RebindProxy(1) + if moved != 1 { + t.Errorf("RebindProxy(1): want moved=1 (only unbound node), got %d", moved) + } + + if nodeAlpha.proxyIndex.Load() != 1 { + t.Errorf("nodeAlpha moved during proxy failure: got %d, want 1 (fail-closed)", nodeAlpha.proxyIndex.Load()) + } + if nodeBeta.proxyIndex.Load() == 1 { + t.Errorf("nodeBeta was not moved away from failed proxy 1") + } + + // Simulate nodeAlpha failure & cooldown while proxy 1 is down. + nodeAlpha.failures.Store(3) + nodeAlpha.cooldownUntil.Store(time.Now().Add(10 * time.Minute).UnixNano()) + + // Now restore proxy 1. + // nodeAlpha should have failures and cooldown reset, remaining on proxy 1. + // nodeBeta should move back to proxy 1. + restoredMoved := pool.RestoreProxy(1) + if restoredMoved != 1 { + t.Errorf("RestoreProxy(1): want moved=1 (unbound node restored), got %d", restoredMoved) + } + + if nodeAlpha.proxyIndex.Load() != 1 { + t.Errorf("nodeAlpha: got proxyIndex=%d, want 1", nodeAlpha.proxyIndex.Load()) + } + if nodeAlpha.failures.Load() != 0 { + t.Errorf("nodeAlpha: failures not cleared upon proxy recovery: got %d", nodeAlpha.failures.Load()) + } + if nodeAlpha.cooldownUntil.Load() != 0 { + t.Errorf("nodeAlpha: cooldown not cleared upon proxy recovery") + } + if nodeBeta.proxyIndex.Load() != 1 { + t.Errorf("nodeBeta: failed to return to preferred proxy 1") + } +} + +func TestNodePool_ReorderingKeysPreservesBindings(t *testing.T) { + transports := &proxyTransports{ + items: []*proxyTransport{ + {index: 0, name: "http://127.0.0.1:18090"}, + {index: 1, name: "http://127.0.0.1:18091"}, + }, + } + for _, tr := range transports.items { + tr.healthy.Store(true) + } + + key1 := "zen-key-number-one" + key2 := "zen-key-number-two" + bindings := map[string]string{ + config.Fingerprint(key1): "http://127.0.0.1:18091", + } + + // Order A: [key1, key2] + poolA, err := nodePool([]string{key1, key2}, transports, 10*time.Second, bindings) + if err != nil { + t.Fatalf("poolA creation failed: %v", err) + } + + // Order B: [key2, key1] (reordered!) + poolB, err := nodePool([]string{key2, key1}, transports, 10*time.Second, bindings) + if err != nil { + t.Fatalf("poolB creation failed: %v", err) + } + + nodeAKey1 := poolA.NodeByID(config.Fingerprint(key1)) + nodeBKey1 := poolB.NodeByID(config.Fingerprint(key1)) + + if nodeAKey1.proxyIndex.Load() != 1 || nodeBKey1.proxyIndex.Load() != 1 { + t.Errorf("key1 binding differed across key reordering: A=%d B=%d", nodeAKey1.proxyIndex.Load(), nodeBKey1.proxyIndex.Load()) + } +} + +func TestKeyStatuses_ReportsBoundFieldWithoutSecrets(t *testing.T) { + transports := &proxyTransports{ + items: []*proxyTransport{ + {index: 0, name: "http://127.0.0.1:18090"}, + }, + } + transports.items[0].healthy.Store(true) + + secretKey := "super-secret-zen-key-xyz99" + bindings := map[string]string{ + config.Fingerprint(secretKey): "http://127.0.0.1:18090", + } + + pool, err := nodePool([]string{secretKey}, transports, 10*time.Second, bindings) + if err != nil { + t.Fatalf("nodePool failed: %v", err) + } + + statuses := keyStatuses("zen", pool) + if len(statuses) != 1 { + t.Fatalf("expected 1 status, got %d", len(statuses)) + } + st := statuses[0] + if !st.Bound { + t.Errorf("expected Bound=true") + } + if st.ID != "xyz99" { + t.Errorf("expected masked ID 'xyz99', got %q", st.ID) + } + // Raw key must not appear anywhere in ID + if st.ID == secretKey { + t.Errorf("raw key leaked into status ID") + } +} + +func TestGateway_BoundKeyFailsClosed(t *testing.T) { + // Setup 2 mock upstreams / proxies + var proxy1Calls, proxy2Calls atomic.Int64 + + server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + proxy1Calls.Add(1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"choices":[{"message":{"content":"response from proxy 1"}}]}`)) + })) + defer server1.Close() + + server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + proxy2Calls.Add(1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"choices":[{"message":{"content":"response from proxy 2"}}]}`)) + })) + defer server2.Close() + + cfg := config.Config{ + Listen: "127.0.0.1:8080", + ServerKeys: []string{"sk-local-test"}, + ZenKeys: []string{"zen-key-alpha", "zen-key-beta"}, + Proxies: []string{server1.URL, server2.URL}, + ProxyBindings: map[string]string{ + config.Fingerprint("zen-key-alpha"): server1.URL, + config.Fingerprint("zen-key-beta"): server2.URL, + }, + Upstream: config.UpstreamConfig{ + Zen: server1.URL, + Go: server1.URL, + Anonymous: server1.URL, + }, + Retry: config.RetryConfig{ + MaxAttempts: 2, + TimeoutSeconds: 5, + }, + Models: config.ModelsConfig{ + RefreshSeconds: 300, + }, + Performance: config.PerformanceConfig{ + MaxIdleConns: 10, + MaxIdleConnsPerHost: 5, + IdleConnTimeoutSeconds: 30, + ConnectTimeoutSeconds: 5, + FailureCooldownSeconds: 15, + }, + Logging: config.LoggingConfig{ + Level: "error", + RingSize: 1000, + }, + Prefer: config.TierZen, + } + + norm, err := config.Normalize("", cfg) + if err != nil { + t.Fatalf("Normalize failed: %v", err) + } + + gw, err := New(norm, nil, nil, nil) + if err != nil { + t.Fatalf("New gateway failed: %v", err) + } + + nodeAlpha := gw.zenNodes.NodeByID(config.Fingerprint("zen-key-alpha")) + if nodeAlpha == nil { + t.Fatalf("nodeAlpha not found") + } + + // Verify that nodeAlpha routes through server1.URL + p := gw.zenNodes.Proxy(nodeAlpha) + if p == nil || p.name != server1.URL { + t.Fatalf("nodeAlpha proxy want %s, got %v", server1.URL, p) + } + + // Simulate failure of server1 proxy + gw.transports.items[0].healthy.Store(false) + gw.rebindUnavailableProxy(gw.transports.items[0], true) + + // Verify nodeAlpha was NOT rebound to server2 + if gw.zenNodes.Proxy(nodeAlpha).name != server1.URL { + t.Errorf("fail-closed violation: nodeAlpha was moved to %s", gw.zenNodes.Proxy(nodeAlpha).name) + } + + // Restore server1 proxy + gw.transports.items[0].healthy.Store(true) + gw.restoreProxy(gw.transports.items[0]) + + if gw.zenNodes.Proxy(nodeAlpha).name != server1.URL { + t.Errorf("nodeAlpha did not stay on server1 after restore") + } +} + +func TestGateway_AnonymousUnaffectedByBindings(t *testing.T) { + transports := &proxyTransports{ + items: []*proxyTransport{ + {index: 0, name: "http://127.0.0.1:18090"}, + {index: 1, name: "http://127.0.0.1:18091"}, + }, + } + for _, tr := range transports.items { + tr.healthy.Store(true) + } + + anon := anonymousPool(true, transports, 10*time.Second, anonymousBackoff{}) + if anon.Len() != 2 { + t.Fatalf("expected 2 anonymous nodes, got %d", anon.Len()) + } + // Anonymous cursor visits all proxies round-robin regardless of key bindings + cursor := anon.CursorFor("") + n1 := cursor.Next() + n2 := cursor.Next() + if n1 == nil || n2 == nil { + t.Fatalf("anonymous cursor returned nil") + } + if n1.proxy.name == n2.proxy.name { + t.Errorf("anonymous cursor did not cycle proxies: got same proxy %s", n1.proxy.name) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 58ea342..e6a0cd1 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -101,6 +101,9 @@ type Gateway struct { // rotation manager is not persisted; RuntimeController replaces it with the // shared one. func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, warpPool *warp.Pool) (*Gateway, error) { + if logger == nil { + logger = slog.Default() + } cfg.Rotation.Defaults() rotationManager, err := rotation.New("", cfg.Rotation) if err != nil { @@ -111,11 +114,11 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, war return nil, err } cooldown := time.Duration(cfg.Performance.FailureCooldownSeconds) * time.Second - zenNodes, err := nodePool(cfg.ZenKeys, transports, cooldown) + zenNodes, err := nodePool(cfg.ZenKeys, transports, cooldown, cfg.ProxyBindings) if err != nil { return nil, fmt.Errorf("zen node pool: %w", err) } - goNodes, err := nodePool(cfg.GoKeys, transports, cooldown) + goNodes, err := nodePool(cfg.GoKeys, transports, cooldown, cfg.ProxyBindings) if err != nil { return nil, fmt.Errorf("go node pool: %w", err) } diff --git a/internal/gateway/pool.go b/internal/gateway/pool.go index 2e98859..c6b84b2 100644 --- a/internal/gateway/pool.go +++ b/internal/gateway/pool.go @@ -608,6 +608,7 @@ type upstreamNode struct { key string index int preferredProxy int + bound bool proxyIndex atomic.Int64 failures atomic.Uint32 cooldownUntil atomic.Int64 @@ -625,11 +626,11 @@ type upstreamNodes struct { bindingCount []int } -// nodePool distributes keys over proxies in round-robin order. When there -// are fewer keys than proxies, the remaining proxies are intentionally idle and -// can take over a key immediately if an active proxy fails. It needs at least -// one proxy transport. -func nodePool(keys []string, transports *proxyTransports, cooldown time.Duration) (*upstreamNodes, error) { +// nodePool distributes keys over proxies. When explicit proxy bindings are +// configured, bound keys are permanently pinned to their specified proxy and +// fail closed if that proxy fails. Unbound keys are distributed in round-robin +// order and can fail over to other proxies. +func nodePool(keys []string, transports *proxyTransports, cooldown time.Duration, bindings map[string]string) (*upstreamNodes, error) { if transports == nil || len(transports.items) == 0 { return nil, fmt.Errorf("at least one proxy transport is required") } @@ -642,9 +643,44 @@ func nodePool(keys []string, transports *proxyTransports, cooldown time.Duration if len(keys) == 0 { return pool, nil } + proxyMap := make(map[string]int, len(transports.items)*2) + for i, t := range transports.items { + proxyMap[t.name] = i + clean, _ := config.ParseProxyEntry(t.name) + proxyMap[clean] = i + } + for i, key := range keys { - proxyIndex := i % len(transports.items) - node := &upstreamNode{key: key, index: i, preferredProxy: proxyIndex} + fp := config.Fingerprint(key) + targetProxy, hasBinding := bindings[fp] + if !hasBinding { + targetProxy, hasBinding = bindings[key] + } + + var proxyIndex int + var bound bool + if hasBinding { + idx, ok := proxyMap[targetProxy] + if !ok { + cleanTarget, _ := config.ParseProxyEntry(targetProxy) + idx, ok = proxyMap[cleanTarget] + } + if !ok { + return nil, fmt.Errorf("bound proxy %q for key %s not found in transports", targetProxy, config.KeyDisplayID(key)) + } + proxyIndex = idx + bound = true + } else { + proxyIndex = i % len(transports.items) + bound = false + } + + node := &upstreamNode{ + key: key, + index: i, + preferredProxy: proxyIndex, + bound: bound, + } node.proxyIndex.Store(int64(proxyIndex)) pool.nodes = append(pool.nodes, node) pool.bindingCount[proxyIndex]++ @@ -666,7 +702,16 @@ func (p *upstreamNodes) RestoreProxy(recoveredProxy int) int { moved := 0 for _, node := range p.nodes { current := int(node.proxyIndex.Load()) - if node.preferredProxy != recoveredProxy || current == recoveredProxy { + if node.preferredProxy != recoveredProxy { + continue + } + if node.bound { + // Clear failures and cooldown so bound node immediately resumes traffic on recovered proxy. + node.failures.Store(0) + node.cooldownUntil.Store(0) + continue + } + if current == recoveredProxy { continue } if current >= 0 && current < len(p.bindingCount) { @@ -726,6 +771,10 @@ func (p *upstreamNodes) RebindProxy(failedProxy int) int { if int(node.proxyIndex.Load()) != failedProxy { continue } + if node.bound { + // Fail-closed: bound nodes never migrate to another proxy or direct route. + continue + } target := p.replacementLocked(failedProxy, true) if target < 0 { target = p.replacementLocked(failedProxy, false) diff --git a/internal/gateway/runtime.go b/internal/gateway/runtime.go index 8ee47aa..bc10bb0 100644 --- a/internal/gateway/runtime.go +++ b/internal/gateway/runtime.go @@ -487,6 +487,7 @@ type KeyStatus struct { Tier string `json:"tier"` Index int `json:"index"` ProxyIndex int `json:"proxy_index"` + Bound bool `json:"bound,omitempty"` Failures uint32 `json:"failures"` CooldownUntil *time.Time `json:"cooldown_until,omitempty"` } @@ -647,7 +648,7 @@ func (m *RuntimeController) DebugRouteForTier(model string, tier config.Tier) (m func keyStatuses(tier string, pool *upstreamNodes) []KeyStatus { result := make([]KeyStatus, 0, len(pool.nodes)) for _, node := range pool.nodes { - status := KeyStatus{ID: config.KeyDisplayID(node.key), Tier: tier, Index: node.index, ProxyIndex: int(node.proxyIndex.Load()), Failures: node.failures.Load()} + status := KeyStatus{ID: config.KeyDisplayID(node.key), Tier: tier, Index: node.index, ProxyIndex: int(node.proxyIndex.Load()), Bound: node.bound, Failures: node.failures.Load()} if until := node.cooldownUntil.Load(); until > time.Now().UnixNano() { value := time.Unix(0, until).UTC() status.CooldownUntil = &value diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 32d10b1..e71bd5b 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -850,7 +850,7 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, body = shaped } setRequestShape(ctx, changed, toolRenames) - useWARP := g.usesWARP(route.ID, override.Tier, false) + useWARP := !node.bound && g.usesWARP(route.ID, override.Tier, false) proxy := nodes.Proxy(node) if !useWARP { if proxy == nil { @@ -945,6 +945,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies if node == nil { break } + attemptUseWARP := !node.bound && useWARP attempts++ // Keep the request-level trace synchronized with the attempt that is // about to be sent. Only the redacted key suffix is retained. @@ -961,7 +962,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies return nil, err, attempts } proxy := nodes.Proxy(node) - if !useWARP { + if !attemptUseWARP { if proxy == nil { lastErr = errors.New("upstream key has no proxy binding") break @@ -971,7 +972,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies } } keyID := config.KeyDisplayID(node.key) - if useWARP { + if attemptUseWARP { setRequestCredential(ctx, route.Tier, keyID, "key", false, nil) } else { setRequestCredential(ctx, route.Tier, keyID, "key", false, proxy) @@ -979,7 +980,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies attemptStarted := time.Now() var resp *http.Response var egress string - if useWARP { + if attemptUseWARP { resp, egress, err = g.doWARPAttempt(ctx, req, baseURL, route.ID, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second) } else { resp, err = doInferenceAttempt(g.inferenceClient(proxy, baseURL, route.ID), req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout) @@ -998,7 +999,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies } recordProxy := proxy proxyLabel := "" - if useWARP { + if attemptUseWARP { recordProxy = warpProxy(egress) proxyLabel = egress g.observeKeyResultWARP(ctx, nodes, node, resp, err)