Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix(GHSA-2jv8-39rp-cqqr): apply auth check before proxying request to environments (#1532)
Kyle Mendell2008e1b93b25
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.goindex b3131df87..1733032ce 100644--- a/backend/internal/bootstrap/bootstrap.go+++ b/backend/internal/bootstrap/bootstrap.go@@ -128,14 +128,27 @@ func handleAgentBootstrapPairing(ctx context.Context, cfg *config.Config, httpCl}defer resp.Body.Close()- if resp.StatusCode != http.StatusOK {- body, _ := io.ReadAll(resp.Body)+ body, _ := io.ReadAll(resp.Body)++ switch resp.StatusCode {+ case http.StatusOK:+ slog.InfoContext(ctx, "Successfully paired agent with manager", "managerUrl", cfg.ManagerApiUrl)+ return nil+ case http.StatusBadRequest:+ // Environment is not in pending status - already paired, this is fine+ if strings.Contains(string(body), "not in pending status") {+ slog.InfoContext(ctx, "Agent already paired with manager", "managerUrl", cfg.ManagerApiUrl)+ return nil+ }+ return fmt.Errorf("pairing failed with status %d: %s", resp.StatusCode, string(body))+ case http.StatusUnauthorized:+ // Invalid API key - could be already paired with a different key, or key was deleted+ // This is not fatal; the agent can still function if it has a valid token configured+ slog.DebugContext(ctx, "Pairing skipped - API key not recognized (agent may already be paired)", "managerUrl", cfg.ManagerApiUrl)+ return nil+ default:return fmt.Errorf("pairing failed with status %d: %s", resp.StatusCode, string(body))}-- slog.InfoContext(ctx, "Successfully paired agent with manager", "managerUrl", cfg.ManagerApiUrl)-- return nil}func runServices(appCtx context.Context, cfg *config.Config, router http.Handler, scheduler interface{ Run(context.Context) error }) error {diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex 75d47993a..2eb6763af 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -14,13 +14,75 @@ import ("github.com/getarcaneapp/arcane/backend/internal/config""github.com/getarcaneapp/arcane/backend/internal/huma""github.com/getarcaneapp/arcane/backend/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/internal/utils/cookie""github.com/getarcaneapp/arcane/types")var registerPlaywrightRoutes []func(apiGroup *gin.RouterGroup, services *Services)-func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {+var loggerSkipPatterns = []string{+ "GET /api/environments/*/ws/containers/*/logs",+ "GET /api/environments/*/ws/containers/*/stats",+ "GET /api/environments/*/ws/containers/*/terminal",+ "GET /api/environments/*/ws/projects/*/logs",+ "GET /api/environments/*/ws/system/stats",+ "GET /_app/*",+ "GET /img",+ "GET /api/fonts/sans",+ "GET /api/fonts/mono",+ "GET /api/fonts/serif",+ "GET /api/health",+ "HEAD /api/health",+}++func shouldLogRequest(c *gin.Context) bool {+ mp := c.Request.Method + " " + c.Request.URL.Path+ for _, pat := range loggerSkipPatterns {+ if pat == mp {+ return false+ }+ if strings.HasSuffix(pat, "/*") {+ prefix := strings.TrimSuffix(pat, "/*")+ if strings.HasPrefix(mp, prefix) {+ return false+ }+ }+ if ok, _ := path.Match(pat, mp); ok {+ return false+ }+ if strings.HasSuffix(pat, "/") && strings.HasPrefix(mp, pat) {+ return false+ }+ }+ return true+}++func createAuthValidator(appServices *Services) middleware.AuthValidator {+ return func(c *gin.Context) bool {+ // Check for API key authentication+ if apiKey := c.GetHeader("X-API-Key"); apiKey != "" {+ user, err := appServices.ApiKey.ValidateApiKey(c.Request.Context(), apiKey)+ return err == nil && user != nil+ }+ // Check for Bearer token authentication+ token := ""+ if auth := c.GetHeader("Authorization"); strings.HasPrefix(auth, "Bearer ") {+ token = strings.TrimPrefix(auth, "Bearer ")+ } else if cookieToken, err := cookie.GetTokenCookie(c); err == nil && cookieToken != "" {+ token = cookieToken+ }++ if token == "" {+ return false+ }++ user, err := appServices.Auth.VerifyToken(c.Request.Context(), token)+ return err == nil && user != nil+ }+}++func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {if cfg.Environment == "production" {gin.SetMode(gin.ReleaseMode)} else {@@ -29,45 +91,8 @@ func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {router := gin.New()router.Use(gin.Recovery())- loggerSkipPatterns := []string{- "GET /api/environments/*/ws/containers/*/logs",- "GET /api/environments/*/ws/containers/*/stats",- "GET /api/environments/*/ws/containers/*/terminal",- "GET /api/environments/*/ws/projects/*/logs",- "GET /api/environments/*/ws/system/stats",- "GET /_app/*",- "GET /img",- "GET /api/fonts/sans",- "GET /api/fonts/mono",- "GET /api/fonts/serif",- "GET /api/health",- "HEAD /api/health",- }-router.Use(sloggin.NewWithConfig(slog.Default(), sloggin.Config{- Filters: []sloggin.Filter{- func(c *gin.Context) bool {- mp := c.Request.Method + " " + c.Request.URL.Path- for _, pat := range loggerSkipPatterns {- if pat == mp {- return false- }- if strings.HasSuffix(pat, "/*") {- prefix := strings.TrimSuffix(pat, "/*")- if strings.HasPrefix(mp, prefix) {- return false- }- }- if ok, _ := path.Match(pat, mp); ok {- return false- }- if strings.HasSuffix(pat, "/") && strings.HasPrefix(mp, pat) {- return false- }- }- return true- },- },+ Filters: []sloggin.Filter{shouldLogRequest},}))authMiddleware := middleware.NewAuthMiddleware(appServices.Auth, cfg).WithApiKeyValidator(appServices.ApiKey)@@ -87,6 +112,7 @@ func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {return env.ApiUrl, env.AccessToken, env.Enabled, nil},appServices.Environment,+ createAuthValidator(appServices),)apiGroup.Use(envMiddleware)diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.goindex 6707357f5..fe82cb000 100644--- a/backend/internal/middleware/environment_middleware.go+++ b/backend/internal/middleware/environment_middleware.go@@ -34,6 +34,7 @@ const (errEnvironmentDisabled = "Environment is disabled"errFailedCreateProxyRequest = "Failed to create proxy request"errProxyRequestFailedPrefix = "Proxy request failed:"+ errUnauthorized = "Authentication required to access remote environments"// proxyTimeout is intentionally generous because some proxied operations// (e.g., image pulls with progress streaming) can take multiple minutes.@@ -44,13 +45,18 @@ const (// Returns: apiURL, accessToken, enabled, errortype EnvResolver func(ctx context.Context, id string) (string, *string, bool, error)+// AuthValidator validates authentication for a request.+// Returns true if the request is authenticated, false otherwise.+type AuthValidator func(c *gin.Context) bool+// EnvironmentMiddleware proxies requests for remote environments to their respective agents.type EnvironmentMiddleware struct {- localID string- paramName string- resolver EnvResolver- envService *services.EnvironmentService- httpClient *http.Client+ localID string+ paramName string+ resolver EnvResolver+ authValidator AuthValidator+ envService *services.EnvironmentService+ httpClient *http.Client}// NewEnvProxyMiddlewareWithParam creates middleware that proxies requests to remote environments.@@ -58,13 +64,15 @@ type EnvironmentMiddleware struct {// - paramName: the URL parameter name containing the environment ID (e.g., "id")// - resolver: function to resolve environment ID to connection details// - envService: environment service for additional lookups-func NewEnvProxyMiddlewareWithParam(localID, paramName string, resolver EnvResolver, envService *services.EnvironmentService) gin.HandlerFunc {+// - authValidator: function to validate authentication before proxying (required for security)+func NewEnvProxyMiddlewareWithParam(localID, paramName string, resolver EnvResolver, envService *services.EnvironmentService, authValidator AuthValidator) gin.HandlerFunc {m := &EnvironmentMiddleware{- localID: localID,- paramName: paramName,- resolver: resolver,- envService: envService,- httpClient: &http.Client{Timeout: proxyTimeout},+ localID: localID,+ paramName: paramName,+ resolver: resolver,+ authValidator: authValidator,+ envService: envService,+ httpClient: &http.Client{Timeout: proxyTimeout},}return m.Handle}@@ -87,6 +95,19 @@ func (m *EnvironmentMiddleware) Handle(c *gin.Context) {return}+ // SECURITY: Validate authentication BEFORE proxying to remote environments.+ // The proxy attaches the agent token to forwarded requests, which grants full access+ // on the remote agent. Without this check, unauthenticated users could access+ // remote environment resources.+ if m.authValidator != nil && !m.authValidator(c) {+ c.JSON(http.StatusUnauthorized, gin.H{+ "success": false,+ "data": gin.H{"error": errUnauthorized},+ })+ c.Abort()+ return+ }+// Resolve remote environmentapiURL, accessToken, enabled, err := m.resolver(c.Request.Context(), envID)if err != nil || apiURL == "" {