Skip to content

Modern Docker Management, Designed for Everyone

fix: improve user validation and password policy feedback (#3851)

baejihoon832cf6eca30b
diff --git a/backend/internal/auth/handler.go b/backend/internal/auth/handler.go
index acd6b2bd8..d3dcb9d3f 100644
--- a/backend/internal/auth/handler.go
+++ b/backend/internal/auth/handler.go
@@ -26,6 +26,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/user"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"
authtypes "github.com/getarcaneapp/arcane/types/v2/auth"
"github.com/getarcaneapp/arcane/types/v2/base"
settingstypes "github.com/getarcaneapp/arcane/types/v2/settings"
@@ -368,7 +369,8 @@ func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordI
case errors.Is(err, ErrInvalidCredentials):
return nil, huma.Error401Unauthorized("Current password is incorrect")
case errors.Is(err, common.ErrValidation):
- return nil, huma.Error400BadRequest(err.Error())
+ passwordPolicy := h.authService.passwordPolicyInternal(ctx)
+ return nil, handlerutil.Error400BadRequestWithType(err.Error(), validation.PasswordPolicyProblemType(passwordPolicy))
default:
return nil, huma.Error500InternalServerError("Failed to change password")
}
diff --git a/backend/internal/auth/service.go b/backend/internal/auth/service.go
index 9d80c82a1..c0dfa3c98 100644
--- a/backend/internal/auth/service.go
+++ b/backend/internal/auth/service.go
@@ -883,10 +883,7 @@ func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPasswor
}
}
- policy := validation.PasswordPolicyStrong
- if s.settingsService != nil {
- policy = s.settingsService.GetStringSetting(ctx, "authPasswordPolicy", validation.PasswordPolicyStrong)
- }
+ policy := s.passwordPolicyInternal(ctx)
if err := validation.ValidatePasswordPolicy(newPassword, policy); err != nil {
return common.Classify(common.ErrValidation, err)
}
@@ -905,6 +902,13 @@ func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPasswor
return nil
}
+func (s *AuthService) passwordPolicyInternal(ctx context.Context) string {
+ if s.settingsService == nil {
+ return validation.PasswordPolicyStrong
+ }
+ return s.settingsService.GetStringSetting(ctx, "authPasswordPolicy", validation.PasswordPolicyStrong)
+}
+
// InvalidateUserTokenCache purges all cached token verifications for a user.
// Call this after admin-initiated role changes, account disable, or user
// deletion so stale verifications cannot grant access for the cache TTL.
diff --git a/backend/internal/user/handler.go b/backend/internal/user/handler.go
index a370aa424..13d637ac1 100644
--- a/backend/internal/user/handler.go
+++ b/backend/internal/user/handler.go
@@ -165,14 +165,21 @@ func (h *UserHandler) ListUsers(ctx context.Context, input *ListUsersInput) (*ha
// CreateUser creates a new usertypes.
func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*handlerutil.Out[usertypes.User], error) {
+ normalizedUsername, err := normalizeUsernameInternal(input.Body.Username)
+ if err != nil {
+ return nil, huma.Error400BadRequest(err.Error())
+ }
+ input.Body.Username = normalizedUsername
+
normalizedEmail, err := NormalizeOptionalEmail(input.Body.Email)
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
input.Body.Email = normalizedEmail
- if err := validation.ValidatePasswordPolicy(input.Body.Password, h.passwordPolicyInternal(ctx)); err != nil {
- return nil, huma.Error400BadRequest(err.Error())
+ passwordPolicy := h.passwordPolicyInternal(ctx)
+ if err := validation.ValidatePasswordPolicy(input.Body.Password, passwordPolicy); err != nil {
+ return nil, handlerutil.Error400BadRequestWithType(err.Error(), validation.PasswordPolicyProblemType(passwordPolicy))
}
hashedPassword, err := h.userService.HashPassword(input.Body.Password)
@@ -195,6 +202,9 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*
createdUser, err := h.userService.CreateUser(ctx, userModel)
if err != nil {
+ if errors.Is(err, ErrUsernameTaken) {
+ return nil, huma.Error409Conflict(ErrUsernameTaken.Error())
+ }
return nil, huma.Error500InternalServerError("Failed to create user")
}
@@ -245,7 +255,11 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*
input.Body.Email = normalizedEmail
if input.Body.Username != nil {
- userModel.Username = *input.Body.Username
+ normalizedUsername, err := normalizeUsernameInternal(*input.Body.Username)
+ if err != nil {
+ return nil, huma.Error400BadRequest(err.Error())
+ }
+ userModel.Username = normalizedUsername
}
if input.Body.DisplayName != nil {
userModel.DisplayName = input.Body.DisplayName
@@ -268,8 +282,9 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*
}
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())
+ passwordPolicy := h.passwordPolicyInternal(ctx)
+ if err := validation.ValidatePasswordPolicy(*input.Body.Password, passwordPolicy); err != nil {
+ return nil, handlerutil.Error400BadRequestWithType(err.Error(), validation.PasswordPolicyProblemType(passwordPolicy))
}
hashedPassword, err := h.userService.HashPassword(*input.Body.Password)
if err != nil {
@@ -287,6 +302,9 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*
if errors.Is(err, ErrCannotRemoveLastAdmin) {
return nil, huma.Error409Conflict(ErrCannotRemoveLastAdmin.Error())
}
+ if errors.Is(err, ErrUsernameTaken) {
+ return nil, huma.Error409Conflict(ErrUsernameTaken.Error())
+ }
if errors.Is(err, common.ErrUserNotFound) {
return nil, huma.Error404NotFound("User not found")
}
diff --git a/backend/internal/user/service.go b/backend/internal/user/service.go
index d4d93b9ca..2a7155898 100644
--- a/backend/internal/user/service.go
+++ b/backend/internal/user/service.go
@@ -51,6 +51,8 @@ type UserService struct {
const (
ErrCannotRemoveLastAdmin = errors.Sentinel("cannot remove the last admin user")
+ ErrUsernameRequired = errors.Sentinel("username is required")
+ ErrUsernameTaken = errors.Sentinel("username already in use")
// ErrInsufficientPrivilege is returned when a caller attempts to modify a
// target whose effective privilege is equal to or higher than the caller's
@@ -138,8 +140,17 @@ func (s *UserService) ValidatePassword(encodedHash, password string) error {
}
func (s *UserService) CreateUser(ctx context.Context, user *common.User) (*common.User, error) {
- err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ username, err := normalizeUsernameInternal(user.Username)
+ if err != nil {
+ return nil, err
+ }
+ user.Username = username
+
+ err = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
if err := tx.Create(user).Error; err != nil {
+ if isDuplicateKeyErrorInternal(tx, err) {
+ return ErrUsernameTaken
+ }
return errors.WrapIf(err, "failed to create user")
}
return nil
@@ -268,6 +279,9 @@ func (s *UserService) UpdateUser(ctx context.Context, user *common.User, actorPe
return err
}
if err := tx.Save(user).Error; err != nil {
+ if isDuplicateKeyErrorInternal(tx, err) {
+ return ErrUsernameTaken
+ }
return errors.WrapIf(err, "failed to update user")
}
return nil
@@ -278,6 +292,22 @@ func (s *UserService) UpdateUser(ctx context.Context, user *common.User, actorPe
return user, nil
}
+func normalizeUsernameInternal(username string) (string, error) {
+ username = strings.TrimSpace(username)
+ if username == "" {
+ return "", ErrUsernameRequired
+ }
+ return username, nil
+}
+
+func isDuplicateKeyErrorInternal(db *gorm.DB, err error) bool {
+ if errors.Is(err, gorm.ErrDuplicatedKey) {
+ return true
+ }
+ translator, ok := db.Dialector.(gorm.ErrorTranslator)
+ return ok && errors.Is(translator.Translate(err), gorm.ErrDuplicatedKey)
+}
+
// SetPassword hashes and persists a new password for the given user and clears
// the first-login password-change requirement for trusted internal callers.
func (s *UserService) SetPassword(ctx context.Context, user *common.User, password string) (*common.User, error) {
diff --git a/backend/internal/user/service_test.go b/backend/internal/user/service_test.go
index 12a44002d..d81c29bd9 100644
--- a/backend/internal/user/service_test.go
+++ b/backend/internal/user/service_test.go
@@ -33,6 +33,9 @@ func setupAuthServiceTestDBInternal(t *testing.T) *database.DB {
&role.ApiKeyPermission{},
&role.OidcRoleMapping{},
))
+ // Production migrations define username as UNIQUE. AutoMigrate cannot infer
+ // that SQL-only constraint from the model, so mirror it in the test schema.
+ require.NoError(t, db.Exec("CREATE UNIQUE INDEX idx_users_username_unique ON users(username)").Error)
// environments and api_keys live in packages that import this one; the
// in-package tests only need the tables to exist.
require.NoError(t, db.Exec("CREATE TABLE IF NOT EXISTS environments (id text PRIMARY KEY, created_at datetime, updated_at datetime, name text, api_url text, status text, enabled numeric, is_edge numeric, hidden numeric, last_seen datetime, last_edge_transport text, access_token text, api_key_id text, parent_environment_id text, swarm_node_id text)").Error)
@@ -189,15 +192,22 @@ func TestDeleteUserRejectsDeletingOnlyCustomAllPermissionsAdmin(t *testing.T) {
require.True(t, users[0].IsGlobalAdmin)
}
-func TestUpdateUserPersistsFontSizeAndMapsToDto(t *testing.T) {
+func TestUserProfileValidationAndPersistence(t *testing.T) {
userSvc, _ := setupUserAndRoleServices(t)
ctx := context.Background()
- u := createTestUser(t, userSvc, "user-1", "fontuser")
+ u := createTestUser(t, userSvc, "user-1", " fontuser ")
+ require.Equal(t, "fontuser", u.Username)
require.Nil(t, u.FontSize, "new users default to no explicit font size")
+ _, err := userSvc.CreateUser(ctx, &common.User{ID: "blank-user", Username: " "})
+ require.ErrorIs(t, err, ErrUsernameRequired)
+
+ _, err = userSvc.CreateUser(ctx, &common.User{ID: "duplicate-user", Username: "fontuser"})
+ require.ErrorIs(t, err, ErrUsernameTaken)
+
u.FontSize = new(16)
- _, err := userSvc.UpdateUser(ctx, u, nil)
+ _, err = userSvc.UpdateUser(ctx, u, nil)
require.NoError(t, err)
reloaded, err := userSvc.GetUserByID(ctx, u.ID)
@@ -209,6 +219,11 @@ func TestUpdateUserPersistsFontSizeAndMapsToDto(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, dto.FontSize)
require.Equal(t, 16, *dto.FontSize)
+
+ conflictingUser := createTestUser(t, userSvc, "user-2", "another-user")
+ conflictingUser.Username = u.Username
+ _, err = userSvc.UpdateUser(ctx, conflictingUser, nil)
+ require.ErrorIs(t, err, ErrUsernameTaken)
}
func TestUserDtoExposesLastLogin(t *testing.T) {
diff --git a/backend/pkg/utils/handlerutil/handlerutil.go b/backend/pkg/utils/handlerutil/handlerutil.go
index 99e5aeb38..fccb8c616 100644
--- a/backend/pkg/utils/handlerutil/handlerutil.go
+++ b/backend/pkg/utils/handlerutil/handlerutil.go
@@ -8,6 +8,7 @@ import (
"fmt"
"io"
"mime/multipart"
+ "net/http"
"strings"
"github.com/danielgtaylor/huma/v2"
@@ -84,6 +85,16 @@ func RequireUser(ctx context.Context) (*common.User, error) {
return user, nil
}
+// Error400BadRequestWithType returns RFC 9457 problem details with a stable type.
+func Error400BadRequestWithType(detail, problemType string) huma.StatusError {
+ return &huma.ErrorModel{
+ Type: problemType,
+ Title: http.StatusText(http.StatusBadRequest),
+ Status: http.StatusBadRequest,
+ Detail: detail,
+ }
+}
+
// ParseMultipartJSONPart decodes one required JSON-valued multipart field.
func ParseMultipartJSONPart[T any](form multipart.Form, partName string) (T, error) {
var result T
diff --git a/backend/pkg/utils/validation/password.go b/backend/pkg/utils/validation/password.go
index 1fbc73e6c..34c7aeb57 100644
--- a/backend/pkg/utils/validation/password.go
+++ b/backend/pkg/utils/validation/password.go
@@ -10,8 +10,21 @@ const (
PasswordPolicyBasic = "basic"
PasswordPolicyStandard = "standard"
PasswordPolicyStrong = "strong"
+
+ passwordPolicyProblemTypePrefix = "urn:arcane:problem:password-policy:" // #nosec G101 -- public problem type, not a credential
)
+// PasswordPolicyProblemType returns the stable problem type for a policy tier.
+// Unknown policy values mirror validation behavior and fall back to strong.
+func PasswordPolicyProblemType(policy string) string {
+ switch policy {
+ case PasswordPolicyBasic, PasswordPolicyStandard:
+ default:
+ policy = PasswordPolicyStrong
+ }
+ return passwordPolicyProblemTypePrefix + policy
+}
+
// 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 {
diff --git a/backend/pkg/utils/validation/password_test.go b/backend/pkg/utils/validation/password_test.go
index 936a790df..f614f30eb 100644
--- a/backend/pkg/utils/validation/password_test.go
+++ b/backend/pkg/utils/validation/password_test.go
@@ -9,6 +9,11 @@ import (
func TestValidatePasswordPolicy(t *testing.T) {
t.Parallel()
+ require.Equal(t, "urn:arcane:problem:password-policy:basic", PasswordPolicyProblemType(PasswordPolicyBasic))
+ require.Equal(t, "urn:arcane:problem:password-policy:standard", PasswordPolicyProblemType(PasswordPolicyStandard))
+ require.Equal(t, "urn:arcane:problem:password-policy:strong", PasswordPolicyProblemType(PasswordPolicyStrong))
+ require.Equal(t, "urn:arcane:problem:password-policy:strong", PasswordPolicyProblemType("bogus-policy"))
+
require.NoError(t, ValidatePasswordPolicy("12345678", PasswordPolicyBasic))
require.Error(t, ValidatePasswordPolicy("1234567", PasswordPolicyBasic))
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 52148b50e..0de6d744d 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -321,6 +321,7 @@
"common_details_description": "Basic information about this {resource}",
"common_url_required": "URL is required",
"common_username_required": "Username is required",
+ "common_max_length": "{field} must be {maxLength} characters or fewer",
"common_name_required": "Name is required",
"common_name_placeholder": "Enter a name",
"common_description_placeholder": "Enter a description",
diff --git a/frontend/src/lib/components/dialogs/first-login-password-dialog.svelte b/frontend/src/lib/components/dialogs/first-login-password-dialog.svelte
index c940ab4ce..772b659e5 100644
--- a/frontend/src/lib/components/dialogs/first-login-password-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/first-login-password-dialog.svelte
@@ -26,7 +26,7 @@
let showNewPassword = $state(false);
let showConfirmPassword = $state(false);
- const isValid = $derived(currentPassword.length > 0 && newPassword.length >= 8 && confirmPassword === newPassword);
+ const isValid = $derived(currentPassword.length > 0 && [...newPassword].length >= 8 && confirmPassword === newPassword);
const changePasswordMutation = createMutation(() => ({
mutationFn: ({ currentPassword, newPassword }: { currentPassword: string; newPassword: string }) =>
authService.changePassword(currentPassword, newPassword),
@@ -36,7 +36,7 @@
onSuccess?.();
},
onError: (err) => {
- error = err instanceof Error ? err.message : m.first_login_error_failed();
+ toast.error(err instanceof Error ? err.message : m.first_login_error_failed());
}
}));
@@ -44,7 +44,7 @@
function handleSubmit() {
if (!isValid) {
- if (newPassword.length < 8) {
+ if ([...newPassword].length < 8) {
error = m.first_login_error_length();
} else if (confirmPassword !== newPassword) {
error = m.first_login_error_mismatch();
diff --git a/frontend/src/lib/components/sheets/user-form-sheet.svelte b/frontend/src/lib/components/sheets/user-form-sheet.svelte
index 009af9fca..cc878a8bb 100644
--- a/frontend/src/lib/components/sheets/user-form-sheet.svelte
+++ b/frontend/src/lib/components/sheets/user-form-sheet.svelte
@@ -18,6 +18,7 @@
password?: string;
roleAssignments?: RoleAssignmentInput[];
};
+ type UserFormSubmission = { user: UserSubmission; isEditMode: boolean; userId?: string };
type UserFormProps = {
open: boolean;
@@ -25,7 +26,7 @@
roles: Role[];
environments: Environment[];
availableRoleAssignments?: RoleAssignmentInput[];
- onSubmit: (data: { user: UserSubmission; isEditMode: boolean; userId?: string }) => void;
+ onSubmit: (data: UserFormSubmission) => Promise<boolean>;
isLoading: boolean;
allowUsernameEdit?: boolean;
};
@@ -40,22 +41,36 @@
isLoading,
allowUsernameEdit = false
}: UserFormProps = $props();
- void open;
let isEditMode = $derived(!!userToEdit);
let canEditUsername = $derived(!isEditMode || allowUsernameEdit);
let isOidcUser = $derived(!!userToEdit?.oidcSubjectId);
let oidcAssignments = $derived(userToEdit?.roleAssignments?.filter((a) => a.source === 'oidc') ?? []);
+ const userFieldMaxLength = 255;
+ const passwordMinLength = 8;
const formSchema = z.object({
username: z
.string()
- .min(1, m.common_username_required())
+ .trim()
+ .refine((value) => value === userToEdit?.username.trim() || value.length > 0, m.common_username_required())
+ .refine(
+ (value) => value === userToEdit?.username.trim() || [...value].length <= userFieldMaxLength,
+ m.common_max_length({ field: m.common_username(), maxLength: userFieldMaxLength })
+ )
// Legacy usernames may contain @; only new or changed usernames are restricted
- .refine((value) => value === userToEdit?.username || !value.includes('@'), m.users_username_no_at()),
- password: z.string().optional(),
- displayName: z.string().optional(),
+ .refine((value) => value === userToEdit?.username.trim() || !value.includes('@'), m.users_username_no_at()),
+ password: z
+ .string()
+ .refine((value) => (isEditMode && value === '') || [...value].length >= passwordMinLength, m.first_login_error_length()),
+ displayName: z
+ .string()
+ .trim()
+ .refine(
+ (value) => [...value].length <= userFieldMaxLength,
+ m.common_max_length({ field: m.common_display_name(), maxLength: userFieldMaxLength })
+ ),
email: z
.string()
.trim()
@@ -82,13 +97,22 @@
let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
- function handleSubmit() {
+ async function submitUser(data: UserFormSubmission) {
+ if (await onSubmit(data)) {
+ form.reset();
+ }
+ }
+
+ async function handleSubmit() {
+ // createForm trims strings for ordinary text fields. Passwords are opaque,
+ // so preserve exactly what the user entered after validating the raw value.
+ const password = $inputs.password.value;
const data = form.validate();
if (!data) return;
// For OIDC users, only allow role assignment changes
if (isOidcUser) {
- onSubmit({
+ await submitUser({
user: { roleAssignments: data.roleAssignments },
isEditMode,
userId: userToEdit?.id
@@ -107,21 +131,22 @@
// Only include username when creating, or when editing changed it — an
// unchanged legacy username with @ would fail the backend pattern check
- if (!isEditMode || (canEditUsername && data.username !== userToEdit?.username)) {
+ if (!isEditMode || (canEditUsername && data.username !== userToEdit?.username.trim())) {
userData.username = data.username;
}
// Only include password if it's provided (for create) or if editing and password is not empty
- if (!isEditMode || (isEditMode && data.password)) {
- userData.password = data.password;
+ if (!isEditMode || (isEditMode && password)) {
+ userData.password = password;
}
- onSubmit({ user: userData, isEditMode, userId: userToEdit?.id });
+ await submitUser({ user: userData, isEditMode, userId: userToEdit?.id });
}
function handleOpenChange(newOpenState: boolean) {
open = newOpenState;
if (!newOpenState) {
+ form.reset();
userToEdit = null;
}
}
@@ -213,6 +238,7 @@
{#snippet footer()}
<SheetFooterActions
bind:open
+ onCancel={() => handleOpenChange(false)}
cancelDisabled={isLoading}
submitAction={isEditMode ? 'save' : 'create'}
submitDisabled={isLoading}
diff --git a/frontend/src/lib/services/api-service.ts b/frontend/src/lib/services/api-service.ts
index d506c9c25..de3a68f6d 100644
--- a/frontend/src/lib/services/api-service.ts
+++ b/frontend/src/lib/services/api-service.ts
@@ -65,18 +65,47 @@ export class APIError extends Error {
}
}
-function extractServerMessage(data: any, includeErrors = false): string | undefined {
- const inner = (data && typeof data === 'object' ? ((data as any).data ?? data) : data) as any;
- if (typeof inner === 'string') {
- return inner;
+const problemMessageFactoriesInternal: Record<string, () => string> = {
+ 'urn:arcane:problem:password-policy:basic': m.security_password_policy_basic_tooltip,
+ 'urn:arcane:problem:password-policy:standard': m.security_password_policy_standard_tooltip,
+ 'urn:arcane:problem:password-policy:strong': m.security_password_policy_strong_tooltip
+};
+
+function asRecordInternal(value: unknown): Record<string, unknown> | undefined {
+ return value !== null && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;
+}
+
+function nonEmptyStringInternal(value: unknown): string | undefined {
+ return typeof value === 'string' && value.trim() ? value : undefined;
+}
+
+export function extractServerMessage(data: unknown, includeErrors = false): string | undefined {
+ const outer = asRecordInternal(data);
+ const innerValue = outer?.['data'] ?? data;
+ const stringValue = nonEmptyStringInternal(innerValue);
+ if (stringValue) return stringValue;
+
+ const inner = asRecordInternal(innerValue);
+ if (!inner) return undefined;
+
+ const problemType = nonEmptyStringInternal(inner['type']);
+ const localizedMessage = problemType ? problemMessageFactoriesInternal[problemType] : undefined;
+ if (localizedMessage) return localizedMessage();
+
+ for (const key of ['error', 'message', 'detail', 'error_description']) {
+ const message = nonEmptyStringInternal(inner[key]);
+ if (message) return message;
}
- if (inner) {
- const msg = inner['error'] || inner['message'] || inner['detail'] || inner['error_description'];
- if (msg) return msg;
- if (includeErrors && Array.isArray(inner['errors']) && inner['errors'].length) {
- return inner['errors'][0]?.message || inner['errors'][0];
- }
+
+ if (includeErrors && Array.isArray(inner['errors']) && inner['errors'].length > 0) {
+ const first = inner['errors'][0];
+ const firstString = nonEmptyStringInternal(first);
+ if (firstString) return firstString;
+
+ const firstError = asRecordInternal(first);
+ return nonEmptyStringInternal(firstError?.['message']) ?? nonEmptyStringInternal(firstError?.['error']);
}
+
return undefined;
}
diff --git a/frontend/src/lib/utils/api.ts b/frontend/src/lib/utils/api.ts
index 6815dc185..8910530e7 100644
--- a/frontend/src/lib/utils/api.ts
+++ b/frontend/src/lib/utils/api.ts
@@ -1,6 +1,6 @@
import { error as kitError } from '@sveltejs/kit';
import { toast } from 'svelte-sonner';
-import { APIError } from '#lib/services/api-service';
+import { APIError, extractServerMessage } from '#lib/services/api-service';
// --- Result wrapper ---
@@ -27,34 +27,14 @@ export async function tryCatch<T, E = Error>(promise: Promise<T>): Promise<Resul
// --- API error extraction ---
-function extractServerMessage(data: any): string | undefined {
- const inner = data && typeof data === 'object' ? ((data as any).data ?? data) : data;
- if (typeof inner === 'string') return inner;
- if (!inner || typeof inner !== 'object') return undefined;
-
- const msg = (inner as any).error || (inner as any).message || (inner as any).detail || (inner as any).error_description;
- if (typeof msg === 'string' && msg.trim()) return msg;
-
- if (Array.isArray((inner as any).errors) && (inner as any).errors.length) {
- const first = (inner as any).errors[0];
- if (typeof first === 'string' && first.trim()) return first;
- if (first && typeof first === 'object') {
- const em = (first as any).message || (first as any).error;
- if (typeof em === 'string' && em.trim()) return em;
- }
- }
-
- return undefined;
-}
-
export function extractApiErrorMessage(error: any): string {
if (!error) return 'Unknown error';
const respData = error?.response?.data;
- const serverMsg = extractServerMessage(respData);
+ const serverMsg = extractServerMessage(respData, true);
if (serverMsg) return serverMsg;
- const bodyMsg = extractServerMessage(error?.body);
+ const bodyMsg = extractServerMessage(error?.body, true);
if (bodyMsg) return bodyMsg;
if (typeof error?.error === 'string' && error.error.trim()) return error.error;
diff --git a/frontend/src/routes/(app)/account/account-security-panel.svelte b/frontend/src/routes/(app)/account/account-security-panel.svelte
index a81a1ba87..633e9df1e 100644
--- a/frontend/src/routes/(app)/account/account-security-panel.svelte
+++ b/frontend/src/routes/(app)/account/account-security-panel.svelte
@@ -20,7 +20,7 @@
let confirmPassword = $state('');
let passwordSaving = $state(false);
let revokingAll = $state(false);
- const passwordValid = $derived(currentPassword.length > 0 && newPassword.length >= 8 && newPassword === confirmPassword);
+ const passwordValid = $derived(currentPassword.length > 0 && [...newPassword].length >= 8 && newPassword === confirmPassword);
async function changePassword() {
if (!passwordValid || passwordSaving) return;
diff --git a/frontend/src/routes/(app)/settings/users/+page.svelte b/frontend/src/routes/(app)/settings/users/+page.svelte
index 18c3fc36d..8f46c17ed 100644
--- a/frontend/src/routes/(app)/settings/users/+page.svelte
+++ b/frontend/src/routes/(app)/settings/users/+page.svelte
@@ -74,7 +74,7 @@
};
isEditMode: boolean;
userId?: string;
- }) {
+ }): Promise<boolean> {
const loading = isEditMode ? 'editing' : 'creating';
isLoading[loading] = true;
@@ -88,7 +88,7 @@
// OIDC users submit role assignments only — skip the empty profile PUT.
if (Object.keys(profile).length === 0 && isAdmin && roleAssignments) {
const assignmentsResult = await tryCatch(roleService.setUserAssignments(userId, { assignments: roleAssignments }));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result: assignmentsResult,
message: m.common_update_failed({ resource: `${m.resource_user()} "${safeUsername}"` }),
setLoadingState: (value) => (isLoading[loading] = value),
@@ -99,11 +99,11 @@
userToEdit = null;
}
});
- return;
+ return !assignmentsResult.error;
}
const result = await tryCatch(userService.update(userId, profile));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.common_update_failed({ resource: `${m.resource_user()} "${safeUsername}"` }),
setLoadingState: (value) => (isLoading[loading] = value),
@@ -117,11 +117,12 @@
userToEdit = null;
}
});
+ return !result.error;
} else {
if (!user.username) {
toast.error(m.common_username_required());
isLoading[loading] = false;
- return;
+ return false;
}
const safeUsername = user.username!.trim() || m.common_unknown();
@@ -134,7 +135,7 @@
};
const result = await tryCatch(userService.create(createUser));
- handleApiResultWithCallbacks({
+ await handleApiResultWithCallbacks({
result,
message: m.common_create_failed({ resource: `${m.resource_user()} "${safeUsername}"` }),
setLoadingState: (value) => (isLoading[loading] = value),
@@ -147,9 +148,11 @@
isDialogOpen.create = false;
}
});
+ return !result.error;
}
} catch (error) {
console.error('Failed to submit user:', error);
+ return false;
}
}
@@ -271,7 +274,7 @@
<UserFormSheet
bind:open={isDialogOpen.edit}
- {userToEdit}
+ bind:userToEdit
roles={data.roles}
environments={data.environments}
availableRoleAssignments={editingAssignments}
diff --git a/tests/spec/rbac.spec.ts b/tests/spec/rbac.spec.ts
index 9a360527e..dd6e719d1 100644
--- a/tests/spec/rbac.spec.ts
+++ b/tests/spec/rbac.spec.ts
@@ -4,7 +4,8 @@ import {
installPageErrorCollector,
test,
type BrowserContext,
- type Page
+ type Page,
+ type Request
} from '../fixtures/test.fixture';
import { readApiData } from '../utils/fetch.util';
import { openRowActionsMenu } from '../utils/table-actions.util';
@@ -142,6 +143,61 @@ async function createRestrictedUserThroughUI(
await dialog.getByRole('button', { name: 'Add assignment', exact: true }).click();
await selectUserAssignment(page, dialog, 1, remoteEnvironmentName, remoteRoleName);
+ let createRequests = 0;
+ const countCreateRequests = (request: Request) => {
+ if (request.method() === 'POST' && new URL(request.url()).pathname === '/api/users') {
+ createRequests += 1;
+ }
+ };
+ page.on('request', countCreateRequests);
+
+ await dialog.getByLabel('Username', { exact: true }).fill(' ');
+ await dialog.getByLabel('Password *', { exact: true }).fill('short');
+ await dialog.getByLabel('Display Name', { exact: true }).fill('x'.repeat(256));
+ await dialog.getByRole('button', { name: 'Create User', exact: true }).click();
+ await expect(dialog.getByText('Username is required', { exact: true })).toBeVisible();
+ await expect(
+ dialog.getByText('Password must be at least 8 characters', { exact: true })
+ ).toBeVisible();
+ await expect(
+ dialog.getByText('Display Name must be 255 characters or fewer', { exact: true })
+ ).toBeVisible();
+ await expect.poll(() => createRequests).toBe(0);
+
+ await dialog.getByLabel('Username', { exact: true }).fill('x'.repeat(256));
+ await dialog.getByLabel('Password *', { exact: true }).fill(password);
+ await dialog.getByLabel('Display Name', { exact: true }).fill('Scoped Browser User');
+ await dialog.getByRole('button', { name: 'Create User', exact: true }).click();
+ await expect(
+ dialog.getByText('Username must be 255 characters or fewer', { exact: true })
+ ).toBeVisible();
+ await expect.poll(() => createRequests).toBe(0);
+ page.off('request', countCreateRequests);
+
+ await dialog.getByLabel('Username', { exact: true }).fill(` ${username} `);
+ await dialog.getByLabel('Password *', { exact: true }).fill(' abcdefgh ');
+ const policyResponsePromise = page.waitForResponse(
+ (response) =>
+ response.status() === 400 &&
+ response.request().method() === 'POST' &&
+ new URL(response.url()).pathname === '/api/users'
+ );
+ await dialog.getByRole('button', { name: 'Create User', exact: true }).click();
+ const policyResponse = await policyResponsePromise;
+ expect(policyResponse.request().postDataJSON()).toMatchObject({
+ username,
+ password: ' abcdefgh '
+ });
+ expect(await policyResponse.json()).toMatchObject({
+ status: 400,
+ type: 'urn:arcane:problem:password-policy:strong'
+ });
+ await expect(
+ page.getByText('12+ chars with upper, lower, number, and symbol.', { exact: true })
+ ).toBeVisible();
+
+ await dialog.getByLabel('Password *', { exact: true }).fill(password);
+
const createResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === 'POST' && new URL(response.url()).pathname === '/api/users'
@@ -156,6 +212,16 @@ async function createRestrictedUserThroughUI(
const user = await readApiData<TestUser>(await createResponsePromise, `Create user ${username}`);
await readApiData<unknown[]>(await assignmentsResponsePromise, `Assign roles to ${username}`);
await expect(dialog).toBeHidden();
+ expect(user.username).toBe(username);
+
+ await page.getByRole('button', { name: 'Create User', exact: true }).click();
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByLabel('Username', { exact: true })).toHaveValue('');
+ await expect(dialog.getByLabel('Password *', { exact: true })).toHaveValue('');
+ await expect(dialog.getByLabel('Display Name', { exact: true })).toHaveValue('');
+ await expect(dialog.getByLabel('Email', { exact: true })).toHaveValue('');
+ await dialog.getByRole('button', { name: 'Cancel', exact: true }).click();
+ await expect(dialog).toBeHidden();
return user;
}
@@ -168,6 +234,50 @@ async function editUserThroughUI(page: Page, user: TestUser) {
const dialog = page.getByRole('dialog', { name: 'Edit User' });
await expect(dialog).toBeVisible();
+ await dialog.getByLabel('Password', { exact: true }).fill('short');
+
+ let profileUpdateRequests = 0;
+ const countProfileUpdateRequests = (request: Request) => {
+ if (request.method() === 'PUT' && new URL(request.url()).pathname === `/api/users/${user.id}`) {
+ profileUpdateRequests += 1;
+ }
+ };
+ page.on('request', countProfileUpdateRequests);
+ await dialog.getByRole('button', { name: 'Save Changes', exact: true }).click();
+ await expect(
+ dialog.getByText('Password must be at least 8 characters', { exact: true })
+ ).toBeVisible();
+ await expect.poll(() => profileUpdateRequests).toBe(0);
+ page.off('request', countProfileUpdateRequests);
+
+ await dialog.getByLabel('Display Name', { exact: true }).fill('Discarded Browser Edit');
+ await dialog.getByLabel('Password', { exact: true }).fill('abcdefgh');
+ const policyResponsePromise = page.waitForResponse(
+ (response) =>
+ response.status() === 400 &&
+ response.request().method() === 'PUT' &&
+ new URL(response.url()).pathname === `/api/users/${user.id}`
+ );
+ await dialog.getByRole('button', { name: 'Save Changes', exact: true }).click();
+ const policyResponse = await policyResponsePromise;
+ expect(await policyResponse.json()).toMatchObject({
+ status: 400,
+ type: 'urn:arcane:problem:password-policy:strong'
+ });
+ await expect(
+ page.getByText('12+ chars with upper, lower, number, and symbol.', { exact: true })
+ ).toBeVisible();
+
+ await dialog.getByRole('button', { name: 'Cancel', exact: true }).click();
+ await expect(dialog).toBeHidden();
+
+ const reopenedMenu = await openRowActionsMenu(page, row);
+ await reopenedMenu.getByRole('menuitem', { name: 'Edit', exact: true }).click();
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByLabel('Password', { exact: true })).toHaveValue('');
+ await expect(dialog.getByLabel('Display Name', { exact: true })).toHaveValue(
+ 'Scoped Browser User'
+ );
await dialog.getByLabel('Display Name', { exact: true }).fill('Scoped Browser User Updated');
const updateResponsePromise = page.waitForResponse(
@@ -182,10 +292,9 @@ async function editUserThroughUI(page: Page, user: TestUser) {
);
await dialog.getByRole('button', { name: 'Save Changes', exact: true }).click();
- const updated = await readApiData<TestUser>(
- await updateResponsePromise,
- `Update user ${user.username}`
- );
+ const updateResponse = await updateResponsePromise;
+ expect(updateResponse.request().postDataJSON()).not.toHaveProperty('password');
+ const updated = await readApiData<TestUser>(updateResponse, `Update user ${user.username}`);
await readApiData<unknown[]>(
await assignmentsResponsePromise,
`Retain roles for ${user.username}`
@@ -306,6 +415,18 @@ test('administers scoped identities and enforces their browser access immediatel
remoteEnvironment.name,
remoteRole.name
);
+ const duplicateUserResponse = await page.request.post('/api/users', {
+ data: {
+ username: ` ${username} `,
+ password,
+ displayName: 'Duplicate Browser User'
+ }
+ });
+ expect(duplicateUserResponse.status()).toBe(409);
+ expect(await duplicateUserResponse.json()).toMatchObject({
+ status: 409,
+ detail: 'username already in use'
+ });
await editUserThroughUI(page, restrictedUser);
noAccessUser = await readApiData<TestUser>(
diff --git a/tests/utils/auth.util.ts b/tests/utils/auth.util.ts
index 2becc0327..61fa46e42 100644
--- a/tests/utils/auth.util.ts
+++ b/tests/utils/auth.util.ts
@@ -1,4 +1,4 @@
-import type { Page } from '@playwright/test';
+import { expect, type Page } from '@playwright/test';
const DEFAULT_PASSWORD = 'arcane-admin';
const TEST_PASSWORD = 'Test-password-123';
@@ -36,6 +36,24 @@ async function changeDefaultPassword(page: Page, currentPassword: string, newPas
await dialog.waitFor({ state: 'visible' });
await dialog.getByRole('textbox', { name: 'Current Password' }).fill(currentPassword);
+ await dialog.getByRole('textbox', { name: 'New Password', exact: true }).fill('abcdefgh');
+ await dialog.getByRole('textbox', { name: 'Confirm New Password' }).fill('abcdefgh');
+ const policyResponsePromise = page.waitForResponse(
+ (response) =>
+ response.status() === 400 &&
+ response.request().method() === 'POST' &&
+ new URL(response.url()).pathname === '/api/auth/password'
+ );
+ await dialog.getByRole('button', { name: 'Change Password' }).click();
+ const policyResponse = await policyResponsePromise;
+ expect(await policyResponse.json()).toMatchObject({
+ status: 400,
+ type: 'urn:arcane:problem:password-policy:strong'
+ });
+ await expect(
+ page.getByText('12+ chars with upper, lower, number, and symbol.', { exact: true })
+ ).toBeVisible();
+
await dialog.getByRole('textbox', { name: 'New Password', exact: true }).fill(newPassword);
await dialog.getByRole('textbox', { name: 'Confirm New Password' }).fill(newPassword);
await dialog.getByRole('button', { name: 'Change Password' }).click();