Skip to content

Modern Docker Management, Designed for Everyone

fix(role): keep a global admin when updating or deleting a role (#4472)

José M. Requena Plens32a0ca34b254
diff --git a/backend/cli/admin/reset_password_test.go b/backend/cli/admin/reset_password_test.go
index 4c9802ca0..86c2776a9 100644
--- a/backend/cli/admin/reset_password_test.go
+++ b/backend/cli/admin/reset_password_test.go
@@ -52,7 +52,7 @@ func createGlobalAdminInternal(t *testing.T, db *database.DB) (*user.User, *user
RequiresPasswordChange: true,
})
require.NoError(t, err)
- require.NoError(t, roleService.SetUserAssignments(ctx, adminUser.ID, []role.UserRoleAssignment{
+ require.NoError(t, roleService.ReplaceUserAssignments(ctx, adminUser.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: authz.BuiltInRoleAdmin},
}))
diff --git a/backend/internal/apikey/service_test.go b/backend/internal/apikey/service_test.go
index c55473d12..2eaa1abaf 100644
--- a/backend/internal/apikey/service_test.go
+++ b/backend/internal/apikey/service_test.go
@@ -271,7 +271,7 @@ func TestUpdateApiKeyRollsBackMetadataWhenPermissionUpdateFails(t *testing.T) {
userSvc := user.NewUserService(db, roleSvc, session.RevokeAllUserSessionsExceptInDB)
service := NewApiKeyService(db, userSvc, roleSvc)
admin := createTestAPIKeyUser(t, ctx, userSvc, "admin-update-rollback", "admin-update-rollback")
- require.NoError(t, roleSvc.SetUserAssignments(ctx, admin.ID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, admin.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: authz.BuiltInRoleAdmin, EnvironmentID: nil},
}))
@@ -840,7 +840,7 @@ func TestCreateEnvironmentApiKeySeedsAllPermissionsScopedToEnv(t *testing.T) {
userSvc := user.NewUserService(db, roleSvc, session.RevokeAllUserSessionsExceptInDB)
service := NewApiKeyService(db, userSvc, roleSvc)
admin := createTestAPIKeyUser(t, ctx, userSvc, "admin-env-bootstrap", "admin-env-bootstrap")
- require.NoError(t, roleSvc.SetUserAssignments(ctx, admin.ID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, admin.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: authz.BuiltInRoleAdmin, EnvironmentID: nil},
}))
@@ -925,7 +925,7 @@ func TestBackfillPermsForKeyDeduplicatesGlobalAndEnvironmentPermissions(t *testi
service := NewApiKeyService(db, userSvc, roleSvc)
admin := createTestAPIKeyUser(t, ctx, userSvc, "admin", "admin")
- require.NoError(t, roleSvc.SetUserAssignments(ctx, admin.ID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, admin.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: authz.BuiltInRoleAdmin},
}))
owner := createTestAPIKeyUser(t, ctx, userSvc, "api-key-owner")
@@ -939,7 +939,7 @@ func TestBackfillPermsForKeyDeduplicatesGlobalAndEnvironmentPermissions(t *testi
Enabled: true,
}).Error)
- require.NoError(t, roleSvc.SetUserAssignments(ctx, owner.ID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, owner.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: authz.BuiltInRoleViewer, EnvironmentID: nil},
{RoleID: authz.BuiltInRoleEditor, EnvironmentID: &envID},
}))
diff --git a/backend/internal/auth/service.go b/backend/internal/auth/service.go
index d8e7c3c7e..db0c8cfb5 100644
--- a/backend/internal/auth/service.go
+++ b/backend/internal/auth/service.go
@@ -567,7 +567,7 @@ func (s *AuthService) syncOidcRoleAssignments(ctx context.Context, localUser *us
})
}
- return s.roleService.ReplaceOidcAssignments(ctx, localUser.ID, desired)
+ return s.roleService.ReplaceUserAssignments(ctx, localUser.ID, role.RoleAssignmentSourceOidc, desired)
}
// extractOidcGroups reads the user's group memberships from the OIDC userinfo
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index 934ce35ca..b2f7e2b7e 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -196,6 +196,7 @@ type initializeStartupStateParams struct {
AppCtx context.Context
Config *config.Config
+ DB *database.DB
Volume *volume.VolumeService
Settings *settings.SettingsService
@@ -328,7 +329,7 @@ func initializeStartupState(p initializeStartupStateParams) {
)
startup.CleanupUnknownSettings(appCtx, p.Settings)
- runRoleStartupTasks(appCtx, p.Role, p.ApiKey, cfg)
+ runRoleStartupTasks(appCtx, p.DB, p.Role, p.ApiKey, cfg)
// Only edge agents auto-pair; direct agents are passive and the manager dials them.
if cfg.AgentMode && cfg.EdgeAgent && cfg.AgentToken != "" && cfg.ManagerApiUrl != "" {
@@ -340,7 +341,7 @@ func initializeStartupState(p initializeStartupStateParams) {
}
}
-func runRoleStartupTasks(ctx context.Context, roleService *role.RoleService, apiKeyService *apikey.ApiKeyService, cfg *config.Config) {
+func runRoleStartupTasks(ctx context.Context, db *database.DB, roleService *role.RoleService, apiKeyService *apikey.ApiKeyService, cfg *config.Config) {
if roleService == nil {
return
}
@@ -362,7 +363,7 @@ func runRoleStartupTasks(ctx context.Context, roleService *role.RoleService, api
if cfg.AgentMode {
return
}
- if err := roleService.AssertGlobalAdminExists(ctx); err != nil {
+ if err := roleService.AssertGlobalAdminExists(ctx, db.WithContext(ctx)); err != nil {
slog.ErrorContext(ctx, "RBAC global admin guard failed", "error", err)
}
}
diff --git a/backend/internal/role/handler.go b/backend/internal/role/handler.go
index 48ee426c6..43ca2a58a 100644
--- a/backend/internal/role/handler.go
+++ b/backend/internal/role/handler.go
@@ -132,6 +132,8 @@ func (h *RoleHandler) UpdateRole(ctx context.Context, input *UpdateRoleInput) (*
return nil, huma.Error409Conflict("role name already in use")
case errors.Is(err, common.ErrUnknownPermission):
return nil, huma.Error400BadRequest(err.Error())
+ case errors.Is(err, common.ErrNoGlobalAdminRemains):
+ return nil, huma.Error409Conflict(err.Error())
}
return nil, huma.Error500InternalServerError("failed to update role: " + err.Error())
}
@@ -180,7 +182,7 @@ func (h *RoleHandler) SetUserRoleAssignments(ctx context.Context, input *SetUser
for i, a := range input.Body.Assignments {
desired[i] = UserRoleAssignment{RoleID: a.RoleID, EnvironmentID: a.EnvironmentID}
}
- if err := h.roleService.SetUserAssignments(ctx, input.UserID, desired); err != nil {
+ if err := h.roleService.ReplaceUserAssignments(ctx, input.UserID, RoleAssignmentSourceManual, desired); err != nil {
switch {
case errors.Is(err, common.ErrUserNotFound):
return nil, huma.Error404NotFound(err.Error())
diff --git a/backend/internal/role/service.go b/backend/internal/role/service.go
index 252738931..eba1a7e99 100644
--- a/backend/internal/role/service.go
+++ b/backend/internal/role/service.go
@@ -32,6 +32,8 @@ 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
)
type RoleService struct {
@@ -88,7 +90,7 @@ func (s *RoleService) EnsureBuiltInRoles(ctx context.Context) error {
})
}
-// BackfillLegacyRoleAssignments converts pre-RBAC users.roles into global assignments once, gated by a kv marker committed with the rows.
+// BackfillLegacyRoleAssignments converts pre-RBAC users.roles into global assignments once.
func (s *RoleService) BackfillLegacyRoleAssignments(ctx context.Context) error {
migrator := s.db.WithContext(ctx).Migrator()
if !migrator.HasColumn("users", "roles") {
@@ -139,7 +141,7 @@ func (s *RoleService) BackfillLegacyRoleAssignments(ctx context.Context) error {
return nil
}
-// legacyRolesContainsAdminInternal reports whether a legacy users.roles JSON value names "admin"; anything else was a regular user.
+// legacyRolesContainsAdminInternal reports whether a legacy users.roles JSON value names "admin".
func legacyRolesContainsAdminInternal(raw string) bool {
var roles []string
if err := json.Unmarshal([]byte(raw), &roles); err != nil {
@@ -153,11 +155,9 @@ func legacyRolesContainsAdminInternal(raw string) bool {
return false
}
-// AssertGlobalAdminExists returns common.ErrNoGlobalAdminRemains if zero
-// non-service users resolve to global administrator permissions. Called at boot
-// after the backfill migration; also called from inside mutation paths.
-func (s *RoleService) AssertGlobalAdminExists(ctx context.Context) error {
- count, err := s.countEffectiveGlobalAdminsInternal(ctx, s.db.WithContext(ctx), "")
+// AssertGlobalAdminExists returns common.ErrNoGlobalAdminRemains when no non-service user is a global admin in tx.
+func (s *RoleService) AssertGlobalAdminExists(ctx context.Context, tx *gorm.DB) error {
+ count, err := s.CountGlobalAdmins(ctx, tx, "")
if err != nil {
return err
}
@@ -167,6 +167,17 @@ func (s *RoleService) AssertGlobalAdminExists(ctx context.Context) error {
return nil
}
+// lockGlobalAdminGuard serializes transactions that can remove a global admin. SQLite already serializes writes.
+func lockGlobalAdminGuard(tx *gorm.DB) error {
+ if tx.Name() != "postgres" {
+ return nil
+ }
+ if err := tx.Exec("SELECT pg_advisory_xact_lock(?)", globalAdminGuardLockKey).Error; err != nil {
+ return fmt.Errorf("failed to lock global admin guard: %w", err)
+ }
+ return nil
+}
+
func (s *RoleService) ListRoles(ctx context.Context, params pagination.QueryParams) ([]Role, pagination.Response, error) {
var roles []Role
query := s.db.WithContext(ctx).Model(&Role{})
@@ -225,13 +236,8 @@ func (s *RoleService) CreateRole(ctx context.Context, name string, description *
return role, nil
}
-// lockAssignedUserRowsInternal locks the user rows of everyone currently
-// assigned to roleID, in deterministic id order. Role-definition writes call
-// this so they serialize with user-domain mutation transactions, whose in-transaction
-// privilege checks lock the same rows: without it a role edit could change a
-// holder's effective admin status between that check and the mutation commit.
-// Returns the affected user ids for post-commit cache invalidation.
-func lockAssignedUserRowsInternal(tx *gorm.DB, roleID string) ([]string, error) {
+// lockAssignedUserRows locks the users holding roleID so role writes serialize with user-domain privilege checks.
+func lockAssignedUserRows(tx *gorm.DB, roleID string) ([]string, error) {
var ids []string
if err := tx.Model(&UserRoleAssignment{}).
Where("role_id = ?", roleID).
@@ -264,6 +270,9 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descripti
var out Role
var affected []string
err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ if err := lockGlobalAdminGuard(tx); err != nil {
+ return err
+ }
var existing Role
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -283,7 +292,7 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descripti
return common.Classify(common.ErrRoleNameTaken, errors.New("Role name already in use"))
}
}
- ids, err := lockAssignedUserRowsInternal(tx, id)
+ ids, err := lockAssignedUserRows(tx, id)
if err != nil {
return err
}
@@ -295,7 +304,11 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descripti
return fmt.Errorf("failed to update role: %w", updateRoleErr)
}
out = existing
- return nil
+ // Narrowing a role can demote every holder, so re-check the global-admin guard.
+ if len(ids) == 0 {
+ return nil
+ }
+ return s.AssertGlobalAdminExists(ctx, tx)
})
if err != nil {
return nil, err
@@ -309,6 +322,9 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descripti
func (s *RoleService) DeleteRole(ctx context.Context, id string) error {
var affected []string
err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ if err := lockGlobalAdminGuard(tx); err != nil {
+ return err
+ }
var existing Role
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -320,8 +336,7 @@ 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.
}
- // Collect affected users before deleting the role.
- ids, err := lockAssignedUserRowsInternal(tx, id)
+ ids, err := lockAssignedUserRows(tx, id)
if err != nil {
return err
}
@@ -329,22 +344,22 @@ func (s *RoleService) DeleteRole(ctx context.Context, id string) error {
if deleteRoleErr := tx.Delete(&Role{}, "id = ?", id).Error; deleteRoleErr != nil {
return fmt.Errorf("failed to delete role: %w", deleteRoleErr)
}
- return nil
+ if len(ids) == 0 {
+ return nil
+ }
+ return s.AssertGlobalAdminExists(ctx, tx)
})
if err != nil {
return err
}
- // Invalidate caches AFTER the transaction commits so a concurrent
- // cache-miss cannot re-populate with stale data from the not-yet-visible
- // delete. Consistent with UpdateRole / SetUserAssignments.
+ // Invalidate after commit so a concurrent cache miss cannot refill stale permissions.
for _, uid := range affected {
s.InvalidateUser(uid)
}
return nil
}
-// CountUsersAssignedToRole returns how many distinct users hold an assignment
-// to the given role (any source, any environment scope).
+// CountUsersAssignedToRole counts distinct users assigned to roleID in any source or scope.
func (s *RoleService) CountUsersAssignedToRole(ctx context.Context, roleID string) (int, error) {
var count int64
if err := s.db.WithContext(ctx).
@@ -357,8 +372,6 @@ func (s *RoleService) CountUsersAssignedToRole(ctx context.Context, roleID strin
return int(count), nil
}
-// ---------- User role assignments ----------
-
func (s *RoleService) ListUserAssignments(ctx context.Context, userID string) ([]UserRoleAssignment, error) {
var out []UserRoleAssignment
if err := s.db.WithContext(ctx).
@@ -370,13 +383,8 @@ func (s *RoleService) ListUserAssignments(ctx context.Context, userID string) ([
return out, nil
}
-// replaceUserAssignmentsForSourceInternal replaces the user's assignments for a
-// single source (manual or oidc), leaving other sources untouched. References
-// are validated inside the tx so a concurrent role/env delete yields a typed
-// error (→ 400) rather than an opaque FK violation, and the global-admin guard
-// is enforced before commit. Shared by SetUserAssignments and
-// ReplaceOidcAssignments.
-func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Context, userID, source string, desired []UserRoleAssignment) error {
+// ReplaceUserAssignments replaces the user's assignments for one source and enforces the global-admin guard.
+func (s *RoleService) ReplaceUserAssignments(ctx context.Context, userID, source string, desired []UserRoleAssignment) error {
seen := make(map[string]struct{}, len(desired))
desired = slices.DeleteFunc(desired, func(a UserRoleAssignment) bool {
key := assignmentKeyInternal(a)
@@ -391,9 +399,10 @@ func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Contex
desired[i].Source = source
}
err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
- // Lock the target's user row so assignment swaps serialize with
- // user-domain update/delete transactions, whose in-transaction privilege
- // checks lock the same row.
+ if err := lockGlobalAdminGuard(tx); err != nil {
+ return err
+ }
+ // Lock the user row so assignment swaps serialize with user-domain privilege checks.
var locked struct{ ID string }
if err := tx.Table("users").
Select("id").
@@ -417,14 +426,7 @@ func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Contex
return fmt.Errorf("failed to insert %s assignments: %w", source, err)
}
}
- count, err := s.countEffectiveGlobalAdminsInternal(ctx, tx, "")
- if err != nil {
- return err
- }
- if count == 0 {
- return common.Classify(common.ErrNoGlobalAdminRemains, errors.New("At least one user must retain a global Admin role assignment")) //nolint:staticcheck // Preserve the existing error message.
- }
- return nil
+ return s.AssertGlobalAdminExists(ctx, tx)
})
if err != nil {
return err
@@ -441,17 +443,7 @@ func assignmentKeyInternal(a UserRoleAssignment) string {
return a.RoleID + "\x00" + envID
}
-// SetUserAssignments replaces the user's source='manual' assignments with the
-// given desired set. Source='oidc' rows are preserved (use
-// ReplaceOidcAssignments for those). Enforces the global-admin guard.
-func (s *RoleService) SetUserAssignments(ctx context.Context, userID string, desired []UserRoleAssignment) error {
- return s.replaceUserAssignmentsForSourceInternal(ctx, userID, RoleAssignmentSourceManual, desired)
-}
-
-// validateAssignmentsExistInternal verifies every distinct RoleID and
-// EnvironmentID referenced by `desired` exists in the database. Returns the
-// first missing reference wrapped in an InvalidRoleAssignmentError so the
-// handler can map it to a 400 with a descriptive message.
+// validateAssignmentsExistInternal returns ErrInvalidRoleAssignment for the first missing role or environment.
func validateAssignmentsExistInternal(tx *gorm.DB, desired []UserRoleAssignment) error {
roleIDSet := make(map[string]struct{}, len(desired))
envIDSet := make(map[string]struct{}, len(desired))
@@ -498,24 +490,7 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []UserRoleAssignment)
return nil
}
-// ReplaceOidcAssignments replaces the user's source='oidc' assignments. Manual
-// assignments are untouched. An OIDC mapping referencing a since-deleted role or
-// environment fails with a typed error; the caller logs and continues login so
-// the user simply receives no OIDC-derived assignments. Enforces the
-// global-admin guard after the swap.
-func (s *RoleService) ReplaceOidcAssignments(ctx context.Context, userID string, desired []UserRoleAssignment) error {
- return s.replaceUserAssignmentsForSourceInternal(ctx, userID, RoleAssignmentSourceOidc, desired)
-}
-
-// CountGlobalAdminsExcludingUser returns the number of non-service users (other
-// than excludedUserID) whose resolved global permissions satisfy IsGlobalAdmin.
-// Used as the authoritative check for "removing this user / demoting this
-// assignment would leave the system with no admin."
-func (s *RoleService) CountGlobalAdminsExcludingUser(ctx context.Context, excludedUserID string) (int, error) {
- return s.countEffectiveGlobalAdminsInternal(ctx, s.db.WithContext(ctx), excludedUserID)
-}
-
-func (s *RoleService) countEffectiveGlobalAdminsInternal(ctx context.Context, tx *gorm.DB, excludedUserID string) (int, error) {
+func (s *RoleService) CountGlobalAdmins(ctx context.Context, tx *gorm.DB, excludedUserID string) (int, error) {
type globalPermissionRow struct {
UserID string `gorm:"column:user_id"`
Permissions string `gorm:"column:permissions"`
@@ -558,10 +533,7 @@ func (s *RoleService) countEffectiveGlobalAdminsInternal(ctx context.Context, tx
return count, nil
}
-// ---------- Permission resolution ----------
-
-// ResolvePermissions returns the effective PermissionSet for a user, caching
-// the result per-user for permissionCacheTTL.
+// ResolvePermissions returns the user's effective permissions, cached for permissionCacheTTL.
func (s *RoleService) ResolvePermissions(ctx context.Context, userID string) (*authz.PermissionSet, error) {
if userID == "" {
return authz.NewPermissionSet(), nil
@@ -582,11 +554,9 @@ func (s *RoleService) ResolvePermissions(ctx context.Context, userID string) (*a
return ps, nil
}
-// ResolveUserPermissionsInDB resolves permissions using the supplied transaction or database handle.
+// ResolveUserPermissionsInDB resolves the user's permissions in tx.
func (s *RoleService) ResolveUserPermissionsInDB(_ context.Context, tx *gorm.DB, userID string) (*authz.PermissionSet, error) {
- // Scan into raw string for the permissions JSON column to avoid GORM's
- // schema-introspection on anonymous local structs (which can't see the
- // type tags needed to wire database.StringSlice's Scanner).
+ // Scan permissions as a raw string; GORM cannot wire StringSlice on anonymous structs.
type row struct {
Permissions string `gorm:"column:permissions"`
EnvironmentID *string `gorm:"column:environment_id"`
@@ -614,8 +584,7 @@ func (s *RoleService) ResolveUserPermissionsInDB(_ context.Context, tx *gorm.DB,
return ps, nil
}
-// decodePermissionsJSONInternal parses the JSON-encoded `roles.permissions` column
-// into a string slice. The column is `[]` for an empty role.
+// decodePermissionsJSONInternal parses the JSON roles.permissions column.
func decodePermissionsJSONInternal(raw string) ([]string, error) {
if raw == "" || raw == "[]" {
return nil, nil
@@ -627,8 +596,7 @@ func decodePermissionsJSONInternal(raw string) ([]string, error) {
return out, nil
}
-// ResolveExecutionPermissions revalidates durable work against current users,
-// key ownership, expiry and permissions without using authentication caches.
+// ResolveExecutionPermissions revalidates durable work against current users and keys, bypassing caches.
func (s *RoleService) ResolveExecutionPermissions(ctx context.Context, userID, keyID string) (*authz.PermissionSet, error) {
if userID == "" {
return nil, errors.New("requesting user unavailable")
@@ -683,8 +651,7 @@ func (s *RoleService) ResolveExecutionPermissions(ctx context.Context, userID, k
return restricted, nil
}
-// ResolveApiKeyPermissions returns the PermissionSet for an API key. Caches
-// per-key. Falls back to an empty set (deny-all) if the key has no perms.
+// ResolveApiKeyPermissions returns the API key's permissions, cached per key.
func (s *RoleService) ResolveApiKeyPermissions(ctx context.Context, apiKeyID string) (*authz.PermissionSet, error) {
if ps, ok, _ := s.apiKeyCache.Get(apiKeyID); ok {
return ps, nil
@@ -718,9 +685,7 @@ func (s *RoleService) resolveApiKeyPermissionsInDBInternal(db *gorm.DB, apiKeyID
return permissions, nil
}
-// SetApiKeyPermissions replaces every permission row on the given API key
-// atomically. Validation that the granted permissions don't exceed the
-// creator's capabilities happens in the handler layer.
+// SetApiKeyPermissions atomically replaces the API key's permission rows.
func (s *RoleService) SetApiKeyPermissions(ctx context.Context, apiKeyID string, grants []ApiKeyPermission) error {
err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
return s.SetApiKeyPermissionsInDB(ctx, tx, apiKeyID, grants)
@@ -732,7 +697,7 @@ func (s *RoleService) SetApiKeyPermissions(ctx context.Context, apiKeyID string,
return nil
}
-// SetApiKeyPermissionsInDB replaces permission rows using the supplied transaction or database handle.
+// SetApiKeyPermissionsInDB replaces the API key's permission rows in tx.
func (s *RoleService) SetApiKeyPermissionsInDB(ctx context.Context, tx *gorm.DB, apiKeyID string, grants []ApiKeyPermission) error {
for i := range grants {
grants[i].ApiKeyID = apiKeyID
@@ -748,8 +713,6 @@ func (s *RoleService) SetApiKeyPermissionsInDB(ctx context.Context, tx *gorm.DB,
return nil
}
-// ---------- OIDC role mappings ----------
-
func (s *RoleService) ListOidcMappings(ctx context.Context) ([]OidcRoleMapping, error) {
var out []OidcRoleMapping
if err := s.db.WithContext(ctx).Order("claim_value, role_id").Find(&out).Error; err != nil {
@@ -880,17 +843,8 @@ func (s *RoleService) DeleteOidcMapping(ctx context.Context, id string) error {
})
}
-// ReconcileEnvOidcMappings replaces every source='env' row in oidc_role_mappings
-// with the set declared by `rawSpec` (a JSON array of role.OidcRoleMappingSpec).
-// Called once at boot. Behavior is declarative:
-//
-// - rawSpec empty / unset → leaves DB rows alone (purely UI-managed mode).
-// - rawSpec is `[]` → wipes any previously-env-managed rows.
-// - rawSpec is a valid JSON array → upserts each spec, deletes stale env rows.
-//
-// Manual rows (source='manual') are never touched. Bad JSON or an unknown role
-// ID returns an error so a misconfigured deployment fails loudly rather than
-// silently dropping mappings.
+// ReconcileEnvOidcMappings replaces source='env' OIDC mappings with rawSpec at boot.
+// Empty rawSpec leaves rows alone; manual rows are never touched.
func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec string) error {
rawSpec = strings.TrimSpace(rawSpec)
if rawSpec == "" {
@@ -910,8 +864,7 @@ func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec stri
}
return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
- // Verify every referenced role exists. Done inside the tx so a concurrent
- // role delete can't race past this check.
+ // Verify roles inside the tx so a concurrent role delete cannot race past it.
roleIDs := make([]string, 0, len(specs))
for _, sp := range specs {
roleIDs = append(roleIDs, sp.RoleID)
@@ -926,8 +879,6 @@ func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec stri
}
}
- // Declarative replace: drop every env-managed row, then insert the new
- // set. Manual rows are untouched.
if err := tx.Where("source = ?", OidcMappingSourceEnv).Delete(&OidcRoleMapping{}).Error; err != nil {
return fmt.Errorf("failed to clear env-managed mappings: %w", err)
}
@@ -952,11 +903,7 @@ func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec stri
})
}
-// ---------- Cache helpers ----------
-
-// InvalidateUser drops the cached PermissionSet for one user. Called from
-// auth_service after a login that mutates assignments, and from any mutation
-// path that doesn't already invalidate explicitly.
+// InvalidateUser drops the cached permissions for one user.
func (s *RoleService) InvalidateUser(userID string) {
s.cacheFillMu.Lock()
defer s.cacheFillMu.Unlock()
@@ -964,7 +911,7 @@ func (s *RoleService) InvalidateUser(userID string) {
s.userCache.Delete(userID)
}
-// InvalidateApiKey drops the cached PermissionSet for one API key.
+// InvalidateApiKey drops the cached permissions for one API key.
func (s *RoleService) InvalidateApiKey(apiKeyID string) {
s.cacheFillMu.Lock()
defer s.cacheFillMu.Unlock()
@@ -972,8 +919,6 @@ func (s *RoleService) InvalidateApiKey(apiKeyID string) {
s.apiKeyCache.Delete(apiKeyID)
}
-// ---------- helpers ----------
-
func validatePermissionsInternal(perms []string) error {
for _, p := range perms {
if !authz.IsKnownPermission(p) {
@@ -985,22 +930,8 @@ func validatePermissionsInternal(perms []string) error {
return nil
}
-// ValidatePermissionsAgainstCaller rejects any permission in `desired` that the
-// caller does not hold at global scope. Sudo callers (agent / env access
-// tokens, bootstrap paths) bypass entirely. Holding a permission only inside a
-// specific environment is intentionally insufficient: roles are reusable
-// templates that can later be assigned globally, so an env-scoped grant must
-// not let the caller mint a global-capable role.
-//
-// Unknown permission strings are rejected first with an UnknownPermissionError
-// so a caller typo-ing a permission gets a descriptive 400 instead of a
-// misleading 403 from the escalation guard below (which would always fire on
-// an unknown perm because no PermissionSet contains it). This also gives the
-// escalation loop a clean invariant: every perm reaching it is real.
-//
-// Callers should run this before persisting role permissions to defend against
-// privilege escalation if the role mutation endpoints are ever exposed beyond
-// global admins.
+// ValidatePermissionsAgainstCaller rejects unknown permissions, then any the caller lacks globally.
+// Env-scoped grants are insufficient because roles can later be assigned globally.
func (s *RoleService) ValidatePermissionsAgainstCaller(caller *authz.PermissionSet, desired []string) error {
if err := validatePermissionsInternal(desired); err != nil {
return err
@@ -1008,9 +939,7 @@ func (s *RoleService) ValidatePermissionsAgainstCaller(caller *authz.PermissionS
return validatePermissionSetAgainstCallerInternal(caller, desired, "")
}
-// ValidateRoleAssignmentAgainstCaller rejects assigning a role at the requested
-// scope when the caller does not hold every permission in that role at that
-// same scope.
+// ValidateRoleAssignmentAgainstCaller rejects a role whose permissions the caller lacks at that scope.
func (s *RoleService) ValidateRoleAssignmentAgainstCaller(ctx context.Context, caller *authz.PermissionSet, roleID string, environmentID *string) error {
role, err := s.GetRole(ctx, roleID)
if err != nil {
diff --git a/backend/internal/role/service_test.go b/backend/internal/role/service_test.go
index fc7907f17..af5625998 100644
--- a/backend/internal/role/service_test.go
+++ b/backend/internal/role/service_test.go
@@ -93,8 +93,8 @@ func TestBackfillLegacyRoleAssignments(t *testing.T) {
}
require.NoError(t, db.Create(&role.UserRoleAssignment{UserID: "seed-admin", RoleID: authz.BuiltInRoleAdmin, Source: role.RoleAssignmentSourceManual}).Error)
envID := "env-1"
- require.NoError(t, roleSvc.SetUserAssignments(ctx, "scoped-manual", []role.UserRoleAssignment{{RoleID: authz.BuiltInRoleViewer, EnvironmentID: &envID}}))
- require.NoError(t, roleSvc.ReplaceOidcAssignments(ctx, "global-oidc", []role.UserRoleAssignment{{RoleID: authz.BuiltInRoleViewer}}))
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, "scoped-manual", role.RoleAssignmentSourceManual, []role.UserRoleAssignment{{RoleID: authz.BuiltInRoleViewer, EnvironmentID: &envID}}))
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, "global-oidc", role.RoleAssignmentSourceOidc, []role.UserRoleAssignment{{RoleID: authz.BuiltInRoleViewer}}))
require.NoError(t, roleSvc.BackfillLegacyRoleAssignments(ctx))
require.Equal(t, []string{authz.BuiltInRoleAdmin}, assignedRoleIDs(t, roleSvc, "legacy-admin"))
@@ -114,7 +114,7 @@ func TestBackfillLegacyRoleAssignments(t *testing.T) {
require.True(t, ps.Allows(authz.PermContainersList, "env-1"))
require.False(t, ps.Allows(authz.PermContainersList, ""))
- require.NoError(t, roleSvc.SetUserAssignments(ctx, "legacy-user", nil))
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, "legacy-user", role.RoleAssignmentSourceManual, nil))
require.NoError(t, db.Exec("INSERT INTO users (id, username, password_hash, roles) VALUES (?, ?, ?, ?)", "later-admin", "later-admin", "unused", `["admin"]`).Error)
require.NoError(t, role.NewRoleService(db).BackfillLegacyRoleAssignments(ctx))
require.Empty(t, assignedRoleIDs(t, roleSvc, "legacy-user"))
@@ -211,34 +211,34 @@ func TestSetUserAssignmentsRejectsUnknownRole(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
victim := createTestUser(t, userSvc, "victim", "victim")
- err := roleSvc.SetUserAssignments(ctx, victim.ID, []role.UserRoleAssignment{
+ err := roleSvc.ReplaceUserAssignments(ctx, victim.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: "role_does_not_exist"},
})
require.Error(t, err)
require.ErrorIs(t, err, common.ErrInvalidRoleAssignment)
}
-func TestReplaceOidcAssignmentsRejectsUnknownRole(t *testing.T) {
+func TestReplaceUserAssignmentsOidcRejectsUnknownRole(t *testing.T) {
ctx := t.Context()
userSvc, roleSvc := setupUserAndRoleServices(t)
oidcUser := createTestUser(t, userSvc, "oidc-user", "oidc-user")
- err := roleSvc.ReplaceOidcAssignments(ctx, oidcUser.ID, []role.UserRoleAssignment{
+ err := roleSvc.ReplaceUserAssignments(ctx, oidcUser.ID, role.RoleAssignmentSourceOidc, []role.UserRoleAssignment{
{RoleID: "role_does_not_exist"},
})
require.Error(t, err)
require.ErrorIs(t, err, common.ErrInvalidRoleAssignment)
}
-func TestReplaceOidcAssignmentsRejectsUnknownEnvironment(t *testing.T) {
+func TestReplaceUserAssignmentsOidcRejectsUnknownEnvironment(t *testing.T) {
ctx := t.Context()
userSvc, roleSvc := setupUserAndRoleServices(t)
oidcUser := createTestUser(t, userSvc, "oidc-user-env", "oidc-user-env")
missingEnv := "env_does_not_exist"
// A valid role scoped to a non-existent environment must fail existence
- // validation (mirrors SetUserAssignments) rather than attempting an insert.
- err := roleSvc.ReplaceOidcAssignments(ctx, oidcUser.ID, []role.UserRoleAssignment{
+ // validation (same as manual assignments) rather than attempting an insert.
+ err := roleSvc.ReplaceUserAssignments(ctx, oidcUser.ID, role.RoleAssignmentSourceOidc, []role.UserRoleAssignment{
{RoleID: authz.BuiltInRoleViewer, EnvironmentID: &missingEnv},
})
require.Error(t, err)
@@ -252,16 +252,16 @@ func TestEffectiveGlobalAdminCountIncludesCustomAllPermissionsRole(t *testing.T)
customRole, err := roleSvc.CreateRole(ctx, "Custom Admin", nil, authz.AllPermissions())
require.NoError(t, err)
- require.NoError(t, roleSvc.SetUserAssignments(ctx, customAdmin.ID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, customAdmin.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: customRole.ID, EnvironmentID: nil},
}))
- count, err := roleSvc.CountGlobalAdminsExcludingUser(ctx, "")
+ count, err := roleSvc.CountGlobalAdmins(ctx, userSvc.DB, "")
require.NoError(t, err)
require.Equal(t, 1, count)
- require.NoError(t, roleSvc.AssertGlobalAdminExists(ctx))
+ require.NoError(t, roleSvc.AssertGlobalAdminExists(ctx, userSvc.DB))
- err = roleSvc.SetUserAssignments(ctx, customAdmin.ID, nil)
+ err = roleSvc.ReplaceUserAssignments(ctx, customAdmin.ID, role.RoleAssignmentSourceManual, nil)
require.Error(t, err)
require.ErrorIs(t, err, common.ErrNoGlobalAdminRemains)
}
@@ -283,17 +283,17 @@ func TestEffectiveGlobalAdminCountIgnoresEnvScopedAndServiceAccounts(t *testing.
}
require.NoError(t, userSvc.WithContext(ctx).Create(serviceAdmin).Error)
- require.NoError(t, roleSvc.SetUserAssignments(ctx, globalAdmin.ID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, globalAdmin.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: customRole.ID, EnvironmentID: nil},
}))
- require.NoError(t, roleSvc.SetUserAssignments(ctx, envScopedAdmin.ID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, envScopedAdmin.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: customRole.ID, EnvironmentID: &envID},
}))
- require.NoError(t, roleSvc.SetUserAssignments(ctx, serviceAdmin.ID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, serviceAdmin.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: customRole.ID, EnvironmentID: nil},
}))
- count, err := roleSvc.CountGlobalAdminsExcludingUser(ctx, "")
+ count, err := roleSvc.CountGlobalAdmins(ctx, userSvc.DB, "")
require.NoError(t, err)
require.Equal(t, 1, count)
}
@@ -333,7 +333,7 @@ func createTestUser(t *testing.T, db *database.DB, id, username string) *user.Us
func grantGlobalAdmin(t *testing.T, roleService *role.RoleService, userID string) {
t.Helper()
- require.NoError(t, roleService.SetUserAssignments(t.Context(), userID, []role.UserRoleAssignment{
+ require.NoError(t, roleService.ReplaceUserAssignments(t.Context(), userID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: authz.BuiltInRoleAdmin},
}))
}
diff --git a/backend/internal/user/service.go b/backend/internal/user/service.go
index c4a217792..3f85ec9c0 100644
--- a/backend/internal/user/service.go
+++ b/backend/internal/user/service.go
@@ -447,7 +447,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {
return fmt.Errorf("failed to count users: %w", err)
}
if count > 0 {
- admins, err := s.roleService.CountGlobalAdminsExcludingUser(ctx, "")
+ admins, err := s.roleService.CountGlobalAdmins(ctx, s.db.DB, "")
if err != nil {
return fmt.Errorf("failed to count global admins: %w", err)
}
@@ -518,7 +518,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {
// grantDefaultAdminRoleInternal grants the global Admin role to the bootstrap
// user. Reached only on fresh bootstrap or zero-admin recovery.
-// SetUserAssignments replaces manual-source rows, so carry forward only the
+// ReplaceUserAssignments replaces manual-source rows, so carry forward only the
// existing manual assignments — copying OIDC-sourced rows here would duplicate
// them as manual and pin them forever.
func (s *UserService) grantDefaultAdminRoleInternal(ctx context.Context, adminUserID string) error {
@@ -541,7 +541,7 @@ func (s *UserService) grantDefaultAdminRoleInternal(ctx context.Context, adminUs
RoleID: authz.BuiltInRoleAdmin,
EnvironmentID: nil,
})
- if setUserAssignmentsErr := s.roleService.SetUserAssignments(ctx, adminUserID, manual); setUserAssignmentsErr != nil {
+ if setUserAssignmentsErr := s.roleService.ReplaceUserAssignments(ctx, adminUserID, role.RoleAssignmentSourceManual, manual); setUserAssignmentsErr != nil {
return fmt.Errorf("failed to grant default admin global role: %w", setUserAssignmentsErr)
}
slog.InfoContext(ctx, "Default admin granted global Admin role assignment", "userId", adminUserID)
@@ -562,7 +562,7 @@ func (s *UserService) DeleteUser(ctx context.Context, id string, actorPerms *aut
return err
}
if ps != nil && ps.IsGlobalAdmin() {
- remaining, countGlobalAdminsExcludingUserErr := s.roleService.CountGlobalAdminsExcludingUser(ctx, id)
+ remaining, countGlobalAdminsExcludingUserErr := s.roleService.CountGlobalAdmins(ctx, s.db.DB, id)
if countGlobalAdminsExcludingUserErr != nil {
return countGlobalAdminsExcludingUserErr
}
@@ -609,7 +609,7 @@ func (s *UserService) ListUsersPaginated(ctx context.Context, params pagination.
func (s *UserService) ToUserResponseDto(ctx context.Context, u User) (user.User, error) {
dto := s.toUserResponseDtoInternal(ctx, u)
if dto.IsGlobalAdmin && s.roleService != nil {
- remaining, err := s.roleService.CountGlobalAdminsExcludingUser(ctx, u.ID)
+ remaining, err := s.roleService.CountGlobalAdmins(ctx, s.db.DB, u.ID)
if err != nil {
return user.User{}, fmt.Errorf("failed to check whether user can be deleted: %w", err)
}
@@ -628,7 +628,7 @@ func (s *UserService) toUserResponseDtosInternal(ctx context.Context, users []Us
if s.roleService == nil {
return result
}
- if total, err := s.roleService.CountGlobalAdminsExcludingUser(ctx, ""); err == nil && total == 1 {
+ if total, err := s.roleService.CountGlobalAdmins(ctx, s.db.DB, ""); err == nil && total == 1 {
for i := range result {
if result[i].IsGlobalAdmin {
result[i].CanDelete = false
diff --git a/backend/internal/user/service_test.go b/backend/internal/user/service_test.go
index 7faf32df4..5cff3d864 100644
--- a/backend/internal/user/service_test.go
+++ b/backend/internal/user/service_test.go
@@ -78,7 +78,7 @@ func createTestUser(t *testing.T, svc *userdomain.UserService, id, username stri
// grantGlobalAdmin assigns the built-in Admin role globally to the user.
func grantGlobalAdmin(t *testing.T, roleSvc *role.RoleService, userID string) {
t.Helper()
- require.NoError(t, roleSvc.SetUserAssignments(t.Context(), userID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.ReplaceUserAssignments(t.Context(), userID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: authz.BuiltInRoleAdmin, EnvironmentID: nil},
}))
}
@@ -198,7 +198,7 @@ func TestDeleteUserRejectsDeletingOnlyCustomAllPermissionsAdmin(t *testing.T) {
customAdmin := createTestUser(t, userSvc, "custom-admin", "custom-admin")
customRole, err := roleSvc.CreateRole(ctx, "Custom Admin", nil, authz.AllPermissions())
require.NoError(t, err)
- require.NoError(t, roleSvc.SetUserAssignments(ctx, customAdmin.ID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, customAdmin.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: customRole.ID, EnvironmentID: nil},
}))
@@ -313,7 +313,7 @@ func TestUpdateUserRejectsNonAdminActorEditingAdmin(t *testing.T) {
manager := createTestUser(t, userSvc, "mgr-1", "manager")
managerRole, err := roleSvc.CreateRole(ctx, "User Manager", nil, []string{authz.PermUsersUpdate})
require.NoError(t, err)
- require.NoError(t, roleSvc.SetUserAssignments(ctx, manager.ID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, manager.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: managerRole.ID, EnvironmentID: nil},
}))
managerPerms, err := roleSvc.ResolvePermissions(ctx, manager.ID)
@@ -354,7 +354,7 @@ func TestUpdateUserAllowsNonAdminActorEditingNonAdmin(t *testing.T) {
manager := createTestUser(t, userSvc, "mgr-1", "manager")
managerRole, err := roleSvc.CreateRole(ctx, "User Manager", nil, []string{authz.PermUsersUpdate})
require.NoError(t, err)
- require.NoError(t, roleSvc.SetUserAssignments(ctx, manager.ID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, manager.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: managerRole.ID, EnvironmentID: nil},
}))
managerPerms, err := roleSvc.ResolvePermissions(ctx, manager.ID)
@@ -392,7 +392,7 @@ func TestDeleteUserRejectsNonAdminActorDeletingAdmin(t *testing.T) {
manager := createTestUser(t, userSvc, "mgr-1", "manager")
managerRole, err := roleSvc.CreateRole(ctx, "User Manager", nil, []string{authz.PermUsersDelete})
require.NoError(t, err)
- require.NoError(t, roleSvc.SetUserAssignments(ctx, manager.ID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.ReplaceUserAssignments(ctx, manager.ID, role.RoleAssignmentSourceManual, []role.UserRoleAssignment{
{RoleID: managerRole.ID, EnvironmentID: nil},
}))
managerPerms, err := roleSvc.ResolvePermissions(ctx, manager.ID)