Amp
Unified · Split
| @@ -112,5 +112,10 @@ func shouldLogRequest(path string) bool { · 111 unmodified lines | ||
| 112 | 112 | if strings.HasPrefix(path, "/v0/management") || strings.HasPrefix(path, "/management") { |
| 113 | 113 | return false |
| 114 | 114 | } |
| 115 | + | |
| 116 | + if strings.HasPrefix(path, "/api") { | |
| 117 | + return strings.HasPrefix(path, "/api/provider") | |
| 118 | + } | |
| 119 | + | |
| 115 | 120 | return true |
| 116 | 121 | } |
| @@ -126,6 +126,9 @@ func (m *AmpModule) Register(ctx modules.Context) error { · 125 unmodified lines | ||
| 126 | 126 | // Always register provider aliases - these work without an upstream |
| 127 | 127 | m.registerProviderAliases(ctx.Engine, ctx.BaseHandler, auth) |
| 128 | 128 | |
| 129 | + // Register management proxy routes once; middleware will gate access when upstream is unavailable. | |
| 130 | + m.registerManagementRoutes(ctx.Engine, ctx.BaseHandler) | |
| 131 | + | |
| 129 | 132 | // If no upstream URL, skip proxy routes but provider aliases are still available |
| 130 | 133 | if upstreamURL == "" { |
| 131 | 134 | log.Debug("amp upstream proxy disabled (no upstream URL configured)") |
| @@ -134,27 +137,11 @@ func (m *AmpModule) Register(ctx modules.Context) error { · 2 unmodified lines | ||
| 134 | 137 | return |
| 135 | 138 | } |
| 136 | 139 | |
| 137 | − // Create secret source with precedence: config > env > file | |
| 138 | − // Cache secrets for 5 minutes to reduce file I/O | |
| 139 | − if m.secretSource == nil { | |
| 140 | − m.secretSource = NewMultiSourceSecret(settings.UpstreamAPIKey, 0 /* default 5min */) | |
| 141 | − } | |
| 142 | − | |
| 143 | − // Create reverse proxy with gzip handling via ModifyResponse | |
| 144 | − proxy, err := createReverseProxy(upstreamURL, m.secretSource) | |
| 145 | − if err != nil { | |
| 140 | + if err := m.enableUpstreamProxy(upstreamURL, &settings); err != nil { | |
| 146 | 141 | regErr = fmt.Errorf("failed to create amp proxy: %w", err) |
| 147 | 142 | return |
| 148 | 143 | } |
| 149 | 144 | |
| 150 | − m.setProxy(proxy) | |
| 151 | − m.enabled = true | |
| 152 | − | |
| 153 | − // Register management proxy routes (requires upstream) | |
| 154 | − // Uses dynamic middleware that checks m.IsRestrictedToLocalhost() for hot-reload support | |
| 155 | − m.registerManagementRoutes(ctx.Engine, ctx.BaseHandler) | |
| 156 | − | |
| 157 | − log.Infof("amp upstream proxy enabled for: %s", upstreamURL) | |
| 158 | 145 | log.Debug("amp provider alias routes registered") |
| 159 | 146 | }) |
| 160 | 147 | |
| @@ -188,18 +175,30 @@ func (m *AmpModule) OnConfigUpdated(cfg *config.Config) error { · 27 unmodified lines | ||
| 188 | 175 | oldSettings := m.lastConfig |
| 189 | 176 | m.configMu.RUnlock() |
| 190 | 177 | |
| 191 | − // Track what changed for logging | |
| 192 | − var changes []string | |
| 178 | + if oldSettings != nil && oldSettings.RestrictManagementToLocalhost != newSettings.RestrictManagementToLocalhost { | |
| 179 | + m.setRestrictToLocalhost(newSettings.RestrictManagementToLocalhost) | |
| 180 | + if !newSettings.RestrictManagementToLocalhost { | |
| 181 | + log.Warnf("amp management routes now accessible from any IP - this is insecure!") | |
| 182 | + } | |
| 183 | + } | |
| 184 | + | |
| 185 | + newUpstreamURL := strings.TrimSpace(newSettings.UpstreamURL) | |
| 186 | + oldUpstreamURL := "" | |
| 187 | + if oldSettings != nil { | |
| 188 | + oldUpstreamURL = strings.TrimSpace(oldSettings.UpstreamURL) | |
| 189 | + } | |
| 190 | + | |
| 191 | + if !m.enabled && newUpstreamURL != "" { | |
| 192 | + if err := m.enableUpstreamProxy(newUpstreamURL, &newSettings); err != nil { | |
| 193 | + log.Errorf("amp config: failed to enable upstream proxy for %s: %v", newUpstreamURL, err) | |
| 194 | + } | |
| 195 | + } | |
| 193 | 196 | |
| 194 | 197 | // Check model mappings change |
| 195 | 198 | modelMappingsChanged := m.hasModelMappingsChanged(oldSettings, &newSettings) |
| 196 | 199 | if modelMappingsChanged { |
| 197 | 200 | if m.modelMapper != nil { |
| 198 | 201 | m.modelMapper.UpdateMappings(newSettings.ModelMappings) |
| 199 | − changes = append(changes, "model-mappings") | |
| 200 | − if m.enabled { | |
| 201 | − log.Infof("amp config partial reload: model mappings updated (%d entries)", len(newSettings.ModelMappings)) | |
| 202 | − } | |
| 203 | 202 | } else if m.enabled { |
| 204 | 203 | log.Warnf("amp model mapper not initialized, skipping model mapping update") |
| 205 | 204 | } |
| @@ -207,25 +206,16 @@ func (m *AmpModule) OnConfigUpdated(cfg *config.Config) error { · 1 unmodified line | ||
| 207 | 206 | |
| 208 | 207 | if m.enabled { |
| 209 | 208 | // Check upstream URL change - now supports hot-reload |
| 210 | − newUpstreamURL := strings.TrimSpace(newSettings.UpstreamURL) | |
| 211 | − oldUpstreamURL := "" | |
| 212 | − if oldSettings != nil { | |
| 213 | − oldUpstreamURL = strings.TrimSpace(oldSettings.UpstreamURL) | |
| 214 | − } | |
| 215 | − | |
| 216 | 209 | if newUpstreamURL == "" && oldUpstreamURL != "" { |
| 217 | − log.Warn("amp upstream URL removed from config, proxy has been disabled") | |
| 218 | 210 | m.setProxy(nil) |
| 219 | − changes = append(changes, "upstream-url(disabled)") | |
| 220 | − } else if newUpstreamURL != oldUpstreamURL && newUpstreamURL != "" { | |
| 211 | + m.enabled = false | |
| 212 | + } else if oldUpstreamURL != "" && newUpstreamURL != oldUpstreamURL && newUpstreamURL != "" { | |
| 221 | 213 | // Recreate proxy with new URL |
| 222 | 214 | proxy, err := createReverseProxy(newUpstreamURL, m.secretSource) |
| 223 | 215 | if err != nil { |
| 224 | 216 | log.Errorf("amp config: failed to create proxy for new upstream URL %s: %v", newUpstreamURL, err) |
| 225 | 217 | } else { |
| 226 | 218 | m.setProxy(proxy) |
| 227 | − changes = append(changes, "upstream-url") | |
| 228 | − log.Infof("amp config partial reload: upstream URL updated (%s -> %s)", oldUpstreamURL, newUpstreamURL) | |
| 229 | 219 | } |
| 230 | 220 | } |
| 231 | 221 | |
| @@ -236,22 +226,10 @@ func (m *AmpModule) OnConfigUpdated(cfg *config.Config) error { · 4 unmodified lines | ||
| 236 | 226 | if ms, ok := m.secretSource.(*MultiSourceSecret); ok { |
| 237 | 227 | ms.UpdateExplicitKey(newSettings.UpstreamAPIKey) |
| 238 | 228 | ms.InvalidateCache() |
| 239 | − changes = append(changes, "upstream-api-key") | |
| 240 | − log.Debug("amp config partial reload: secret cache invalidated") | |
| 241 | 229 | } |
| 242 | 230 | } |
| 243 | 231 | } |
| 244 | 232 | |
| 245 | − // Check restrict-management-to-localhost change - now supports hot-reload | |
| 246 | − if oldSettings != nil && oldSettings.RestrictManagementToLocalhost != newSettings.RestrictManagementToLocalhost { | |
| 247 | − m.setRestrictToLocalhost(newSettings.RestrictManagementToLocalhost) | |
| 248 | − changes = append(changes, "restrict-management-to-localhost") | |
| 249 | − if newSettings.RestrictManagementToLocalhost { | |
| 250 | − log.Infof("amp config partial reload: management routes now restricted to localhost") | |
| 251 | − } else { | |
| 252 | − log.Warnf("amp config partial reload: management routes now accessible from any IP - this is insecure!") | |
| 253 | − } | |
| 254 | − } | |
| 255 | 233 | } |
| 256 | 234 | |
| 257 | 235 | // Store current config for next comparison |
| @@ -260,13 +238,26 @@ func (m *AmpModule) OnConfigUpdated(cfg *config.Config) error { · 2 unmodified lines | ||
| 260 | 238 | m.lastConfig = &settingsCopy |
| 261 | 239 | m.configMu.Unlock() |
| 262 | 240 | |
| 263 | − // Log summary if any changes detected | |
| 264 | − if len(changes) > 0 { | |
| 265 | − log.Debugf("amp config partial reload completed: %v", changes) | |
| 266 | − } else { | |
| 267 | − log.Debug("amp config checked: no changes detected") | |
| 241 | + return nil | |
| 242 | +} | |
| 243 | + | |
| 244 | +func (m *AmpModule) enableUpstreamProxy(upstreamURL string, settings *config.AmpCode) error { | |
| 245 | + if m.secretSource == nil { | |
| 246 | + m.secretSource = NewMultiSourceSecret(settings.UpstreamAPIKey, 0 /* default 5min */) | |
| 247 | + } else if ms, ok := m.secretSource.(*MultiSourceSecret); ok { | |
| 248 | + ms.UpdateExplicitKey(settings.UpstreamAPIKey) | |
| 249 | + ms.InvalidateCache() | |
| 268 | 250 | } |
| 269 | 251 | |
| 252 | + proxy, err := createReverseProxy(upstreamURL, m.secretSource) | |
| 253 | + if err != nil { | |
| 254 | + return err | |
| 255 | + } | |
| 256 | + | |
| 257 | + m.setProxy(proxy) | |
| 258 | + m.enabled = true | |
| 259 | + | |
| 260 | + log.Infof("amp upstream proxy enabled for: %s", upstreamURL) | |
| 270 | 261 | return nil |
| 271 | 262 | } |
| 272 | 263 | |
| @@ -48,25 +48,25 @@ func logAmpRouting(routeType AmpRouteType, requestedModel, resolvedModel, provid · 47 unmodified lines | ||
| 48 | 48 | case RouteTypeLocalProvider: |
| 49 | 49 | fields["cost"] = "free" |
| 50 | 50 | fields["source"] = "local_oauth" |
| 51 | − log.WithFields(fields).Infof("[amp] using local provider for model: %s", requestedModel) | |
| 51 | + log.WithFields(fields).Debugf("amp using local provider for model: %s", requestedModel) | |
| 52 | 52 | |
| 53 | 53 | case RouteTypeModelMapping: |
| 54 | 54 | fields["cost"] = "free" |
| 55 | 55 | fields["source"] = "local_oauth" |
| 56 | 56 | fields["mapping"] = requestedModel + " -> " + resolvedModel |
| 57 | − log.WithFields(fields).Infof("[amp] model mapped: %s -> %s", requestedModel, resolvedModel) | |
| 57 | + // model mapping already logged in mapper; avoid duplicate here | |
| 58 | 58 | |
| 59 | 59 | case RouteTypeAmpCredits: |
| 60 | 60 | fields["cost"] = "amp_credits" |
| 61 | 61 | fields["source"] = "ampcode.com" |
| 62 | 62 | fields["model_id"] = requestedModel // Explicit model_id for easy config reference |
| 63 | − log.WithFields(fields).Warnf("[amp] forwarding to ampcode.com (uses amp credits) - model_id: %s | To use local proxy, add to config: amp-model-mappings: [{from: \"%s\", to: \"<your-local-model>\"}]", requestedModel, requestedModel) | |
| 63 | + log.WithFields(fields).Warnf("forwarding to ampcode.com (uses amp credits) - model_id: %s | To use local proxy, add to config: amp-model-mappings: [{from: \"%s\", to: \"<your-local-model>\"}]", requestedModel, requestedModel) | |
| 64 | 64 | |
| 65 | 65 | case RouteTypeNoProvider: |
| 66 | 66 | fields["cost"] = "none" |
| 67 | 67 | fields["source"] = "error" |
| 68 | 68 | fields["model_id"] = requestedModel // Explicit model_id for easy config reference |
| 69 | − log.WithFields(fields).Warnf("[amp] no provider available for model_id: %s", requestedModel) | |
| 69 | + log.WithFields(fields).Warnf("no provider available for model_id: %s", requestedModel) | |
| 70 | 70 | } |
| 71 | 71 | } |
| 72 | 72 | |
| @@ -2,10 +2,12 @@ package amp · 1 unmodified line | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "net" |
| 5 | + "net/http" | |
| 5 | 6 | "net/http/httputil" |
| 6 | 7 | "strings" |
| 7 | 8 | |
| 8 | 9 | "github.com/gin-gonic/gin" |
| 10 | + "github.com/router-for-me/CLIProxyAPI/v6/internal/logging" | |
| 9 | 11 | "github.com/router-for-me/CLIProxyAPI/v6/internal/util" |
| 10 | 12 | "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers" |
| 11 | 13 | "github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/claude" |
| @@ -78,6 +80,21 @@ func noCORSMiddleware() gin.HandlerFunc { · 66 unmodified lines | ||
| 78 | 80 | } |
| 79 | 81 | } |
| 80 | 82 | |
| 83 | +// managementAvailabilityMiddleware short-circuits management routes when the upstream | |
| 84 | +// proxy is disabled, preventing noisy localhost warnings and accidental exposure. | |
| 85 | +func (m *AmpModule) managementAvailabilityMiddleware() gin.HandlerFunc { | |
| 86 | + return func(c *gin.Context) { | |
| 87 | + if m.getProxy() == nil { | |
| 88 | + logging.SkipGinRequestLogging(c) | |
| 89 | + c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{ | |
| 90 | + "error": "amp upstream proxy not available", | |
| 91 | + }) | |
| 92 | + return | |
| 93 | + } | |
| 94 | + c.Next() | |
| 95 | + } | |
| 96 | +} | |
| 97 | + | |
| 81 | 98 | // registerManagementRoutes registers Amp management proxy routes |
| 82 | 99 | // These routes proxy through to the Amp control plane for OAuth, user management, etc. |
| 83 | 100 | // Uses dynamic middleware and proxy getter for hot-reload support. |
| @@ -85,14 +102,12 @@ func (m *AmpModule) registerManagementRoutes(engine *gin.Engine, baseHandler *ha · 1 unmodified line | ||
| 85 | 102 | ampAPI := engine.Group("/api") |
| 86 | 103 | |
| 87 | 104 | // Always disable CORS for management routes to prevent browser-based attacks |
| 88 | − ampAPI.Use(noCORSMiddleware()) | |
| 105 | + ampAPI.Use(m.managementAvailabilityMiddleware(), noCORSMiddleware()) | |
| 89 | 106 | |
| 90 | 107 | // Apply dynamic localhost-only restriction (hot-reloadable via m.IsRestrictedToLocalhost()) |
| 91 | 108 | ampAPI.Use(m.localhostOnlyMiddleware()) |
| 92 | 109 | |
| 93 | − if m.IsRestrictedToLocalhost() { | |
| 94 | − log.Info("amp management routes restricted to localhost only (CORS disabled)") | |
| 95 | − } else { | |
| 110 | + if !m.IsRestrictedToLocalhost() { | |
| 96 | 111 | log.Warn("amp management routes are NOT restricted to localhost - this is insecure!") |
| 97 | 112 | } |
| 98 | 113 | |
| @@ -127,7 +142,8 @@ func (m *AmpModule) registerManagementRoutes(engine *gin.Engine, baseHandler *ha · 28 unmodified lines | ||
| 127 | 142 | |
| 128 | 143 | // Root-level routes that AMP CLI expects without /api prefix |
| 129 | 144 | // These need the same security middleware as the /api/* routes (dynamic for hot-reload) |
| 130 | − rootMiddleware := []gin.HandlerFunc{noCORSMiddleware(), m.localhostOnlyMiddleware()} | |
| 145 | + rootMiddleware := []gin.HandlerFunc{m.managementAvailabilityMiddleware(), noCORSMiddleware(), m.localhostOnlyMiddleware()} | |
| 146 | + engine.GET("/threads/*path", append(rootMiddleware, proxyHandler)...) | |
| 131 | 147 | engine.GET("/threads.rss", append(rootMiddleware, proxyHandler)...) |
| 132 | 148 | |
| 133 | 149 | // Root-level auth routes for CLI login flow |
| @@ -47,6 +47,7 @@ func TestRegisterManagementRoutes(t *testing.T) { · 46 unmodified lines | ||
| 47 | 47 | {"/api/meta", http.MethodGet}, |
| 48 | 48 | {"/api/telemetry", http.MethodGet}, |
| 49 | 49 | {"/api/threads", http.MethodGet}, |
| 50 | + {"/threads/", http.MethodGet}, | |
| 50 | 51 | {"/threads.rss", http.MethodGet}, // Root-level route (no /api prefix) |
| 51 | 52 | {"/api/otel", http.MethodGet}, |
| 52 | 53 | {"/api/tab", http.MethodGet}, |
| @@ -14,6 +14,8 @@ import ( · 13 unmodified lines | ||
| 14 | 14 | log "github.com/sirupsen/logrus" |
| 15 | 15 | ) |
| 16 | 16 | |
| 17 | +const skipGinLogKey = "__gin_skip_request_logging__" | |
| 18 | + | |
| 17 | 19 | // GinLogrusLogger returns a Gin middleware handler that logs HTTP requests and responses |
| 18 | 20 | // using logrus. It captures request details including method, path, status code, latency, |
| 19 | 21 | // client IP, and any error messages, formatting them in a Gin-style log format. |
| @@ -28,6 +30,10 @@ func GinLogrusLogger() gin.HandlerFunc { · 8 unmodified lines | ||
| 28 | 30 | |
| 29 | 31 | c.Next() |
| 30 | 32 | |
| 33 | + if shouldSkipGinRequestLogging(c) { | |
| 34 | + return | |
| 35 | + } | |
| 36 | + | |
| 31 | 37 | if raw != "" { |
| 32 | 38 | path = path + "?" + raw |
| 33 | 39 | } |
| @@ -77,3 +83,24 @@ func GinLogrusRecovery() gin.HandlerFunc { · 43 unmodified lines | ||
| 77 | 83 | c.AbortWithStatus(http.StatusInternalServerError) |
| 78 | 84 | }) |
| 79 | 85 | } |
| 86 | + | |
| 87 | +// SkipGinRequestLogging marks the provided Gin context so that GinLogrusLogger | |
| 88 | +// will skip emitting a log line for the associated request. | |
| 89 | +func SkipGinRequestLogging(c *gin.Context) { | |
| 90 | + if c == nil { | |
| 91 | + return | |
| 92 | + } | |
| 93 | + c.Set(skipGinLogKey, true) | |
| 94 | +} | |
| 95 | + | |
| 96 | +func shouldSkipGinRequestLogging(c *gin.Context) bool { | |
| 97 | + if c == nil { | |
| 98 | + return false | |
| 99 | + } | |
| 100 | + val, exists := c.Get(skipGinLogKey) | |
| 101 | + if !exists { | |
| 102 | + return false | |
| 103 | + } | |
| 104 | + flag, ok := val.(bool) | |
| 105 | + return ok && flag | |
| 106 | +} | |