Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: incorrect api-key validation
Kyle Mendellcfaf05f6b620
diff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.goindex 13751354b..191d54344 100644--- a/backend/internal/huma/huma.go+++ b/backend/internal/huma/huma.go@@ -186,7 +186,7 @@ func SetupAPI(router *gin.Engine, apiGroup *gin.RouterGroup, cfg *config.Config,api := humagin.NewWithGroup(router, apiGroup, humaConfig)// Add authentication middleware- api.UseMiddleware(middleware.NewAuthBridge(svc.Auth, svc.ApiKey, cfg))+ api.UseMiddleware(middleware.NewAuthBridge(api, svc.Auth, svc.ApiKey, cfg))// Register all Huma handlersregisterHandlers(api, svc)diff --git a/backend/internal/huma/middleware/auth.go b/backend/internal/huma/middleware/auth.goindex 031d6f412..eb2d68ffd 100644--- a/backend/internal/huma/middleware/auth.go+++ b/backend/internal/huma/middleware/auth.go@@ -55,8 +55,12 @@ type securityRequirements struct {apiKeyAuth bool}+type operationProvider interface {+ Operation() *huma.Operation+}+// parseSecurityRequirements extracts security requirements from a Huma operation.-func parseSecurityRequirements(ctx huma.Context) securityRequirements {+func parseSecurityRequirements(ctx operationProvider) securityRequirements {reqs := securityRequirements{}if ctx.Operation() == nil || len(ctx.Operation().Security) == 0 {return reqs@@ -138,7 +142,7 @@ func createAgentSudoUser() *models.User {// NewAuthBridge creates a Huma middleware that validates JWT tokens and// enforces security requirements defined on operations.-func NewAuthBridge(authService *services.AuthService, apiKeyService *services.ApiKeyService, cfg *config.Config) func(ctx huma.Context, next func(huma.Context)) {+func NewAuthBridge(api huma.API, authService *services.AuthService, apiKeyService *services.ApiKeyService, cfg *config.Config) func(ctx huma.Context, next func(huma.Context)) {return func(ctx huma.Context, next func(huma.Context)) {if authService == nil {next(ctx)@@ -161,17 +165,22 @@ func NewAuthBridge(authService *services.AuthService, apiKeyService *services.Apreturn}- if reqs.bearerAuth {- if user, ok := tryBearerAuth(ctx, authService); ok {+ // If API key header is present and API key auth is allowed, prioritize it.+ // If validation fails, do NOT fall back to Bearer auth.+ if reqs.apiKeyAuth && ctx.Header(headerApiKey) != "" {+ if user, ok := tryApiKeyAuth(ctx, apiKeyService); ok {newCtx := setUserInContext(ctx.Context(), user)ctx = huma.WithContext(ctx, newCtx)next(ctx)return}+ // API key was present but invalid. Fail immediately.+ huma.WriteErr(api, ctx, http.StatusUnauthorized, "Unauthorized: invalid API key")+ return}- if reqs.apiKeyAuth {- if user, ok := tryApiKeyAuth(ctx, apiKeyService); ok {+ if reqs.bearerAuth {+ if user, ok := tryBearerAuth(ctx, authService); ok {newCtx := setUserInContext(ctx.Context(), user)ctx = huma.WithContext(ctx, newCtx)next(ctx)@@ -180,9 +189,7 @@ func NewAuthBridge(authService *services.AuthService, apiKeyService *services.Ap}// Write unauthorized response directly- ctx.SetStatus(http.StatusUnauthorized)- ctx.SetHeader("Content-Type", "application/json")- _, _ = ctx.BodyWriter().Write([]byte(`{"$schema":"","title":"Unauthorized","status":401,"detail":"Unauthorized: valid authentication required"}`))+ huma.WriteErr(api, ctx, http.StatusUnauthorized, "Unauthorized: valid authentication required")}}diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.goindex cf814967a..6c2b84946 100644--- a/backend/internal/services/auth_service.go+++ b/backend/internal/services/auth_service.go@@ -575,21 +575,18 @@ func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*modreturn nil, ErrTokenVersionMismatch}- user := &models.User{- BaseModel: models.BaseModel{ID: claims.ID},- Username: claims.Username,- Roles: models.StringSlice(claims.Roles),- }-- if claims.Email != "" {- user.Email = &claims.Email- }-- if claims.DisplayName != "" {- user.DisplayName = &claims.DisplayName+ // Verify user exists in DB+ // This ensures that if the database is wiped or user is deleted, the token becomes invalid+ // even if the JWT signature is still valid (e.g. same JWT_SECRET).+ dbUser, err := s.userService.GetUserByID(ctx, claims.ID)+ if err != nil {+ if errors.Is(err, ErrUserNotFound) {+ return nil, ErrInvalidToken+ }+ return nil, err}- return user, nil+ return dbUser, nil}func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPassword, newPassword string) error {diff --git a/backend/internal/services/auth_service_test.go b/backend/internal/services/auth_service_test.goindex 93e52ee68..89f1d5f1c 100644--- a/backend/internal/services/auth_service_test.go+++ b/backend/internal/services/auth_service_test.go@@ -70,37 +70,67 @@ func makeAccessToken(t *testing.T, secret []byte, subject string, id string, use}func TestVerifyToken_ValidClaims(t *testing.T) {+ db := setupAuthServiceTestDB(t)+ userSvc := NewUserService(db)s := newTestAuthService("")+ s.userService = userSvc++ // Create user in DB+ email := "[email protected]"+ displayName := "Alice"+ user := &models.User{+ BaseModel: models.BaseModel{ID: "u123"},+ Username: "alice",+ Email: &email,+ DisplayName: &displayName,+ Roles: models.StringSlice{"user", "admin"},+ }+ _, err := userSvc.CreateUser(context.Background(), user)+ require.NoError(t, err)+exp := time.Now().Add(5 * time.Minute)token := makeAccessToken(t, s.jwtSecret, "access", "u123", "alice", []string{"user", "admin"}, "[email protected]", "Alice", exp)- user, err := s.VerifyToken(context.Background(), token)+ verifiedUser, err := s.VerifyToken(context.Background(), token)if err != nil {t.Fatalf("VerifyToken error: %v", err)}- if user.ID != "u123" {- t.Errorf("id %q", user.ID)+ if verifiedUser.ID != "u123" {+ t.Errorf("id %q", verifiedUser.ID)}- if user.Username != "alice" {- t.Errorf("username %q", user.Username)+ if verifiedUser.Username != "alice" {+ t.Errorf("username %q", verifiedUser.Username)}- if len(user.Roles) != 2 || user.Roles[0] != "user" || user.Roles[1] != "admin" {- t.Errorf("roles %v", user.Roles)+ if len(verifiedUser.Roles) != 2 || verifiedUser.Roles[0] != "user" || verifiedUser.Roles[1] != "admin" {+ t.Errorf("roles %v", verifiedUser.Roles)}- if user.Email == nil || *user.Email != "[email protected]" {- t.Errorf("email %v", user.Email)+ if verifiedUser.Email == nil || *verifiedUser.Email != "[email protected]" {+ t.Errorf("email %v", verifiedUser.Email)}- if user.DisplayName == nil || *user.DisplayName != "Alice" {- t.Errorf("displayName %v", user.DisplayName)+ if verifiedUser.DisplayName == nil || *verifiedUser.DisplayName != "Alice" {+ t.Errorf("displayName %v", verifiedUser.DisplayName)}}func TestVerifyToken_Expired(t *testing.T) {+ db := setupAuthServiceTestDB(t)+ userSvc := NewUserService(db)s := newTestAuthService("")+ s.userService = userSvc++ // Create user in DB+ user := &models.User{+ BaseModel: models.BaseModel{ID: "u1"},+ Username: "bob",+ Roles: models.StringSlice{"user"},+ }+ _, err := userSvc.CreateUser(context.Background(), user)+ require.NoError(t, err)+exp := time.Now().Add(-1 * time.Minute)token := makeAccessToken(t, s.jwtSecret, "access", "u1", "bob", []string{"user"}, "", "", exp)- _, err := s.VerifyToken(context.Background(), token)+ _, err = s.VerifyToken(context.Background(), token)if !errors.Is(err, ErrExpiredToken) {t.Errorf("want ErrExpiredToken, got %v", err)}