Skip to content

Modern Docker Management, Designed for Everyone

fix: enforce configured password policy on all password creation and reset paths (#3505)

Kyle Mendelle1c68d9e535f
diff --git a/backend/api/api.go b/backend/api/api.go
index f50c3bd2b..5cb512b65 100644
--- a/backend/api/api.go
+++ b/backend/api/api.go
@@ -365,7 +365,7 @@ func registerHandlersInternal(api huma.API, deps HandlerDeps, handlerAppCtx hand
handlers.RegisterFederatedCredentials(api, deps.Federated)
handlers.RegisterRoles(api, deps.Role)
handlers.RegisterAppImages(api, deps.AppImages)
- handlers.RegisterUsers(api, deps.User, deps.Auth)
+ handlers.RegisterUsers(api, deps.User, deps.Auth, deps.Settings)
handlers.RegisterProjects(api, deps.Project, deps.Activity, handlerAppCtx)
handlers.RegisterVersion(api, deps.Version)
handlers.RegisterEvents(api, deps.Event)
diff --git a/backend/api/handlers/auth.go b/backend/api/handlers/auth.go
index a48eef065..9bceea776 100644
--- a/backend/api/handlers/auth.go
+++ b/backend/api/handlers/auth.go
@@ -397,6 +397,8 @@ func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordI
switch {
case errors.Is(err, services.ErrInvalidCredentials):
return nil, huma.Error401Unauthorized("Current password is incorrect")
+ case errors.Is(err, common.ErrValidation):
+ return nil, huma.Error400BadRequest(err.Error())
default:
return nil, huma.Error500InternalServerError("Failed to change password")
}
diff --git a/backend/api/handlers/users.go b/backend/api/handlers/users.go
index 0ab121ec5..c8a86737f 100644
--- a/backend/api/handlers/users.go
+++ b/backend/api/handlers/users.go
@@ -19,8 +19,9 @@ import (
// UserHandler handles user management endpoints.
type UserHandler struct {
- userService *services.UserService
- authService *services.AuthService
+ userService *services.UserService
+ authService *services.AuthService
+ settingsService *services.SettingsService
}
// ============================================================================
@@ -88,8 +89,8 @@ type GetUserAvatarOutput struct {
// ============================================================================
// RegisterUsers registers all user management endpoints.
-func RegisterUsers(api huma.API, userService *services.UserService, authService *services.AuthService) {
- h := &UserHandler{userService: userService, authService: authService}
+func RegisterUsers(api huma.API, userService *services.UserService, authService *services.AuthService, settingsService *services.SettingsService) {
+ h := &UserHandler{userService: userService, authService: authService, settingsService: settingsService}
huma.Register(api, huma.Operation{
OperationID: "listUsers",
@@ -189,6 +190,10 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*
}
input.Body.Email = normalizedEmail
+ if err := validation.ValidatePasswordPolicy(input.Body.Password, h.passwordPolicyInternal(ctx)); err != nil {
+ return nil, huma.Error400BadRequest(err.Error())
+ }
+
hashedPassword, err := h.userService.HashPassword(input.Body.Password)
if err != nil {
return nil, huma.Error500InternalServerError("Failed to hash password")
@@ -276,7 +281,17 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*
userModel.TimeFormat = *input.Body.TimeFormat
}
+ userModel.UpdatedAt = new(time.Now())
+
+ callerPerms, err := h.checkUpdateUserPrivilegesInternal(ctx, input, userModel.ID)
+ if err != nil {
+ return nil, err
+ }
+
if input.Body.Password != nil && *input.Body.Password != "" {
+ if err := validation.ValidatePasswordPolicy(*input.Body.Password, h.passwordPolicyInternal(ctx)); err != nil {
+ return nil, huma.Error400BadRequest(err.Error())
+ }
hashedPassword, err := h.userService.HashPassword(*input.Body.Password)
if err != nil {
return nil, huma.Error500InternalServerError("Failed to hash password")
@@ -284,26 +299,6 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*
userModel.PasswordHash = hashedPassword
}
- userModel.UpdatedAt = new(time.Now())
-
- // Privilege ordering: a non-admin caller may not modify a global admin
- // target, nor set another user's password. The service re-enforces the
- // target-admin check.
- callerPerms, _ := humamw.PermissionsFromContext(ctx)
- caller, _ := models.CurrentUserFromContext(ctx)
- if callerPerms != nil && !callerPerms.IsGlobalAdmin() {
- if input.Body.Password != nil && *input.Body.Password != "" && caller != nil && caller.ID != userModel.ID {
- return nil, huma.Error403Forbidden(services.ErrInsufficientPrivilege.Error())
- }
- targetPerms, err := h.userService.ResolveUserPermissions(ctx, userModel.ID)
- if err != nil {
- return nil, huma.Error500InternalServerError("Failed to resolve target permissions")
- }
- if targetPerms != nil && targetPerms.IsGlobalAdmin() {
- return nil, huma.Error403Forbidden(services.ErrInsufficientPrivilege.Error())
- }
- }
-
updatedUser, err := h.userService.UpdateUser(ctx, userModel, callerPerms)
if err != nil {
if errors.Is(err, services.ErrInsufficientPrivilege) {
@@ -417,3 +412,31 @@ func normalizeOptionalEmailInternal(email *string) (*string, error) {
return &trimmedEmail, nil
}
+
+// checkUpdateUserPrivilegesInternal enforces that a non-admin caller may not
+// modify a global admin target, nor set another user's password. The service
+// re-enforces the target-admin check.
+func (h *UserHandler) checkUpdateUserPrivilegesInternal(ctx context.Context, input *UpdateUserInput, targetID string) (*authz.PermissionSet, error) {
+ callerPerms, _ := humamw.PermissionsFromContext(ctx)
+ caller, _ := models.CurrentUserFromContext(ctx)
+ if callerPerms != nil && !callerPerms.IsGlobalAdmin() {
+ if input.Body.Password != nil && *input.Body.Password != "" && caller != nil && caller.ID != targetID {
+ return nil, huma.Error403Forbidden(services.ErrInsufficientPrivilege.Error())
+ }
+ targetPerms, err := h.userService.ResolveUserPermissions(ctx, targetID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError("Failed to resolve target permissions")
+ }
+ if targetPerms != nil && targetPerms.IsGlobalAdmin() {
+ return nil, huma.Error403Forbidden(services.ErrInsufficientPrivilege.Error())
+ }
+ }
+ return callerPerms, nil
+}
+
+func (h *UserHandler) passwordPolicyInternal(ctx context.Context) string {
+ if h.settingsService == nil {
+ return validation.PasswordPolicyStrong
+ }
+ return h.settingsService.GetStringSetting(ctx, "authPasswordPolicy", validation.PasswordPolicyStrong)
+}
diff --git a/backend/cli/admin/reset_password.go b/backend/cli/admin/reset_password.go
index c3f73af78..af420a40e 100644
--- a/backend/cli/admin/reset_password.go
+++ b/backend/cli/admin/reset_password.go
@@ -7,7 +7,6 @@ import (
"log/slog"
"os"
"strings"
- "unicode/utf8"
"emperror.dev/errors"
"github.com/spf13/cobra"
@@ -15,7 +14,9 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"
)
const defaultAdminUsername = "arcane"
@@ -66,12 +67,14 @@ func runResetPasswordCommandInternal(cmd *cobra.Command, _ []string) error {
}
}()
- password, err := readNewPasswordInternal(cmd.OutOrStdout())
+ policy := passwordPolicyFromDBInternal(cmd.Context(), db)
+
+ password, err := readNewPasswordInternal(cmd.OutOrStdout(), policy)
if err != nil {
return err
}
- if err := resetPasswordInternal(cmd.Context(), db, username, password); err != nil {
+ if err := resetPasswordInternal(cmd.Context(), db, username, password, policy); err != nil {
return err
}
@@ -91,7 +94,7 @@ func ensurePasswordResetEnabledInternal(cfg *config.Config) error {
return nil
}
-func readNewPasswordInternal(out io.Writer) (string, error) {
+func readNewPasswordInternal(out io.Writer, policy string) (string, error) {
password, err := readPasswordInternal(out, "New password: ")
if err != nil {
return "", errors.WrapIf(err, "failed to read new password")
@@ -102,7 +105,7 @@ func readNewPasswordInternal(out io.Writer) (string, error) {
return "", errors.WrapIf(err, "failed to read password confirmation")
}
- if err := validatePasswordPairInternal(password, confirmation); err != nil {
+ if err := validatePasswordPairInternal(password, confirmation, policy); err != nil {
return "", err
}
return password, nil
@@ -122,9 +125,9 @@ func readPasswordInternal(out io.Writer, prompt string) (string, error) {
return string(password), nil
}
-func validatePasswordPairInternal(password, confirmation string) error {
- if utf8.RuneCountInString(password) < 8 {
- return errors.New("password must be at least 8 characters")
+func validatePasswordPairInternal(password, confirmation, policy string) error {
+ if err := validation.ValidatePasswordPolicy(password, policy); err != nil {
+ return err
}
if password != confirmation {
return errors.New("passwords do not match")
@@ -132,7 +135,16 @@ func validatePasswordPairInternal(password, confirmation string) error {
return nil
}
-func resetPasswordInternal(ctx context.Context, db *database.DB, username, password string) error {
+func passwordPolicyFromDBInternal(ctx context.Context, db *database.DB) string {
+ var setting models.SettingVariable
+ err := db.WithContext(ctx).First(&setting, "key = ?", "authPasswordPolicy").Error
+ if err != nil || strings.TrimSpace(setting.Value) == "" {
+ return validation.PasswordPolicyStrong
+ }
+ return setting.Value
+}
+
+func resetPasswordInternal(ctx context.Context, db *database.DB, username, password, policy string) error {
if db == nil {
return errors.New("database is nil")
}
@@ -141,8 +153,8 @@ func resetPasswordInternal(ctx context.Context, db *database.DB, username, passw
if username == "" {
return errors.New("username cannot be empty")
}
- if utf8.RuneCountInString(password) < 8 {
- return errors.New("password must be at least 8 characters")
+ if err := validation.ValidatePasswordPolicy(password, policy); err != nil {
+ return err
}
roleService := services.NewRoleService(db)
diff --git a/backend/cli/admin/reset_password_test.go b/backend/cli/admin/reset_password_test.go
index bfefab99d..05fbb129b 100644
--- a/backend/cli/admin/reset_password_test.go
+++ b/backend/cli/admin/reset_password_test.go
@@ -14,6 +14,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"
"github.com/getarcaneapp/arcane/types/v2/auth"
)
@@ -68,7 +69,7 @@ func TestResetPasswordInternalResetsPasswordAndRevokesSessions(t *testing.T) {
secondSession, _, err := sessionService.CreateSession(ctx, adminUser.ID, time.Now().Add(time.Hour), auth.SessionMeta{})
require.NoError(t, err)
- require.NoError(t, resetPasswordInternal(ctx, db, "arcane", "new-password"))
+ require.NoError(t, resetPasswordInternal(ctx, db, "arcane", "new-password", validation.PasswordPolicyBasic))
updatedUser, err := userService.GetUserByID(ctx, adminUser.ID)
require.NoError(t, err)
@@ -100,7 +101,7 @@ func TestResetPasswordInternalRollsBackWhenSessionRevocationFails(t *testing.T)
END;
`).Error)
- err = resetPasswordInternal(ctx, db, adminUser.Username, "new-password")
+ err = resetPasswordInternal(ctx, db, adminUser.Username, "new-password", validation.PasswordPolicyBasic)
require.Error(t, err)
require.ErrorContains(t, err, "forced session revocation failure")
@@ -127,7 +128,7 @@ func TestResetPasswordInternalRejectsNonAdmin(t *testing.T) {
})
require.NoError(t, err)
- err = resetPasswordInternal(ctx, db, nonAdmin.Username, "new-password")
+ err = resetPasswordInternal(ctx, db, nonAdmin.Username, "new-password", validation.PasswordPolicyBasic)
require.Error(t, err)
require.ErrorContains(t, err, "effective global administrator")
@@ -143,7 +144,7 @@ func TestEnsurePasswordResetEnabledInternal(t *testing.T) {
}
func TestValidatePasswordPairInternal(t *testing.T) {
- require.ErrorContains(t, validatePasswordPairInternal("short", "short"), "at least 8")
- require.ErrorContains(t, validatePasswordPairInternal("new-password", "different"), "do not match")
- require.NoError(t, validatePasswordPairInternal("new-password", "new-password"))
+ require.ErrorContains(t, validatePasswordPairInternal("short", "short", validation.PasswordPolicyBasic), "at least 8")
+ require.ErrorContains(t, validatePasswordPairInternal("new-password", "different", validation.PasswordPolicyBasic), "do not match")
+ require.NoError(t, validatePasswordPairInternal("new-password", "new-password", validation.PasswordPolicyBasic))
}
diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.go
index b5e09b7bb..e93fda1b8 100644
--- a/backend/internal/services/auth_service.go
+++ b/backend/internal/services/auth_service.go
@@ -17,6 +17,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/jwtclaims"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"
"github.com/getarcaneapp/arcane/types/v2/auth"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
@@ -835,6 +836,14 @@ func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPasswor
}
}
+ policy := validation.PasswordPolicyStrong
+ if s.settingsService != nil {
+ policy = s.settingsService.GetStringSetting(ctx, "authPasswordPolicy", validation.PasswordPolicyStrong)
+ }
+ if err := validation.ValidatePasswordPolicy(newPassword, policy); err != nil {
+ return common.Classify(common.ErrValidation, err)
+ }
+
if _, err = s.userService.SetPasswordAndRevokeSessionsExcept(ctx, user, newPassword, currentSessionID); err != nil {
return err
}
diff --git a/backend/internal/services/auth_service_test.go b/backend/internal/services/auth_service_test.go
index 579c44040..1c3ce8bfa 100644
--- a/backend/internal/services/auth_service_test.go
+++ b/backend/internal/services/auth_service_test.go
@@ -582,7 +582,7 @@ func TestChangePassword_RevokesAllSessions(t *testing.T) {
sessionA, _ := createTestSession(t, db, user.ID, time.Now().Add(time.Hour))
sessionB, _ := createTestSession(t, db, user.ID, time.Now().Add(time.Hour))
- require.NoError(t, s.ChangePassword(context.Background(), user.ID, "old-password", "new-password", ""))
+ require.NoError(t, s.ChangePassword(context.Background(), user.ID, "old-password", "New-password1!", ""))
sessionA, err = s.sessionService.GetSessionByID(context.Background(), sessionA.ID)
require.NoError(t, err)
@@ -612,7 +612,7 @@ func TestChangePassword_KeepsCurrentSessionAlive(t *testing.T) {
current, _ := createTestSession(t, db, user.ID, time.Now().Add(time.Hour))
other, _ := createTestSession(t, db, user.ID, time.Now().Add(time.Hour))
- require.NoError(t, s.ChangePassword(context.Background(), user.ID, "old-password", "new-password", current.ID))
+ require.NoError(t, s.ChangePassword(context.Background(), user.ID, "old-password", "New-password1!", current.ID))
current, err = s.sessionService.GetSessionByID(context.Background(), current.ID)
require.NoError(t, err)
diff --git a/backend/pkg/utils/validation/password.go b/backend/pkg/utils/validation/password.go
new file mode 100644
index 000000000..1fbc73e6c
--- /dev/null
+++ b/backend/pkg/utils/validation/password.go
@@ -0,0 +1,49 @@
+package validation
+
+import (
+ "unicode"
+
+ "emperror.dev/errors"
+)
+
+const (
+ PasswordPolicyBasic = "basic"
+ PasswordPolicyStandard = "standard"
+ PasswordPolicyStrong = "strong"
+)
+
+// ValidatePasswordPolicy checks a password against the named policy tier.
+// Unknown policy values are treated as strong so a corrupted setting fails closed.
+func ValidatePasswordPolicy(password, policy string) error {
+ var length int
+ var hasUpper, hasLower, hasDigit, hasSymbol bool
+ for _, r := range password {
+ length++
+ switch {
+ case unicode.IsUpper(r):
+ hasUpper = true
+ case unicode.IsLower(r):
+ hasLower = true
+ case unicode.IsDigit(r):
+ hasDigit = true
+ case unicode.IsPunct(r) || unicode.IsSymbol(r) || unicode.IsSpace(r):
+ hasSymbol = true
+ }
+ }
+
+ switch policy {
+ case PasswordPolicyBasic:
+ if length < 8 {
+ return errors.New("password must be at least 8 characters")
+ }
+ case PasswordPolicyStandard:
+ if length < 10 || !hasUpper || !hasLower || !hasDigit {
+ return errors.New("password must be at least 10 characters and include an uppercase letter, a lowercase letter, and a number")
+ }
+ default:
+ if length < 12 || !hasUpper || !hasLower || !hasDigit || !hasSymbol {
+ return errors.New("password must be at least 12 characters and include an uppercase letter, a lowercase letter, a number, and a symbol")
+ }
+ }
+ return nil
+}
diff --git a/backend/pkg/utils/validation/password_test.go b/backend/pkg/utils/validation/password_test.go
new file mode 100644
index 000000000..936a790df
--- /dev/null
+++ b/backend/pkg/utils/validation/password_test.go
@@ -0,0 +1,21 @@
+package validation
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestValidatePasswordPolicy(t *testing.T) {
+ t.Parallel()
+
+ require.NoError(t, ValidatePasswordPolicy("12345678", PasswordPolicyBasic))
+ require.Error(t, ValidatePasswordPolicy("1234567", PasswordPolicyBasic))
+
+ require.NoError(t, ValidatePasswordPolicy("Abcdefghi1", PasswordPolicyStandard))
+ require.Error(t, ValidatePasswordPolicy("abcdefghij1", PasswordPolicyStandard))
+
+ require.NoError(t, ValidatePasswordPolicy("Abcdefghij1!", PasswordPolicyStrong))
+ require.Error(t, ValidatePasswordPolicy("Abcdefghijk1", PasswordPolicyStrong))
+ require.Error(t, ValidatePasswordPolicy("Abcdefgh1!", "bogus-policy"))
+}
diff --git a/tests/utils/auth.util.ts b/tests/utils/auth.util.ts
index b38f8279b..2becc0327 100644
--- a/tests/utils/auth.util.ts
+++ b/tests/utils/auth.util.ts
@@ -1,7 +1,7 @@
import type { Page } from '@playwright/test';
const DEFAULT_PASSWORD = 'arcane-admin';
-const TEST_PASSWORD = 'test-password-123';
+const TEST_PASSWORD = 'Test-password-123';
async function login(page: Page): Promise<string> {
await page.goto('/login');