Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: harden auth and authorization, keep browser sessions alive across tabs (#4492)
Kyle Mendell0e0a1d1fdd8f
diff --git a/backend/api/buildables.go b/backend/api/buildables.goindex 9965cd86d..c4375d422 100644--- a/backend/api/buildables.go+++ b/backend/api/buildables.go@@ -5,7 +5,6 @@ package apiimport ("errors""net/http"- "time"authtypes "github.com/getarcaneapp/arcane/types/v2/auth""github.com/getarcaneapp/arcane/types/v2/base"@@ -85,11 +84,9 @@ func registerAutoLoginRoutes(apiGroup *echo.Group, authService *auth.AuthServicereturn c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "Failed to map user"})}- maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)- maxAge += 60expiresAt := tokenPair.ExpiresAt- for _, tokenCookie := range cookie.BuildTokenCookieStringFor(maxAge, tokenPair.BrowserToken, cookie.SecureCookieFromRequest(c.Request())) {+ for _, tokenCookie := range tokenPair.CookieHeaders(cookie.SecureCookieFromRequest(c.Request())) {c.Response().Header().Add("Set-Cookie", tokenCookie)}return c.JSON(http.StatusOK, base.ApiResponse[authtypes.AuthenticationResponse]{diff --git a/backend/cli/admin/reset_password.go b/backend/cli/admin/reset_password.goindex 04e51e489..9ac5ae8c6 100644--- a/backend/cli/admin/reset_password.go+++ b/backend/cli/admin/reset_password.go@@ -176,7 +176,7 @@ func resetPasswordInternal(ctx context.Context, db *database.DB, username, passwreturn fmt.Errorf("user %q does not have effective global administrator permissions", username)}- if _, setPasswordAndRevokeSessionsExceptErr := userService.SetPasswordAndRevokeSessionsExcept(ctx, target, password, ""); setPasswordAndRevokeSessionsExceptErr != nil {+ if _, setPasswordAndRevokeSessionsExceptErr := userService.SetPasswordAndRevokeSessionsExcept(ctx, target, password, "", nil); setPasswordAndRevokeSessionsExceptErr != nil {return fmt.Errorf("failed to reset password: %w", setPasswordAndRevokeSessionsExceptErr)}diff --git a/backend/cli/admin/reset_password_test.go b/backend/cli/admin/reset_password_test.goindex 86c2776a9..29a95e023 100644--- a/backend/cli/admin/reset_password_test.go+++ b/backend/cli/admin/reset_password_test.go@@ -43,7 +43,7 @@ func createGlobalAdminInternal(t *testing.T, db *database.DB) (*user.User, *userroleService := role.NewRoleService(db)require.NoError(t, roleService.EnsureBuiltInRoles(ctx))userService := user.NewUserService(db, roleService, session.RevokeAllUserSessionsExceptInDB)- passwordHash, err := userService.HashPassword("old-password")+ passwordHash, err := userService.HashPassword(t.Context(), "old-password")require.NoError(t, err)adminUser, err := userService.CreateUser(ctx, &user.User{ID: "admin-1",@@ -73,8 +73,8 @@ func TestResetPasswordInternalResetsPasswordAndRevokesSessions(t *testing.T) {updatedUser, err := userService.GetUserByID(ctx, adminUser.ID)require.NoError(t, err)- require.NoError(t, userService.ValidatePassword(updatedUser.PasswordHash, "new-password"))- require.Error(t, userService.ValidatePassword(updatedUser.PasswordHash, "old-password"))+ require.NoError(t, userService.ValidatePassword(t.Context(), updatedUser.PasswordHash, "new-password"))+ require.Error(t, userService.ValidatePassword(t.Context(), updatedUser.PasswordHash, "old-password"))require.False(t, updatedUser.RequiresPasswordChange)revokedFirst, err := sessionService.GetSessionByID(ctx, firstSession.ID)@@ -107,7 +107,7 @@ func TestResetPasswordInternalRollsBackWhenSessionRevocationFails(t *testing.T)unchangedUser, err := userService.GetUserByID(ctx, adminUser.ID)require.NoError(t, err)- require.NoError(t, userService.ValidatePassword(unchangedUser.PasswordHash, "old-password"))+ require.NoError(t, userService.ValidatePassword(t.Context(), unchangedUser.PasswordHash, "old-password"))require.True(t, unchangedUser.RequiresPasswordChange)unchangedSession, err := sessionService.GetSessionByID(ctx, localSession.ID)require.NoError(t, err)@@ -118,7 +118,7 @@ func TestResetPasswordInternalRejectsNonAdmin(t *testing.T) {db := newResetPasswordTestDBInternal(t)ctx := t.Context()_, userService := createGlobalAdminInternal(t, db)- passwordHash, err := userService.HashPassword("old-password")+ passwordHash, err := userService.HashPassword(t.Context(), "old-password")require.NoError(t, err)nonAdmin, err := userService.CreateUser(ctx, &user.User{ID: "user-1",@@ -134,7 +134,7 @@ func TestResetPasswordInternalRejectsNonAdmin(t *testing.T) {unchangedUser, err := userService.GetUserByID(ctx, nonAdmin.ID)require.NoError(t, err)- require.NoError(t, userService.ValidatePassword(unchangedUser.PasswordHash, "old-password"))+ require.NoError(t, userService.ValidatePassword(t.Context(), unchangedUser.PasswordHash, "old-password"))require.True(t, unchangedUser.RequiresPasswordChange)}diff --git a/backend/internal/apikey/service.go b/backend/internal/apikey/service.goindex ea9c97277..53911a79b 100644--- a/backend/internal/apikey/service.go+++ b/backend/internal/apikey/service.go@@ -1,6 +1,7 @@package apikeyimport (+ "cmp""context""crypto/hmac""crypto/rand"@@ -19,6 +20,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/apikey""github.com/samber/hot""go.getarcane.app/kit/normalization"+ "go.getarcane.app/kit/pkg""gorm.io/gorm""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -65,33 +67,17 @@ var defaultAdminAPIKeyDescription = func() *string {}()type ApiKeyService struct {- db *database.DB- userService *user.UserService- roleService *role.RoleService- argon2Params *user.Argon2Params- // validatedKeyCache is a per-process cache of Argon2id-validated API keys,- // keyed by HMAC-SHA256 of the raw key under cacheKeyPepper. Entries are only- // written after a full hash validation, so a hit safely skips the Argon2id- // derivation. Expiry is re-checked on every hit and entries are invalidated- // on key update/delete.+ db *database.DB+ userService *user.UserService+ roleService *role.RoleService+ argon2Params *user.Argon2ParamsvalidatedKeyCache *hot.HotCache[string, ApiKey]- // cacheKeyPepper is a random per-process HMAC key for deriving cache keys.- // Generated keys carry 256 bits of entropy, but the static admin key is- // operator-provided and may be weak; the pepper keeps its in-memory digest- // useless for offline brute-force (e.g. from a memory dump). Argon2id- // remains the sole persistent hash.- cacheKeyPepper []byte- // cacheGen is bumped by every invalidation; cache fills are guarded by- // cacheFillMu and dropped when the generation moved after the fill's DB- // read. Without this, a validation that read the key row just before a- // revocation would republish the deleted key after eviction already ran,- // letting it authenticate for a full cache TTL.- cacheGen atomic.Uint64- cacheFillMu sync.Mutex- // lastUsedMu guards lastUsedWrites, which debounces last_used_at writes so- // each key opens at most one write transaction per apiKeyLastUsedWriteWindow.- lastUsedMu sync.Mutex- lastUsedWrites map[string]time.Time+ rejectedKeyCache *hot.HotCache[string, struct{}]+ cacheKeyPepper []byte+ cacheGen atomic.Uint64+ cacheFillMu sync.Mutex+ lastUsedMu sync.Mutex+ lastUsedWrites map[string]time.Time}func NewApiKeyService(db *database.DB, userService *user.UserService, roleService *role.RoleService) *ApiKeyService {@@ -109,6 +95,10 @@ func NewApiKeyService(db *database.DB, userService *user.UserService, roleServicWithTTL(15 * time.Second).WithJanitor().Build(),+ rejectedKeyCache: hot.NewHotCache[string, struct{}](hot.LRU, 4096).+ WithTTL(30 * time.Second).+ WithJanitor().+ Build(),lastUsedWrites: make(map[string]time.Time),}}@@ -223,14 +213,6 @@ func (s *ApiKeyService) generateApiKey() (string, error) {return apiKeyPrefix + hex.EncodeToString(bytes), nil}-func (s *ApiKeyService) hashApiKey(key string) (string, error) {- return s.userService.HashPassword(key)-}--func (s *ApiKeyService) validateApiKeyHash(hash, key string) error {- return s.userService.ValidatePassword(hash, key)-}-func parseAPIKeyPrefixInternal(rawKey string) (string, error) {rawKey = strings.TrimSpace(rawKey)if !strings.HasPrefix(rawKey, apiKeyPrefix) {@@ -353,19 +335,20 @@ func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, callerPreturn nil, err}- created, err := s.createAPIKeyWithRawKey(ctx, &userID, rawKey, req, nil, nil, ApiKeyKindScoped)- if err != nil {- return nil, err- }- if s.roleService != nil {- grants := toApiKeyPermissionRowsInternal(created.ID, req.Permissions)- if setApiKeyPermissionsErr := s.roleService.SetApiKeyPermissions(ctx, created.ID, grants); setApiKeyPermissionsErr != nil {- return nil, fmt.Errorf("failed to persist api key permissions: %w", setApiKeyPermissionsErr)+ var created *apikey.ApiKeyCreatedDto+ if createTxErr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {+ var createErr error+ if created, createErr = s.createAPIKeyWithRawKey(ctx, tx, &userID, rawKey, req, nil, nil, ApiKeyKindScoped); createErr != nil {+ return createErr}- // Re-load the just-persisted grants into the response DTO so the- // frontend doesn't see `"permissions": null` on a successful create.- created.Permissions = s.loadKeyGrantsInternal(ctx, created.ID)+ if setApiKeyPermissionsErr := s.roleService.SetApiKeyPermissionsInDB(ctx, tx, created.ID, toApiKeyPermissionRowsInternal(created.ID, req.Permissions)); setApiKeyPermissionsErr != nil {+ return fmt.Errorf("failed to persist api key permissions: %w", setApiKeyPermissionsErr)+ }+ return nil+ }); createTxErr != nil {+ return nil, createTxErr}+ created.Permissions = s.loadKeyGrantsInternal(ctx, created.ID)return created, nil}@@ -434,7 +417,7 @@ func (s *ApiKeyService) CreatePersonalApiKey(ctx context.Context, userID string,return nil, err}- created, err := s.createAPIKeyWithRawKey(ctx, &userID, rawKey, apikey.CreateApiKey{+ created, err := s.createAPIKeyWithRawKey(ctx, s.db.DB, &userID, rawKey, apikey.CreateApiKey{Name: req.Name,Description: req.Description,ExpiresAt: req.ExpiresAt,@@ -448,6 +431,7 @@ func (s *ApiKeyService) CreatePersonalApiKey(ctx context.Context, userID string,func (s *ApiKeyService) createAPIKeyWithRawKey(ctx context.Context,+ db *gorm.DB,userID *string,rawKey string,req apikey.CreateApiKey,@@ -461,7 +445,7 @@ func (s *ApiKeyService) createAPIKeyWithRawKey(return nil, err}- keyHash, err := s.hashApiKey(rawKey)+ keyHash, err := s.userService.HashPassword(ctx, rawKey)if err != nil {return nil, fmt.Errorf("failed to hash API key: %w", err)}@@ -477,9 +461,10 @@ func (s *ApiKeyService) createAPIKeyWithRawKey(EnvironmentID: environmentID,ExpiresAt: req.ExpiresAt,}- if createAPIKeyErr := s.db.WithContext(ctx).Create(ak).Error; createAPIKeyErr != nil {+ if createAPIKeyErr := db.WithContext(ctx).Create(ak).Error; createAPIKeyErr != nil {return nil, fmt.Errorf("failed to create API key: %w", createAPIKeyErr)}+ s.rejectedKeyCache.Delete(s.hashRawAPIKeyInternal(rawKey))// A just-minted environment key is about to be linked as the// environment's pairing key, so present it as bootstrap already.return &apikey.ApiKeyCreatedDto{@@ -555,7 +540,7 @@ func toAPIKeyDTOWithPermissionsInternal(ak *ApiKey, isBootstrap bool) apikey.Api}func (s *ApiKeyService) CreateDefaultAdminAPIKey(ctx context.Context, userID, rawKey string) (*apikey.ApiKeyCreatedDto, error) {- return s.createAPIKeyWithRawKey(ctx, &userID, rawKey, apikey.CreateApiKey{+ return s.createAPIKeyWithRawKey(ctx, s.db.DB, &userID, rawKey, apikey.CreateApiKey{Name: defaultAdminAPIKeyName,Description: defaultAdminAPIKeyDescription,}, new(managedByAdminBootstrap), nil, ApiKeyKindScoped)@@ -607,13 +592,16 @@ func (s *ApiKeyService) deleteManagedAPIKeysByIDs(tx *gorm.DB, ids []string) errreturn nil}-func (s *ApiKeyService) findMatchingManagedAPIKey(rawKey string, managedKeys []ApiKey) int {+func (s *ApiKeyService) findMatchingManagedAPIKey(ctx context.Context, rawKey string, managedKeys []ApiKey) (int, error) {for i, managedKey := range managedKeys {- if err := s.validateApiKeyHash(managedKey.KeyHash, rawKey); err == nil {- return i+ if err := s.userService.ValidatePassword(ctx, managedKey.KeyHash, rawKey); err == nil {+ return i, nil+ }+ if ctx.Err() != nil {+ return -1, ctx.Err()}}- return -1+ return -1, nil}func managedAPIKeyDeleteIDsInternal(managedKeys []ApiKey, keepIndex int) []string {@@ -640,13 +628,13 @@ func (s *ApiKeyService) updateMatchingManagedAPIKey(tx *gorm.DB, apiKeyID stringreturn nil}-func (s *ApiKeyService) createManagedDefaultAdminAPIKey(tx *gorm.DB, userID, rawKey string) error {+func (s *ApiKeyService) createManagedDefaultAdminAPIKey(ctx context.Context, tx *gorm.DB, userID, rawKey string) error {keyPrefix, err := parseAPIKeyPrefixInternal(rawKey)if err != nil {return err}- keyHash, err := s.hashApiKey(rawKey)+ keyHash, err := s.userService.HashPassword(ctx, rawKey)if err != nil {return fmt.Errorf("failed to hash API key: %w", err)}@@ -670,7 +658,7 @@ func (s *ApiKeyService) createManagedDefaultAdminAPIKey(tx *gorm.DB, userID, raw// the transaction commits. Invalidating pre-commit is ineffective: a concurrent// validation can still read the old committed row, snapshot the already-bumped// generation, and republish the entry so it survives the commit.-func (s *ApiKeyService) reconcileManagedAPIKeys(tx *gorm.DB, userID, rawKey string) ([]string, error) {+func (s *ApiKeyService) reconcileManagedAPIKeys(ctx context.Context, tx *gorm.DB, userID, rawKey string) ([]string, error) {managedKeys, err := s.listManagedAPIKeys(tx, userID)if err != nil {return nil, err@@ -681,7 +669,10 @@ func (s *ApiKeyService) reconcileManagedAPIKeys(tx *gorm.DB, userID, rawKey strireturn deleteIDs, s.deleteManagedAPIKeysByIDs(tx, deleteIDs)}- matchingIndex := s.findMatchingManagedAPIKey(rawKey, managedKeys)+ matchingIndex, err := s.findMatchingManagedAPIKey(ctx, rawKey, managedKeys)+ if err != nil {+ return nil, err+ }if matchingIndex >= 0 {if updateMatchingManagedAPIKeyErr := s.updateMatchingManagedAPIKey(tx, managedKeys[matchingIndex].ID); updateMatchingManagedAPIKeyErr != nil {return nil, updateMatchingManagedAPIKeyErr@@ -699,7 +690,7 @@ func (s *ApiKeyService) reconcileManagedAPIKeys(tx *gorm.DB, userID, rawKey strireturn nil, deleteRemovedManagedKeysErr}- return deleteIDs, s.createManagedDefaultAdminAPIKey(tx, userID, rawKey)+ return deleteIDs, s.createManagedDefaultAdminAPIKey(ctx, tx, userID, rawKey)}func (s *ApiKeyService) ReconcileDefaultAdminAPIKey(ctx context.Context, rawKey string) error {@@ -712,13 +703,14 @@ func (s *ApiKeyService) ReconcileDefaultAdminAPIKey(ctx context.Context, rawKeyvar affectedIDs []stringif transactionErr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- affectedIDs, err = s.reconcileManagedAPIKeys(tx, adminUser.ID, rawKey)+ affectedIDs, err = s.reconcileManagedAPIKeys(ctx, tx, adminUser.ID, rawKey)return err}); transactionErr != nil {// Rolled back: the DB is unchanged, so cached entries are still valid.return transactionErr}s.invalidateValidatedKeysInternal(affectedIDs...)+ s.rejectedKeyCache.Delete(s.hashRawAPIKeyInternal(rawKey))return nil}@@ -733,7 +725,7 @@ func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environmentenvIDShort = environmentID[:8]}name := "Environment Bootstrap Key - " + envIDShort- created, err := s.createAPIKeyWithRawKey(ctx, nil, rawKey, apikey.CreateApiKey{+ created, err := s.createAPIKeyWithRawKey(ctx, s.db.DB, nil, rawKey, apikey.CreateApiKey{Name: name,Description: new("Auto-generated key for environment pairing"),}, nil, &environmentID, ApiKeyKindScoped)@@ -897,19 +889,21 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerPerms *authz.Per}}- if req.Name != nil {- ak.Name = *req.Name- }- if req.Description != nil {- ak.Description = req.Description- }- if req.ExpiresAt != nil {- ak.ExpiresAt = req.ExpiresAt+ changes := ApiKey{+ BaseModel: database.BaseModel{+ UpdatedAt: new(time.Now()),+ },+ Name: cmp.Or(kit.FromPtr(req.Name), ak.Name),+ Description: cmp.Or(req.Description, ak.Description),+ ExpiresAt: cmp.Or(req.ExpiresAt, ak.ExpiresAt),}permissionsUpdated := falseif err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- if err := tx.Save(&ak).Error; err != nil {+ if err := tx.Model(&ApiKey{}).+ Where("id = ?", ak.ID).+ Select("name", "description", "expires_at", "updated_at").+ Updates(&changes).Error; err != nil {return fmt.Errorf("failed to update API key: %w", err)}if req.Permissions != nil && s.roleService != nil {@@ -929,17 +923,17 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerPerms *authz.Perreturn &apikey.ApiKey{ID: ak.ID,- Name: ak.Name,- Description: ak.Description,+ Name: changes.Name,+ Description: changes.Description,KeyPrefix: ak.KeyPrefix,UserID: ak.UserID,Kind: ak.Kind,IsStatic: isStaticAPIKeyInternal(ak),IsBootstrap: false, // an environment-referenced key can't reach this return- ExpiresAt: ak.ExpiresAt,+ ExpiresAt: changes.ExpiresAt,LastUsedAt: ak.LastUsedAt,CreatedAt: ak.CreatedAt,- UpdatedAt: ak.UpdatedAt,+ UpdatedAt: changes.UpdatedAt,Permissions: s.loadKeyGrantsInternal(ctx, ak.ID),}, nil}@@ -994,6 +988,11 @@ func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {return nil}+func (s *ApiKeyService) Stop() {+ s.validatedKeyCache.StopJanitor()+ s.rejectedKeyCache.StopJanitor()+}+func (s *ApiKeyService) ValidateApiKey(ctx context.Context, rawKey string) (*user.User, error) {localUser, _, err := s.ValidateApiKeyWithID(ctx, rawKey)return localUser, err@@ -1002,7 +1001,7 @@ func (s *ApiKeyService) ValidateApiKey(ctx context.Context, rawKey string) (*use// ValidateApiKeyWithID is like ValidateApiKey but additionally returns the// API key record so callers can resolve permissions according to its kind.func (s *ApiKeyService) ValidateApiKeyWithID(ctx context.Context, rawKey string) (*user.User, *ApiKey, error) {- apiKey, err := s.validateRawAPIKeyInternal(ctx, rawKey)+ apiKey, err := s.ValidateRawApiKey(ctx, rawKey)if err != nil {return nil, nil, err}@@ -1020,17 +1019,14 @@ func (s *ApiKeyService) ValidateApiKeyWithID(ctx context.Context, rawKey string)}func (s *ApiKeyService) GetEnvironmentByApiKey(ctx context.Context, rawKey string) (*string, error) {- apiKey, err := s.validateRawAPIKeyInternal(ctx, rawKey)+ apiKey, err := s.ValidateRawApiKey(ctx, rawKey)if err != nil {return nil, err}return apiKey.EnvironmentID, nil}-// validateRawAPIKeyInternal resolves a raw key to its validated record. A cache-// hit skips the per-candidate Argon2id derivation; expiry is always re-checked-// so a key expiring mid-TTL is rejected immediately.-func (s *ApiKeyService) validateRawAPIKeyInternal(ctx context.Context, rawKey string) (*ApiKey, error) {+func (s *ApiKeyService) ValidateRawApiKey(ctx context.Context, rawKey string) (*ApiKey, error) {rawKey = strings.TrimSpace(rawKey)keyPrefix, err := parseAPIKeyPrefixInternal(rawKey)if err != nil {@@ -1046,6 +1042,9 @@ func (s *ApiKeyService) validateRawAPIKeyInternal(ctx context.Context, rawKey sts.markApiKeyUsedDebouncedInternal(ctx, cached.ID)return &cached, nil}+ if _, rejected, _ := s.rejectedKeyCache.Get(cacheKey); rejected {+ return nil, ErrApiKeyInvalid+ }// Snapshot before the read: if a revocation lands between this read and the// publish below, the generation will have moved and the publish is dropped.@@ -1056,7 +1055,7 @@ func (s *ApiKeyService) validateRawAPIKeyInternal(ctx context.Context, rawKey st}for _, apiKey := range apiKeys {- if validateApiKeyHashErr := s.validateApiKeyHash(apiKey.KeyHash, rawKey); validateApiKeyHashErr == nil {+ if validateErr := s.userService.ValidatePassword(ctx, apiKey.KeyHash, rawKey); validateErr == nil {if apiKey.ExpiresAt != nil && apiKey.ExpiresAt.Before(time.Now()) {return nil, ErrApiKeyExpired}@@ -1066,8 +1065,12 @@ func (s *ApiKeyService) validateRawAPIKeyInternal(ctx context.Context, rawKey streturn &apiKey, nil}+ if ctx.Err() != nil {+ return nil, ctx.Err()+ }}+ s.rejectedKeyCache.Set(cacheKey, struct{}{})return nil, ErrApiKeyInvalid}diff --git a/backend/internal/apikey/service_test.go b/backend/internal/apikey/service_test.goindex 2eaa1abaf..24b76e869 100644--- a/backend/internal/apikey/service_test.go+++ b/backend/internal/apikey/service_test.go@@ -12,6 +12,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/apikey""github.com/libtnb/sqlite""github.com/stretchr/testify/require"+ "go.getarcane.app/kit/pkg""gorm.io/gorm""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -850,11 +851,13 @@ func TestCreateEnvironmentApiKeySeedsAllPermissionsScopedToEnv(t *testing.T) {// Resolve the per-key permission set and confirm every permission is// present, scoped to the bootstrap env (not global).- ps, err := roleSvc.ResolveApiKeyPermissions(ctx, created.ID)- require.NoError(t, err)- require.Empty(t, ps.Global, "bootstrap key permissions must land in PerEnv, not Global")- envPerms, ok := ps.PerEnv[envID]- require.True(t, ok)+ var grants []role.ApiKeyPermission+ require.NoError(t, db.WithContext(ctx).Where("api_key_id = ?", created.ID).Find(&grants).Error)+ envPerms := make(map[string]struct{}, len(grants))+ for _, grant := range grants {+ require.Equal(t, envID, kit.FromPtr(grant.EnvironmentID), "bootstrap key permissions must be scoped to the environment, not global")+ envPerms[grant.Permission] = struct{}{}+ }for _, p := range authz.AllPermissions() {_, has := envPerms[p]require.True(t, has, "missing permission %s on bootstrap key", p)@@ -903,11 +906,9 @@ func TestBackfillApiKeyPermissionsRepairsExistingBootstrapKey(t *testing.T) {var keys []ApiKeyrequire.NoError(t, db.WithContext(ctx).Where("environment_id = ?", envID).Find(&keys).Error)require.Len(t, keys, 1)- ps, err := roleSvc.ResolveApiKeyPermissions(ctx, keys[0].ID)- require.NoError(t, err)- envPerms, ok := ps.PerEnv[envID]- require.True(t, ok)- require.Len(t, envPerms, len(authz.AllPermissions()))+ var grants []role.ApiKeyPermission+ require.NoError(t, db.WithContext(ctx).Where("api_key_id = ? AND environment_id = ?", keys[0].ID, envID).Find(&grants).Error)+ require.Len(t, grants, len(authz.AllPermissions()))var scopedPerms []role.ApiKeyPermissionrequire.NoError(t, db.WithContext(ctx).Where("api_key_id = ?", scopedKey.ID).Find(&scopedPerms).Error)diff --git a/backend/internal/auth/handler.go b/backend/internal/auth/handler.goindex a7ae85d26..4ec201eaf 100644--- a/backend/internal/auth/handler.go+++ b/backend/internal/auth/handler.go@@ -2,6 +2,7 @@ package authimport ("bytes"+ "cmp""context""crypto/subtle""errors"@@ -15,7 +16,6 @@ import ("net/http""reflect""strings"- "time""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/types/v2/activity"@@ -59,14 +59,22 @@ type LoginOutput struct {Body base.ApiResponse[auth.AuthenticationResponse]}+type LogoutInput struct {+ SecureRefreshCookie string `cookie:"__Secure-refresh" doc:"Refresh cookie (HTTPS)"`+ InsecureRefreshCookie string `cookie:"refresh" doc:"Refresh cookie (HTTP)"`+ Body *auth.Logout `required:"false"`+}+type LogoutOutput struct {SetCookie []string `header:"Set-Cookie" doc:"Cleared session cookie"`Body base.ApiResponse[base.MessageResponse]}type RefreshTokenInput struct {- UserAgent string `header:"User-Agent"`- Body auth.Refresh+ UserAgent string `header:"User-Agent"`+ SecureRefreshCookie string `cookie:"__Secure-refresh" doc:"Refresh cookie (HTTPS)"`+ InsecureRefreshCookie string `cookie:"refresh" doc:"Refresh cookie (HTTP)"`+ Body *auth.Refresh `required:"false"`}type RefreshTokenOutput struct {@@ -145,12 +153,10 @@ func (h *AuthHandler) Login(ctx context.Context, input *LoginInput) (*LoginOutpureturn nil, huma.Error500InternalServerError("Failed to map user")}- maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)- maxAge += 60expiresAt := tokenPair.ExpiresAtreturn &LoginOutput{- SetCookie: cookie.BuildTokenCookieStringFor(maxAge, tokenPair.BrowserToken, cookie.SecureCookieFromContext(ctx)),+ SetCookie: tokenPair.CookieHeaders(cookie.SecureCookieFromContext(ctx)),Body: base.ApiResponse[auth.AuthenticationResponse]{Success: true,Data: auth.AuthenticationResponse{@@ -166,20 +172,28 @@ func (h *AuthHandler) Login(ctx context.Context, input *LoginInput) (*LoginOutpu}// Logout clears the authentication session.-func (h *AuthHandler) Logout(ctx context.Context, input *struct{}) (*LogoutOutput, error) {+func (h *AuthHandler) Logout(ctx context.Context, input *LogoutInput) (*LogoutOutput, error) {if h.authService != nil {if sessionID, exists := middleware.GetCurrentSessionIDFromContext(ctx); exists {if err := h.authService.RevokeSession(ctx, sessionID); err != nil {slog.ErrorContext(ctx, "Failed to revoke session on logout; clearing cookie anyway", "sessionId", sessionID, "error", err)}}+ if refreshToken := cmp.Or(kit.FromPtr(input.Body).RefreshToken, input.SecureRefreshCookie, input.InsecureRefreshCookie); refreshToken != "" {+ if err := h.authService.RevokeSessionByRefreshToken(ctx, refreshToken); err != nil {+ slog.WarnContext(ctx, "Failed to revoke refresh token session on logout", "error", err)+ }+ }if userModel, exists := userdomain.CurrentUserFromContext(ctx); exists {h.authService.LogLogout(ctx, userModel)}}return &LogoutOutput{- SetCookie: cookie.BuildClearTokenCookieStringsFor(cookie.SecureCookieFromContext(ctx)),+ SetCookie: append(+ cookie.BuildClearTokenCookieStringsFor(cookie.SecureCookieFromContext(ctx)),+ cookie.BuildClearRefreshCookieStringsFor(cookie.SecureCookieFromContext(ctx))...,+ ),Body: base.ApiResponse[base.MessageResponse]{Success: true,Data: base.MessageResponse{@@ -217,25 +231,27 @@ func (h *AuthHandler) GetCurrentUser(ctx context.Context, input *struct{}) (*han// RefreshToken obtains a new access token using a refresh token.func (h *AuthHandler) RefreshToken(ctx context.Context, input *RefreshTokenInput) (*RefreshTokenOutput, error) {- tokenPair, err := h.authService.RefreshToken(ctx, input.Body.RefreshToken, handlerutil.SessionMetaFromContext(ctx, input.UserAgent))+ refreshToken := cmp.Or(kit.FromPtr(input.Body).RefreshToken, input.SecureRefreshCookie, input.InsecureRefreshCookie)+ if refreshToken == "" {+ return nil, huma.Error401Unauthorized("Invalid or expired refresh token")+ }+ tokenPair, err := h.authService.RefreshToken(ctx, refreshToken, handlerutil.SessionMetaFromContext(ctx, input.UserAgent))if err != nil {switch {case errors.Is(err, common.ErrInvalidToken),errors.Is(err, common.ErrExpiredToken),errors.Is(err, common.ErrTokenValidation),errors.Is(err, common.ErrSessionRevoked),- errors.Is(err, common.ErrTokenVersionMismatch):+ errors.Is(err, common.ErrTokenVersionMismatch),+ errors.Is(err, common.ErrUserNotFound):return nil, huma.Error401Unauthorized("Invalid or expired refresh token")default:return nil, huma.Error500InternalServerError("Failed to refresh token")}}- maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)- maxAge += 60-return &RefreshTokenOutput{- SetCookie: cookie.BuildTokenCookieStringFor(maxAge, tokenPair.BrowserToken, cookie.SecureCookieFromContext(ctx)),+ SetCookie: tokenPair.CookieHeaders(cookie.SecureCookieFromContext(ctx)),Body: base.ApiResponse[auth.TokenRefreshResponse]{Success: true,Data: auth.TokenRefreshResponse{@@ -264,6 +280,8 @@ func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordIswitch {case errors.Is(err, ErrInvalidCredentials):return nil, huma.Error401Unauthorized("Current password is incorrect")+ case errors.Is(err, common.ErrForbidden):+ return nil, huma.Error403Forbidden(err.Error())case errors.Is(err, common.ErrValidation):passwordPolicy := h.authService.passwordPolicy(ctx)return nil, handlerutil.Error400BadRequestWithType(err.Error(), validation.PasswordPolicyProblemType(passwordPolicy))@@ -285,7 +303,8 @@ func (h *AuthHandler) LogoutAllOtherSessions(ctx context.Context, input *struct{currentSessionID, _ := middleware.GetCurrentSessionIDFromContext(ctx)if logoutAllOtherSessionsErr := h.authService.LogoutAllOtherSessions(ctx, userModel.ID, currentSessionID); logoutAllOtherSessionsErr != nil {- return nil, huma.Error500InternalServerError("failed to revoke sessions: " + logoutAllOtherSessionsErr.Error())+ slog.ErrorContext(ctx, "Failed to revoke other sessions", "userId", userModel.ID, "error", logoutAllOtherSessionsErr)+ return nil, huma.Error500InternalServerError("failed to revoke sessions")}return handlerutil.MessageOutput("All other sessions signed out", ""), nil@@ -318,6 +337,9 @@ func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfilif normalizeOptionalEmailErr != nil {return nil, huma.Error400BadRequest(normalizeOptionalEmailErr.Error())}+ if !strings.EqualFold(kit.FromPtr(normalized), kit.FromPtr(userModel.Email)) && h.settingsService.GetBoolSetting(ctx, "oidcMergeAccounts", false) {+ return nil, huma.Error403Forbidden("email cannot be changed while OIDC account merging is enabled")+ }userModel.Email = normalized}if input.Body.Locale != nil {@@ -363,6 +385,9 @@ func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfilupdated, err := h.userService.UpdateUser(ctx, userModel, nil)if err != nil {+ if errors.Is(err, userdomain.ErrEmailTaken) {+ return nil, huma.Error409Conflict(userdomain.ErrEmailTaken.Error())+ }return nil, huma.Error500InternalServerError("Failed to update user")}h.authService.InvalidateUserTokenCache(updated.ID)@@ -516,6 +541,9 @@ func normalizeAvatarImage(data []byte, mimeType string) ([]byte, string) {}func imageHasTransparency(img image.Image) bool {+ if opaque, ok := img.(interface{ Opaque() bool }); ok {+ return !opaque.Opaque()+ }bounds := img.Bounds()for y := bounds.Min.Y; y < bounds.Max.Y; y++ {for x := bounds.Min.X; x < bounds.Max.X; x++ {diff --git a/backend/internal/auth/helpers.go b/backend/internal/auth/helpers.goindex 76f308873..b63c5d44c 100644--- a/backend/internal/auth/helpers.go+++ b/backend/internal/auth/helpers.go@@ -19,9 +19,10 @@ import (const (browserSessionSigningKeySize = 64- accessTokenSubject = "access"- browserTokenSubject = "browser_session"- refreshTokenSubject = "refresh"+ accessTokenSubject = "access"+ browserTokenSubject = "browser_session"+ refreshTokenSubject = "refresh"+ browserRefreshSubject = "browser_refresh"claimSessionID = "sid"claimUserID = "user_id"@@ -133,8 +134,8 @@ func signedTokenAlgorithm(rawToken string) (string, bool) {return algorithm.String(), true}-func parseRefreshToken(ctx context.Context, rawToken string, key *mldsa.PublicKey) (*refreshTokenClaims, error) {- token, err := jwt.ParseString(rawToken, append(tokenParseOptions, jwt.WithKey(jwa.MLDSA87(), key), jwt.WithContext(ctx))...)+func parseRefreshToken(ctx context.Context, rawToken, wantSubject string, key jwt.ParseOption) (*refreshTokenClaims, error) {+ token, err := jwt.ParseString(rawToken, append(tokenParseOptions, key, jwt.WithContext(ctx))...)if err != nil {claimErr := errors.Is(err, jwt.MissingRequiredClaimError{}) || errors.Is(err, jwt.ClaimValidationError{})return nil, kit.Ternary[error](claimErr, common.ErrTokenValidation, common.ErrInvalidToken)@@ -144,7 +145,7 @@ func parseRefreshToken(ctx context.Context, rawToken string, key *mldsa.PublicKeid, _ := token.JwtID()userID, _ := jwt.Get[string](token, claimUserID)sessionID, _ := jwt.Get[string](token, claimSessionID)- if subject != refreshTokenSubject || id == "" || userID == "" || sessionID == "" {+ if subject != wantSubject || id == "" || userID == "" || sessionID == "" {return nil, common.ErrTokenValidation}diff --git a/backend/internal/auth/service.go b/backend/internal/auth/service.goindex db0c8cfb5..a9f873849 100644--- a/backend/internal/auth/service.go+++ b/backend/internal/auth/service.go@@ -31,6 +31,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/jwtclaims""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation")@@ -43,10 +44,19 @@ var ()type TokenPair struct {- AccessToken string `json:"accessToken"`- BrowserToken string `json:"-"`- RefreshToken string `json:"refreshToken"`- ExpiresAt time.Time `json:"expiresAt"`+ AccessToken string `json:"accessToken"`+ BrowserToken string `json:"-"`+ RefreshToken string `json:"refreshToken"`+ BrowserRefresh string `json:"-"`+ ExpiresAt time.Time `json:"expiresAt"`+ RefreshExpiresAt time.Time `json:"-"`+}++func (p *TokenPair) CookieHeaders(secure bool) []string {+ return append(+ cookie.BuildTokenCookieStringFor(max(int(time.Until(p.ExpiresAt).Seconds()), 0)+60, p.BrowserToken, secure),+ cookie.BuildRefreshCookieStringFor(int(time.Until(p.RefreshExpiresAt).Seconds()), p.BrowserRefresh, secure),+ )}type verifiedTokenEntry struct {@@ -67,13 +77,25 @@ type AuthService struct {browserSigningKey []byterefreshExpiry time.Durationconfig *config.Config- // tokenCache is a per-process in-memory cache for verified tokens. A hit- // skips signature verification and the user/session lookups; revocation in- // this process purges entries, revocation by another process is visible- // once the TTL lapses.- tokenCache *hot.HotCache[string, verifiedTokenEntry]- cacheGen atomic.Uint64- cacheFillMu sync.Mutex+ tokenCache *hot.HotCache[string, verifiedTokenEntry]+ cacheGen atomic.Uint64+ cacheFillMu sync.Mutex+ dummyMu sync.Mutex+ dummyHash string+}++func (s *AuthService) dummyPasswordHash(ctx context.Context) (string, error) {+ s.dummyMu.Lock()+ defer s.dummyMu.Unlock()+ if s.dummyHash != "" {+ return s.dummyHash, nil+ }+ hash, err := s.userService.HashPassword(ctx, uuid.New().String())+ if err != nil {+ return "", fmt.Errorf("failed to prepare dummy password hash: %w", err)+ }+ s.dummyHash = hash+ return hash, nil}func NewAuthService(@@ -233,9 +255,22 @@ func (s *AuthService) AuthenticateLocalPrimary(ctx context.Context, username, pa}}if localUser == nil {+ dummyHash, dummyErr := s.dummyPasswordHash(ctx)+ if dummyErr != nil {+ return nil, dummyErr+ }+ _ = s.userService.ValidatePassword(ctx, dummyHash, password)return nil, ErrInvalidCredentials}- if validatePasswordErr := s.userService.ValidatePassword(localUser.PasswordHash, password); validatePasswordErr != nil {+ passwordHash := localUser.PasswordHash+ if passwordHash == "" {+ dummyHash, dummyErr := s.dummyPasswordHash(ctx)+ if dummyErr != nil {+ return nil, dummyErr+ }+ passwordHash = dummyHash+ }+ if validatePasswordErr := s.userService.ValidatePassword(ctx, passwordHash, password); validatePasswordErr != nil {return nil, ErrInvalidCredentials}@@ -384,7 +419,7 @@ func (s *AuthService) findOrCreateOidcUser(ctx context.Context, userInfo auth.Oicase existingUser == nil:case !userInfo.EmailVerified:// Only a provider-verified email may claim an existing account.- return nil, false, errors.New("email not verified by OIDC provider; cannot merge accounts")+ return nil, false, common.Classify(common.ErrForbidden, errors.New("email not verified by OIDC provider; cannot merge accounts"))default:slog.InfoContext(ctx, "Merging OIDC account with existing user", "email", userInfo.Email, "subject", userInfo.Subject)// Perform the merge atomically to avoid races when multiple OIDC subjects share the same email@@ -398,10 +433,8 @@ func (s *AuthService) findOrCreateOidcUser(ctx context.Context, userInfo auth.Oiif mergeErr != nil {return nil, false, mergeErr}- if merged != nil {- if syncErr := s.syncOidcRoleAssignments(ctx, merged, userInfo, tokenResp); syncErr != nil {- slog.WarnContext(ctx, "failed to sync OIDC role assignments on user merge", "error", syncErr, "userId", merged.ID)- }+ if syncErr := s.syncOidcRoleAssignments(ctx, merged, userInfo, tokenResp); syncErr != nil {+ return nil, false, fmt.Errorf("failed to sync OIDC role assignments on user merge: %w", syncErr)}return merged, false, nil}@@ -467,7 +500,7 @@ func (s *AuthService) createOidcUser(ctx context.Context, userInfo auth.OidcUserreturn nil, createErr}if syncOidcRoleAssignmentsErr := s.syncOidcRoleAssignments(ctx, localUser, userInfo, tokenResp); syncOidcRoleAssignmentsErr != nil {- slog.WarnContext(ctx, "failed to sync OIDC role assignments on user create", "error", syncOidcRoleAssignmentsErr, "userId", localUser.ID)+ return nil, fmt.Errorf("failed to sync OIDC role assignments on user create: %w", syncOidcRoleAssignmentsErr)}return localUser, nil}@@ -523,7 +556,7 @@ func (s *AuthService) updateOidcUser(ctx context.Context, localUser *user.User,return nil, err}if syncErr := s.syncOidcRoleAssignments(ctx, updated, userInfo, tokenResp); syncErr != nil {- slog.WarnContext(ctx, "failed to sync OIDC role assignments on user update", "error", syncErr, "userId", updated.ID)+ return nil, fmt.Errorf("failed to sync OIDC role assignments on user update: %w", syncErr)}return updated, nil}@@ -567,7 +600,12 @@ func (s *AuthService) syncOidcRoleAssignments(ctx context.Context, localUser *us})}- return s.roleService.ReplaceUserAssignments(ctx, localUser.ID, role.RoleAssignmentSourceOidc, desired)+ err = s.roleService.ReplaceUserAssignments(ctx, localUser.ID, role.RoleAssignmentSourceOidc, desired)+ if errors.Is(err, common.ErrNoGlobalAdminRemains) {+ slog.WarnContext(ctx, "OIDC role sync would remove the last global admin; keeping existing assignments", "userId", localUser.ID)+ return nil+ }+ return err}// extractOidcGroups reads the user's group memberships from the OIDC userinfo@@ -655,12 +693,23 @@ func (s *AuthService) loadBrowserSigningKey(ctx context.Context) ([]byte, error)return key, nil}-func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string, meta auth.SessionMeta) (*TokenPair, error) {+func (s *AuthService) parseAnyRefreshToken(ctx context.Context, refreshToken string) (*refreshTokenClaims, error) {+ if algorithm, _ := signedTokenAlgorithm(refreshToken); algorithm == jwa.HS512().String() {+ browserKey, err := s.loadBrowserSigningKey(ctx)+ if err != nil {+ return nil, err+ }+ return parseRefreshToken(ctx, refreshToken, browserRefreshSubject, jwt.WithKey(jwa.HS512(), browserKey))+ }signingKey, err := s.loadSigningKey(ctx)if err != nil {return nil, err}- claims, err := parseRefreshToken(ctx, refreshToken, signingKey.PublicKey())+ return parseRefreshToken(ctx, refreshToken, refreshTokenSubject, jwt.WithKey(jwa.MLDSA87(), signingKey.PublicKey()))+}++func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string, meta auth.SessionMeta) (*TokenPair, error) {+ claims, err := s.parseAnyRefreshToken(ctx, refreshToken)if err != nil {return nil, err}@@ -684,12 +733,12 @@ func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string, metreturn nil, validateActiveErr}- rotatedSession, refreshJTI, err := s.sessionService.RotateRefreshToken(ctx, claims.SessionID, claims.ID, meta)+ localUser, err := s.userService.GetUserByID(ctx, claims.UserID)if err != nil {return nil, err}- localUser, err := s.userService.GetUserByID(ctx, claims.UserID)+ rotatedSession, refreshJTI, err := s.sessionService.RotateRefreshToken(ctx, claims.SessionID, claims.ID, meta)if err != nil {return nil, err}@@ -801,8 +850,11 @@ func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPassworreturn err}+ if localUser.PasswordHash == "" && kit.FromPtr(localUser.OidcSubjectId) != "" {+ return common.Classify(common.ErrForbidden, errors.New("local passwords cannot be set for accounts managed by an identity provider"))+ }if localUser.PasswordHash != "" {- if validatePasswordErr := s.userService.ValidatePassword(localUser.PasswordHash, currentPassword); validatePasswordErr != nil {+ if validatePasswordErr := s.userService.ValidatePassword(ctx, localUser.PasswordHash, currentPassword); validatePasswordErr != nil {return ErrInvalidCredentials}}@@ -812,7 +864,7 @@ func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPassworreturn common.Classify(common.ErrValidation, validatePasswordPolicyErr)}- if _, err = s.userService.SetPasswordAndRevokeSessionsExcept(ctx, localUser, newPassword, currentSessionID); err != nil {+ if _, err = s.userService.SetPasswordAndRevokeSessionsExcept(ctx, localUser, newPassword, currentSessionID, nil); err != nil {return err}// The current session's cached user still carries the old password flags.@@ -862,6 +914,18 @@ func (s *AuthService) RevokeSession(ctx context.Context, sessionID string) errorreturn nil}+func (s *AuthService) Stop() {+ s.tokenCache.StopJanitor()+}++func (s *AuthService) RevokeSessionByRefreshToken(ctx context.Context, refreshToken string) error {+ claims, err := s.parseAnyRefreshToken(ctx, refreshToken)+ if err != nil {+ return err+ }+ return s.RevokeSession(ctx, claims.SessionID)+}+// LogoutAllOtherSessions revokes every active session for userID except// currentSessionID, so the caller stays signed in on their current device.func (s *AuthService) LogoutAllOtherSessions(ctx context.Context, userID, currentSessionID string) error {@@ -957,11 +1021,32 @@ func (s *AuthService) buildTokenPair(ctx context.Context, localUser *user.User,return nil, err}+ browserRefreshBuilder := jwt.NewBuilder().+ JwtID(refreshJTI).+ Subject(browserRefreshSubject).+ IssuedAt(now).+ Expiration(localSession.ExpiresAt).+ Claim(claimUserID, localUser.ID).+ Claim(claimSessionID, localSession.ID)+ if config.Version != "" {+ browserRefreshBuilder.Claim(claimAppVersion, config.Version)+ }+ browserRefresh, err := browserRefreshBuilder.Build()+ if err != nil {+ return nil, err+ }+ browserRefreshBytes, err := jwt.Sign(browserRefresh, jwt.WithKey(jwa.HS512(), browserSigningKey))+ if err != nil {+ return nil, err+ }+return &TokenPair{- AccessToken: string(accessTokenBytes),- BrowserToken: string(browserTokenBytes),- RefreshToken: string(refreshTokenBytes),- ExpiresAt: accessTokenExpiry,+ AccessToken: string(accessTokenBytes),+ BrowserToken: string(browserTokenBytes),+ RefreshToken: string(refreshTokenBytes),+ BrowserRefresh: string(browserRefreshBytes),+ ExpiresAt: accessTokenExpiry,+ RefreshExpiresAt: localSession.ExpiresAt,}, nil}diff --git a/backend/internal/auth/service_test.go b/backend/internal/auth/service_test.goindex ab361675a..535924167 100644--- a/backend/internal/auth/service_test.go+++ b/backend/internal/auth/service_test.go@@ -600,6 +600,44 @@ func TestRefreshToken_RotatesJTI(t *testing.T) {require.ErrorIs(t, err, common.ErrInvalidToken)}+func TestRefreshToken_AcceptsBrowserRefreshToken(t *testing.T) {+ db := setupAuthServiceTestDB(t)+ userSvc := user.NewUserService(db, nil, session.RevokeAllUserSessionsExceptInDB)+ settingsSvc, err := newSettingsServiceForAuthTest(t, t.Context(), db)+ require.NoError(t, err)+ s := newTestAuthService()+ s.userService = userSvc+ s.settingsService = settingsSvc+ s.sessionService = session.NewSessionService(db)++ localUser := &user.User{+ ID: "u-browser-refresh",+ Username: "browser-refresh-user",+ }+ _, err = userSvc.CreateUser(t.Context(), localUser)+ require.NoError(t, err)++ exp := time.Now().Add(5 * time.Minute)+ localSession, refreshJTI := createTestSession(t, db, localUser.ID, exp)+ first, err := s.RefreshToken(t.Context(), makeRefreshToken(t, s.signingKey, refreshJTI, exp, localUser.ID, localSession.ID), auth.SessionMeta{})+ require.NoError(t, err)+ require.NotEmpty(t, first.BrowserRefresh)+ require.Less(t, len(first.BrowserRefresh), 4096)+ require.WithinDuration(t, exp, first.RefreshExpiresAt, time.Second)++ second, err := s.RefreshToken(t.Context(), first.BrowserRefresh, auth.SessionMeta{})+ require.NoError(t, err)++ _, err = s.RefreshToken(t.Context(), first.RefreshToken, auth.SessionMeta{})+ require.ErrorIs(t, err, common.ErrInvalidToken)+ _, err = s.RefreshToken(t.Context(), first.BrowserRefresh, auth.SessionMeta{})+ require.ErrorIs(t, err, common.ErrInvalidToken)++ require.NoError(t, s.RevokeSessionByRefreshToken(t.Context(), second.BrowserRefresh))+ _, err = s.RefreshToken(t.Context(), second.BrowserRefresh, auth.SessionMeta{})+ require.ErrorIs(t, err, common.ErrSessionRevoked)+}+func TestRefreshToken_RejectsRevokedSession(t *testing.T) {db := setupAuthServiceTestDB(t)userSvc := user.NewUserService(db, nil, session.RevokeAllUserSessionsExceptInDB)@@ -633,7 +671,7 @@ func TestChangePassword_RevokesAllSessions(t *testing.T) {s.userService = userSvcs.sessionService = session.NewSessionService(db)- passwordHash, err := userSvc.HashPassword("old-password")+ passwordHash, err := userSvc.HashPassword(t.Context(), "old-password")require.NoError(t, err)localUser := &user.User{ID: "u-password",@@ -663,7 +701,7 @@ func TestChangePassword_KeepsCurrentSessionAlive(t *testing.T) {s.userService = userSvcs.sessionService = session.NewSessionService(db)- passwordHash, err := userSvc.HashPassword("old-password")+ passwordHash, err := userSvc.HashPassword(t.Context(), "old-password")require.NoError(t, err)localUser := &user.User{ID: "u-keep",@@ -903,16 +941,15 @@ func TestAuthenticateLocalPrimary_EmailFallback(t *testing.T) {s.userService = userSvcs.settingsService = settingsSvc- hash, err := userSvc.HashPassword("hunter22!")+ hash, err := userSvc.HashPassword(t.Context(), "hunter22!")require.NoError(t, err)- dupHash, err := userSvc.HashPassword("dup-two-pass!")+ dupHash, err := userSvc.HashPassword(t.Context(), "dup-two-pass!")require.NoError(t, err)for _, u := range []*user.User{{ID: "u-email-login", Username: "bob", Email: new("[email protected]"), PasswordHash: hash},{ID: "u-unicode", Username: "José", Email: new("josé@example.com"), PasswordHash: hash},{ID: "u-decomposed", Username: "Jose\u0301", Email: new("jose\[email protected]"), PasswordHash: hash},{ID: "u-dup-1", Username: "dup1", Email: new("[email protected]"), PasswordHash: hash},- {ID: "u-dup-2", Username: "dup2", Email: new("[email protected]"), PasswordHash: dupHash},{ID: "u-carol", Username: "[email protected]", Email: new("[email protected]"), PasswordHash: hash},{ID: "u-col-a", Username: "[email protected]", PasswordHash: hash},{ID: "u-col-b", Username: "colb", Email: new("[email protected]"), PasswordHash: dupHash},@@ -921,6 +958,7 @@ func TestAuthenticateLocalPrimary_EmailFallback(t *testing.T) {require.NoError(t, err)}+ require.NoError(t, db.Create(&user.User{ID: "u-dup-2", Username: "dup2", Email: new("[email protected]"), PasswordHash: dupHash}).Error)require.NoError(t, db.Create(&user.User{ID: "u-legacy-spaces", Username: " Jose\u0301 ", Email: new(" [email protected] "), PasswordHash: hash,}).Error)diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex e214c21d3..5f70ab074 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -80,18 +80,26 @@ func createAuthValidator(deps api.HandlerDeps) middleware.AuthValidator {req := c.Request()// Check for API key authenticationif apiKey := req.Header.Get(middleware.HeaderApiKey); apiKey != "" {+ key, err := deps.ApiKey.Service().ValidateRawApiKey(ctx, apiKey)+ if err != nil {+ return nil, nil, false+ }// User-owned API key: personal keys inherit the owner's role// permissions; scoped keys are limited to their own grants.- if user, key, err := deps.ApiKey.Service().ValidateApiKeyWithID(ctx, apiKey); err == nil && user != nil {- if key != nil && key.Kind != apikey.ApiKeyKindPersonal {+ if key.UserID != nil {+ user, userErr := deps.User.Service().GetUserByID(ctx, *key.UserID)+ if userErr != nil {+ return nil, nil, false+ }+ if key.Kind != apikey.ApiKeyKindPersonal {return resolveKey(ctx, key.ID), user.Actor(), true}return resolveUser(ctx, user.Actor()), user.Actor(), true}// Environment bootstrap key (user_id = NULL): used by the proxy when forwarding// requests to a remote env whose apiUrl resolves back to this manager.- if envID, err := deps.ApiKey.Service().GetEnvironmentByApiKey(ctx, apiKey); err == nil && envID != nil {- return authz.EnvironmentPermissionSet(*envID), nil, true+ if key.EnvironmentID != nil {+ return authz.EnvironmentPermissionSet(*key.EnvironmentID), nil, true}return nil, nil, false}@@ -202,6 +210,7 @@ func newRouter(p RouterParams) (*echo.Echo, *edge.TunnelServer) {}})e.Use(secureCookieContextMiddleware(trustedProxyNets))+ e.Use(middleware.WarnUntrustedForwardedFor(trustedProxyNets))authMiddleware := p.AuthMiddlewaree.Use(middleware.NewCORSMiddleware(cfg).Add())@@ -212,7 +221,6 @@ func newRouter(p RouterParams) (*echo.Echo, *edge.TunnelServer) {apiGroup.Use(middleware.PerIPRateLimitForPaths([]string{"/api/auth/login",- "/api/auth/refresh","/api/auth/passkey/login/begin","/api/auth/passkey/login/finish","/api/auth/passkey/mobile/finish",@@ -223,6 +231,9 @@ func newRouter(p RouterParams) (*echo.Echo, *edge.TunnelServer) {"/api/oidc/callback",}, 5, 5,))+ apiGroup.Use(middleware.PerIPRateLimitForPaths(+ []string{"/api/auth/refresh"}, 30, 30,+ ))apiGroup.Use(middleware.PerIPRateLimitForPaths([]string{"/api/auth/federated/token"}, 10, 10,))diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.goindex 5f25c7276..0b84c384b 100644--- a/backend/internal/common/errors.go+++ b/backend/internal/common/errors.go@@ -104,6 +104,7 @@ var (ErrRoleNotFound = Classify(ErrNotFound, errors.New("Role not found"))ErrRoleBuiltIn = Classify(ErrForbidden, errors.New("Built-in role cannot be modified"))ErrRoleNameTaken = Classify(ErrConflict, errors.New("Role name already in use"))+ ErrRoleUsedByFederatedCredential = Classify(ErrConflict, errors.New("Role is used by a federated credential"))ErrUnknownPermission = Classify(ErrValidation, errors.New("Unknown permission"))ErrRolePermissionEscalation = Classify(ErrForbidden, errors.New("cannot grant a permission you do not hold"))ErrInvalidRoleAssignment = Classify(ErrBadRequest, errors.New("invalid role assignment"))diff --git a/backend/internal/di/di.go b/backend/internal/di/di.goindex 69f4a67a3..eea7f2759 100644--- a/backend/internal/di/di.go+++ b/backend/internal/di/di.go@@ -76,8 +76,8 @@ var ServiceOptions = fx.Options(fx.Annotate(activity.NewActivityService, fx.As(fx.Self()), fx.As(new(activitylib.Service))),fx.Annotate(event.NewEventService, fx.OnStop(func(ctx context.Context, service *event.EventService) error { return service.Stop(ctx) })),job.NewJobService,- role.NewRoleService,- apikey.NewApiKeyService,+ fx.Annotate(role.NewRoleService, fx.OnStop((*role.RoleService).Stop)),+ fx.Annotate(apikey.NewApiKeyService, fx.OnStop((*apikey.ApiKeyService).Stop)),func(db *database.DB, roles *role.RoleService) *user.UserService {return user.NewUserService(db, roles, session.RevokeAllUserSessionsExceptInDB)},@@ -108,7 +108,7 @@ var ServiceOptions = fx.Options(backup.NewRecoveryKeyStore,upload.NewUploadService,health.NewService,- auth.NewAuthService,+ fx.Annotate(auth.NewAuthService, fx.OnStop((*auth.AuthService).Stop)),settings.NewSettingsSearchService,fx.Annotate(settings.NewSettingsService, fx.OnStop(func(ctx context.Context, service *settings.SettingsService) error { return service.Stop(ctx) })),provideVolumeService,diff --git a/backend/internal/middleware/ratelimit.go b/backend/internal/middleware/ratelimit.goindex ba569f386..44f10e0f7 100644--- a/backend/internal/middleware/ratelimit.go+++ b/backend/internal/middleware/ratelimit.go@@ -2,9 +2,10 @@ package middlewareimport ("cmp"+ "log/slog""net""net/http"- "sort"+ "slices""strings""sync""time"@@ -25,6 +26,11 @@ type ipRateLimiter struct {maxEntries int}+type limiterAge struct {+ key string+ seen time.Time+}+type limiterEntry struct {limiter *rate.Limiterseen time.Time@@ -69,7 +75,7 @@ func (l *ipRateLimiter) trimForNewEntryInternal(key string) {if l.maxEntries <= 0 || len(l.limiters) < l.maxEntries {return}- l.evictOldestEntriesInternal(len(l.limiters)-l.maxEntries+1, key)+ l.evictOldestEntriesInternal(max(len(l.limiters)-l.maxEntries+1, l.maxEntries/10), key)}func (l *ipRateLimiter) trimToMaxEntriesInternal(protectedKey string) {@@ -84,22 +90,16 @@ func (l *ipRateLimiter) evictOldestEntriesInternal(count int, protectedKey strinreturn}- entries := make([]struct {- key string- seen time.Time- }, 0, len(l.limiters))+ entries := make([]limiterAge, 0, len(l.limiters))for key, entry := range l.limiters {if key == protectedKey {continue}- entries = append(entries, struct {- key string- seen time.Time- }{key: key, seen: entry.seen})+ entries = append(entries, limiterAge{key: key, seen: entry.seen})}- sort.Slice(entries, func(i, j int) bool {- return entries[i].seen.Before(entries[j].seen)+ slices.SortFunc(entries, func(a, b limiterAge) int {+ return a.seen.Compare(b.seen)})for i := 0; i < count && i < len(entries); i++ {@@ -229,13 +229,38 @@ func PerIPRateLimitForPaths(paths []string, perMinute, burst int) echo.Middlewar}}+func WarnUntrustedForwardedFor(trustedProxyNets []*net.IPNet) echo.MiddlewareFunc {+ var once sync.Once+ return func(next echo.HandlerFunc) echo.HandlerFunc {+ return func(c *echo.Context) error {+ req := c.Request()+ if req.Header.Get("X-Forwarded-For") == "" {+ return next(c)+ }+ host, _, err := net.SplitHostPort(req.RemoteAddr)+ ip := net.ParseIP(kit.Ternary(err != nil, req.RemoteAddr, host))+ if ip == nil || !slices.ContainsFunc(trustedProxyNets, func(n *net.IPNet) bool { return n.Contains(ip) }) {+ once.Do(func() {+ slog.WarnContext(req.Context(),+ "X-Forwarded-For received from an untrusted peer; clients behind this proxy share one rate-limit bucket. Set TRUSTED_PROXIES to the proxy's address range.",+ "peer", req.RemoteAddr)+ })+ }+ return next(c)+ }+ }+}+func clientIPForRateLimitInternal(c *echo.Context) string {- if ip := strings.TrimSpace(c.RealIP()); ip != "" {- return ip+ host := strings.TrimSpace(c.RealIP())+ if host == "" {+ var err error+ if host, _, err = net.SplitHostPort(c.Request().RemoteAddr); err != nil {+ host = c.Request().RemoteAddr+ }}- host, _, err := net.SplitHostPort(c.Request().RemoteAddr)- if err != nil {- return c.Request().RemoteAddr+ if ip := net.ParseIP(host); ip != nil && ip.To4() == nil {+ return ip.Mask(net.CIDRMask(64, 128)).String() + "/64"}return host}diff --git a/backend/internal/oidc/handler.go b/backend/internal/oidc/handler.goindex cc408a5c7..7791e1b3b 100644--- a/backend/internal/oidc/handler.go+++ b/backend/internal/oidc/handler.go@@ -5,7 +5,6 @@ import ("errors""log/slog""strings"- "time""github.com/danielgtaylor/huma/v2"authtypes "github.com/getarcaneapp/arcane/types/v2/auth"@@ -132,6 +131,9 @@ func (h *OidcHandler) GetOidcStatus(ctx context.Context, _ *GetOidcStatusInput)// GetOidcConfig returns the OIDC client configuration.func (h *OidcHandler) GetOidcConfig(ctx context.Context, input *GetOidcConfigInput) (*GetOidcConfigOutput, error) {oidcConfig, err := h.authService.GetOidcConfig(ctx)+ if errors.Is(err, auth.ErrOidcAuthDisabled) {+ return nil, huma.Error400BadRequest(auth.ErrOidcAuthDisabled.Error())+ }if err != nil {return nil, huma.Error500InternalServerError("Failed to get OIDC configuration")}@@ -232,6 +234,12 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcCuserModel, isNewUser, err := h.authService.PrepareOidcLogin(ctx, *userInfo, tokenResp)if err != nil {slog.ErrorContext(ctx, "OIDC login preparation failed", "error", err, "subject", userInfo.Subject)+ switch {+ case errors.Is(err, common.ErrForbidden):+ return nil, huma.Error403Forbidden(err.Error())+ case errors.Is(err, common.ErrConflict):+ return nil, huma.Error409Conflict(err.Error())+ }return nil, huma.Error500InternalServerError("Authentication failed")}@@ -262,9 +270,7 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcCreturn nil, huma.Error500InternalServerError("Authentication failed")}if mobileRedirectURI == "" {- maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)- maxAge += 60 // Add 60 seconds buffer for clock skew- setCookies = append(setCookies, cookie.BuildTokenCookieStringFor(maxAge, tokenPair.BrowserToken, cookie.SecureCookieFromContext(ctx))...)+ setCookies = append(setCookies, tokenPair.CookieHeaders(cookie.SecureCookieFromContext(ctx))...)}expiresAt := tokenPair.ExpiresAt@@ -335,6 +341,12 @@ func (h *OidcHandler) ExchangeDeviceToken(ctx context.Context, input *ExchangeDeuserModel, isNewUser, err := h.authService.PrepareOidcLogin(ctx, *userInfo, tokenResp)if err != nil {slog.ErrorContext(ctx, "OIDC login preparation failed", "error", err, "subject", userInfo.Subject)+ switch {+ case errors.Is(err, common.ErrForbidden):+ return nil, huma.Error403Forbidden(err.Error())+ case errors.Is(err, common.ErrConflict):+ return nil, huma.Error409Conflict(err.Error())+ }return nil, huma.Error500InternalServerError("Authentication failed")}// The device flow has no way to satisfy a WebAuthn assertion: the CLI has nodiff --git a/backend/internal/oidc/service.go b/backend/internal/oidc/service.goindex f35c87700..8b1bc7f19 100644--- a/backend/internal/oidc/service.go+++ b/backend/internal/oidc/service.go@@ -100,7 +100,7 @@ func NewOidcService(authService *auth.AuthService, settingsService *settings.SethttpClient: &oidcClient,insecureHttpClient: &insecureClient,keySetManager: keySetManager,- providerCache: hot.NewHotCache[oidcProviderKey, *oidc.Provider](hot.LRU, 4).Build(),+ providerCache: hot.NewHotCache[oidcProviderKey, *oidc.Provider](hot.LRU, 4).WithTTL(time.Hour).Build(),}}diff --git a/backend/internal/passkey/handler.go b/backend/internal/passkey/handler.goindex 964bdf1e9..1dfdd2796 100644--- a/backend/internal/passkey/handler.go+++ b/backend/internal/passkey/handler.go@@ -202,7 +202,7 @@ func (h *PasskeyHandler) FinishPasskeyLogin(ctx context.Context, input *PasskeyLreturn nil, err}return &PasskeyLoginFinishOutput{- SetCookie: tokenCookieInternal(ctx, tokenPair),+ SetCookie: tokenPair.CookieHeaders(cookie.SecureCookieFromContext(ctx)),Body: base.ApiResponse[authtypes.AuthenticationResponse]{Success: true, Data: *response},}, nil}@@ -264,7 +264,7 @@ func (h *PasskeyHandler) FinishMFA(ctx context.Context, input *PasskeyMFAFinishIreturn nil, err}return &PasskeyMFAFinishOutput{- SetCookie: tokenCookieInternal(ctx, tokenPair),+ SetCookie: tokenPair.CookieHeaders(cookie.SecureCookieFromContext(ctx)),Body: base.ApiResponse[authtypes.AuthenticationResponse]{Success: true, Data: *response},}, nil}@@ -283,7 +283,7 @@ func (h *PasskeyHandler) UseRecoveryCode(ctx context.Context, input *PasskeyRecoreturn nil, err}return &PasskeyRecoveryOutput{- SetCookie: tokenCookieInternal(ctx, tokenPair),+ SetCookie: tokenPair.CookieHeaders(cookie.SecureCookieFromContext(ctx)),Body: base.ApiResponse[authtypes.AuthenticationResponse]{Success: true, Data: *response},}, nil}@@ -412,7 +412,7 @@ func (h *PasskeyHandler) PasswordStepUp(ctx context.Context, input *PasswordStepif strings.TrimSpace(userModel.PasswordHash) == "" {return nil, huma.Error400BadRequest("this account has no local password")}- if validatePasswordErr := h.userService.ValidatePassword(userModel.PasswordHash, input.Body.Password); validatePasswordErr != nil {+ if validatePasswordErr := h.userService.ValidatePassword(ctx, userModel.PasswordHash, input.Body.Password); validatePasswordErr != nil {return nil, huma.Error401Unauthorized("password is incorrect")}grant, err := h.passkeyService.CreatePasswordStepUpGrant(ctx, actor.ID, sessionID)@@ -517,11 +517,6 @@ func marshalCredentialInternal(credential map[string]any) ([]byte, error) {return json.Marshal(credential)}-func tokenCookieInternal(ctx context.Context, tokenPair *auth.TokenPair) []string {- maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0) + 60- return cookie.BuildTokenCookieStringFor(maxAge, tokenPair.BrowserToken, cookie.SecureCookieFromContext(ctx))-}-func passkeyHTTPErrorInternal(err error) error {switch {case errors.Is(err, ErrPasskeyNotFound):diff --git a/backend/internal/passkey/service.go b/backend/internal/passkey/service.goindex c0c983c5d..b5fb3a063 100644--- a/backend/internal/passkey/service.go+++ b/backend/internal/passkey/service.go@@ -1005,7 +1005,7 @@ func (s *PasskeyService) RegenerateRecoveryCodes(ctx context.Context, userID, se}err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {var user userdomain.User- if loadRecoveryUserErr := tx.Where("id = ?", userID).First(&user).Error; loadRecoveryUserErr != nil {+ if loadRecoveryUserErr := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID).First(&user).Error; loadRecoveryUserErr != nil {return fmt.Errorf("failed to load user for recovery code regeneration: %w", loadRecoveryUserErr)}if !user.PasskeyMFAEnabled {@@ -1094,6 +1094,11 @@ func (s *PasskeyService) sweepCeremoniesInternal(ctx context.Context) error {Delete(&PasskeyCeremony{}).Error; err != nil {return fmt.Errorf("failed to sweep passkey ceremonies: %w", err)}+ if err := s.db.WithContext(ctx).+ Where("expires_at <= ?", now.Add(-24*time.Hour)).+ Delete(&AuthTransaction{}).Error; err != nil {+ return fmt.Errorf("failed to sweep authentication transactions: %w", err)+ }return nil}@@ -1322,6 +1327,18 @@ func (s *PasskeyService) updateCredentialAfterAssertionInternal(ctx context.Contreturn ErrPasskeyResponse}now := time.Now()+ if credential.Authenticator.CloneWarning {+ slog.WarnContext(ctx, "passkey assertion rejected: signature counter regressed", "passkeyId", credentialModelID, "userId", adapter.model.ID)+ if err := s.db.WithContext(ctx).Model(&Passkey{}).+ Where("id = ? AND user_id = ? AND rp_id = ?", credentialModelID, adapter.model.ID, s.rpID).+ Updates(map[string]any{+ "clone_warning": true,+ "updated_at": now,+ }).Error; err != nil {+ slog.WarnContext(ctx, "failed to flag cloned passkey", "passkeyId", credentialModelID, "error", err)+ }+ return ErrPasskeyResponse+ }result := s.db.WithContext(ctx).Model(&Passkey{}).Where("id = ? AND user_id = ? AND rp_id = ?", credentialModelID, adapter.model.ID, s.rpID).Updates(map[string]any{diff --git a/backend/internal/role/handler.go b/backend/internal/role/handler.goindex 43ca2a58a..d89291441 100644--- a/backend/internal/role/handler.go+++ b/backend/internal/role/handler.go@@ -149,7 +149,7 @@ func (h *RoleHandler) DeleteRole(ctx context.Context, input *DeleteRoleInput) (*return nil, huma.Error404NotFound("role not found")case errors.Is(err, common.ErrRoleBuiltIn):return nil, huma.Error403Forbidden("built-in roles cannot be deleted")- case errors.Is(err, common.ErrNoGlobalAdminRemains):+ case errors.Is(err, common.ErrNoGlobalAdminRemains), errors.Is(err, common.ErrRoleUsedByFederatedCredential):return nil, huma.Error409Conflict(err.Error())}return nil, huma.Error500InternalServerError("failed to delete role: " + err.Error())diff --git a/backend/internal/role/service.go b/backend/internal/role/service.goindex eba1a7e99..6f33a2389 100644--- a/backend/internal/role/service.go+++ b/backend/internal/role/service.go@@ -30,10 +30,9 @@ import ()const (- permissionCacheTTL = 60 * time.Second- legacyRoleBackfillCompletedKey = "migration.legacy_user_roles.v1.completed"- // Postgres advisory lock key ("arcane" in ASCII) for lockGlobalAdminGuard.- globalAdminGuardLockKey int64 = 0x617263616e65+ permissionCacheTTL = 60 * time.Second+ legacyRoleBackfillCompletedKey = "migration.legacy_user_roles.v1.completed"+ globalAdminGuardLockKey int64 = 0x617263616e65)type RoleService struct {@@ -167,8 +166,7 @@ func (s *RoleService) AssertGlobalAdminExists(ctx context.Context, tx *gorm.DB)return nil}-// lockGlobalAdminGuard serializes transactions that can remove a global admin. SQLite already serializes writes.-func lockGlobalAdminGuard(tx *gorm.DB) error {+func (s *RoleService) LockGlobalAdminGuard(tx *gorm.DB) error {if tx.Name() != "postgres" {return nil}@@ -270,7 +268,7 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descriptivar out Rolevar affected []stringerr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- if err := lockGlobalAdminGuard(tx); err != nil {+ if err := s.LockGlobalAdminGuard(tx); err != nil {return err}var existing Role@@ -322,7 +320,7 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descriptifunc (s *RoleService) DeleteRole(ctx context.Context, id string) error {var affected []stringerr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- if err := lockGlobalAdminGuard(tx); err != nil {+ if err := s.LockGlobalAdminGuard(tx); err != nil {return err}var existing Role@@ -336,6 +334,14 @@ func (s *RoleService) DeleteRole(ctx context.Context, id string) error {return common.Classify(common.ErrRoleBuiltIn, errors.New("Built-in role cannot be modified")) //nolint:staticcheck // Preserve the existing error message.}+ var federatedCredentialCount int64+ if countErr := tx.Table("federated_credentials").Where("role_id = ?", id).Count(&federatedCredentialCount).Error; countErr != nil {+ return fmt.Errorf("failed to check federated credentials for role: %w", countErr)+ }+ if federatedCredentialCount > 0 {+ return common.ErrRoleUsedByFederatedCredential+ }+ids, err := lockAssignedUserRows(tx, id)if err != nil {return err@@ -399,7 +405,7 @@ func (s *RoleService) ReplaceUserAssignments(ctx context.Context, userID, sourcedesired[i].Source = source}err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- if err := lockGlobalAdminGuard(tx); err != nil {+ if err := s.LockGlobalAdminGuard(tx); err != nil {return err}// Lock the user row so assignment swaps serialize with user-domain privilege checks.@@ -628,7 +634,7 @@ func (s *RoleService) ResolveExecutionPermissions(ctx context.Context, userID, kcase "personal":permissions, err = s.ResolveUserPermissionsInDB(ctx, db, userID)case "scoped":- permissions, err = s.resolveApiKeyPermissionsInDBInternal(db, keyID)+ permissions, err = s.resolveApiKeyPermissionsInDBInternal(ctx, db, keyID)default:return nil, errors.New("requesting API key kind is invalid")}@@ -657,7 +663,7 @@ func (s *RoleService) ResolveApiKeyPermissions(ctx context.Context, apiKeyID strreturn ps, nil}gen := s.apiKeyCacheGen.Load()- permissions, err := s.resolveApiKeyPermissionsInDBInternal(s.db.WithContext(ctx), apiKeyID)+ permissions, err := s.resolveApiKeyPermissionsInDBInternal(ctx, s.db.WithContext(ctx), apiKeyID)if err != nil {return nil, err}@@ -669,17 +675,37 @@ func (s *RoleService) ResolveApiKeyPermissions(ctx context.Context, apiKeyID strreturn permissions, nil}-func (s *RoleService) resolveApiKeyPermissionsInDBInternal(db *gorm.DB, apiKeyID string) (*authz.PermissionSet, error) {+func (s *RoleService) resolveApiKeyPermissionsInDBInternal(ctx context.Context, db *gorm.DB, apiKeyID string) (*authz.PermissionSet, error) {+ var key struct{ UserID *string }+ if err := db.Table("api_keys").Select("user_id").Where("id = ?", apiKeyID).Take(&key).Error; err != nil {+ return nil, fmt.Errorf("failed to load api key owner: %w", err)+ }+ if kit.FromPtr(key.UserID) == "" {+ return authz.NewPermissionSet(), nil+ }+ owner, err := s.ResolveUserPermissionsInDB(ctx, db, *key.UserID)+ if err != nil {+ return nil, err+ }var grants []ApiKeyPermission- if err := db.Where("api_key_id = ?", apiKeyID).Find(&grants).Error; err != nil {- return nil, fmt.Errorf("failed to resolve api key permissions: %w", err)+ if findGrantsErr := db.Where("api_key_id = ?", apiKeyID).Find(&grants).Error; findGrantsErr != nil {+ return nil, fmt.Errorf("failed to resolve api key permissions: %w", findGrantsErr)}permissions := authz.NewPermissionSet()for _, grant := range grants {- if grant.EnvironmentID == nil {+ switch {+ case grant.EnvironmentID != nil:+ if owner.Allows(grant.Permission, *grant.EnvironmentID) {+ permissions.AddEnv(*grant.EnvironmentID, grant.Permission)+ }+ case owner.Allows(grant.Permission, ""):permissions.AddGlobal(grant.Permission)- } else {- permissions.AddEnv(*grant.EnvironmentID, grant.Permission)+ default:+ for envID, envPermissions := range owner.PerEnv {+ if _, ok := envPermissions[grant.Permission]; ok {+ permissions.AddEnv(envID, grant.Permission)+ }+ }}}return permissions, nil@@ -736,7 +762,7 @@ func (s *RoleService) CreateOidcMapping(ctx context.Context, claimValue, roleID}var mapping OidcRoleMappingerr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- if err := validateRoleIDsExistInternal(tx, []string{roleID}); err != nil {+ if err := validateAssignmentsExistInternal(tx, []UserRoleAssignment{{RoleID: roleID, EnvironmentID: environmentID}}); err != nil {return err}mapping = OidcRoleMapping{@@ -777,7 +803,7 @@ func (s *RoleService) UpdateOidcMapping(ctx context.Context, id, claimValue, rolif existing.Source == OidcMappingSourceEnv {return common.Classify(common.ErrOidcMappingEnvManaged, errors.New("OIDC role mapping is managed by OIDC_ROLE_MAPPINGS and cannot be edited at runtime"))}- if err := validateRoleIDsExistInternal(tx, []string{roleID}); err != nil {+ if err := validateAssignmentsExistInternal(tx, []UserRoleAssignment{{RoleID: roleID, EnvironmentID: environmentID}}); err != nil {return err}existing.ClaimValue = claimValue@@ -795,35 +821,6 @@ func (s *RoleService) UpdateOidcMapping(ctx context.Context, id, claimValue, rolreturn &out, nil}-func validateRoleIDsExistInternal(tx *gorm.DB, roleIDs []string) error {- if len(roleIDs) == 0 {- return nil- }- roleIDSet := make(map[string]struct{}, len(roleIDs))- for _, roleID := range roleIDs {- if roleID == "" {- return errors.New("role id is required")- }- roleIDSet[roleID] = struct{}{}- }-- normalized := slices.Collect(maps.Keys(roleIDSet))- var found []string- if err := tx.Model(&Role{}).Where("id IN ?", normalized).Pluck("id", &found).Error; err != nil {- return fmt.Errorf("failed to verify role ids: %w", err)- }- foundSet := make(map[string]struct{}, len(found))- for _, id := range found {- foundSet[id] = struct{}{}- }- for _, id := range normalized {- if _, ok := foundSet[id]; !ok {- return common.Classify(common.ErrInvalidRoleAssignment, fmt.Errorf("invalid role assignment: role %q does not exist", id))- }- }- return nil-}-func (s *RoleService) DeleteOidcMapping(ctx context.Context, id string) error {return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {var existing OidcRoleMapping@@ -909,6 +906,13 @@ func (s *RoleService) InvalidateUser(userID string) {defer s.cacheFillMu.Unlock()s.userCacheGen.Add(1)s.userCache.Delete(userID)+ s.apiKeyCacheGen.Add(1)+ s.apiKeyCache.Purge()+}++func (s *RoleService) Stop() {+ s.userCache.StopJanitor()+ s.apiKeyCache.StopJanitor()}// InvalidateApiKey drops the cached permissions for one API key.diff --git a/backend/internal/role/service_test.go b/backend/internal/role/service_test.goindex af5625998..7a40ccddd 100644--- a/backend/internal/role/service_test.go+++ b/backend/internal/role/service_test.go@@ -402,6 +402,7 @@ func TestResolveExecutionPermissions(t *testing.T) {t.Run("scoped keys bypass cached grants", func(t *testing.T) {db, service := setupUserAndRoleServices(t)owner := createTestUser(t, db, "owner", "owner")+ grantGlobalAdmin(t, service, owner.ID)environmentID := "env-1"key := testApiKeyRow{ID: "scoped", Kind: "scoped", UserID: &owner.ID, EnvironmentID: &environmentID}require.NoError(t, db.Create(&key).Error)diff --git a/backend/internal/user/handler.go b/backend/internal/user/handler.goindex 52775e2a6..378e2e467 100644--- a/backend/internal/user/handler.go+++ b/backend/internal/user/handler.go@@ -9,6 +9,7 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/user"+ "go.getarcane.app/kit/pkg""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -99,7 +100,7 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*return nil, handlerutil.Error400BadRequestWithType(validatePasswordPolicyErr.Error(), validation.PasswordPolicyProblemType(passwordPolicy))}- hashedPassword, err := h.userService.HashPassword(input.Body.Password)+ hashedPassword, err := h.userService.HashPassword(ctx, input.Body.Password)if err != nil {return nil, huma.Error500InternalServerError("Failed to hash password")}@@ -122,6 +123,9 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*if errors.Is(err, ErrUsernameTaken) {return nil, huma.Error409Conflict(ErrUsernameTaken.Error())}+ if errors.Is(err, ErrEmailTaken) {+ return nil, huma.Error409Conflict(ErrEmailTaken.Error())+ }return nil, huma.Error500InternalServerError("Failed to create user")}@@ -203,12 +207,6 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*if validatePasswordPolicyErr := validation.ValidatePasswordPolicy(*input.Body.Password, passwordPolicy); validatePasswordPolicyErr != nil {return nil, handlerutil.Error400BadRequestWithType(validatePasswordPolicyErr.Error(), validation.PasswordPolicyProblemType(passwordPolicy))}- hashedPassword, hashPasswordErr := h.userService.HashPassword(*input.Body.Password)- if hashPasswordErr != nil {- return nil, huma.Error500InternalServerError("Failed to hash password")- }- userModel.PasswordHash = hashedPassword- userModel.RequiresPasswordChange = false}updatedUser, err := h.userService.UpdateUser(ctx, userModel, callerPerms)@@ -222,12 +220,24 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*if errors.Is(err, ErrUsernameTaken) {return nil, huma.Error409Conflict(ErrUsernameTaken.Error())}+ if errors.Is(err, ErrEmailTaken) {+ return nil, huma.Error409Conflict(ErrEmailTaken.Error())+ }if errors.Is(err, common.ErrUserNotFound) {return nil, huma.Error404NotFound("User not found")}return nil, huma.Error500InternalServerError("Failed to update user")}+ if input.Body.Password != nil && *input.Body.Password != "" {+ caller, _ := userctx.CurrentUserFromContext(ctx)+ currentSessionID, _ := middleware.GetCurrentSessionIDFromContext(ctx)+ exceptSessionID := kit.Ternary(caller != nil && caller.ID == updatedUser.ID, currentSessionID, "")+ if _, setPasswordErr := h.userService.SetPasswordAndRevokeSessionsExcept(ctx, updatedUser, *input.Body.Password, exceptSessionID, callerPerms); setPasswordErr != nil {+ return nil, huma.Error500InternalServerError("Failed to update password")+ }+ }+if h.invalidateUserTokenCache != nil {h.invalidateUserTokenCache(updatedUser.ID)}diff --git a/backend/internal/user/service.go b/backend/internal/user/service.goindex 3f85ec9c0..942a1ca69 100644--- a/backend/internal/user/service.go+++ b/backend/internal/user/service.go@@ -51,6 +51,7 @@ type UserService struct {db *database.DBroleService *role.RoleServiceargon2Params *Argon2Params+ argon2Slots chan struct{}revokeSessionsExcept func(context.Context, *gorm.DB, string, string) error}@@ -58,6 +59,7 @@ var (ErrCannotRemoveLastAdmin = errors.New("cannot remove the last admin user")ErrUsernameRequired = errors.New("username is required")ErrUsernameTaken = errors.New("username already in use")+ ErrEmailTaken = common.Classify(common.ErrConflict, errors.New("email 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@@ -70,18 +72,25 @@ func NewUserService(db *database.DB, roleService *role.RoleService, revokeSessiodb: db,roleService: roleService,argon2Params: DefaultArgon2Params(),+ argon2Slots: make(chan struct{}, 4),revokeSessionsExcept: revokeSessionsExcept,}}-func (s *UserService) HashPassword(password string) (string, error) {+func (s *UserService) HashPassword(ctx context.Context, password string) (string, error) {salt := make([]byte, s.argon2Params.saltLength)_, err := rand.Read(salt)if err != nil {return "", err}+ select {+ case s.argon2Slots <- struct{}{}:+ case <-ctx.Done():+ return "", ctx.Err()+ }hash := argon2.IDKey([]byte(password), salt, s.argon2Params.iterations, s.argon2Params.memory, s.argon2Params.parallelism, s.argon2Params.keyLength)+ <-s.argon2Slotsb64Salt := base64.RawStdEncoding.EncodeToString(salt)b64Hash := base64.RawStdEncoding.EncodeToString(hash)@@ -91,7 +100,7 @@ func (s *UserService) HashPassword(password string) (string, error) {return encodedHash, nil}-func (s *UserService) ValidatePassword(encodedHash, password string) error {+func (s *UserService) ValidatePassword(ctx context.Context, encodedHash, password string) error {parts := strings.Split(encodedHash, "$")if len(parts) != 6 {return errors.New("invalid hash format")@@ -128,7 +137,13 @@ func (s *UserService) ValidatePassword(encodedHash, password string) error {return errors.New("invalid hash length")}+ select {+ case s.argon2Slots <- struct{}{}:+ case <-ctx.Done():+ return ctx.Err()+ }comparisonHash := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, uint32(hashLen))+ <-s.argon2Slots// constant-time compareif subtle.ConstantTimeCompare(comparisonHash, decodedHash) != 1 {@@ -149,6 +164,11 @@ func (s *UserService) CreateUser(ctx context.Context, localUser *User) (*User, elocalUser.Username = usernameerr = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {+ if localUser.OidcSubjectId == nil {+ if ensureEmailErr := ensureEmailAvailable(tx, localUser.ID, localUser.Email); ensureEmailErr != nil {+ return ensureEmailErr+ }+ }if createUserErr := tx.Create(localUser).Error; createUserErr != nil {if isDuplicateKeyErrorInternal(tx, createUserErr) {return ErrUsernameTaken@@ -276,24 +296,66 @@ func (s *UserService) UpdateUser(ctx context.Context, localUser *User, actorPermif err := normalization.Normalize(localUser); err != nil {return nil, err}+ var updated Usererr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {if err := s.checkTargetPrivilegeInternal(ctx, tx, actorPerms, localUser.ID); err != nil {return err}- if err := tx.Save(localUser).Error; err != nil {+ var current User+ if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", localUser.ID).First(¤t).Error; err != nil {+ return fmt.Errorf("failed to load user: %w", err)+ }+ if !strings.EqualFold(kit.FromPtr(current.Email), kit.FromPtr(localUser.Email)) {+ if err := ensureEmailAvailable(tx, localUser.ID, localUser.Email); err != nil {+ return err+ }+ }+ if err := tx.Model(&User{}).+ Where("id = ?", localUser.ID).+ Select("username", "display_name", "email", "locale", "time_format", "font_size", "preferences", "updated_at").+ Updates(&User{+ BaseModel: database.BaseModel{+ UpdatedAt: new(time.Now()),+ },+ Username: localUser.Username,+ DisplayName: localUser.DisplayName,+ Email: localUser.Email,+ Locale: localUser.Locale,+ TimeFormat: localUser.TimeFormat,+ FontSize: localUser.FontSize,+ Preferences: localUser.Preferences,+ }).Error; err != nil {if isDuplicateKeyErrorInternal(tx, err) {return ErrUsernameTaken}return fmt.Errorf("failed to update user: %w", err)}+ if reloadErr := tx.Where("id = ?", localUser.ID).First(&updated).Error; reloadErr != nil {+ return fmt.Errorf("failed to reload user: %w", reloadErr)+ }return nil})if err != nil {return nil, err}+ *localUser = updatedreturn localUser, nil}+func ensureEmailAvailable(tx *gorm.DB, userID string, email *string) error {+ if kit.FromPtr(email) == "" {+ return nil+ }+ var ids []string+ if err := tx.Model(&User{}).+ Where("LOWER(email) = LOWER(?) AND id <> ?", *email, userID).+ Limit(1).+ Pluck("id", &ids).Error; err != nil {+ return fmt.Errorf("failed to check email availability: %w", err)+ }+ return kit.Ternary[error](len(ids) > 0, ErrEmailTaken, nil)+}+// TouchLastLogin updates only the user's last login time.func (s *UserService) TouchLastLogin(ctx context.Context, userID string, at time.Time) error {err := s.db.DB.WithContext(ctx).@@ -331,21 +393,45 @@ func (s *UserService) SetPassword(ctx context.Context, localUser *User, passwordreturn nil, errors.New("user is nil")}- hashedPassword, err := s.HashPassword(password)+ hashedPassword, err := s.HashPassword(ctx, password)if err != nil {return nil, fmt.Errorf("failed to hash password: %w", err)}- localUser.PasswordHash = hashedPassword- localUser.RequiresPasswordChange = false- return s.UpdateUser(ctx, localUser, nil)+ var updated User+ err = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {+ result := tx.Model(&User{}).+ Where("id = ?", localUser.ID).+ Select("password_hash", "requires_password_change", "updated_at").+ Updates(&User{+ BaseModel: database.BaseModel{+ UpdatedAt: new(time.Now()),+ },+ PasswordHash: hashedPassword,+ })+ if result.Error != nil {+ return fmt.Errorf("failed to update user password: %w", result.Error)+ }+ if result.RowsAffected == 0 {+ return common.ErrUserNotFound+ }+ if reloadErr := tx.Where("id = ?", localUser.ID).First(&updated).Error; reloadErr != nil {+ return fmt.Errorf("failed to reload user: %w", reloadErr)+ }+ return nil+ })+ if err != nil {+ return nil, err+ }+ *localUser = updated+ return localUser, nil}// SetPasswordAndRevokeSessionsExcept atomically sets a new password, clears// the first-login password-change requirement, and revokes every session for// the user except exceptSessionID. Pass an empty exceptSessionID to revoke all// sessions. This is for trusted internal callers.-func (s *UserService) SetPasswordAndRevokeSessionsExcept(ctx context.Context, localUser *User, password, exceptSessionID string) (*User, error) {+func (s *UserService) SetPasswordAndRevokeSessionsExcept(ctx context.Context, localUser *User, password, exceptSessionID string, actorPerms *authz.PermissionSet) (*User, error) {if localUser == nil {return nil, errors.New("user is nil")}@@ -353,13 +439,16 @@ func (s *UserService) SetPasswordAndRevokeSessionsExcept(ctx context.Context, loreturn nil, common.ErrUserNotFound}- hashedPassword, err := s.HashPassword(password)+ hashedPassword, err := s.HashPassword(ctx, password)if err != nil {return nil, fmt.Errorf("failed to hash password: %w", err)}var updatedUser Usererr = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {+ if privilegeErr := s.checkTargetPrivilegeInternal(ctx, tx, actorPerms, localUser.ID); privilegeErr != nil {+ return privilegeErr+ }if loadPasswordResetUserErr := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", localUser.ID).First(&updatedUser).Error; loadPasswordResetUserErr != nil {@@ -406,7 +495,7 @@ func (s *UserService) AttachOidcSubjectTransactional(ctx context.Context, userID// If already linked to a different subject, abortif u.OidcSubjectId != nil && *u.OidcSubjectId != "" && *u.OidcSubjectId != subject {- return errors.New("user already linked to another OIDC subject")+ return common.Classify(common.ErrConflict, errors.New("user already linked to another OIDC subject"))}// Link subject@@ -422,7 +511,8 @@ func (s *UserService) AttachOidcSubjectTransactional(ctx context.Context, userIDif err := tx.Save(&u).Error; err != nil {// Bubble up uniqueness violations with a clearer messageif strings.Contains(strings.ToLower(err.Error()), "unique") || strings.Contains(strings.ToLower(err.Error()), "duplicate key") {- return fmt.Errorf("oidc subject is already linked to another user: %w", err)+ slog.WarnContext(ctx, "OIDC subject link rejected by uniqueness constraint", "userId", userID, "error", err)+ return common.Classify(common.ErrConflict, errors.New("oidc subject is already linked to another user"))}return fmt.Errorf("failed to persist OIDC merge: %w", err)}@@ -468,7 +558,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {}if count == 0 {- hashedPassword, err := s.HashPassword("arcane-admin")+ hashedPassword, err := s.HashPassword(ctx, "arcane-admin")if err != nil {return fmt.Errorf("failed to hash default admin password: %w", err)}@@ -553,33 +643,29 @@ func (s *UserService) grantDefaultAdminRoleInternal(ctx context.Context, adminUs// be present in ctx. Pass nil for internal service-to-service calls. A// non-admin caller may not delete a global admin target.func (s *UserService) DeleteUser(ctx context.Context, id string, actorPerms *authz.PermissionSet) error {- // Last-admin guard: if this user's effective permissions make them the only- // global admin, refuse the delete. Checked outside the transaction because- // role.RoleService uses its own session and the guard spans rows.- if s.roleService != nil {- ps, err := s.roleService.ResolvePermissions(ctx, id)- if err != nil {+ err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {+ if err := s.roleService.LockGlobalAdminGuard(tx); err != nil {return err}- if ps != nil && ps.IsGlobalAdmin() {- remaining, countGlobalAdminsExcludingUserErr := s.roleService.CountGlobalAdmins(ctx, s.db.DB, id)- if countGlobalAdminsExcludingUserErr != nil {- return countGlobalAdminsExcludingUserErr- }- if remaining == 0 {- return ErrCannotRemoveLastAdmin- }- }- }- return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {if err := s.checkTargetPrivilegeInternal(ctx, tx, actorPerms, id); err != nil {return err}- if err := tx.Delete(&User{}, "id = ?", id).Error; err != nil {- return fmt.Errorf("failed to delete user: %w", err)+ targetPerms, err := s.roleService.ResolveUserPermissionsInDB(ctx, tx, id)+ if err != nil {+ return fmt.Errorf("failed to resolve target permissions: %w", err)}- return nil+ if deleteErr := tx.Delete(&User{}, "id = ?", id).Error; deleteErr != nil {+ return fmt.Errorf("failed to delete user: %w", deleteErr)+ }+ if !targetPerms.IsGlobalAdmin() {+ return nil+ }+ return s.roleService.AssertGlobalAdminExists(ctx, tx)})+ if errors.Is(err, common.ErrNoGlobalAdminRemains) {+ return ErrCannotRemoveLastAdmin+ }+ return err}func (s *UserService) ListUsersPaginated(ctx context.Context, params pagination.QueryParams) ([]user.User, pagination.Response, error) {diff --git a/backend/internal/user/service_test.go b/backend/internal/user/service_test.goindex 5cff3d864..3d47fc898 100644--- a/backend/internal/user/service_test.go+++ b/backend/internal/user/service_test.go@@ -102,7 +102,7 @@ func TestSetPasswordUpdatesHashAndClearsPasswordChangeRequirement(t *testing.T)userSvc, _ := setupUserAndRoleServices(t)ctx := t.Context()- oldHash, err := userSvc.HashPassword("old-password")+ oldHash, err := userSvc.HashPassword(t.Context(), "old-password")require.NoError(t, err)localUser, err := userSvc.CreateUser(ctx, &userdomain.User{ID: "password-user",@@ -117,8 +117,8 @@ func TestSetPasswordUpdatesHashAndClearsPasswordChangeRequirement(t *testing.T)updated, err := userSvc.GetUserByID(ctx, localUser.ID)require.NoError(t, err)- require.NoError(t, userSvc.ValidatePassword(updated.PasswordHash, "new-password"))- require.Error(t, userSvc.ValidatePassword(updated.PasswordHash, "old-password"))+ require.NoError(t, userSvc.ValidatePassword(t.Context(), updated.PasswordHash, "new-password"))+ require.Error(t, userSvc.ValidatePassword(t.Context(), updated.PasswordHash, "old-password"))require.False(t, updated.RequiresPasswordChange)}@@ -264,9 +264,7 @@ func TestUserDtoExposesLastLogin(t *testing.T) {require.Nil(t, dto.LastLogin, "a user who has never signed in has no last login")loginAt := time.Date(2026, 8, 2, 15, 4, 5, 0, time.UTC)- u.LastLogin = &loginAt- _, err = userSvc.UpdateUser(ctx, u, nil)- require.NoError(t, err)+ require.NoError(t, userSvc.TouchLastLogin(ctx, u.ID, loginAt))reloaded, err := userSvc.GetUserByID(ctx, u.ID)require.NoError(t, err)diff --git a/backend/internal/webhook/handler.go b/backend/internal/webhook/handler.goindex 1a6f948ce..9dcc11a63 100644--- a/backend/internal/webhook/handler.go+++ b/backend/internal/webhook/handler.go@@ -9,6 +9,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/user""github.com/getarcaneapp/arcane/types/v2/webhook"+ "github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/userctx")@@ -63,6 +64,7 @@ func (h *WebhookHandler) CreateWebhook(ctx context.Context, input *CreateWebhookactor = *currentUser}+ callerPerms, _ := middleware.PermissionsFromContext(ctx)wh, rawToken, err := h.webhookService.CreateWebhook(ctx,input.Body.Name,@@ -71,8 +73,12 @@ func (h *WebhookHandler) CreateWebhook(ctx context.Context, input *CreateWebhookinput.Body.TargetID,input.EnvironmentID,actor,+ callerPerms,)if err != nil {+ if errors.Is(err, ErrWebhookForbidden) {+ return nil, huma.Error403Forbidden(ErrWebhookForbidden.Error())+ }if errors.Is(err, ErrWebhookInvalidType) {return nil, huma.Error400BadRequest("invalid target type, must be 'container', 'project', 'updater', or 'gitops'")}@@ -112,8 +118,12 @@ func (h *WebhookHandler) UpdateWebhook(ctx context.Context, input *UpdateWebhookactor = *currentUser}- wh, err := h.webhookService.UpdateWebhook(ctx, input.WebhookID, input.EnvironmentID, input.Body.Enabled, actor)+ callerPerms, _ := middleware.PermissionsFromContext(ctx)+ wh, err := h.webhookService.UpdateWebhook(ctx, input.WebhookID, input.EnvironmentID, input.Body.Enabled, actor, callerPerms)if err != nil {+ if errors.Is(err, ErrWebhookForbidden) {+ return nil, huma.Error403Forbidden(ErrWebhookForbidden.Error())+ }if errors.Is(err, ErrWebhookNotFound) {return nil, huma.Error404NotFound("webhook not found")}diff --git a/backend/internal/webhook/service.go b/backend/internal/webhook/service.goindex 133bf950e..d5ece7b55 100644--- a/backend/internal/webhook/service.go+++ b/backend/internal/webhook/service.go@@ -26,6 +26,7 @@ import ("go.getarcane.app/sys/crypto""gorm.io/gorm"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/container""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment"@@ -33,6 +34,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/gitops""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/updater"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils")@@ -51,6 +53,7 @@ var (ErrWebhookInvalidType = errors.New("invalid webhook target type")ErrWebhookInvalidAction = errors.New("invalid webhook action type")ErrWebhookMissingTarget = errors.New("target ID is required for container, project, and gitops webhook types")+ ErrWebhookForbidden = common.Classify(common.ErrForbidden, errors.New("you do not have permission to run this webhook action"))// remoteWebhookTargetListPaths lists agent endpoints for target types whose records live in the agent's database.remoteWebhookTargetListPaths = map[string]string{@@ -223,6 +226,37 @@ func resolveWebhookActionTypeInternal(targetType, actionType string) (string, erreturn "", ErrWebhookInvalidAction}+var webhookActionPermissions = map[string]map[string]string{+ WebhookTargetTypeContainer: {+ WebhookActionTypeUpdate: authz.PermImageUpdatesCheck,+ WebhookActionTypeStart: authz.PermContainersStart,+ WebhookActionTypeStop: authz.PermContainersStop,+ WebhookActionTypeRestart: authz.PermContainersRestart,+ WebhookActionTypeRedeploy: authz.PermContainersRedeploy,+ },+ WebhookTargetTypeProject: {+ WebhookActionTypeUpdate: authz.PermProjectsUpdate,+ WebhookActionTypeUp: authz.PermProjectsDeploy,+ WebhookActionTypeDown: authz.PermProjectsDown,+ WebhookActionTypeRestart: authz.PermProjectsRestart,+ WebhookActionTypeRedeploy: authz.PermProjectsDeploy,+ },+ WebhookTargetTypeUpdater: {+ WebhookActionTypeRun: authz.PermImageUpdatesCheck,+ },+ WebhookTargetTypeGitOps: {+ WebhookActionTypeSync: authz.PermGitOpsSync,+ },+}++func authorizeWebhookAction(callerPerms *authz.PermissionSet, targetType, actionType, environmentID string) error {+ permission, ok := webhookActionPermissions[targetType][actionType]+ if !ok || !callerPerms.Allows(permission, environmentID) {+ return ErrWebhookForbidden+ }+ return nil+}+func resolvedWebhookActionTypeInternal(targetType, actionType string) string {resolvedActionType, err := resolveWebhookActionTypeInternal(targetType, actionType)if err != nil {@@ -233,7 +267,12 @@ func resolvedWebhookActionTypeInternal(targetType, actionType string) string {// CreateWebhook creates a new webhook targeting a stack, the environment-wide updater, or a gitops sync.// It returns the webhook record with the raw token populated (only available at creation time).-func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, actionType, targetID, environmentID string, actor user.Actor) (*Webhook, string, error) {+func (s *WebhookService) CreateWebhook(+ ctx context.Context,+ name, targetType, actionType, targetID, environmentID string,+ actor user.Actor,+ callerPerms *authz.PermissionSet,+) (*Webhook, string, error) {input := webhook.CreateInput{Name: name, TargetType: targetType, ActionType: actionType, TargetID: targetID}if err := normalization.Normalize(&input); err != nil {return nil, "", err@@ -242,6 +281,9 @@ func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, acif err != nil {return nil, "", err}+ if authorizeErr := authorizeWebhookAction(callerPerms, targetType, resolvedActionType, environmentID); authorizeErr != nil {+ return nil, "", authorizeErr+ }targetRef := ""@@ -484,7 +526,7 @@ func (s *WebhookService) DeleteWebhook(ctx context.Context, id, environmentID st}// UpdateWebhook updates the enabled state of a webhook, scoped to an environment.-func (s *WebhookService) UpdateWebhook(ctx context.Context, id, environmentID string, enabled bool, actor user.Actor) (*Webhook, error) {+func (s *WebhookService) UpdateWebhook(ctx context.Context, id, environmentID string, enabled bool, actor user.Actor, callerPerms *authz.PermissionSet) (*Webhook, error) {var wh Webhookerr := s.db.WithContext(ctx).Where("id = ? AND environment_id = ?", id, environmentID).@@ -495,6 +537,9 @@ func (s *WebhookService) UpdateWebhook(ctx context.Context, id, environmentID stif err != nil {return nil, fmt.Errorf("failed to get webhook: %w", err)}+ if authorizeErr := authorizeWebhookAction(callerPerms, wh.TargetType, resolvedWebhookActionTypeInternal(wh.TargetType, wh.ActionType), wh.EnvironmentID); authorizeErr != nil {+ return nil, authorizeErr+ }if updateWebhookErr := s.db.WithContext(ctx).Model(&wh).Update("enabled", enabled).Error; updateWebhookErr != nil {return nil, fmt.Errorf("failed to update webhook: %w", updateWebhookErr)diff --git a/backend/internal/webhook/service_test.go b/backend/internal/webhook/service_test.goindex cbda24b4c..94dd7fba9 100644--- a/backend/internal/webhook/service_test.go+++ b/backend/internal/webhook/service_test.go@@ -24,6 +24,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz")// setupWebhookServiceTestDB creates an isolated in-memory SQLite DB for each test.@@ -135,7 +136,7 @@ func TestIsKnownToken_StoredIdentity(t *testing.T) {ctx := t.Context()db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, raw, err := svc.CreateWebhook(ctx, "known", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ wh, raw, err := svc.CreateWebhook(ctx, "known", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)require.True(t, svc.IsKnownToken(raw))@@ -150,7 +151,7 @@ func TestIsKnownToken_StoredIdentity(t *testing.T) {restarted := newTestWebhookService(db)require.NoError(t, restarted.LoadTokenHashes(ctx))require.True(t, restarted.IsKnownToken(raw), "existing tokens must be recognized before their first request after restart")- _, err = restarted.UpdateWebhook(ctx, wh.ID, "env-1", false, user.Actor{})+ _, err = restarted.UpdateWebhook(ctx, wh.ID, "env-1", false, user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)require.True(t, restarted.IsKnownToken(raw), "disabled tokens retain their independent abuse budget")require.ErrorIs(t, restarted.TriggerByToken(ctx, raw), ErrWebhookDisabled)@@ -165,9 +166,9 @@ func TestKnownTokenRateLimit_ExhaustedIPDoesNotBlockFirstUse(t *testing.T) {ctx := t.Context()db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, first, err := svc.CreateWebhook(ctx, "first", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ _, first, err := svc.CreateWebhook(ctx, "first", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)- _, second, err := svc.CreateWebhook(ctx, "second", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p2", "env-1", user.Actor{})+ _, second, err := svc.CreateWebhook(ctx, "second", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p2", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)svc = newTestWebhookService(db)require.NoError(t, svc.LoadTokenHashes(ctx))@@ -203,12 +204,12 @@ func TestLoadTokenHashes_FailurePreservesIndex(t *testing.T) {ctx := t.Context()db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, raw, err := svc.CreateWebhook(ctx, "known", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ _, raw, err := svc.CreateWebhook(ctx, "known", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)require.NoError(t, db.Migrator().DropTable(&Webhook{}))require.Error(t, svc.LoadTokenHashes(ctx))require.True(t, svc.IsKnownToken(raw))- _, failed, err := svc.CreateWebhook(ctx, "failed", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ _, failed, err := svc.CreateWebhook(ctx, "failed", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.Error(t, err)require.Empty(t, failed)require.Len(t, svc.tokenHashes, 1)@@ -228,7 +229,7 @@ func TestKnownTokenIndex_ConcurrentReloadAndCRUD(t *testing.T) {}})for range 30 {- wh, raw, err := svc.CreateWebhook(ctx, "known", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ wh, raw, err := svc.CreateWebhook(ctx, "known", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)require.True(t, svc.IsKnownToken(raw))require.NoError(t, svc.DeleteWebhook(ctx, wh.ID, "env-1", user.Actor{}))@@ -242,7 +243,7 @@ func TestCreateWebhook_TokenNotStoredInPlaintext(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, rawToken, err := svc.CreateWebhook(ctx, "my-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "project-id", "env-1", user.Actor{})+ wh, rawToken, err := svc.CreateWebhook(ctx, "my-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "project-id", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)require.NotEmpty(t, rawToken)@@ -256,7 +257,7 @@ func TestCreateWebhook_PrefixMatchesToken(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, rawToken, err := svc.CreateWebhook(ctx, " cafe\u0301 hook ", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ wh, rawToken, err := svc.CreateWebhook(ctx, " cafe\u0301 hook ", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)hexPart := strings.TrimPrefix(rawToken, webhookTokenPrefix)@@ -273,7 +274,7 @@ func TestCreateWebhook_InvalidTargetTypeRejected(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, _, err := svc.CreateWebhook(ctx, "bad", "invalid-type", WebhookActionTypeUpdate, "c1", "env-1", user.Actor{})+ _, _, err := svc.CreateWebhook(ctx, "bad", "invalid-type", WebhookActionTypeUpdate, "c1", "env-1", user.Actor{}, authz.SudoPermissionSet())assert.ErrorIs(t, err, ErrWebhookInvalidType)}@@ -287,7 +288,7 @@ func TestCreateWebhook_EmptyTargetIDRejectedForNonUpdaterTypes(t *testing.T) {WebhookTargetTypeProject,WebhookTargetTypeGitOps,} {- _, _, err := svc.CreateWebhook(ctx, "hook", targetType, defaultTestWebhookActionType(targetType), "", "env-1", user.Actor{})+ _, _, err := svc.CreateWebhook(ctx, "hook", targetType, defaultTestWebhookActionType(targetType), "", "env-1", user.Actor{}, authz.SudoPermissionSet())assert.ErrorIs(t, err, ErrWebhookMissingTarget, "expected ErrWebhookMissingTarget for type %s with empty targetID", targetType)}}@@ -297,7 +298,7 @@ func TestCreateWebhook_InvalidActionTypeRejected(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, _, err := svc.CreateWebhook(ctx, "bad-action", WebhookTargetTypeContainer, WebhookActionTypeDown, "container-id", "env-1", user.Actor{})+ _, _, err := svc.CreateWebhook(ctx, "bad-action", WebhookTargetTypeContainer, WebhookActionTypeDown, "container-id", "env-1", user.Actor{}, authz.SudoPermissionSet())assert.ErrorIs(t, err, ErrWebhookInvalidAction)}@@ -306,11 +307,11 @@ func TestCreateWebhook_EmptyActionTypeDefaultsPerTarget(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- projectWebhook, _, err := svc.CreateWebhook(ctx, "project-hook", WebhookTargetTypeProject, "", "project-id", "env-1", user.Actor{})+ projectWebhook, _, err := svc.CreateWebhook(ctx, "project-hook", WebhookTargetTypeProject, "", "project-id", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)assert.Equal(t, WebhookActionTypeUpdate, projectWebhook.ActionType)- updaterWebhook, _, err := svc.CreateWebhook(ctx, "updater-hook", WebhookTargetTypeUpdater, "", "", "env-1", user.Actor{})+ updaterWebhook, _, err := svc.CreateWebhook(ctx, "updater-hook", WebhookTargetTypeUpdater, "", "", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)assert.Equal(t, WebhookActionTypeRun, updaterWebhook.ActionType)}@@ -320,7 +321,7 @@ func TestCreateWebhook_EmptyTargetIDAcceptedForUpdaterType(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "updater-hook", WebhookTargetTypeUpdater, WebhookActionTypeRun, "", "env-1", user.Actor{})+ wh, _, err := svc.CreateWebhook(ctx, "updater-hook", WebhookTargetTypeUpdater, WebhookActionTypeRun, "", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)assert.Empty(t, wh.TargetID)}@@ -330,7 +331,7 @@ func TestCreateWebhook_ContainerTypeAccepted(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "container-hook", WebhookTargetTypeContainer, WebhookActionTypeUpdate, "container-id", "env-1", user.Actor{})+ wh, _, err := svc.CreateWebhook(ctx, "container-hook", WebhookTargetTypeContainer, WebhookActionTypeUpdate, "container-id", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)assert.Equal(t, WebhookTargetTypeContainer, wh.TargetType)assert.Equal(t, WebhookActionTypeUpdate, wh.ActionType)@@ -341,7 +342,7 @@ func TestCreateWebhook_ProjectTypeAccepted(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "stack-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "project-id", "env-1", user.Actor{})+ wh, _, err := svc.CreateWebhook(ctx, "stack-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "project-id", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)assert.Equal(t, WebhookTargetTypeProject, wh.TargetType)assert.Equal(t, WebhookActionTypeUpdate, wh.ActionType)@@ -352,7 +353,7 @@ func TestCreateWebhook_UpdaterTypeAccepted(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "updater-hook", WebhookTargetTypeUpdater, WebhookActionTypeRun, "", "env-1", user.Actor{})+ wh, _, err := svc.CreateWebhook(ctx, "updater-hook", WebhookTargetTypeUpdater, WebhookActionTypeRun, "", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)assert.Equal(t, WebhookTargetTypeUpdater, wh.TargetType)assert.Equal(t, WebhookActionTypeRun, wh.ActionType)@@ -363,7 +364,7 @@ func TestCreateWebhook_GitOpsTypeAccepted(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "gitops-hook", WebhookTargetTypeGitOps, WebhookActionTypeSync, "sync-id", "env-1", user.Actor{})+ wh, _, err := svc.CreateWebhook(ctx, "gitops-hook", WebhookTargetTypeGitOps, WebhookActionTypeSync, "sync-id", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)assert.Equal(t, WebhookTargetTypeGitOps, wh.TargetType)assert.Equal(t, WebhookActionTypeSync, wh.ActionType)@@ -374,7 +375,7 @@ func TestCreateWebhook_EnabledByDefault(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "enabled", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ wh, _, err := svc.CreateWebhook(ctx, "enabled", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)assert.True(t, wh.Enabled)}@@ -384,9 +385,9 @@ func TestCreateWebhook_UniqueTokensEachCall(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, token1, err := svc.CreateWebhook(ctx, "h1", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ _, token1, err := svc.CreateWebhook(ctx, "h1", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)- _, token2, err := svc.CreateWebhook(ctx, "h2", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p2", "env-1", user.Actor{})+ _, token2, err := svc.CreateWebhook(ctx, "h2", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p2", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)assert.NotEqual(t, token1, token2)@@ -397,9 +398,9 @@ func TestListWebhooks_ScopedToEnvironment(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, _, err := svc.CreateWebhook(ctx, "env1-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ _, _, err := svc.CreateWebhook(ctx, "env1-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)- _, _, err = svc.CreateWebhook(ctx, "env2-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p2", "env-2", user.Actor{})+ _, _, err = svc.CreateWebhook(ctx, "env2-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p2", "env-2", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)list, err := svc.ListWebhooks(ctx, "env-1")@@ -428,11 +429,11 @@ func TestListWebhookSummaries_ResolvesTargetNames(t *testing.T) {require.NoError(t, db.WithContext(ctx).Exec(`INSERT INTO projects (id, name) VALUES (?, ?)`, "project-1", "Main Project").Error)require.NoError(t, db.WithContext(ctx).Exec(`INSERT INTO gitops_syncs (id, environment_id, name) VALUES (?, ?, ?)`, "sync-1", types.LocalDockerEnvironmentID, "Deploy Sync").Error)- _, _, err := svc.CreateWebhook(ctx, "project-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "project-1", types.LocalDockerEnvironmentID, user.Actor{})+ _, _, err := svc.CreateWebhook(ctx, "project-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "project-1", types.LocalDockerEnvironmentID, user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)- _, _, err = svc.CreateWebhook(ctx, "updater-hook", WebhookTargetTypeUpdater, WebhookActionTypeRun, "", types.LocalDockerEnvironmentID, user.Actor{})+ _, _, err = svc.CreateWebhook(ctx, "updater-hook", WebhookTargetTypeUpdater, WebhookActionTypeRun, "", types.LocalDockerEnvironmentID, user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)- _, _, err = svc.CreateWebhook(ctx, "gitops-hook", WebhookTargetTypeGitOps, WebhookActionTypeSync, "sync-1", types.LocalDockerEnvironmentID, user.Actor{})+ _, _, err = svc.CreateWebhook(ctx, "gitops-hook", WebhookTargetTypeGitOps, WebhookActionTypeSync, "sync-1", types.LocalDockerEnvironmentID, user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)summaries, err := svc.ListWebhookSummaries(ctx, types.LocalDockerEnvironmentID)@@ -478,7 +479,7 @@ func TestGetWebhookByID_ReturnsCorrectWebhook(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- created, _, err := svc.CreateWebhook(ctx, "get-me", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ created, _, err := svc.CreateWebhook(ctx, "get-me", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)got, err := svc.GetWebhookByID(ctx, created.ID, "env-1")@@ -491,7 +492,7 @@ func TestGetWebhookByID_NotFoundForWrongEnvironment(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- created, _, err := svc.CreateWebhook(ctx, "env-scoped", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ created, _, err := svc.CreateWebhook(ctx, "env-scoped", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)_, err = svc.GetWebhookByID(ctx, created.ID, "env-2")@@ -512,7 +513,7 @@ func TestDeleteWebhook_RemovesRecord(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- created, _, err := svc.CreateWebhook(ctx, "delete-me", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ created, _, err := svc.CreateWebhook(ctx, "delete-me", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)require.NoError(t, svc.DeleteWebhook(ctx, created.ID, "env-1", user.Actor{}))@@ -526,7 +527,7 @@ func TestDeleteWebhook_NotFoundForWrongEnvironment(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- created, _, err := svc.CreateWebhook(ctx, "env-scoped-delete", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ created, _, err := svc.CreateWebhook(ctx, "env-scoped-delete", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)err = svc.DeleteWebhook(ctx, created.ID, "env-2", user.Actor{})@@ -551,15 +552,15 @@ func TestUpdateWebhook_DisableAndEnable(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "proj-1", "env-1", user.Actor{})+ wh, _, err := svc.CreateWebhook(ctx, "hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "proj-1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)assert.True(t, wh.Enabled)- updated, err := svc.UpdateWebhook(ctx, wh.ID, "env-1", false, user.Actor{})+ updated, err := svc.UpdateWebhook(ctx, wh.ID, "env-1", false, user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)assert.False(t, updated.Enabled)- updated, err = svc.UpdateWebhook(ctx, wh.ID, "env-1", true, user.Actor{})+ updated, err = svc.UpdateWebhook(ctx, wh.ID, "env-1", true, user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)assert.True(t, updated.Enabled)}@@ -569,19 +570,45 @@ func TestUpdateWebhook_NotFoundForWrongEnvironment(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "proj-1", "env-1", user.Actor{})+ wh, _, err := svc.CreateWebhook(ctx, "hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "proj-1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)- _, err = svc.UpdateWebhook(ctx, wh.ID, "env-other", false, user.Actor{})+ _, err = svc.UpdateWebhook(ctx, wh.ID, "env-other", false, user.Actor{}, authz.SudoPermissionSet())assert.ErrorIs(t, err, ErrWebhookNotFound)}+func TestCreateWebhook_RequiresTargetActionPermission(t *testing.T) {+ ctx := t.Context()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ webhookOnly := authz.NewPermissionSet()+ webhookOnly.AddEnv("env-1", authz.PermWebhooksCreate, authz.PermWebhooksUpdate)+ _, _, err := svc.CreateWebhook(ctx, "down", WebhookTargetTypeProject, WebhookActionTypeDown, "p1", "env-1", user.Actor{}, webhookOnly)+ require.ErrorIs(t, err, ErrWebhookForbidden)++ otherEnv := authz.NewPermissionSet()+ otherEnv.AddEnv("env-2", authz.PermProjectsDown)+ _, _, err = svc.CreateWebhook(ctx, "down", WebhookTargetTypeProject, WebhookActionTypeDown, "p1", "env-1", user.Actor{}, otherEnv)+ require.ErrorIs(t, err, ErrWebhookForbidden)++ allowed := authz.NewPermissionSet()+ allowed.AddEnv("env-1", authz.PermProjectsDown)+ wh, _, err := svc.CreateWebhook(ctx, "down", WebhookTargetTypeProject, WebhookActionTypeDown, "p1", "env-1", user.Actor{}, allowed)+ require.NoError(t, err)++ _, err = svc.UpdateWebhook(ctx, wh.ID, "env-1", false, user.Actor{}, webhookOnly)+ require.ErrorIs(t, err, ErrWebhookForbidden)+ _, err = svc.UpdateWebhook(ctx, wh.ID, "env-1", false, user.Actor{}, allowed)+ require.NoError(t, err)+}+func TestUpdateWebhook_NotFoundForUnknownID(t *testing.T) {ctx := t.Context()db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, err := svc.UpdateWebhook(ctx, "does-not-exist", "env-1", false, user.Actor{})+ _, err := svc.UpdateWebhook(ctx, "does-not-exist", "env-1", false, user.Actor{}, authz.SudoPermissionSet())assert.ErrorIs(t, err, ErrWebhookNotFound)}@@ -610,7 +637,7 @@ func TestTriggerByToken_WrongHash_NotFound(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, rawToken, err := svc.CreateWebhook(ctx, "hash-check", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ _, rawToken, err := svc.CreateWebhook(ctx, "hash-check", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)// Flip the last character of the token@@ -630,7 +657,7 @@ func TestTriggerByToken_DisabledWebhook(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- created, rawToken, err := svc.CreateWebhook(ctx, "disabled-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{})+ created, rawToken, err := svc.CreateWebhook(ctx, "disabled-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", user.Actor{}, authz.SudoPermissionSet())require.NoError(t, err)require.NoError(t, db.WithContext(ctx).Model(&Webhook{}).Where("id = ?", created.ID).Update("enabled", false).Error)diff --git a/backend/pkg/authz/permission_set.go b/backend/pkg/authz/permission_set.goindex 817d967ac..17b311c56 100644--- a/backend/pkg/authz/permission_set.go+++ b/backend/pkg/authz/permission_set.go@@ -60,11 +60,6 @@ func (ps *PermissionSet) AllowsAny(perm string) bool {// be considered an administrator. True for sudo callers and for callers whose// Global set contains every defined permission. Used by the backward-compat// IsAdminFromContext helper and by last-admin guards.-//-// Implementation: first checks cardinality against TotalPermissionsCount() for a-// fast early exit, then walks AllPermissions() to confirm every known-// permission is present. This guards against a ps.Global that contains the right-// count but includes injected unknown permissions instead of all real ones.func (ps *PermissionSet) IsGlobalAdmin() bool {if ps == nil {return false@@ -72,9 +67,6 @@ func (ps *PermissionSet) IsGlobalAdmin() bool {if ps.Sudo {return true}- if len(ps.Global) != TotalPermissionsCount() {- return false- }for _, permission := range AllPermissions() {if _, ok := ps.Global[permission]; !ok {return falsediff --git a/backend/pkg/utils/cookie/cookie_util.go b/backend/pkg/utils/cookie/cookie_util.goindex ab0c4af04..a62856b95 100644--- a/backend/pkg/utils/cookie/cookie_util.go+++ b/backend/pkg/utils/cookie/cookie_util.go@@ -13,6 +13,10 @@ var (TokenCookieName = "__Host-token" // #nosec G101: cookie name label, not a credentialInsecureTokenCookieName = "token" // #nosec G101: cookie name label, not a credentialOidcStateCookieName = "oidc_state"++ RefreshCookieName = "__Secure-refresh"+ InsecureRefreshCookieName = "refresh"+ RefreshCookiePath = "/api/auth")// Legacy ML-DSA browser tokens exceed the 4096-byte cookie limit, so readers@@ -60,6 +64,18 @@ func GetTokenCookieFromHeader(cookieHeader string) (string, error) {return GetTokenCookie(&http.Request{Header: http.Header{"Cookie": []string{cookieHeader}}})}+func BuildRefreshCookieStringFor(maxAgeInSeconds int, value string, secure bool) string {+ return buildCookieString(kit.Ternary(secure, RefreshCookieName, InsecureRefreshCookieName), RefreshCookiePath, value, max(maxAgeInSeconds, 0), secure, http.SameSiteStrictMode)+}++func BuildClearRefreshCookieStringsFor(secure bool) []string {+ headers := []string{buildCookieString(InsecureRefreshCookieName, RefreshCookiePath, "", -1, false, http.SameSiteStrictMode)}+ if secure {+ headers = append(headers, buildCookieString(RefreshCookieName, RefreshCookiePath, "", -1, true, http.SameSiteStrictMode))+ }+ return headers+}+func GetTokenCookie(r *http.Request) (string, error) {if value, err := readTokenCookieInternal(r, TokenCookieName); err == nil {return value, nil@@ -122,7 +138,7 @@ func BuildTokenCookieStringFor(maxAgeInSeconds int, token string, secure bool) [headers = append(headers, cookie.String())}for i := len(chunks); i < tokenCookieMaxChunks; i++ {- headers = append(headers, buildClearTokenCookieStringInternal(tokenCookieChunkNameInternal(base, i), secure))+ headers = append(headers, buildCookieString(tokenCookieChunkNameInternal(base, i), "/", "", -1, secure, http.SameSiteLaxMode))}return headers}@@ -134,23 +150,23 @@ func BuildTokenCookieStringFor(maxAgeInSeconds int, token string, secure bool) [func BuildClearTokenCookieStringsFor(secure bool) []string {var headers []stringfor i := range tokenCookieMaxChunks {- headers = append(headers, buildClearTokenCookieStringInternal(tokenCookieChunkNameInternal(InsecureTokenCookieName, i), false))+ headers = append(headers, buildCookieString(tokenCookieChunkNameInternal(InsecureTokenCookieName, i), "/", "", -1, false, http.SameSiteLaxMode))if secure {- headers = append(headers, buildClearTokenCookieStringInternal(tokenCookieChunkNameInternal(TokenCookieName, i), true))+ headers = append(headers, buildCookieString(tokenCookieChunkNameInternal(TokenCookieName, i), "/", "", -1, true, http.SameSiteLaxMode))}}return headers}-func buildClearTokenCookieStringInternal(name string, secure bool) string {+func buildCookieString(name, path, value string, maxAge int, secure bool, sameSite http.SameSite) string {cookie := &http.Cookie{ // #nosec G124: Secure mirrors the caller-provided TLS state so the clear directive matches whichever cookie variant (__Host-token vs. token) was originally set.Name: name,- Value: "",- Path: "/",- MaxAge: -1,+ Value: value,+ Path: path,+ MaxAge: maxAge,HttpOnly: true,Secure: secure,- SameSite: http.SameSiteLaxMode,+ SameSite: sameSite,}return cookie.String()}diff --git a/frontend/src/lib/services/auth-service.ts b/frontend/src/lib/services/auth-service.tsindex 2be8e0388..fd5205a03 100644--- a/frontend/src/lib/services/auth-service.ts+++ b/frontend/src/lib/services/auth-service.ts@@ -17,9 +17,13 @@ import { tryCatch } from '#lib/utils/try-catch.js';import BaseAPIService, { APIError, SessionCancelledError, currentSessionSignal } from './api-service';-const REFRESH_TOKEN_KEY = 'arcane_refresh_token';+const LEGACY_REFRESH_TOKEN_KEY = 'arcane_refresh_token';const TOKEN_EXPIRY_KEY = 'arcane_token_expiry';+const REFRESH_LOCK_NAME = 'arcane-token-refresh';const REFRESH_BUFFER_MS = 5 * 60 * 1000; // Refresh 5 minutes before expiry+const REFRESH_JITTER_MS = 5000;+const REFRESH_RACE_GRACE_MS = 3000;+const REFRESH_RACE_POLL_MS = 150;export class MFARequiredError extends Error {constructor(public readonly challenge: MFAChallenge) {@@ -31,43 +35,63 @@ export class MFARequiredError extends Error {class AuthService extends BaseAPIService {private refreshTimer: ReturnType<typeof setTimeout> | null = null;private isRefreshing = false;+ private refreshGeneration = 0;private refreshSubscribers: Array<(token: string | null, error?: Error) => void> = [];private logoutRequest: Promise<boolean> | null = null;constructor() {super();BaseAPIService.setTokenRefreshHandler(() => this.refreshAccessToken());+ if (typeof window === 'undefined') return;+ try {+ sessionStorage.removeItem(LEGACY_REFRESH_TOKEN_KEY);+ sessionStorage.removeItem(TOKEN_EXPIRY_KEY);+ } catch (e) {+ console.error('Failed to remove legacy token data:', e);+ }+ const storedExpiry = this.getStoredExpiry();+ if (storedExpiry) this.scheduleTokenRefresh(storedExpiry);+ window.addEventListener('storage', (event) => {+ if (event.key !== TOKEN_EXPIRY_KEY) return;+ if (event.newValue) {+ this.scheduleTokenRefresh(event.newValue);+ } else {+ this.clearRefreshTimer();+ }+ });}- private storeTokenData(refreshToken: string, expiresAt: string): void {+ private storeTokenData(expiresAt: string): void {if (typeof window === 'undefined') return;try {- sessionStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);- sessionStorage.setItem(TOKEN_EXPIRY_KEY, expiresAt);+ localStorage.setItem(TOKEN_EXPIRY_KEY, expiresAt);this.scheduleTokenRefresh(expiresAt);} catch (e) {console.error('Failed to store token data:', e);}}- private getStoredRefreshToken(): string | null {+ private getStoredExpiry(): string | null {if (typeof window === 'undefined') return null;try {- return sessionStorage.getItem(REFRESH_TOKEN_KEY);+ return localStorage.getItem(TOKEN_EXPIRY_KEY);} catch {return null;}}+ private clearRefreshTimer(): void {+ if (this.refreshTimer) {+ clearTimeout(this.refreshTimer);+ this.refreshTimer = null;+ }+ }+private clearTokenData(): void {if (typeof window === 'undefined') return;try {- sessionStorage.removeItem(REFRESH_TOKEN_KEY);- sessionStorage.removeItem(TOKEN_EXPIRY_KEY);- if (this.refreshTimer) {- clearTimeout(this.refreshTimer);- this.refreshTimer = null;- }+ localStorage.removeItem(TOKEN_EXPIRY_KEY);+ this.clearRefreshTimer();} catch (e) {console.error('Failed to clear token data:', e);}@@ -76,14 +100,12 @@ class AuthService extends BaseAPIService {private scheduleTokenRefresh(expiresAt: string): void {if (typeof window === 'undefined') return;- if (this.refreshTimer) {- clearTimeout(this.refreshTimer);- }+ this.clearRefreshTimer();const expiryTime = parseInstant(expiresAt);if (!expiryTime) return;const timeUntilExpiry = Temporal.Now.instant().until(expiryTime).total('milliseconds');- const refreshTime = Math.max(0, timeUntilExpiry - REFRESH_BUFFER_MS);+ const refreshTime = Math.max(0, timeUntilExpiry - REFRESH_BUFFER_MS - Math.random() * REFRESH_JITTER_MS);if (refreshTime > 0) {this.refreshTimer = setTimeout(() => {@@ -100,12 +122,40 @@ class AuthService extends BaseAPIService {}}- async refreshAccessToken(): Promise<string | null> {- const refreshToken = this.getStoredRefreshToken();- if (!refreshToken) {- throw new Error('No refresh token available');+ private refreshedElsewhere(expiryBefore: string | null): boolean {+ const current = this.getStoredExpiry();+ const currentInstant = current ? parseInstant(current) : null;+ if (!current || current === expiryBefore || !currentInstant) return false;+ const beforeInstant = expiryBefore ? parseInstant(expiryBefore) : null;+ if (beforeInstant && Temporal.Instant.compare(currentInstant, beforeInstant) <= 0) return false;+ return Temporal.Now.instant().until(currentInstant).total('milliseconds') > REFRESH_BUFFER_MS;+ }++ private async refreshedElsewhereSoon(expiryBefore: string | null): Promise<boolean> {+ const deadline = Date.now() + REFRESH_RACE_GRACE_MS;+ while (!this.refreshedElsewhere(expiryBefore)) {+ if (Date.now() >= deadline) return false;+ await new Promise((resolve) => setTimeout(resolve, REFRESH_RACE_POLL_MS));}+ return true;+ }++ private async requestTokenRefresh(expiryBefore: string | null, session: AbortSignal): Promise<string | null> {+ if (this.refreshedElsewhere(expiryBefore)) return null;++ const response = await this.handleResponse<{+ token?: string;+ expiresAt?: string;+ }>(this.api.post('/auth/refresh'));++ if (session.aborted) throw new SessionCancelledError();+ if (response.expiresAt) {+ this.storeTokenData(response.expiresAt);+ }+ return response.token || null;+ }+ async refreshAccessToken(): Promise<string | null> {if (this.isRefreshing) {return new Promise<string | null>((resolve, reject) => {this.refreshSubscribers.push((token: string | null, error?: Error) => {@@ -116,48 +166,46 @@ class AuthService extends BaseAPIService {}this.isRefreshing = true;+ const generation = ++this.refreshGeneration;const session = currentSessionSignal();+ const expiryBefore = this.getStoredExpiry();+ const coordinated = typeof navigator !== 'undefined' && 'locks' in navigator;const operationResult = await tryCatch(- (async () => {- const response = await this.handleResponse<{- token?: string;- refreshToken?: string;- expiresAt?: string;- }>(this.api.post('/auth/refresh', { refreshToken }));-- // Logout already reset the refresh state; a later login may own it now.- if (session.aborted) throw new SessionCancelledError();- if (response.refreshToken && response.expiresAt) {- this.storeTokenData(response.refreshToken, response.expiresAt);- }-- const token = response.token || null;- this.refreshSubscribers.forEach((callback) => callback(token));- this.refreshSubscribers = [];- this.isRefreshing = false;-- return token;- })()+ coordinated+ ? navigator.locks.request(REFRESH_LOCK_NAME, () => this.requestTokenRefresh(expiryBefore, session))+ : this.requestTokenRefresh(expiryBefore, session));- if (operationResult.error !== null) {- const error = operationResult.error;- if (session.aborted) throw new SessionCancelledError();- const err = error instanceof Error ? error : new Error('Token refresh failed');- console.error('Token refresh failed:', err);- // Only drop the stored refresh token when the server definitively rejects it- // (HTTP 401). Transient failures — a network error or the backend briefly- // down during a self-update — must keep the token so a later retry recovers.- if (error instanceof APIError && error.status === 401) {- this.clearTokenData();- }- this.refreshSubscribers.forEach((callback) => callback(null, err));++ const subscribers = generation === this.refreshGeneration ? this.refreshSubscribers : [];+ if (generation === this.refreshGeneration) {this.refreshSubscribers = [];this.isRefreshing = false;- throw err;- } else {+ }++ if (session.aborted) {+ const cancelled = new SessionCancelledError();+ subscribers.forEach((callback) => callback(null, cancelled));+ throw cancelled;+ }+ if (operationResult.error === null) {+ subscribers.forEach((callback) => callback(operationResult.data));return operationResult.data;}++ const error = operationResult.error;+ const rejected = error instanceof APIError && error.status === 401;+ if (rejected && (coordinated ? this.refreshedElsewhere(expiryBefore) : await this.refreshedElsewhereSoon(expiryBefore))) {+ subscribers.forEach((callback) => callback(null));+ return null;+ }+ const err = error instanceof Error ? error : new Error('Token refresh failed');+ console.error('Token refresh failed:', err);+ if (rejected) {+ this.clearTokenData();+ }+ subscribers.forEach((callback) => callback(null, err));+ throw err;}async login(credentials: LoginCredentials): Promise<User> {@@ -182,8 +230,8 @@ class AuthService extends BaseAPIService {}BaseAPIService.beginSession();- if (data.refreshToken && data.expiresAt) {- this.storeTokenData(data.refreshToken, data.expiresAt);+ if (data.expiresAt) {+ this.storeTokenData(data.expiresAt);}await userStore.setUser(data.user);@@ -260,6 +308,7 @@ class AuthService extends BaseAPIService {this.refreshSubscribers.forEach((callback) => callback(null, new SessionCancelledError()));this.refreshSubscribers = [];this.isRefreshing = false;+ this.refreshGeneration++;this.resetAuthenticatedState(queryClient);const request: Promise<boolean> = tryCatch(this.api.post('/auth/logout', undefined, { timeout: 10_000 })).then((result) => {diff --git a/frontend/src/lib/types/auth.ts b/frontend/src/lib/types/auth.tsindex 01fe5a6e1..47427b8fa 100644--- a/frontend/src/lib/types/auth.ts+++ b/frontend/src/lib/types/auth.ts@@ -234,7 +234,6 @@ export type AuthenticationResponse = {success: boolean;status: AuthenticationStatus;token?: string;- refreshToken?: string;expiresAt?: string;user?: User;mfa?: MFAChallenge;diff --git a/tests/spec/auth.spec.ts b/tests/spec/auth.spec.tsindex 1bb8aca52..c29585ea8 100644--- a/tests/spec/auth.spec.ts+++ b/tests/spec/auth.spec.ts@@ -1,23 +1,18 @@import { test, expect, type Page } from '../fixtures/test.fixture';import authUtil from '../utils/auth.util';-const REFRESH_TOKEN_KEY = 'arcane_refresh_token';const TOKEN_EXPIRY_KEY = 'arcane_token_expiry';const REFRESH_COOKIE = 'arcane_refresh_test=complete';/**- * Register an addInitScript that plants a fake refresh token in sessionStorage+ * Register an addInitScript that plants a token expiry in localStorage* BEFORE any page JavaScript runs on every navigation. Unlike page.evaluate(),* addInitScript survives page.goto() calls made later in the test.*/async function registerTokenSeeding(page: Page) {- await page.addInitScript(- ({ tokenKey, expiryKey }: { tokenKey: string; expiryKey: string }) => {- sessionStorage.setItem(tokenKey, 'playwright-test-refresh-token');- sessionStorage.setItem(expiryKey, new Date(Date.now() + 3_600_000).toISOString());- },- { tokenKey: REFRESH_TOKEN_KEY, expiryKey: TOKEN_EXPIRY_KEY }- );+ await page.addInitScript((expiryKey: string) => {+ localStorage.setItem(expiryKey, new Date(Date.now() + 3_600_000).toISOString());+ }, TOKEN_EXPIRY_KEY);}/**diff --git a/tests/spec/updates.spec.ts b/tests/spec/updates.spec.tsindex 4e76d11ef..853f3f42f 100644--- a/tests/spec/updates.spec.ts+++ b/tests/spec/updates.spec.ts@@ -362,7 +362,6 @@ test.describe('Container updates', () => {});test.describe('Arcane upgrades', () => {- const REFRESH_TOKEN_KEY = 'arcane_refresh_token';const TOKEN_EXPIRY_KEY = 'arcane_token_expiry';const REFRESH_COOKIE = 'arcane_refresh_test=complete';const reloadCounts = new WeakMap<Page, number>();@@ -428,15 +427,11 @@ test.describe('Arcane upgrades', () => {}async function registerTokenSeeding(page: Page) {- await page.addInitScript(- ({ tokenKey, expiryKey }: { tokenKey: string; expiryKey: string }) => {- if (!sessionStorage.getItem(tokenKey)) {- sessionStorage.setItem(tokenKey, 'playwright-test-refresh-token');- sessionStorage.setItem(expiryKey, new Date(Date.now() + 3_600_000).toISOString());- }- },- { tokenKey: REFRESH_TOKEN_KEY, expiryKey: TOKEN_EXPIRY_KEY }- );+ await page.addInitScript((expiryKey: string) => {+ if (!localStorage.getItem(expiryKey)) {+ localStorage.setItem(expiryKey, new Date(Date.now() + 3_600_000).toISOString());+ }+ }, TOKEN_EXPIRY_KEY);}async function fulfillJob(route: Route, status: JobStatus, managerStatus: ManagerStatus) {@@ -897,7 +892,7 @@ test.describe('Arcane upgrades', () => {}});- test('a transient refresh failure keeps the token and recovers on the next poll', async ({+ test('a transient refresh failure keeps the session and recovers on the next poll', async ({page}) => {registerReloadCounter(page);@@ -943,8 +938,8 @@ test.describe('Arcane upgrades', () => {await expect.poll(() => refreshCalls, { timeout: 10_000 }).toBe(1);await expect- .poll(() => page.evaluate((key: string) => sessionStorage.getItem(key), REFRESH_TOKEN_KEY))- .toBe('playwright-test-refresh-token');+ .poll(() => page.evaluate((key: string) => localStorage.getItem(key), TOKEN_EXPIRY_KEY))+ .not.toBeNull();await expect.poll(() => currentReloadCount(page), { timeout: 15_000 }).toBe(2);expect(refreshCalls).toBe(2);});@@ -1007,11 +1002,12 @@ test.describe('Arcane upgrades', () => {).toBeVisible();});- test('a missing refresh token during an upgrade redirects to login instead of polling', async ({+ test('a missing refresh cookie during an upgrade redirects to login instead of polling', async ({page}) => {let refreshCalls = 0;let updateStarted = false;+ await page.context().clearCookies({ name: /^(__Secure-)?refresh$/ });await page.route('**/api/auth/refresh', async (route) => {if (!updateStarted) {await route.continue();@@ -1053,7 +1049,7 @@ test.describe('Arcane upgrades', () => {await expect.poll(() => updateStarted).toBe(true);await page.waitForURL(/\/login(?:\?|$)/, { timeout: 10_000 });- expect(refreshCalls).toBe(0);+ expect(refreshCalls).toBe(1);await expect(page.getByRole('button', { name: 'Sign in to Arcane', exact: true })).toBeVisible();diff --git a/types/auth/auth.go b/types/auth/auth.goindex 4cb04e8e7..0f3b350e8 100644--- a/types/auth/auth.go+++ b/types/auth/auth.go@@ -14,7 +14,11 @@ type Login struct {// Refresh represents the token refresh request body.type Refresh struct {- RefreshToken string `json:"refreshToken" minLength:"1" doc:"Refresh token used to obtain a new access token"`+ RefreshToken string `json:"refreshToken,omitempty" doc:"Refresh token used to obtain a new access token; browsers send it as a cookie instead"`+}++type Logout struct {+ RefreshToken string `json:"refreshToken,omitempty" doc:"Refresh token whose session is revoked even when the access token has expired"`}// PasswordChange represents the password change request body.