hkfires commited on
Commit
4651cf5
·
1 Parent(s): f5e431c

refactor(config): consolidate Amp settings into AmpCode struct

Browse files
internal/api/modules/amp/amp.go CHANGED
@@ -95,7 +95,8 @@ func (m *AmpModule) Name() string {
95
  // This implements the RouteModuleV2 interface with Context.
96
  // Routes are registered only once via sync.Once for idempotent behavior.
97
  func (m *AmpModule) Register(ctx modules.Context) error {
98
- upstreamURL := strings.TrimSpace(ctx.Config.AmpUpstreamURL)
 
99
 
100
  // Determine auth middleware (from module or context)
101
  auth := m.getAuthMiddleware(ctx)
@@ -104,7 +105,7 @@ func (m *AmpModule) Register(ctx modules.Context) error {
104
  var regErr error
105
  m.registerOnce.Do(func() {
106
  // Initialize model mapper from config (for routing unavailable models to alternatives)
107
- m.modelMapper = NewModelMapper(ctx.Config.AmpModelMappings)
108
 
109
  // Always register provider aliases - these work without an upstream
110
  m.registerProviderAliases(ctx.Engine, ctx.BaseHandler, auth)
@@ -120,7 +121,7 @@ func (m *AmpModule) Register(ctx modules.Context) error {
120
  // Create secret source with precedence: config > env > file
121
  // Cache secrets for 5 minutes to reduce file I/O
122
  if m.secretSource == nil {
123
- m.secretSource = NewMultiSourceSecret(ctx.Config.AmpUpstreamAPIKey, 0 /* default 5min */)
124
  }
125
 
126
  // Create reverse proxy with gzip handling via ModifyResponse
@@ -136,7 +137,7 @@ func (m *AmpModule) Register(ctx modules.Context) error {
136
  // Register management proxy routes (requires upstream)
137
  // Restrict to localhost by default for security (prevents drive-by browser attacks)
138
  handler := proxyHandler(proxy)
139
- m.registerManagementRoutes(ctx.Engine, ctx.BaseHandler, handler, ctx.Config.AmpRestrictManagementToLocalhost)
140
 
141
  log.Infof("Amp upstream proxy enabled for: %s", upstreamURL)
142
  log.Debug("Amp provider alias routes registered")
@@ -166,8 +167,9 @@ func (m *AmpModule) getAuthMiddleware(ctx modules.Context) gin.HandlerFunc {
166
  func (m *AmpModule) OnConfigUpdated(cfg *config.Config) error {
167
  // Update model mappings (hot-reload supported)
168
  if m.modelMapper != nil {
169
- log.Infof("amp config updated: reloading %d model mapping(s)", len(cfg.AmpModelMappings))
170
- m.modelMapper.UpdateMappings(cfg.AmpModelMappings)
 
171
  } else {
172
  log.Warnf("amp model mapper not initialized, skipping model mapping update")
173
  }
@@ -177,7 +179,7 @@ func (m *AmpModule) OnConfigUpdated(cfg *config.Config) error {
177
  return nil
178
  }
179
 
180
- upstreamURL := strings.TrimSpace(cfg.AmpUpstreamURL)
181
  if upstreamURL == "" {
182
  log.Warn("Amp upstream URL removed from config, restart required to disable")
183
  return nil
 
95
  // This implements the RouteModuleV2 interface with Context.
96
  // Routes are registered only once via sync.Once for idempotent behavior.
97
  func (m *AmpModule) Register(ctx modules.Context) error {
98
+ settings := ctx.Config.AmpCode
99
+ upstreamURL := strings.TrimSpace(settings.UpstreamURL)
100
 
101
  // Determine auth middleware (from module or context)
102
  auth := m.getAuthMiddleware(ctx)
 
105
  var regErr error
106
  m.registerOnce.Do(func() {
107
  // Initialize model mapper from config (for routing unavailable models to alternatives)
108
+ m.modelMapper = NewModelMapper(settings.ModelMappings)
109
 
110
  // Always register provider aliases - these work without an upstream
111
  m.registerProviderAliases(ctx.Engine, ctx.BaseHandler, auth)
 
121
  // Create secret source with precedence: config > env > file
122
  // Cache secrets for 5 minutes to reduce file I/O
123
  if m.secretSource == nil {
124
+ m.secretSource = NewMultiSourceSecret(settings.UpstreamAPIKey, 0 /* default 5min */)
125
  }
126
 
127
  // Create reverse proxy with gzip handling via ModifyResponse
 
137
  // Register management proxy routes (requires upstream)
138
  // Restrict to localhost by default for security (prevents drive-by browser attacks)
139
  handler := proxyHandler(proxy)
140
+ m.registerManagementRoutes(ctx.Engine, ctx.BaseHandler, handler, settings.RestrictManagementToLocalhost)
141
 
142
  log.Infof("Amp upstream proxy enabled for: %s", upstreamURL)
143
  log.Debug("Amp provider alias routes registered")
 
167
  func (m *AmpModule) OnConfigUpdated(cfg *config.Config) error {
168
  // Update model mappings (hot-reload supported)
169
  if m.modelMapper != nil {
170
+ settings := cfg.AmpCode
171
+ log.Infof("amp config updated: reloading %d model mapping(s)", len(settings.ModelMappings))
172
+ m.modelMapper.UpdateMappings(settings.ModelMappings)
173
  } else {
174
  log.Warnf("amp model mapper not initialized, skipping model mapping update")
175
  }
 
179
  return nil
180
  }
181
 
182
+ upstreamURL := strings.TrimSpace(cfg.AmpCode.UpstreamURL)
183
  if upstreamURL == "" {
184
  log.Warn("Amp upstream URL removed from config, restart required to disable")
185
  return nil
internal/api/modules/amp/amp_test.go CHANGED
@@ -56,8 +56,10 @@ func TestAmpModule_Register_WithUpstream(t *testing.T) {
56
  m := NewLegacy(accessManager, func(c *gin.Context) { c.Next() })
57
 
58
  cfg := &config.Config{
59
- AmpUpstreamURL: upstream.URL,
60
- AmpUpstreamAPIKey: "test-key",
 
 
61
  }
62
 
63
  ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }}
@@ -86,7 +88,9 @@ func TestAmpModule_Register_WithoutUpstream(t *testing.T) {
86
  m := NewLegacy(accessManager, func(c *gin.Context) { c.Next() })
87
 
88
  cfg := &config.Config{
89
- AmpUpstreamURL: "", // No upstream
 
 
90
  }
91
 
92
  ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }}
@@ -121,7 +125,9 @@ func TestAmpModule_Register_InvalidUpstream(t *testing.T) {
121
  m := NewLegacy(accessManager, func(c *gin.Context) { c.Next() })
122
 
123
  cfg := &config.Config{
124
- AmpUpstreamURL: "://invalid-url",
 
 
125
  }
126
 
127
  ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }}
@@ -151,7 +157,7 @@ func TestAmpModule_OnConfigUpdated_CacheInvalidation(t *testing.T) {
151
  }
152
 
153
  // Update config - should invalidate cache
154
- if err := m.OnConfigUpdated(&config.Config{AmpUpstreamURL: "http://x"}); err != nil {
155
  t.Fatal(err)
156
  }
157
 
@@ -175,7 +181,7 @@ func TestAmpModule_OnConfigUpdated_URLRemoved(t *testing.T) {
175
  m.secretSource = ms
176
 
177
  // Config update with empty URL - should log warning but not error
178
- cfg := &config.Config{AmpUpstreamURL: ""}
179
 
180
  if err := m.OnConfigUpdated(cfg); err != nil {
181
  t.Fatalf("unexpected error: %v", err)
@@ -187,7 +193,7 @@ func TestAmpModule_OnConfigUpdated_NonMultiSourceSecret(t *testing.T) {
187
  m := &AmpModule{enabled: true}
188
  m.secretSource = NewStaticSecretSource("static-key")
189
 
190
- cfg := &config.Config{AmpUpstreamURL: "http://example.com"}
191
 
192
  // Should not error or panic
193
  if err := m.OnConfigUpdated(cfg); err != nil {
@@ -240,8 +246,10 @@ func TestAmpModule_SecretSource_FromConfig(t *testing.T) {
240
 
241
  // Config with explicit API key
242
  cfg := &config.Config{
243
- AmpUpstreamURL: upstream.URL,
244
- AmpUpstreamAPIKey: "config-key",
 
 
245
  }
246
 
247
  ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }}
@@ -283,7 +291,7 @@ func TestAmpModule_ProviderAliasesAlwaysRegistered(t *testing.T) {
283
 
284
  m := NewLegacy(accessManager, func(c *gin.Context) { c.Next() })
285
 
286
- cfg := &config.Config{AmpUpstreamURL: scenario.configURL}
287
 
288
  ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }}
289
  if err := m.Register(ctx); err != nil && scenario.configURL != "" {
 
56
  m := NewLegacy(accessManager, func(c *gin.Context) { c.Next() })
57
 
58
  cfg := &config.Config{
59
+ AmpCode: config.AmpCode{
60
+ UpstreamURL: upstream.URL,
61
+ UpstreamAPIKey: "test-key",
62
+ },
63
  }
64
 
65
  ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }}
 
88
  m := NewLegacy(accessManager, func(c *gin.Context) { c.Next() })
89
 
90
  cfg := &config.Config{
91
+ AmpCode: config.AmpCode{
92
+ UpstreamURL: "", // No upstream
93
+ },
94
  }
95
 
96
  ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }}
 
125
  m := NewLegacy(accessManager, func(c *gin.Context) { c.Next() })
126
 
127
  cfg := &config.Config{
128
+ AmpCode: config.AmpCode{
129
+ UpstreamURL: "://invalid-url",
130
+ },
131
  }
132
 
133
  ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }}
 
157
  }
158
 
159
  // Update config - should invalidate cache
160
+ if err := m.OnConfigUpdated(&config.Config{AmpCode: config.AmpCode{UpstreamURL: "http://x"}}); err != nil {
161
  t.Fatal(err)
162
  }
163
 
 
181
  m.secretSource = ms
182
 
183
  // Config update with empty URL - should log warning but not error
184
+ cfg := &config.Config{AmpCode: config.AmpCode{UpstreamURL: ""}}
185
 
186
  if err := m.OnConfigUpdated(cfg); err != nil {
187
  t.Fatalf("unexpected error: %v", err)
 
193
  m := &AmpModule{enabled: true}
194
  m.secretSource = NewStaticSecretSource("static-key")
195
 
196
+ cfg := &config.Config{AmpCode: config.AmpCode{UpstreamURL: "http://example.com"}}
197
 
198
  // Should not error or panic
199
  if err := m.OnConfigUpdated(cfg); err != nil {
 
246
 
247
  // Config with explicit API key
248
  cfg := &config.Config{
249
+ AmpCode: config.AmpCode{
250
+ UpstreamURL: upstream.URL,
251
+ UpstreamAPIKey: "config-key",
252
+ },
253
  }
254
 
255
  ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }}
 
291
 
292
  m := NewLegacy(accessManager, func(c *gin.Context) { c.Next() })
293
 
294
+ cfg := &config.Config{AmpCode: config.AmpCode{UpstreamURL: scenario.configURL}}
295
 
296
  ctx := modules.Context{Engine: r, BaseHandler: base, Config: cfg, AuthMiddleware: func(c *gin.Context) { c.Next() }}
297
  if err := m.Register(ctx); err != nil && scenario.configURL != "" {
internal/config/config.go CHANGED
@@ -26,22 +26,8 @@ type Config struct {
26
  // TLS config controls HTTPS server settings.
27
  TLS TLSConfig `yaml:"tls" json:"tls"`
28
 
29
- // AmpUpstreamURL defines the upstream Amp control plane used for non-provider calls.
30
- AmpUpstreamURL string `yaml:"amp-upstream-url" json:"amp-upstream-url"`
31
-
32
- // AmpUpstreamAPIKey optionally overrides the Authorization header when proxying Amp upstream calls.
33
- AmpUpstreamAPIKey string `yaml:"amp-upstream-api-key" json:"amp-upstream-api-key"`
34
-
35
- // AmpRestrictManagementToLocalhost restricts Amp management routes (/api/user, /api/threads, etc.)
36
- // to only accept connections from localhost (127.0.0.1, ::1). When true, prevents drive-by
37
- // browser attacks and remote access to management endpoints. Default: true (recommended).
38
- AmpRestrictManagementToLocalhost bool `yaml:"amp-restrict-management-to-localhost" json:"amp-restrict-management-to-localhost"`
39
-
40
- // AmpModelMappings defines model name mappings for Amp CLI requests.
41
- // When Amp requests a model that isn't available locally, these mappings
42
- // allow routing to an alternative model that IS available.
43
- // Example: Map "claude-opus-4.5" -> "claude-sonnet-4" when opus isn't available.
44
- AmpModelMappings []AmpModelMapping `yaml:"amp-model-mappings" json:"amp-model-mappings"`
45
 
46
  // AuthDir is the directory where authentication token files are stored.
47
  AuthDir string `yaml:"auth-dir" json:"-"`
@@ -58,44 +44,44 @@ type Config struct {
58
  // DisableCooling disables quota cooldown scheduling when true.
59
  DisableCooling bool `yaml:"disable-cooling" json:"disable-cooling"`
60
 
 
 
 
 
 
61
  // QuotaExceeded defines the behavior when a quota is exceeded.
62
  QuotaExceeded QuotaExceeded `yaml:"quota-exceeded" json:"quota-exceeded"`
63
 
64
  // WebsocketAuth enables or disables authentication for the WebSocket API.
65
  WebsocketAuth bool `yaml:"ws-auth" json:"ws-auth"`
66
 
67
- // GlAPIKey exposes the legacy generative language API key list for backward compatibility.
68
- GlAPIKey []string `yaml:"generative-language-api-key" json:"generative-language-api-key"`
69
-
70
  // GeminiKey defines Gemini API key configurations with optional routing overrides.
71
  GeminiKey []GeminiKey `yaml:"gemini-api-key" json:"gemini-api-key"`
72
 
73
- // VertexCompatAPIKey defines Vertex AI-compatible API key configurations for third-party providers.
74
- // Used for services that use Vertex AI-style paths but with simple API key authentication.
75
- VertexCompatAPIKey []VertexCompatKey `yaml:"vertex-api-key" json:"vertex-api-key"`
76
 
77
- // RequestRetry defines the retry times when the request failed.
78
- RequestRetry int `yaml:"request-retry" json:"request-retry"`
79
- // MaxRetryInterval defines the maximum wait time in seconds before retrying a cooled-down credential.
80
- MaxRetryInterval int `yaml:"max-retry-interval" json:"max-retry-interval"`
81
 
82
  // ClaudeKey defines a list of Claude API key configurations as specified in the YAML configuration file.
83
  ClaudeKey []ClaudeKey `yaml:"claude-api-key" json:"claude-api-key"`
84
 
85
- // Codex defines a list of Codex API key configurations as specified in the YAML configuration file.
86
- CodexKey []CodexKey `yaml:"codex-api-key" json:"codex-api-key"`
87
-
88
  // OpenAICompatibility defines OpenAI API compatibility configurations for external providers.
89
  OpenAICompatibility []OpenAICompatibility `yaml:"openai-compatibility" json:"openai-compatibility"`
90
 
91
- // RemoteManagement nests management-related options under 'remote-management'.
92
- RemoteManagement RemoteManagement `yaml:"remote-management" json:"-"`
 
93
 
94
- // Payload defines default and override rules for provider payload parameters.
95
- Payload PayloadConfig `yaml:"payload" json:"payload"`
96
 
97
  // OAuthExcludedModels defines per-provider global model exclusions applied to OAuth/file-backed auth entries.
98
  OAuthExcludedModels map[string][]string `yaml:"oauth-excluded-models,omitempty" json:"oauth-excluded-models,omitempty"`
 
 
 
99
  }
100
 
101
  // TLSConfig holds HTTPS server settings.
@@ -140,6 +126,26 @@ type AmpModelMapping struct {
140
  To string `yaml:"to" json:"to"`
141
  }
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  // PayloadConfig defines default and override parameter rules applied to provider payloads.
144
  type PayloadConfig struct {
145
  // Default defines rules that only set parameters when they are missing in the payload.
@@ -318,7 +324,7 @@ func LoadConfigOptional(configFile string, optional bool) (*Config, error) {
318
  cfg.LoggingToFile = false
319
  cfg.UsageStatisticsEnabled = false
320
  cfg.DisableCooling = false
321
- cfg.AmpRestrictManagementToLocalhost = true // Default to secure: only localhost access
322
  if err = yaml.Unmarshal(data, &cfg); err != nil {
323
  if optional {
324
  // In cloud deploy mode, if YAML parsing fails, return empty config instead of error.
 
26
  // TLS config controls HTTPS server settings.
27
  TLS TLSConfig `yaml:"tls" json:"tls"`
28
 
29
+ // RemoteManagement nests management-related options under 'remote-management'.
30
+ RemoteManagement RemoteManagement `yaml:"remote-management" json:"-"`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
  // AuthDir is the directory where authentication token files are stored.
33
  AuthDir string `yaml:"auth-dir" json:"-"`
 
44
  // DisableCooling disables quota cooldown scheduling when true.
45
  DisableCooling bool `yaml:"disable-cooling" json:"disable-cooling"`
46
 
47
+ // RequestRetry defines the retry times when the request failed.
48
+ RequestRetry int `yaml:"request-retry" json:"request-retry"`
49
+ // MaxRetryInterval defines the maximum wait time in seconds before retrying a cooled-down credential.
50
+ MaxRetryInterval int `yaml:"max-retry-interval" json:"max-retry-interval"`
51
+
52
  // QuotaExceeded defines the behavior when a quota is exceeded.
53
  QuotaExceeded QuotaExceeded `yaml:"quota-exceeded" json:"quota-exceeded"`
54
 
55
  // WebsocketAuth enables or disables authentication for the WebSocket API.
56
  WebsocketAuth bool `yaml:"ws-auth" json:"ws-auth"`
57
 
 
 
 
58
  // GeminiKey defines Gemini API key configurations with optional routing overrides.
59
  GeminiKey []GeminiKey `yaml:"gemini-api-key" json:"gemini-api-key"`
60
 
61
+ // GlAPIKey exposes the legacy generative language API key list for backward compatibility.
62
+ GlAPIKey []string `yaml:"generative-language-api-key" json:"generative-language-api-key"`
 
63
 
64
+ // Codex defines a list of Codex API key configurations as specified in the YAML configuration file.
65
+ CodexKey []CodexKey `yaml:"codex-api-key" json:"codex-api-key"`
 
 
66
 
67
  // ClaudeKey defines a list of Claude API key configurations as specified in the YAML configuration file.
68
  ClaudeKey []ClaudeKey `yaml:"claude-api-key" json:"claude-api-key"`
69
 
 
 
 
70
  // OpenAICompatibility defines OpenAI API compatibility configurations for external providers.
71
  OpenAICompatibility []OpenAICompatibility `yaml:"openai-compatibility" json:"openai-compatibility"`
72
 
73
+ // VertexCompatAPIKey defines Vertex AI-compatible API key configurations for third-party providers.
74
+ // Used for services that use Vertex AI-style paths but with simple API key authentication.
75
+ VertexCompatAPIKey []VertexCompatKey `yaml:"vertex-api-key" json:"vertex-api-key"`
76
 
77
+ // AmpCode contains Amp CLI upstream configuration, management restrictions, and model mappings.
78
+ AmpCode AmpCode `yaml:"ampcode" json:"ampcode"`
79
 
80
  // OAuthExcludedModels defines per-provider global model exclusions applied to OAuth/file-backed auth entries.
81
  OAuthExcludedModels map[string][]string `yaml:"oauth-excluded-models,omitempty" json:"oauth-excluded-models,omitempty"`
82
+
83
+ // Payload defines default and override rules for provider payload parameters.
84
+ Payload PayloadConfig `yaml:"payload" json:"payload"`
85
  }
86
 
87
  // TLSConfig holds HTTPS server settings.
 
126
  To string `yaml:"to" json:"to"`
127
  }
128
 
129
+ // AmpCode groups Amp CLI integration settings including upstream routing,
130
+ // optional overrides, management route restrictions, and model fallback mappings.
131
+ type AmpCode struct {
132
+ // UpstreamURL defines the upstream Amp control plane used for non-provider calls.
133
+ UpstreamURL string `yaml:"upstream-url" json:"upstream-url"`
134
+
135
+ // UpstreamAPIKey optionally overrides the Authorization header when proxying Amp upstream calls.
136
+ UpstreamAPIKey string `yaml:"upstream-api-key" json:"upstream-api-key"`
137
+
138
+ // RestrictManagementToLocalhost restricts Amp management routes (/api/user, /api/threads, etc.)
139
+ // to only accept connections from localhost (127.0.0.1, ::1). When true, prevents drive-by
140
+ // browser attacks and remote access to management endpoints. Default: true (recommended).
141
+ RestrictManagementToLocalhost bool `yaml:"restrict-management-to-localhost" json:"restrict-management-to-localhost"`
142
+
143
+ // ModelMappings defines model name mappings for Amp CLI requests.
144
+ // When Amp requests a model that isn't available locally, these mappings
145
+ // allow routing to an alternative model that IS available.
146
+ ModelMappings []AmpModelMapping `yaml:"model-mappings" json:"model-mappings"`
147
+ }
148
+
149
  // PayloadConfig defines default and override parameter rules applied to provider payloads.
150
  type PayloadConfig struct {
151
  // Default defines rules that only set parameters when they are missing in the payload.
 
324
  cfg.LoggingToFile = false
325
  cfg.UsageStatisticsEnabled = false
326
  cfg.DisableCooling = false
327
+ cfg.AmpCode.RestrictManagementToLocalhost = true // Default to secure: only localhost access
328
  if err = yaml.Unmarshal(data, &cfg); err != nil {
329
  if optional {
330
  // In cloud deploy mode, if YAML parsing fails, return empty config instead of error.