History

feat(amp): add per-client upstream API key mapping support

hkfires committed 10 months ago

Commit 225e2c61 parent d8fc48514 files · +836 −69Browse files

Unified · Split

14 files
  1. config.example.yaml +13 −0
  2. internal/api/handlers/management/config_lists.go +148 −0
  3. internal/api/modules/amp/amp.go +85 −4
  4. internal/api/modules/amp/amp_test.go +38 −0
  5. internal/api/modules/amp/proxy.go +35 −0
  6. internal/api/modules/amp/proxy_test.go +157 −0
  7. internal/api/modules/amp/routes.go +39 −0
  8. internal/api/modules/amp/secret.go +82 −0
  9. internal/api/modules/amp/secret_test.go +86 −0
  10. internal/api/server.go +4 −0
  11. internal/config/config.go +16 −0
  12. internal/util/gemini_schema_test.go +0 −65
  13. internal/watcher/diff/config_diff.go +45 −0
  14. test/amp_management_test.go +88 −0
config.example.yaml+13−0
@@ -35,6 +35,7 @@ auth-dir: "~/.cli-proxy-api" · 34 unmodified lines
3535 api-keys:
3636 - "your-api-key-1"
3737 - "your-api-key-2"
38+ - "your-api-key-3"
3839
3940 # Enable debug logging
4041 debug: false
@@ -166,6 +167,18 @@ ws-auth: false · 125 unmodified lines
166167 # upstream-url: "https://ampcode.com"
167168 # # Optional: Override API key for Amp upstream (otherwise uses env or file)
168169 # upstream-api-key: ""
170+# # Per-client upstream API key mapping
171+# # Maps client API keys (from top-level api-keys) to different Amp upstream API keys.
172+# # Useful when different clients need to use different Amp accounts/quotas.
173+# # If a client key isn't mapped, falls back to upstream-api-key (default behavior).
174+# upstream-api-keys:
175+# - upstream-api-key: "amp_key_for_team_a" # Upstream key to use for these clients
176+# api-keys: # Client keys that use this upstream key
177+# - "your-api-key-1"
178+# - "your-api-key-2"
179+# - upstream-api-key: "amp_key_for_team_b"
180+# api-keys:
181+# - "your-api-key-3"
169182 # # Restrict Amp management routes (/api/auth, /api/user, etc.) to localhost only (default: false)
170183 # restrict-management-to-localhost: false
171184 # # Force model mappings to run before checking local API keys (default: false)
internal/api/handlers/management/config_lists.go+148−0
@@ -940,3 +940,151 @@ func (h *Handler) GetAmpForceModelMappings(c *gin.Context) { · 939 unmodified lines
940940 func (h *Handler) PutAmpForceModelMappings(c *gin.Context) {
941941 h.updateBoolField(c, func(v bool) { h.cfg.AmpCode.ForceModelMappings = v })
942942 }
943+
944+// GetAmpUpstreamAPIKeys returns the ampcode upstream API keys mapping.
945+func (h *Handler) GetAmpUpstreamAPIKeys(c *gin.Context) {
946+ if h == nil || h.cfg == nil {
947+ c.JSON(200, gin.H{"upstream-api-keys": []config.AmpUpstreamAPIKeyEntry{}})
948+ return
949+ }
950+ c.JSON(200, gin.H{"upstream-api-keys": h.cfg.AmpCode.UpstreamAPIKeys})
951+}
952+
953+// PutAmpUpstreamAPIKeys replaces all ampcode upstream API keys mappings.
954+func (h *Handler) PutAmpUpstreamAPIKeys(c *gin.Context) {
955+ var body struct {
956+ Value []config.AmpUpstreamAPIKeyEntry `json:"value"`
957+ }
958+ if err := c.ShouldBindJSON(&body); err != nil {
959+ c.JSON(400, gin.H{"error": "invalid body"})
960+ return
961+ }
962+ // Normalize entries: trim whitespace, filter empty
963+ normalized := normalizeAmpUpstreamAPIKeyEntries(body.Value)
964+ h.cfg.AmpCode.UpstreamAPIKeys = normalized
965+ h.persist(c)
966+}
967+
968+// PatchAmpUpstreamAPIKeys adds or updates upstream API keys entries.
969+// Matching is done by upstream-api-key value.
970+func (h *Handler) PatchAmpUpstreamAPIKeys(c *gin.Context) {
971+ var body struct {
972+ Value []config.AmpUpstreamAPIKeyEntry `json:"value"`
973+ }
974+ if err := c.ShouldBindJSON(&body); err != nil {
975+ c.JSON(400, gin.H{"error": "invalid body"})
976+ return
977+ }
978+
979+ existing := make(map[string]int)
980+ for i, entry := range h.cfg.AmpCode.UpstreamAPIKeys {
981+ existing[strings.TrimSpace(entry.UpstreamAPIKey)] = i
982+ }
983+
984+ for _, newEntry := range body.Value {
985+ upstreamKey := strings.TrimSpace(newEntry.UpstreamAPIKey)
986+ if upstreamKey == "" {
987+ continue
988+ }
989+ normalizedEntry := config.AmpUpstreamAPIKeyEntry{
990+ UpstreamAPIKey: upstreamKey,
991+ APIKeys: normalizeAPIKeysList(newEntry.APIKeys),
992+ }
993+ if idx, ok := existing[upstreamKey]; ok {
994+ h.cfg.AmpCode.UpstreamAPIKeys[idx] = normalizedEntry
995+ } else {
996+ h.cfg.AmpCode.UpstreamAPIKeys = append(h.cfg.AmpCode.UpstreamAPIKeys, normalizedEntry)
997+ existing[upstreamKey] = len(h.cfg.AmpCode.UpstreamAPIKeys) - 1
998+ }
999+ }
1000+ h.persist(c)
1001+}
1002+
1003+// DeleteAmpUpstreamAPIKeys removes specified upstream API keys entries.
1004+// Body must be JSON: {"value": ["<upstream-api-key>", ...]}.
1005+// If "value" is an empty array, clears all entries.
1006+// If JSON is invalid or "value" is missing/null, returns 400 and does not persist any change.
1007+func (h *Handler) DeleteAmpUpstreamAPIKeys(c *gin.Context) {
1008+ var body struct {
1009+ Value []string `json:"value"`
1010+ }
1011+ if err := c.ShouldBindJSON(&body); err != nil {
1012+ c.JSON(400, gin.H{"error": "invalid body"})
1013+ return
1014+ }
1015+
1016+ if body.Value == nil {
1017+ c.JSON(400, gin.H{"error": "missing value"})
1018+ return
1019+ }
1020+
1021+ // Empty array means clear all
1022+ if len(body.Value) == 0 {
1023+ h.cfg.AmpCode.UpstreamAPIKeys = nil
1024+ h.persist(c)
1025+ return
1026+ }
1027+
1028+ toRemove := make(map[string]bool)
1029+ for _, key := range body.Value {
1030+ trimmed := strings.TrimSpace(key)
1031+ if trimmed == "" {
1032+ continue
1033+ }
1034+ toRemove[trimmed] = true
1035+ }
1036+ if len(toRemove) == 0 {
1037+ c.JSON(400, gin.H{"error": "empty value"})
1038+ return
1039+ }
1040+
1041+ newEntries := make([]config.AmpUpstreamAPIKeyEntry, 0, len(h.cfg.AmpCode.UpstreamAPIKeys))
1042+ for _, entry := range h.cfg.AmpCode.UpstreamAPIKeys {
1043+ if !toRemove[strings.TrimSpace(entry.UpstreamAPIKey)] {
1044+ newEntries = append(newEntries, entry)
1045+ }
1046+ }
1047+ h.cfg.AmpCode.UpstreamAPIKeys = newEntries
1048+ h.persist(c)
1049+}
1050+
1051+// normalizeAmpUpstreamAPIKeyEntries normalizes a list of upstream API key entries.
1052+func normalizeAmpUpstreamAPIKeyEntries(entries []config.AmpUpstreamAPIKeyEntry) []config.AmpUpstreamAPIKeyEntry {
1053+ if len(entries) == 0 {
1054+ return nil
1055+ }
1056+ out := make([]config.AmpUpstreamAPIKeyEntry, 0, len(entries))
1057+ for _, entry := range entries {
1058+ upstreamKey := strings.TrimSpace(entry.UpstreamAPIKey)
1059+ if upstreamKey == "" {
1060+ continue
1061+ }
1062+ apiKeys := normalizeAPIKeysList(entry.APIKeys)
1063+ out = append(out, config.AmpUpstreamAPIKeyEntry{
1064+ UpstreamAPIKey: upstreamKey,
1065+ APIKeys: apiKeys,
1066+ })
1067+ }
1068+ if len(out) == 0 {
1069+ return nil
1070+ }
1071+ return out
1072+}
1073+
1074+// normalizeAPIKeysList trims and filters empty strings from a list of API keys.
1075+func normalizeAPIKeysList(keys []string) []string {
1076+ if len(keys) == 0 {
1077+ return nil
1078+ }
1079+ out := make([]string, 0, len(keys))
1080+ for _, k := range keys {
1081+ trimmed := strings.TrimSpace(k)
1082+ if trimmed != "" {
1083+ out = append(out, trimmed)
1084+ }
1085+ }
1086+ if len(out) == 0 {
1087+ return nil
1088+ }
1089+ return out
1090+}
internal/api/modules/amp/amp.go+85−4
@@ -227,11 +227,20 @@ func (m *AmpModule) OnConfigUpdated(cfg *config.Config) error { · 226 unmodified lines
227227 }
228228 }
229229
230− // Check API key change
230+ // Check API key change (both default and per-client mappings)
231231 apiKeyChanged := m.hasAPIKeyChanged(oldSettings, &newSettings)
232− if apiKeyChanged {
232+ upstreamAPIKeysChanged := m.hasUpstreamAPIKeysChanged(oldSettings, &newSettings)
233+ if apiKeyChanged || upstreamAPIKeysChanged {
233234 if m.secretSource != nil {
234− if ms, ok := m.secretSource.(*MultiSourceSecret); ok {
235+ if ms, ok := m.secretSource.(*MappedSecretSource); ok {
236+ if apiKeyChanged {
237+ ms.UpdateDefaultExplicitKey(newSettings.UpstreamAPIKey)
238+ ms.InvalidateCache()
239+ }
240+ if upstreamAPIKeysChanged {
241+ ms.UpdateMappings(newSettings.UpstreamAPIKeys)
242+ }
243+ } else if ms, ok := m.secretSource.(*MultiSourceSecret); ok {
235244 ms.UpdateExplicitKey(newSettings.UpstreamAPIKey)
236245 ms.InvalidateCache()
237246 }
@@ -251,10 +260,22 @@ func (m *AmpModule) OnConfigUpdated(cfg *config.Config) error { · 13 unmodified lines
251260
252261 func (m *AmpModule) enableUpstreamProxy(upstreamURL string, settings *config.AmpCode) error {
253262 if m.secretSource == nil {
254− m.secretSource = NewMultiSourceSecret(settings.UpstreamAPIKey, 0 /* default 5min */)
263+ // Create MultiSourceSecret as the default source, then wrap with MappedSecretSource
264+ defaultSource := NewMultiSourceSecret(settings.UpstreamAPIKey, 0 /* default 5min */)
265+ mappedSource := NewMappedSecretSource(defaultSource)
266+ mappedSource.UpdateMappings(settings.UpstreamAPIKeys)
267+ m.secretSource = mappedSource
268+ } else if ms, ok := m.secretSource.(*MappedSecretSource); ok {
269+ ms.UpdateDefaultExplicitKey(settings.UpstreamAPIKey)
270+ ms.InvalidateCache()
271+ ms.UpdateMappings(settings.UpstreamAPIKeys)
255272 } else if ms, ok := m.secretSource.(*MultiSourceSecret); ok {
273+ // Legacy path: wrap existing MultiSourceSecret with MappedSecretSource
256274 ms.UpdateExplicitKey(settings.UpstreamAPIKey)
257275 ms.InvalidateCache()
276+ mappedSource := NewMappedSecretSource(ms)
277+ mappedSource.UpdateMappings(settings.UpstreamAPIKeys)
278+ m.secretSource = mappedSource
258279 }
259280
260281 proxy, err := createReverseProxy(upstreamURL, m.secretSource)
@@ -313,6 +334,66 @@ func (m *AmpModule) hasAPIKeyChanged(old *config.AmpCode, new *config.AmpCode) b · 52 unmodified lines
313334 return oldKey != newKey
314335 }
315336
337+// hasUpstreamAPIKeysChanged compares old and new per-client upstream API key mappings.
338+func (m *AmpModule) hasUpstreamAPIKeysChanged(old *config.AmpCode, new *config.AmpCode) bool {
339+ if old == nil {
340+ return len(new.UpstreamAPIKeys) > 0
341+ }
342+
343+ if len(old.UpstreamAPIKeys) != len(new.UpstreamAPIKeys) {
344+ return true
345+ }
346+
347+ // Build map for comparison: upstreamKey -> set of clientKeys
348+ type entryInfo struct {
349+ upstreamKey string
350+ clientKeys map[string]struct{}
351+ }
352+ oldEntries := make([]entryInfo, len(old.UpstreamAPIKeys))
353+ for i, entry := range old.UpstreamAPIKeys {
354+ clientKeys := make(map[string]struct{}, len(entry.APIKeys))
355+ for _, k := range entry.APIKeys {
356+ trimmed := strings.TrimSpace(k)
357+ if trimmed == "" {
358+ continue
359+ }
360+ clientKeys[trimmed] = struct{}{}
361+ }
362+ oldEntries[i] = entryInfo{
363+ upstreamKey: strings.TrimSpace(entry.UpstreamAPIKey),
364+ clientKeys: clientKeys,
365+ }
366+ }
367+
368+ for i, newEntry := range new.UpstreamAPIKeys {
369+ if i >= len(oldEntries) {
370+ return true
371+ }
372+ oldE := oldEntries[i]
373+ if strings.TrimSpace(newEntry.UpstreamAPIKey) != oldE.upstreamKey {
374+ return true
375+ }
376+ newKeys := make(map[string]struct{}, len(newEntry.APIKeys))
377+ for _, k := range newEntry.APIKeys {
378+ trimmed := strings.TrimSpace(k)
379+ if trimmed == "" {
380+ continue
381+ }
382+ newKeys[trimmed] = struct{}{}
383+ }
384+ if len(newKeys) != len(oldE.clientKeys) {
385+ return true
386+ }
387+ for k := range newKeys {
388+ if _, ok := oldE.clientKeys[k]; !ok {
389+ return true
390+ }
391+ }
392+ }
393+
394+ return false
395+}
396+
316397 // GetModelMapper returns the model mapper instance (for testing/debugging).
317398 func (m *AmpModule) GetModelMapper() *DefaultModelMapper {
318399 return m.modelMapper
internal/api/modules/amp/amp_test.go+38−0
@@ -312,3 +312,41 @@ func TestAmpModule_ProviderAliasesAlwaysRegistered(t *testing.T) { · 311 unmodified lines
312312 })
313313 }
314314 }
315+
316+func TestAmpModule_hasUpstreamAPIKeysChanged_DetectsRemovedKeyWithDuplicateInput(t *testing.T) {
317+ m := &AmpModule{}
318+
319+ oldCfg := &config.AmpCode{
320+ UpstreamAPIKeys: []config.AmpUpstreamAPIKeyEntry{
321+ {UpstreamAPIKey: "u1", APIKeys: []string{"k1", "k2"}},
322+ },
323+ }
324+ newCfg := &config.AmpCode{
325+ UpstreamAPIKeys: []config.AmpUpstreamAPIKeyEntry{
326+ {UpstreamAPIKey: "u1", APIKeys: []string{"k1", "k1"}},
327+ },
328+ }
329+
330+ if !m.hasUpstreamAPIKeysChanged(oldCfg, newCfg) {
331+ t.Fatal("expected change to be detected when k2 is removed but new list contains duplicates")
332+ }
333+}
334+
335+func TestAmpModule_hasUpstreamAPIKeysChanged_IgnoresEmptyAndWhitespaceKeys(t *testing.T) {
336+ m := &AmpModule{}
337+
338+ oldCfg := &config.AmpCode{
339+ UpstreamAPIKeys: []config.AmpUpstreamAPIKeyEntry{
340+ {UpstreamAPIKey: "u1", APIKeys: []string{"k1", "k2"}},
341+ },
342+ }
343+ newCfg := &config.AmpCode{
344+ UpstreamAPIKeys: []config.AmpUpstreamAPIKeyEntry{
345+ {UpstreamAPIKey: "u1", APIKeys: []string{" k1 ", "", "k2", " "}},
346+ },
347+ }
348+
349+ if m.hasUpstreamAPIKeysChanged(oldCfg, newCfg) {
350+ t.Fatal("expected no change when only whitespace/empty entries differ")
351+ }
352+}
internal/api/modules/amp/proxy.go+35−0
@@ -15,6 +15,33 @@ import ( · 14 unmodified lines
1515 log "github.com/sirupsen/logrus"
1616 )
1717
18+func removeQueryValuesMatching(req *http.Request, key string, match string) {
19+ if req == nil || req.URL == nil || match == "" {
20+ return
21+ }
22+
23+ q := req.URL.Query()
24+ values, ok := q[key]
25+ if !ok || len(values) == 0 {
26+ return
27+ }
28+
29+ kept := make([]string, 0, len(values))
30+ for _, v := range values {
31+ if v == match {
32+ continue
33+ }
34+ kept = append(kept, v)
35+ }
36+
37+ if len(kept) == 0 {
38+ q.Del(key)
39+ } else {
40+ q[key] = kept
41+ }
42+ req.URL.RawQuery = q.Encode()
43+}
44+
1845 // readCloser wraps a reader and forwards Close to a separate closer.
1946 // Used to restore peeked bytes while preserving upstream body Close behavior.
2047 type readCloser struct {
@@ -45,6 +72,14 @@ func createReverseProxy(upstreamURL string, secretSource SecretSource) (*httputi · 24 unmodified lines
4572 // We will set our own Authorization using the configured upstream-api-key
4673 req.Header.Del("Authorization")
4774 req.Header.Del("X-Api-Key")
75+ req.Header.Del("X-Goog-Api-Key")
76+
77+ // Remove query-based credentials if they match the authenticated client API key.
78+ // This prevents leaking client auth material to the Amp upstream while avoiding
79+ // breaking unrelated upstream query parameters.
80+ clientKey := getClientAPIKeyFromContext(req.Context())
81+ removeQueryValuesMatching(req, "key", clientKey)
82+ removeQueryValuesMatching(req, "auth_token", clientKey)
4883
4984 // Preserve correlation headers for debugging
5085 if req.Header.Get("X-Request-ID") == "" {
internal/api/modules/amp/proxy_test.go+157−0
@@ -3,11 +3,15 @@ package amp · 2 unmodified lines
33 import (
44 "bytes"
55 "compress/gzip"
6+ "context"
67 "fmt"
78 "io"
89 "net/http"
910 "net/http/httptest"
11+ "strings"
1012 "testing"
13+
14+ "github.com/router-for-me/CLIProxyAPI/v6/internal/config"
1115 )
1216
1317 // Helper: compress data with gzip
@@ -306,6 +310,159 @@ func TestReverseProxy_EmptySecret(t *testing.T) { · 292 unmodified lines
306310 }
307311 }
308312
313+func TestReverseProxy_StripsClientCredentialsFromHeadersAndQuery(t *testing.T) {
314+ type captured struct {
315+ headers http.Header
316+ query string
317+ }
318+ got := make(chan captured, 1)
319+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
320+ got <- captured{headers: r.Header.Clone(), query: r.URL.RawQuery}
321+ w.WriteHeader(200)
322+ w.Write([]byte(`ok`))
323+ }))
324+ defer upstream.Close()
325+
326+ proxy, err := createReverseProxy(upstream.URL, NewStaticSecretSource("upstream"))
327+ if err != nil {
328+ t.Fatal(err)
329+ }
330+
331+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
332+ // Simulate clientAPIKeyMiddleware injection (per-request)
333+ ctx := context.WithValue(r.Context(), clientAPIKeyContextKey{}, "client-key")
334+ proxy.ServeHTTP(w, r.WithContext(ctx))
335+ }))
336+ defer srv.Close()
337+
338+ req, err := http.NewRequest(http.MethodGet, srv.URL+"/test?key=client-key&key=keep&auth_token=client-key&foo=bar", nil)
339+ if err != nil {
340+ t.Fatal(err)
341+ }
342+ req.Header.Set("Authorization", "Bearer client-key")
343+ req.Header.Set("X-Api-Key", "client-key")
344+ req.Header.Set("X-Goog-Api-Key", "client-key")
345+
346+ res, err := http.DefaultClient.Do(req)
347+ if err != nil {
348+ t.Fatal(err)
349+ }
350+ res.Body.Close()
351+
352+ c := <-got
353+
354+ // These are client-provided credentials and must not reach the upstream.
355+ if v := c.headers.Get("X-Goog-Api-Key"); v != "" {
356+ t.Fatalf("X-Goog-Api-Key should be stripped, got: %q", v)
357+ }
358+
359+ // We inject upstream Authorization/X-Api-Key, so the client auth must not survive.
360+ if v := c.headers.Get("Authorization"); v != "Bearer upstream" {
361+ t.Fatalf("Authorization should be upstream-injected, got: %q", v)
362+ }
363+ if v := c.headers.Get("X-Api-Key"); v != "upstream" {
364+ t.Fatalf("X-Api-Key should be upstream-injected, got: %q", v)
365+ }
366+
367+ // Query-based credentials should be stripped only when they match the authenticated client key.
368+ // Should keep unrelated values and parameters.
369+ if strings.Contains(c.query, "auth_token=client-key") || strings.Contains(c.query, "key=client-key") {
370+ t.Fatalf("query credentials should be stripped, got raw query: %q", c.query)
371+ }
372+ if !strings.Contains(c.query, "key=keep") || !strings.Contains(c.query, "foo=bar") {
373+ t.Fatalf("expected query to keep non-credential params, got raw query: %q", c.query)
374+ }
375+}
376+
377+func TestReverseProxy_InjectsMappedSecret_FromRequestContext(t *testing.T) {
378+ gotHeaders := make(chan http.Header, 1)
379+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
380+ gotHeaders <- r.Header.Clone()
381+ w.WriteHeader(200)
382+ w.Write([]byte(`ok`))
383+ }))
384+ defer upstream.Close()
385+
386+ defaultSource := NewStaticSecretSource("default")
387+ mapped := NewMappedSecretSource(defaultSource)
388+ mapped.UpdateMappings([]config.AmpUpstreamAPIKeyEntry{
389+ {
390+ UpstreamAPIKey: "u1",
391+ APIKeys: []string{"k1"},
392+ },
393+ })
394+
395+ proxy, err := createReverseProxy(upstream.URL, mapped)
396+ if err != nil {
397+ t.Fatal(err)
398+ }
399+
400+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
401+ // Simulate clientAPIKeyMiddleware injection (per-request)
402+ ctx := context.WithValue(r.Context(), clientAPIKeyContextKey{}, "k1")
403+ proxy.ServeHTTP(w, r.WithContext(ctx))
404+ }))
405+ defer srv.Close()
406+
407+ res, err := http.Get(srv.URL + "/test")
408+ if err != nil {
409+ t.Fatal(err)
410+ }
411+ res.Body.Close()
412+
413+ hdr := <-gotHeaders
414+ if hdr.Get("X-Api-Key") != "u1" {
415+ t.Fatalf("X-Api-Key missing or wrong, got: %q", hdr.Get("X-Api-Key"))
416+ }
417+ if hdr.Get("Authorization") != "Bearer u1" {
418+ t.Fatalf("Authorization missing or wrong, got: %q", hdr.Get("Authorization"))
419+ }
420+}
421+
422+func TestReverseProxy_MappedSecret_FallsBackToDefault(t *testing.T) {
423+ gotHeaders := make(chan http.Header, 1)
424+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
425+ gotHeaders <- r.Header.Clone()
426+ w.WriteHeader(200)
427+ w.Write([]byte(`ok`))
428+ }))
429+ defer upstream.Close()
430+
431+ defaultSource := NewStaticSecretSource("default")
432+ mapped := NewMappedSecretSource(defaultSource)
433+ mapped.UpdateMappings([]config.AmpUpstreamAPIKeyEntry{
434+ {
435+ UpstreamAPIKey: "u1",
436+ APIKeys: []string{"k1"},
437+ },
438+ })
439+
440+ proxy, err := createReverseProxy(upstream.URL, mapped)
441+ if err != nil {
442+ t.Fatal(err)
443+ }
444+
445+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
446+ ctx := context.WithValue(r.Context(), clientAPIKeyContextKey{}, "k2")
447+ proxy.ServeHTTP(w, r.WithContext(ctx))
448+ }))
449+ defer srv.Close()
450+
451+ res, err := http.Get(srv.URL + "/test")
452+ if err != nil {
453+ t.Fatal(err)
454+ }
455+ res.Body.Close()
456+
457+ hdr := <-gotHeaders
458+ if hdr.Get("X-Api-Key") != "default" {
459+ t.Fatalf("X-Api-Key fallback missing or wrong, got: %q", hdr.Get("X-Api-Key"))
460+ }
461+ if hdr.Get("Authorization") != "Bearer default" {
462+ t.Fatalf("Authorization fallback missing or wrong, got: %q", hdr.Get("Authorization"))
463+ }
464+}
465+
309466 func TestReverseProxy_ErrorHandler(t *testing.T) {
310467 // Point proxy to a non-routable address to trigger error
311468 proxy, err := createReverseProxy("http://127.0.0.1:1", NewStaticSecretSource(""))
internal/api/modules/amp/routes.go+39−0
@@ -1,6 +1,7 @@
11 package amp
22
33 import (
4+ "context"
45 "errors"
56 "net"
67 "net/http"
@@ -16,6 +17,37 @@ import ( · 9 unmodified lines
1617 log "github.com/sirupsen/logrus"
1718 )
1819
20+// clientAPIKeyContextKey is the context key used to pass the client API key
21+// from gin.Context to the request context for SecretSource lookup.
22+type clientAPIKeyContextKey struct{}
23+
24+// clientAPIKeyMiddleware injects the authenticated client API key from gin.Context["apiKey"]
25+// into the request context so that SecretSource can look it up for per-client upstream routing.
26+func clientAPIKeyMiddleware() gin.HandlerFunc {
27+ return func(c *gin.Context) {
28+ // Extract the client API key from gin context (set by AuthMiddleware)
29+ if apiKey, exists := c.Get("apiKey"); exists {
30+ if keyStr, ok := apiKey.(string); ok && keyStr != "" {
31+ // Inject into request context for SecretSource.Get(ctx) to read
32+ ctx := context.WithValue(c.Request.Context(), clientAPIKeyContextKey{}, keyStr)
33+ c.Request = c.Request.WithContext(ctx)
34+ }
35+ }
36+ c.Next()
37+ }
38+}
39+
40+// getClientAPIKeyFromContext retrieves the client API key from request context.
41+// Returns empty string if not present.
42+func getClientAPIKeyFromContext(ctx context.Context) string {
43+ if val := ctx.Value(clientAPIKeyContextKey{}); val != nil {
44+ if keyStr, ok := val.(string); ok {
45+ return keyStr
46+ }
47+ }
48+ return ""
49+}
50+
1951 // localhostOnlyMiddleware returns a middleware that dynamically checks the module's
2052 // localhost restriction setting. This allows hot-reload of the restriction without restarting.
2153 func (m *AmpModule) localhostOnlyMiddleware() gin.HandlerFunc {
@@ -129,6 +161,9 @@ func (m *AmpModule) registerManagementRoutes(engine *gin.Engine, baseHandler *ha · 107 unmodified lines
129161 authWithBypass = wrapManagementAuth(auth, "/threads", "/auth", "/docs", "/settings")
130162 }
131163
164+ // Inject client API key into request context for per-client upstream routing
165+ ampAPI.Use(clientAPIKeyMiddleware())
166+
132167 // Dynamic proxy handler that uses m.getProxy() for hot-reload support
133168 proxyHandler := func(c *gin.Context) {
134169 // Swallow ErrAbortHandler panics from ReverseProxy copyResponse to avoid noisy stack traces
@@ -175,6 +210,8 @@ func (m *AmpModule) registerManagementRoutes(engine *gin.Engine, baseHandler *ha · 40 unmodified lines
175210 if authWithBypass != nil {
176211 rootMiddleware = append(rootMiddleware, authWithBypass)
177212 }
213+ // Add clientAPIKeyMiddleware after auth for per-client upstream routing
214+ rootMiddleware = append(rootMiddleware, clientAPIKeyMiddleware())
178215 engine.GET("/threads", append(rootMiddleware, proxyHandler)...)
179216 engine.GET("/threads/*path", append(rootMiddleware, proxyHandler)...)
180217 engine.GET("/docs", append(rootMiddleware, proxyHandler)...)
@@ -244,6 +281,8 @@ func (m *AmpModule) registerProviderAliases(engine *gin.Engine, baseHandler *han · 63 unmodified lines
244281 if auth != nil {
245282 ampProviders.Use(auth)
246283 }
284+ // Inject client API key into request context for per-client upstream routing
285+ ampProviders.Use(clientAPIKeyMiddleware())
247286
248287 provider := ampProviders.Group("/:provider")
249288
internal/api/modules/amp/secret.go+82−0
@@ -9,6 +9,9 @@ import ( · 8 unmodified lines
99 "strings"
1010 "sync"
1111 "time"
12+
13+ "github.com/router-for-me/CLIProxyAPI/v6/internal/config"
14+ log "github.com/sirupsen/logrus"
1215 )
1316
1417 // SecretSource provides Amp API keys with configurable precedence and caching
@@ -164,3 +167,82 @@ func NewStaticSecretSource(key string) *StaticSecretSource { · 149 unmodified lines
164167 func (s *StaticSecretSource) Get(ctx context.Context) (string, error) {
165168 return s.key, nil
166169 }
170+
171+// MappedSecretSource wraps a default SecretSource and adds per-client API key mapping.
172+// When a request context contains a client API key that matches a configured mapping,
173+// the corresponding upstream key is returned. Otherwise, falls back to the default source.
174+type MappedSecretSource struct {
175+ defaultSource SecretSource
176+ mu sync.RWMutex
177+ lookup map[string]string // clientKey -> upstreamKey
178+}
179+
180+// NewMappedSecretSource creates a MappedSecretSource wrapping the given default source.
181+func NewMappedSecretSource(defaultSource SecretSource) *MappedSecretSource {
182+ return &MappedSecretSource{
183+ defaultSource: defaultSource,
184+ lookup: make(map[string]string),
185+ }
186+}
187+
188+// Get retrieves the Amp API key, checking per-client mappings first.
189+// If the request context contains a client API key that matches a configured mapping,
190+// returns the corresponding upstream key. Otherwise, falls back to the default source.
191+func (s *MappedSecretSource) Get(ctx context.Context) (string, error) {
192+ // Try to get client API key from request context
193+ clientKey := getClientAPIKeyFromContext(ctx)
194+ if clientKey != "" {
195+ s.mu.RLock()
196+ if upstreamKey, ok := s.lookup[clientKey]; ok && upstreamKey != "" {
197+ s.mu.RUnlock()
198+ return upstreamKey, nil
199+ }
200+ s.mu.RUnlock()
201+ }
202+
203+ // Fall back to default source
204+ return s.defaultSource.Get(ctx)
205+}
206+
207+// UpdateMappings rebuilds the client-to-upstream key mapping from configuration entries.
208+// If the same client key appears in multiple entries, logs a warning and uses the first one.
209+func (s *MappedSecretSource) UpdateMappings(entries []config.AmpUpstreamAPIKeyEntry) {
210+ newLookup := make(map[string]string)
211+
212+ for _, entry := range entries {
213+ upstreamKey := strings.TrimSpace(entry.UpstreamAPIKey)
214+ if upstreamKey == "" {
215+ continue
216+ }
217+ for _, clientKey := range entry.APIKeys {
218+ trimmedKey := strings.TrimSpace(clientKey)
219+ if trimmedKey == "" {
220+ continue
221+ }
222+ if _, exists := newLookup[trimmedKey]; exists {
223+ // Log warning for duplicate client key, first one wins
224+ log.Warnf("amp upstream-api-keys: client API key appears in multiple entries; using first mapping.")
225+ continue
226+ }
227+ newLookup[trimmedKey] = upstreamKey
228+ }
229+ }
230+
231+ s.mu.Lock()
232+ s.lookup = newLookup
233+ s.mu.Unlock()
234+}
235+
236+// UpdateDefaultExplicitKey updates the explicit key on the underlying MultiSourceSecret (if applicable).
237+func (s *MappedSecretSource) UpdateDefaultExplicitKey(key string) {
238+ if ms, ok := s.defaultSource.(*MultiSourceSecret); ok {
239+ ms.UpdateExplicitKey(key)
240+ }
241+}
242+
243+// InvalidateCache invalidates cache on the underlying MultiSourceSecret (if applicable).
244+func (s *MappedSecretSource) InvalidateCache() {
245+ if ms, ok := s.defaultSource.(*MultiSourceSecret); ok {
246+ ms.InvalidateCache()
247+ }
248+}
internal/api/modules/amp/secret_test.go+86−0
@@ -8,6 +8,10 @@ import ( · 7 unmodified lines
88 "sync"
99 "testing"
1010 "time"
11+
12+ "github.com/router-for-me/CLIProxyAPI/v6/internal/config"
13+ log "github.com/sirupsen/logrus"
14+ "github.com/sirupsen/logrus/hooks/test"
1115 )
1216
1317 func TestMultiSourceSecret_PrecedenceOrder(t *testing.T) {
@@ -278,3 +282,85 @@ func TestMultiSourceSecret_CacheEmptyResult(t *testing.T) { · 264 unmodified lines
278282 t.Fatalf("after cache expiry, expected new-value, got %q", got3)
279283 }
280284 }
285+
286+func TestMappedSecretSource_UsesMappingFromContext(t *testing.T) {
287+ defaultSource := NewStaticSecretSource("default")
288+ s := NewMappedSecretSource(defaultSource)
289+ s.UpdateMappings([]config.AmpUpstreamAPIKeyEntry{
290+ {
291+ UpstreamAPIKey: "u1",
292+ APIKeys: []string{"k1"},
293+ },
294+ })
295+
296+ ctx := context.WithValue(context.Background(), clientAPIKeyContextKey{}, "k1")
297+ got, err := s.Get(ctx)
298+ if err != nil {
299+ t.Fatalf("unexpected error: %v", err)
300+ }
301+ if got != "u1" {
302+ t.Fatalf("want u1, got %q", got)
303+ }
304+
305+ ctx = context.WithValue(context.Background(), clientAPIKeyContextKey{}, "k2")
306+ got, err = s.Get(ctx)
307+ if err != nil {
308+ t.Fatalf("unexpected error: %v", err)
309+ }
310+ if got != "default" {
311+ t.Fatalf("want default fallback, got %q", got)
312+ }
313+}
314+
315+func TestMappedSecretSource_DuplicateClientKey_FirstWins(t *testing.T) {
316+ defaultSource := NewStaticSecretSource("default")
317+ s := NewMappedSecretSource(defaultSource)
318+ s.UpdateMappings([]config.AmpUpstreamAPIKeyEntry{
319+ {
320+ UpstreamAPIKey: "u1",
321+ APIKeys: []string{"k1"},
322+ },
323+ {
324+ UpstreamAPIKey: "u2",
325+ APIKeys: []string{"k1"},
326+ },
327+ })
328+
329+ ctx := context.WithValue(context.Background(), clientAPIKeyContextKey{}, "k1")
330+ got, err := s.Get(ctx)
331+ if err != nil {
332+ t.Fatalf("unexpected error: %v", err)
333+ }
334+ if got != "u1" {
335+ t.Fatalf("want u1 (first wins), got %q", got)
336+ }
337+}
338+
339+func TestMappedSecretSource_DuplicateClientKey_LogsWarning(t *testing.T) {
340+ hook := test.NewLocal(log.StandardLogger())
341+ defer hook.Reset()
342+
343+ defaultSource := NewStaticSecretSource("default")
344+ s := NewMappedSecretSource(defaultSource)
345+ s.UpdateMappings([]config.AmpUpstreamAPIKeyEntry{
346+ {
347+ UpstreamAPIKey: "u1",
348+ APIKeys: []string{"k1"},
349+ },
350+ {
351+ UpstreamAPIKey: "u2",
352+ APIKeys: []string{"k1"},
353+ },
354+ })
355+
356+ foundWarning := false
357+ for _, entry := range hook.AllEntries() {
358+ if entry.Level == log.WarnLevel && entry.Message == "amp upstream-api-keys: client API key appears in multiple entries; using first mapping." {
359+ foundWarning = true
360+ break
361+ }
362+ }
363+ if !foundWarning {
364+ t.Fatal("expected warning log for duplicate client key, but none was found")
365+ }
366+}
internal/api/server.go+4−0
@@ -551,6 +551,10 @@ func (s *Server) registerManagementRoutes() { · 550 unmodified lines
551551 mgmt.GET("/ampcode/force-model-mappings", s.mgmt.GetAmpForceModelMappings)
552552 mgmt.PUT("/ampcode/force-model-mappings", s.mgmt.PutAmpForceModelMappings)
553553 mgmt.PATCH("/ampcode/force-model-mappings", s.mgmt.PutAmpForceModelMappings)
554+ mgmt.GET("/ampcode/upstream-api-keys", s.mgmt.GetAmpUpstreamAPIKeys)
555+ mgmt.PUT("/ampcode/upstream-api-keys", s.mgmt.PutAmpUpstreamAPIKeys)
556+ mgmt.PATCH("/ampcode/upstream-api-keys", s.mgmt.PatchAmpUpstreamAPIKeys)
557+ mgmt.DELETE("/ampcode/upstream-api-keys", s.mgmt.DeleteAmpUpstreamAPIKeys)
554558
555559 mgmt.GET("/request-retry", s.mgmt.GetRequestRetry)
556560 mgmt.PUT("/request-retry", s.mgmt.PutRequestRetry)
internal/config/config.go+16−0
@@ -163,6 +163,11 @@ type AmpCode struct { · 162 unmodified lines
163163 // UpstreamAPIKey optionally overrides the Authorization header when proxying Amp upstream calls.
164164 UpstreamAPIKey string `yaml:"upstream-api-key" json:"upstream-api-key"`
165165
166+ // UpstreamAPIKeys maps client API keys (from top-level api-keys) to upstream API keys.
167+ // When a client authenticates with a key that matches an entry, that upstream key is used.
168+ // If no match is found, falls back to UpstreamAPIKey (default behavior).
169+ UpstreamAPIKeys []AmpUpstreamAPIKeyEntry `yaml:"upstream-api-keys,omitempty" json:"upstream-api-keys,omitempty"`
170+
166171 // RestrictManagementToLocalhost restricts Amp management routes (/api/user, /api/threads, etc.)
167172 // to only accept connections from localhost (127.0.0.1, ::1). When true, prevents drive-by
168173 // browser attacks and remote access to management endpoints. Default: false (API key auth is sufficient).
@@ -178,6 +183,17 @@ type AmpCode struct { · 9 unmodified lines
178183 ForceModelMappings bool `yaml:"force-model-mappings" json:"force-model-mappings"`
179184 }
180185
186+// AmpUpstreamAPIKeyEntry maps a set of client API keys to a specific upstream API key.
187+// When a request is authenticated with one of the APIKeys, the corresponding UpstreamAPIKey
188+// is used for the upstream Amp request.
189+type AmpUpstreamAPIKeyEntry struct {
190+ // UpstreamAPIKey is the API key to use when proxying to the Amp upstream.
191+ UpstreamAPIKey string `yaml:"upstream-api-key" json:"upstream-api-key"`
192+
193+ // APIKeys are the client API keys (from top-level api-keys) that map to this upstream key.
194+ APIKeys []string `yaml:"api-keys" json:"api-keys"`
195+}
196+
181197 // PayloadConfig defines default and override parameter rules applied to provider payloads.
182198 type PayloadConfig struct {
183199 // Default defines rules that only set parameters when they are missing in the payload.
internal/util/gemini_schema_test.go+0−65
@@ -614,71 +614,6 @@ func TestCleanJSONSchemaForAntigravity_MultipleNonNullTypes(t *testing.T) { · 613 unmodified lines
614614 }
615615 }
616616
617−func TestCleanJSONSchemaForGemini_PropertyNamesRemoval(t *testing.T) {
618− // propertyNames is used to validate object property names (e.g., must match a pattern)
619− // Gemini doesn't support this keyword and will reject requests containing it
620− input := `{
621− "type": "object",
622− "properties": {
623− "metadata": {
624− "type": "object",
625− "propertyNames": {
626− "pattern": "^[a-zA-Z_][a-zA-Z0-9_]*$"
627− },
628− "additionalProperties": {
629− "type": "string"
630− }
631− }
632− }
633− }`
634−
635− expected := `{
636− "type": "object",
637− "properties": {
638− "metadata": {
639− "type": "object"
640− }
641− }
642− }`
643−
644− result := CleanJSONSchemaForGemini(input)
645− compareJSON(t, expected, result)
646−
647− // Verify propertyNames is completely removed
648− if strings.Contains(result, "propertyNames") {
649− t.Errorf("propertyNames keyword should be removed, got: %s", result)
650− }
651−}
652−
653−func TestCleanJSONSchemaForGemini_PropertyNamesRemoval_Nested(t *testing.T) {
654− // Test deeply nested propertyNames (as seen in real Claude tool schemas)
655− input := `{
656− "type": "object",
657− "properties": {
658− "items": {
659− "type": "array",
660− "items": {
661− "type": "object",
662− "properties": {
663− "config": {
664− "type": "object",
665− "propertyNames": {
666− "type": "string"
667− }
668− }
669− }
670− }
671− }
672− }
673− }`
674−
675− result := CleanJSONSchemaForGemini(input)
676−
677− if strings.Contains(result, "propertyNames") {
678− t.Errorf("Nested propertyNames should be removed, got: %s", result)
679− }
680−}
681−
682617 func compareJSON(t *testing.T, expectedJSON, actualJSON string) {
683618 var expMap, actMap map[string]interface{}
684619 errExp := json.Unmarshal([]byte(expectedJSON), &expMap)
internal/watcher/diff/config_diff.go+45−0
@@ -185,6 +185,11 @@ func BuildConfigChangeDetails(oldCfg, newCfg *config.Config) []string { · 184 unmodified lines
185185 if oldCfg.AmpCode.ForceModelMappings != newCfg.AmpCode.ForceModelMappings {
186186 changes = append(changes, fmt.Sprintf("ampcode.force-model-mappings: %t -> %t", oldCfg.AmpCode.ForceModelMappings, newCfg.AmpCode.ForceModelMappings))
187187 }
188+ oldUpstreamAPIKeysCount := len(oldCfg.AmpCode.UpstreamAPIKeys)
189+ newUpstreamAPIKeysCount := len(newCfg.AmpCode.UpstreamAPIKeys)
190+ if !equalUpstreamAPIKeys(oldCfg.AmpCode.UpstreamAPIKeys, newCfg.AmpCode.UpstreamAPIKeys) {
191+ changes = append(changes, fmt.Sprintf("ampcode.upstream-api-keys: updated (%d -> %d entries)", oldUpstreamAPIKeysCount, newUpstreamAPIKeysCount))
192+ }
188193
189194 if entries, _ := DiffOAuthExcludedModelChanges(oldCfg.OAuthExcludedModels, newCfg.OAuthExcludedModels); len(entries) > 0 {
190195 changes = append(changes, entries...)
@@ -301,3 +306,43 @@ func formatProxyURL(raw string) string { · 110 unmodified lines
301306 }
302307 return scheme + "://" + host
303308 }
309+
310+func equalStringSet(a, b []string) bool {
311+ if len(a) == 0 && len(b) == 0 {
312+ return true
313+ }
314+ aSet := make(map[string]struct{}, len(a))
315+ for _, k := range a {
316+ aSet[strings.TrimSpace(k)] = struct{}{}
317+ }
318+ bSet := make(map[string]struct{}, len(b))
319+ for _, k := range b {
320+ bSet[strings.TrimSpace(k)] = struct{}{}
321+ }
322+ if len(aSet) != len(bSet) {
323+ return false
324+ }
325+ for k := range aSet {
326+ if _, ok := bSet[k]; !ok {
327+ return false
328+ }
329+ }
330+ return true
331+}
332+
333+// equalUpstreamAPIKeys compares two slices of AmpUpstreamAPIKeyEntry for equality.
334+// Comparison is done by count and content (upstream key and client keys).
335+func equalUpstreamAPIKeys(a, b []config.AmpUpstreamAPIKeyEntry) bool {
336+ if len(a) != len(b) {
337+ return false
338+ }
339+ for i := range a {
340+ if strings.TrimSpace(a[i].UpstreamAPIKey) != strings.TrimSpace(b[i].UpstreamAPIKey) {
341+ return false
342+ }
343+ if !equalStringSet(a[i].APIKeys, b[i].APIKeys) {
344+ return false
345+ }
346+ }
347+ return true
348+}
test/amp_management_test.go+88−0
@@ -56,6 +56,10 @@ func setupAmpRouter(h *management.Handler) *gin.Engine { · 55 unmodified lines
5656 mgmt.GET("/ampcode/upstream-api-key", h.GetAmpUpstreamAPIKey)
5757 mgmt.PUT("/ampcode/upstream-api-key", h.PutAmpUpstreamAPIKey)
5858 mgmt.DELETE("/ampcode/upstream-api-key", h.DeleteAmpUpstreamAPIKey)
59+ mgmt.GET("/ampcode/upstream-api-keys", h.GetAmpUpstreamAPIKeys)
60+ mgmt.PUT("/ampcode/upstream-api-keys", h.PutAmpUpstreamAPIKeys)
61+ mgmt.PATCH("/ampcode/upstream-api-keys", h.PatchAmpUpstreamAPIKeys)
62+ mgmt.DELETE("/ampcode/upstream-api-keys", h.DeleteAmpUpstreamAPIKeys)
5963 mgmt.GET("/ampcode/restrict-management-to-localhost", h.GetAmpRestrictManagementToLocalhost)
6064 mgmt.PUT("/ampcode/restrict-management-to-localhost", h.PutAmpRestrictManagementToLocalhost)
6165 mgmt.GET("/ampcode/model-mappings", h.GetAmpModelMappings)
@@ -188,6 +192,90 @@ func TestPutAmpUpstreamAPIKey(t *testing.T) { · 126 unmodified lines
188192 }
189193 }
190194
195+func TestPutAmpUpstreamAPIKeys_PersistsAndReturns(t *testing.T) {
196+ h, configPath := newAmpTestHandler(t)
197+ r := setupAmpRouter(h)
198+
199+ body := `{"value":[{"upstream-api-key":" u1 ","api-keys":[" k1 ","","k2"]}]}`
200+ req := httptest.NewRequest(http.MethodPut, "/v0/management/ampcode/upstream-api-keys", bytes.NewBufferString(body))
201+ req.Header.Set("Content-Type", "application/json")
202+ w := httptest.NewRecorder()
203+ r.ServeHTTP(w, req)
204+
205+ if w.Code != http.StatusOK {
206+ t.Fatalf("expected status %d, got %d: %s", http.StatusOK, w.Code, w.Body.String())
207+ }
208+
209+ // Verify it was persisted to disk
210+ loaded, err := config.LoadConfig(configPath)
211+ if err != nil {
212+ t.Fatalf("failed to load config from disk: %v", err)
213+ }
214+ if len(loaded.AmpCode.UpstreamAPIKeys) != 1 {
215+ t.Fatalf("expected 1 upstream-api-keys entry, got %d", len(loaded.AmpCode.UpstreamAPIKeys))
216+ }
217+ entry := loaded.AmpCode.UpstreamAPIKeys[0]
218+ if entry.UpstreamAPIKey != "u1" {
219+ t.Fatalf("expected upstream-api-key u1, got %q", entry.UpstreamAPIKey)
220+ }
221+ if len(entry.APIKeys) != 2 || entry.APIKeys[0] != "k1" || entry.APIKeys[1] != "k2" {
222+ t.Fatalf("expected api-keys [k1 k2], got %#v", entry.APIKeys)
223+ }
224+
225+ // Verify it is returned by GET /ampcode
226+ req = httptest.NewRequest(http.MethodGet, "/v0/management/ampcode", nil)
227+ w = httptest.NewRecorder()
228+ r.ServeHTTP(w, req)
229+ if w.Code != http.StatusOK {
230+ t.Fatalf("expected status %d, got %d", http.StatusOK, w.Code)
231+ }
232+ var resp map[string]config.AmpCode
233+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
234+ t.Fatalf("failed to unmarshal response: %v", err)
235+ }
236+ if got := resp["ampcode"].UpstreamAPIKeys; len(got) != 1 || got[0].UpstreamAPIKey != "u1" {
237+ t.Fatalf("expected upstream-api-keys to be present after update, got %#v", got)
238+ }
239+}
240+
241+func TestDeleteAmpUpstreamAPIKeys_ClearsAll(t *testing.T) {
242+ h, _ := newAmpTestHandler(t)
243+ r := setupAmpRouter(h)
244+
245+ // Seed with one entry
246+ putBody := `{"value":[{"upstream-api-key":"u1","api-keys":["k1"]}]}`
247+ req := httptest.NewRequest(http.MethodPut, "/v0/management/ampcode/upstream-api-keys", bytes.NewBufferString(putBody))
248+ req.Header.Set("Content-Type", "application/json")
249+ w := httptest.NewRecorder()
250+ r.ServeHTTP(w, req)
251+ if w.Code != http.StatusOK {
252+ t.Fatalf("expected status %d, got %d: %s", http.StatusOK, w.Code, w.Body.String())
253+ }
254+
255+ deleteBody := `{"value":[]}`
256+ req = httptest.NewRequest(http.MethodDelete, "/v0/management/ampcode/upstream-api-keys", bytes.NewBufferString(deleteBody))
257+ req.Header.Set("Content-Type", "application/json")
258+ w = httptest.NewRecorder()
259+ r.ServeHTTP(w, req)
260+ if w.Code != http.StatusOK {
261+ t.Fatalf("expected status %d, got %d", http.StatusOK, w.Code)
262+ }
263+
264+ req = httptest.NewRequest(http.MethodGet, "/v0/management/ampcode/upstream-api-keys", nil)
265+ w = httptest.NewRecorder()
266+ r.ServeHTTP(w, req)
267+ if w.Code != http.StatusOK {
268+ t.Fatalf("expected status %d, got %d", http.StatusOK, w.Code)
269+ }
270+ var resp map[string][]config.AmpUpstreamAPIKeyEntry
271+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
272+ t.Fatalf("failed to unmarshal response: %v", err)
273+ }
274+ if resp["upstream-api-keys"] != nil && len(resp["upstream-api-keys"]) != 0 {
275+ t.Fatalf("expected cleared list, got %#v", resp["upstream-api-keys"])
276+ }
277+}
278+
191279 // TestDeleteAmpUpstreamAPIKey verifies DELETE /v0/management/ampcode/upstream-api-key clears the API key.
192280 func TestDeleteAmpUpstreamAPIKey(t *testing.T) {
193281 h, _ := newAmpTestHandler(t)

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t