Skip to content

Modern Docker Management, Designed for Everyone

fix: better rbac frontend UX for selecting permissions (#2783)

Kyle Mendell23e24b6829c3
diff --git a/backend/api/handlers/customize.go b/backend/api/handlers/customize.go
index 0a00fab58..f03a74077 100644
--- a/backend/api/handlers/customize.go
+++ b/backend/api/handlers/customize.go
@@ -35,6 +35,13 @@ type GetCustomizeCategoriesOutput struct {
Body []category.Category
}
+var customizeCategoryPermissionsInternal = map[string][]string{
+ "templates": {authz.PermTemplatesList, authz.PermTemplatesRead},
+ "registries": {authz.PermRegistriesList, authz.PermRegistriesRead},
+ "variables": {authz.PermTemplatesRead},
+ "git-repositories": {authz.PermGitReposList, authz.PermGitReposRead},
+}
+
// RegisterCustomize registers customization endpoints using Huma.
func RegisterCustomize(api huma.API, customizeSearchService *services.CustomizeSearchService) {
h := &CustomizeHandler{
@@ -52,7 +59,6 @@ func RegisterCustomize(api huma.API, customizeSearchService *services.CustomizeS
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequirePermission(api, authz.PermCustomizeManage),
}, h.Search)
huma.Register(api, huma.Operation{
@@ -66,10 +72,41 @@ func RegisterCustomize(api huma.API, customizeSearchService *services.CustomizeS
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequirePermission(api, authz.PermCustomizeManage),
}, h.GetCategories)
}
+func canAccessCustomizeCategoryInternal(ps *authz.PermissionSet, categoryID string) bool {
+ if ps == nil {
+ return false
+ }
+ if ps.Allows(authz.PermCustomizeManage, "") {
+ return true
+ }
+ perms, ok := customizeCategoryPermissionsInternal[categoryID]
+ if !ok {
+ return false
+ }
+ for _, perm := range perms {
+ if ps.Allows(perm, "") {
+ return true
+ }
+ }
+ return false
+}
+
+func filterCustomizeCategoriesInternal(ps *authz.PermissionSet, categories []category.Category) []category.Category {
+ if ps == nil {
+ return []category.Category{}
+ }
+ filtered := make([]category.Category, 0, len(categories))
+ for _, cat := range categories {
+ if canAccessCustomizeCategoryInternal(ps, cat.ID) {
+ filtered = append(filtered, cat)
+ }
+ }
+ return filtered
+}
+
// Search searches customization options by query.
func (h *CustomizeHandler) Search(ctx context.Context, input *SearchCustomizeInput) (*SearchCustomizeOutput, error) {
if h.customizeSearchService == nil {
@@ -80,19 +117,10 @@ func (h *CustomizeHandler) Search(ctx context.Context, input *SearchCustomizeInp
return nil, huma.Error400BadRequest((&common.QueryParameterRequiredError{}).Error())
}
- results := h.customizeSearchService.Search(input.Body.Query)
-
ps, _ := humamw.PermissionsFromContext(ctx)
- if !ps.IsGlobalAdmin() {
- filtered := []category.Category{}
- for _, cat := range results.Results {
- if cat.ID != "registries" && cat.ID != "variables" {
- filtered = append(filtered, cat)
- }
- }
- results.Results = filtered
- results.Count = len(filtered)
- }
+ results := h.customizeSearchService.Search(input.Body.Query)
+ results.Results = filterCustomizeCategoriesInternal(ps, results.Results)
+ results.Count = len(results.Results)
return &SearchCustomizeOutput{
Body: results,
@@ -105,18 +133,8 @@ func (h *CustomizeHandler) GetCategories(ctx context.Context, input *GetCustomiz
return nil, huma.Error500InternalServerError("service not available")
}
- categories := h.customizeSearchService.GetCustomizeCategories()
-
ps, _ := humamw.PermissionsFromContext(ctx)
- if !ps.IsGlobalAdmin() {
- filtered := []category.Category{}
- for _, cat := range categories {
- if cat.ID != "registries" && cat.ID != "variables" {
- filtered = append(filtered, cat)
- }
- }
- categories = filtered
- }
+ categories := filterCustomizeCategoriesInternal(ps, h.customizeSearchService.GetCustomizeCategories())
return &GetCustomizeCategoriesOutput{
Body: categories,
diff --git a/backend/api/handlers/roles.go b/backend/api/handlers/roles.go
index 307c123eb..240f04b7b 100644
--- a/backend/api/handlers/roles.go
+++ b/backend/api/handlers/roles.go
@@ -156,10 +156,9 @@ func RegisterRoles(api huma.API, roleService *services.RoleService) {
Method: http.MethodGet,
Path: "/roles/available-permissions",
Summary: "Get the permission manifest",
- Description: "Returns every permission the server recognizes, grouped by resource. Used by the role editor UI.",
+ Description: "Returns every permission the server recognizes, grouped by resource. Used by permission-picking UIs.",
Tags: []string{"Roles"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequirePermission(api, authz.PermRolesRead),
}, h.GetPermissionsManifest)
huma.Register(api, huma.Operation{
@@ -408,6 +407,7 @@ func buildPermissionsManifestInternal() roletypes.PermissionsManifest {
Permission: action.Permission,
Label: action.Label,
Description: action.Description,
+ Requires: requiredPermissionsForPickerInternal(action.Permission),
}
}
resources[i] = roletypes.PermissionResource{
@@ -417,5 +417,53 @@ func buildPermissionsManifestInternal() roletypes.PermissionsManifest {
Actions: actions,
}
}
- return roletypes.PermissionsManifest{Resources: resources}
+ return roletypes.PermissionsManifest{
+ Resources: resources,
+ Presets: []roletypes.PermissionPreset{
+ {
+ Key: "editor",
+ Label: "All permissions (non-admin)",
+ Description: "Matches the built-in Editor permission set.",
+ Permissions: authz.BuiltInEditorPermissions(),
+ },
+ {
+ Key: "global-admin",
+ Label: "Global Admin",
+ Description: "Select every permission in the manifest.",
+ Permissions: authz.AllPermissions(),
+ },
+ },
+ }
+}
+
+func requiredPermissionsForPickerInternal(permission string) []string {
+ switch permission {
+ case authz.PermSettingsWrite,
+ authz.PermApiKeysList,
+ authz.PermApiKeysRead,
+ authz.PermApiKeysCreate,
+ authz.PermApiKeysUpdate,
+ authz.PermApiKeysDelete,
+ authz.PermFederatedList,
+ authz.PermFederatedRead,
+ authz.PermFederatedCreate,
+ authz.PermFederatedUpdate,
+ authz.PermFederatedDelete,
+ authz.PermUsersList,
+ authz.PermUsersRead,
+ authz.PermUsersCreate,
+ authz.PermUsersUpdate,
+ authz.PermUsersDelete,
+ authz.PermRolesList,
+ authz.PermRolesRead,
+ authz.PermWebhooksList,
+ authz.PermWebhooksCreate,
+ authz.PermWebhooksUpdate,
+ authz.PermWebhooksDelete,
+ authz.PermNotificationsManage,
+ authz.PermDiagnosticsRead:
+ return []string{authz.PermSettingsRead}
+ default:
+ return nil
+ }
}
diff --git a/backend/api/handlers/settings.go b/backend/api/handlers/settings.go
index bfe5e76eb..84f8e2546 100644
--- a/backend/api/handlers/settings.go
+++ b/backend/api/handlers/settings.go
@@ -71,6 +71,20 @@ type GetCategoriesOutput struct {
Body []category.Category
}
+var settingsCategoryPermissionsInternal = map[string][]string{
+ "activity": {authz.PermSettingsRead},
+ "apikeys": {authz.PermApiKeysList, authz.PermApiKeysRead},
+ "appearance": {authz.PermSettingsRead},
+ "authentication": {authz.PermSettingsRead},
+ "build": {authz.PermSettingsRead},
+ "jobschedule": {authz.PermJobsManage},
+ "notifications": {authz.PermNotificationsManage},
+ "security": {authz.PermSettingsRead},
+ "timeouts": {authz.PermSettingsRead},
+ "users": {authz.PermUsersList, authz.PermUsersRead},
+ "webhooks": {authz.PermWebhooksList},
+}
+
// validateProjectsDirectoryValueInternal validates a projects directory value allowing:
// - Unix absolute paths (/...)
// - Windows drive paths (C:/..., C:\...)
@@ -171,7 +185,6 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequirePermission(api, authz.PermSettingsRead),
}, h.Search)
huma.Register(api, huma.Operation{
@@ -185,10 +198,53 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequirePermission(api, authz.PermSettingsRead),
}, h.GetCategories)
}
+func permissionSetAllowsAtAnyScopeInternal(ps *authz.PermissionSet, perm string) bool {
+ if ps == nil {
+ return false
+ }
+ if ps.Allows(perm, "") {
+ return true
+ }
+ for envID := range ps.PerEnv {
+ if ps.Allows(perm, envID) {
+ return true
+ }
+ }
+ return false
+}
+
+func canAccessSettingsCategoryInternal(ps *authz.PermissionSet, categoryID string) bool {
+ if ps == nil {
+ return false
+ }
+ perms, ok := settingsCategoryPermissionsInternal[categoryID]
+ if !ok {
+ return false
+ }
+ for _, perm := range perms {
+ if permissionSetAllowsAtAnyScopeInternal(ps, perm) {
+ return true
+ }
+ }
+ return false
+}
+
+func filterSettingsCategoriesInternal(ps *authz.PermissionSet, categories []category.Category) []category.Category {
+ if ps == nil {
+ return []category.Category{}
+ }
+ filtered := make([]category.Category, 0, len(categories))
+ for _, cat := range categories {
+ if canAccessSettingsCategoryInternal(ps, cat.ID) {
+ filtered = append(filtered, cat)
+ }
+ }
+ return filtered
+}
+
func (h *SettingsHandler) appendRuntimeSettingsInternal(settingsDto []settings.PublicSetting, includeAuthenticatedOnly bool) []settings.PublicSetting {
if !includeAuthenticatedOnly {
return settingsDto
@@ -416,7 +472,10 @@ func (h *SettingsHandler) Search(ctx context.Context, input *SearchSettingsInput
return nil, huma.Error400BadRequest((&common.QueryParameterRequiredError{}).Error())
}
+ ps, _ := humamw.PermissionsFromContext(ctx)
results := h.settingsSearchService.Search(input.Body.Query)
+ results.Results = filterSettingsCategoriesInternal(ps, results.Results)
+ results.Count = len(results.Results)
return &SearchSettingsOutput{Body: results}, nil
}
@@ -426,6 +485,7 @@ func (h *SettingsHandler) GetCategories(ctx context.Context, input *struct{}) (*
return nil, huma.Error500InternalServerError("service not available")
}
- categories := h.settingsSearchService.GetSettingsCategories()
+ ps, _ := humamw.PermissionsFromContext(ctx)
+ categories := filterSettingsCategoriesInternal(ps, h.settingsSearchService.GetSettingsCategories())
return &GetCategoriesOutput{Body: categories}, nil
}
diff --git a/backend/internal/services/user_service.go b/backend/internal/services/user_service.go
index 8bdb1dd33..947e06737 100644
--- a/backend/internal/services/user_service.go
+++ b/backend/internal/services/user_service.go
@@ -477,6 +477,7 @@ func (s *UserService) toUserResponseDtoInternal(ctx context.Context, u models.Us
}
}
if ps, err := s.roleService.ResolvePermissions(ctx, &u); err == nil && ps != nil {
+ dto.IsGlobalAdmin = ps.IsGlobalAdmin()
dto.PermissionsByEnv = permissionSetToMap(ps)
}
return dto
diff --git a/cli/go.mod b/cli/go.mod
index f3c451fe9..06d9b002a 100644
--- a/cli/go.mod
+++ b/cli/go.mod
@@ -16,6 +16,7 @@ require (
github.com/spf13/cobra v1.10.2
github.com/spf13/pflag v1.0.10
github.com/spf13/viper v1.21.0
+ github.com/stretchr/testify v1.11.1
go.withmatt.com/size v0.0.0-20250220224316-11aee5773e67
)
@@ -35,6 +36,7 @@ require (
github.com/compose-spec/compose-go/v2 v2.11.0 // indirect
github.com/containerd/errdefs v1.0.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect
+ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/docker/go-connections v0.7.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
@@ -59,6 +61,7 @@ require (
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/pelletier/go-toml/v2 v2.3.1 // indirect
+ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/sagikazarmark/locafero v0.12.0 // indirect
github.com/sahilm/fuzzy v0.1.2 // indirect
@@ -79,4 +82,5 @@ require (
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.45.0 // indirect
golang.org/x/text v0.37.0 // indirect
+ gopkg.in/yaml.v3 v3.0.1 // indirect
)
diff --git a/frontend/src/lib/components/forms/role-assignments-editor.svelte b/frontend/src/lib/components/forms/role-assignments-editor.svelte
index a0a63b368..126c5a497 100644
--- a/frontend/src/lib/components/forms/role-assignments-editor.svelte
+++ b/frontend/src/lib/components/forms/role-assignments-editor.svelte
@@ -1,5 +1,6 @@
<script lang="ts">
import * as Select from '$lib/components/ui/select';
+ import { Checkbox } from '$lib/components/ui/checkbox';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import {
@@ -33,6 +34,8 @@
...environments.map((env) => ({ id: env.id, name: env.name }))
]);
+ const quickPresetRoles = $derived(roles.filter((role) => role.id === BUILT_IN_ROLE_EDITOR || role.id === BUILT_IN_ROLE_ADMIN));
+
function getRoleVariant(roleId: string) {
switch (roleId) {
case BUILT_IN_ROLE_ADMIN:
@@ -87,9 +90,54 @@
function roleSelectedLabel(value: string): string {
return roles.find((r) => r.id === value)?.name ?? m.common_select_option();
}
+
+ function hasGlobalRoleAssignment(roleId: string): boolean {
+ return assignments.some((assignment) => assignment.roleId === roleId && !assignment.environmentId);
+ }
+
+ function toggleQuickPreset(roleId: string, checked: boolean) {
+ if (disabled) return;
+ const conflictingRoleId =
+ roleId === BUILT_IN_ROLE_ADMIN ? BUILT_IN_ROLE_EDITOR : roleId === BUILT_IN_ROLE_EDITOR ? BUILT_IN_ROLE_ADMIN : '';
+ let next = assignments;
+ if (checked) {
+ if (conflictingRoleId) {
+ next = next.filter((assignment) => !(assignment.roleId === conflictingRoleId && !assignment.environmentId));
+ }
+ if (!next.some((assignment) => assignment.roleId === roleId && !assignment.environmentId)) {
+ next = [...next, { roleId, environmentId: undefined }];
+ }
+ } else {
+ next = next.filter((assignment) => !(assignment.roleId === roleId && !assignment.environmentId));
+ }
+ assignments = next;
+ }
</script>
<div class="space-y-3">
+ {#if quickPresetRoles.length > 0}
+ <div class="space-y-2 rounded-md border p-3">
+ {#each quickPresetRoles as role (role.id)}
+ <label class="flex cursor-pointer items-start gap-3 rounded-md p-2 hover:bg-accent/40">
+ <Checkbox
+ checked={hasGlobalRoleAssignment(role.id)}
+ {disabled}
+ onCheckedChange={(checked) => toggleQuickPreset(role.id, checked === true)}
+ />
+ <div class="flex flex-col gap-1">
+ <div class="flex items-center gap-2">
+ <StatusBadge text={role.name} variant={getRoleVariant(role.id)} size="sm" minWidth="none" />
+ <span class="text-xs text-muted-foreground">{m.users_role_assignments_scope_global()}</span>
+ </div>
+ {#if role.description}
+ <span class="text-muted-foreground text-xs">{role.description}</span>
+ {/if}
+ </div>
+ </label>
+ {/each}
+ </div>
+ {/if}
+
{#if assignments.length === 0}
<p class="text-muted-foreground rounded-md border border-dashed p-4 text-center text-sm">
{m.users_role_assignments_description()}
diff --git a/frontend/src/lib/components/role-editor/permission-picker.svelte b/frontend/src/lib/components/role-editor/permission-picker.svelte
index b38fa7654..8c2dd6c39 100644
--- a/frontend/src/lib/components/role-editor/permission-picker.svelte
+++ b/frontend/src/lib/components/role-editor/permission-picker.svelte
@@ -3,7 +3,8 @@
import { Checkbox } from '$lib/components/ui/checkbox';
import { Input } from '$lib/components/ui/input';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
- import type { PermissionsManifest, PermissionResource, PermissionAction } from '$lib/types/auth';
+ import type { PermissionsManifest, PermissionResource, PermissionAction, PermissionPreset } from '$lib/types/auth';
+ import { normalizePermissionSelection } from '$lib/utils/permissions';
import { m } from '$lib/paraglide/messages';
type Props = {
@@ -40,9 +41,14 @@
);
const selectedSet = $derived(new Set(selected));
+ const presets = $derived(manifest.presets ?? []);
const openValues: string[] = $derived(normalizedQuery ? filteredGroups.map((g) => g.resource.key) : []);
+ function replaceSelected(next: string[]) {
+ selected = normalizePermissionSelection(manifest, next);
+ }
+
function countSelectedInGroup(resource: PermissionResource): number {
let count = 0;
for (const action of resource.actions) {
@@ -63,9 +69,9 @@
const groupPerms = resource.actions.map((a) => a.permission);
if (checked) {
const without = selected.filter((p) => !groupPerms.includes(p));
- selected = [...without, ...groupPerms];
+ replaceSelected([...without, ...groupPerms]);
} else {
- selected = selected.filter((p) => !groupPerms.includes(p));
+ replaceSelected(selected.filter((p) => !groupPerms.includes(p)));
}
}
@@ -73,15 +79,48 @@
if (disabled) return;
if (checked) {
if (!selected.includes(permission)) {
- selected = [...selected, permission];
+ replaceSelected([...selected, permission]);
}
} else {
- selected = selected.filter((p) => p !== permission);
+ replaceSelected(selected.filter((p) => p !== permission));
+ }
+ }
+
+ function isPresetSelected(preset: PermissionPreset): boolean {
+ return preset.permissions.length > 0 && preset.permissions.every((permission) => selectedSet.has(permission));
+ }
+
+ function togglePreset(preset: PermissionPreset, checked: boolean) {
+ if (disabled) return;
+ if (checked) {
+ replaceSelected([...selected, ...preset.permissions]);
+ } else {
+ replaceSelected(selected.filter((permission) => !preset.permissions.includes(permission)));
}
}
</script>
<div class="space-y-4">
+ {#if presets.length > 0}
+ <div class="space-y-2 rounded-md border p-3">
+ {#each presets as preset (preset.key)}
+ <label class="flex cursor-pointer items-start gap-3 rounded-md p-2 hover:bg-accent/40">
+ <Checkbox
+ checked={isPresetSelected(preset)}
+ {disabled}
+ onCheckedChange={(checked) => togglePreset(preset, checked === true)}
+ />
+ <div class="flex flex-col gap-0.5">
+ <span class="text-sm leading-none font-medium">{preset.label}</span>
+ {#if preset.description}
+ <span class="text-muted-foreground text-xs">{preset.description}</span>
+ {/if}
+ </div>
+ </label>
+ {/each}
+ </div>
+ {/if}
+
{#if showSearch}
<Input type="text" placeholder={m.permissions_search_placeholder()} bind:value={query} {disabled} />
{/if}
diff --git a/frontend/src/lib/components/role-editor/role-editor.svelte b/frontend/src/lib/components/role-editor/role-editor.svelte
index b2c744fcc..4a03b24ca 100644
--- a/frontend/src/lib/components/role-editor/role-editor.svelte
+++ b/frontend/src/lib/components/role-editor/role-editor.svelte
@@ -5,6 +5,7 @@
import StatusBadge from '$lib/components/badges/status-badge.svelte';
import PermissionPicker from './permission-picker.svelte';
import type { Role, PermissionsManifest } from '$lib/types/auth';
+ import { normalizePermissionSelection } from '$lib/utils/permissions';
import { CopyIcon } from '$lib/icons';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/settings';
@@ -32,7 +33,7 @@
const formData = $derived({
name: role?.name ?? '',
description: role?.description ?? '',
- permissions: role?.permissions ?? []
+ permissions: normalizePermissionSelection(manifest, role?.permissions ?? [])
});
const { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
diff --git a/frontend/src/lib/components/sheets/api-key-form-sheet.svelte b/frontend/src/lib/components/sheets/api-key-form-sheet.svelte
index 91e2e4b88..fb99f9d29 100644
--- a/frontend/src/lib/components/sheets/api-key-form-sheet.svelte
+++ b/frontend/src/lib/components/sheets/api-key-form-sheet.svelte
@@ -5,6 +5,7 @@
import PermissionPicker from '$lib/components/role-editor/permission-picker.svelte';
import type { ApiKey } from '$lib/types/auth';
import type { PermissionsManifest, ApiKeyPermissionGrant } from '$lib/types/auth';
+ import { normalizePermissionSelection } from '$lib/utils/permissions';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/settings';
import * as m from '$lib/paraglide/messages.js';
@@ -52,7 +53,10 @@
name: apiKeyToEdit?.name || '',
description: apiKeyToEdit?.description || '',
expiresAt: apiKeyToEdit?.expiresAt ? new Date(apiKeyToEdit.expiresAt) : undefined,
- permissions: availablePermissions.map((p) => p.permission)
+ permissions: normalizePermissionSelection(
+ manifest,
+ availablePermissions.map((p) => p.permission)
+ )
});
let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.ts
index 7b9d8e620..87abdd1cb 100644
--- a/frontend/src/lib/config/navigation-config.ts
+++ b/frontend/src/lib/config/navigation-config.ts
@@ -67,6 +67,41 @@ export type NavigationSections = {
settingsItems: NavigationItem[];
};
+const CUSTOMIZE_LANDING_PERMISSIONS = [
+ 'customize:manage',
+ 'templates:list',
+ 'templates:read',
+ 'registries:list',
+ 'registries:read',
+ 'git-repositories:list',
+ 'git-repositories:read'
+];
+
+const SETTINGS_LANDING_PERMISSIONS = [
+ 'settings:read',
+ 'apikeys:list',
+ 'apikeys:read',
+ 'webhooks:list',
+ 'jobs:manage',
+ 'notifications:manage',
+ 'users:list',
+ 'users:read',
+ 'roles:list',
+ 'roles:read',
+ 'diagnostics:read'
+];
+
+// `/settings` is a mixed landing page: some subpages are global-only while
+// others are driven by the currently selected environment (for example
+// webhooks, notifications, and jobs). We intentionally use env scope here so
+// the landing page is reachable when the selected environment grants one of
+// those env-scoped capabilities.
+const SETTINGS_LANDING_RULE: RouteAccessRule = {
+ prefix: '/settings',
+ perms: SETTINGS_LANDING_PERMISSIONS,
+ scope: 'env'
+};
+
export const navigationItems: NavigationSections = {
managementItems: [
{
@@ -99,7 +134,6 @@ export const navigationItems: NavigationSections = {
icon: CustomizeIcon,
shortcut: ['mod', '4'],
scope: 'global',
- requiredPermission: 'customize:manage',
items: [
{
title: m.templates_title(),
@@ -217,8 +251,6 @@ export const navigationItems: NavigationSections = {
url: '/settings',
icon: SettingsIcon,
shortcut: ['mod', '0'],
- scope: 'global',
- requiredPermission: 'settings:read',
items: [
{
title: m.api_key_page_title(),
@@ -405,9 +437,11 @@ export function getRouteAccessRules(): RouteAccessRule[] {
const out: RouteAccessRule[] = [];
routeAccessRulesForItems(navigationItems.managementItems, out);
routeAccessRulesForItems(navigationItems.resourceItems, out);
+ out.push({ prefix: '/customize', perms: CUSTOMIZE_LANDING_PERMISSIONS, scope: 'global' });
out.push({ prefix: '/swarm', perms: ['swarm:read'], scope: 'env' });
routeAccessRulesForItems(navigationItems.swarmItems, out);
routeAccessRulesForItems(navigationItems.settingsItems, out);
+ out.push(SETTINGS_LANDING_RULE);
return out;
}
@@ -417,6 +451,7 @@ export function getRouteFallbackRules(): RouteAccessRule[] {
rule.prefix === '/dashboard' ||
rule.prefix === '/containers' ||
rule.prefix === '/projects' ||
+ rule.prefix === '/customize' ||
rule.prefix === '/images' ||
rule.prefix === '/volumes' ||
rule.prefix === '/networks' ||
diff --git a/frontend/src/lib/stores/user-store.ts b/frontend/src/lib/stores/user-store.ts
index 2edd4f3f2..be659ea19 100644
--- a/frontend/src/lib/stores/user-store.ts
+++ b/frontend/src/lib/stores/user-store.ts
@@ -51,10 +51,11 @@ const hasAnyPermission = (perms: string[], envId?: string): boolean => {
return perms.some((p) => set.has(p));
};
-/** Returns true if the caller holds the built-in Admin role globally OR is a sudo caller. */
+/** Returns true if the caller effectively holds global administrator access. */
const isGlobalAdmin = (): boolean => {
const user = get(userStore);
if (!user) return false;
+ if (typeof user.isGlobalAdmin === 'boolean') return user.isGlobalAdmin;
const global = user.permissionsByEnv?.[GLOBAL_SCOPE];
if (global?.includes(SUDO_PERMISSION)) return true;
return !!user.roleAssignments?.some((a) => a.roleId === BUILT_IN_ROLE_ADMIN && !a.environmentId);
diff --git a/frontend/src/lib/types/auth.ts b/frontend/src/lib/types/auth.ts
index 461fcd829..4034b3605 100644
--- a/frontend/src/lib/types/auth.ts
+++ b/frontend/src/lib/types/auth.ts
@@ -68,6 +68,7 @@ export type UpdateOidcRoleMapping = CreateOidcRoleMapping;
export type PermissionsManifest = {
resources: PermissionResource[];
+ presets?: PermissionPreset[];
};
export type PermissionResource = {
@@ -82,6 +83,14 @@ export type PermissionAction = {
permission: string;
label: string;
description?: string;
+ requires?: string[];
+};
+
+export type PermissionPreset = {
+ key: string;
+ label: string;
+ description?: string;
+ permissions: string[];
};
export type ApiKeyPermissionGrant = {
@@ -108,6 +117,7 @@ export type User = {
email?: string;
roleAssignments: RoleAssignmentSummary[];
permissionsByEnv: Record<string, string[]>;
+ isGlobalAdmin?: boolean;
canDelete?: boolean;
createdAt: string;
lastLogin?: string;
@@ -125,6 +135,7 @@ export type CreateUser = Omit<
| 'lastLogin'
| 'oidcSubjectId'
| 'passwordHash'
+ | 'isGlobalAdmin'
| 'requiresPasswordChange'
| 'roleAssignments'
| 'permissionsByEnv'
diff --git a/frontend/src/lib/utils/auth.ts b/frontend/src/lib/utils/auth.ts
index 7644fc854..8a7256be8 100644
--- a/frontend/src/lib/utils/auth.ts
+++ b/frontend/src/lib/utils/auth.ts
@@ -62,6 +62,7 @@ const PROTECTED_PREFIXES = [
const UNAUTHENTICATED_ONLY_PREFIXES = ['/login', '/oidc/login', '/oidc/callback', '/auth/oidc/callback', '/img', '/favicon.ico'];
function isUserGlobalAdmin(user: User): boolean {
+ if (typeof user.isGlobalAdmin === 'boolean') return user.isGlobalAdmin;
const global = user.permissionsByEnv?.[GLOBAL_SCOPE];
if (global?.includes(SUDO_PERMISSION)) return true;
return !!user.roleAssignments?.some((a) => a.roleId === BUILT_IN_ROLE_ADMIN && !a.environmentId);
diff --git a/frontend/src/lib/utils/permissions.ts b/frontend/src/lib/utils/permissions.ts
new file mode 100644
index 000000000..e227e4105
--- /dev/null
+++ b/frontend/src/lib/utils/permissions.ts
@@ -0,0 +1,26 @@
+import type { PermissionsManifest } from '$lib/types/auth';
+
+export function normalizePermissionSelection(manifest: PermissionsManifest, selected: string[]): string[] {
+ const requiredByPermission = new Map<string, string[]>();
+ for (const resource of manifest.resources) {
+ for (const action of resource.actions) {
+ requiredByPermission.set(action.permission, action.requires ?? []);
+ }
+ }
+
+ const out = new Set(selected);
+ let changed = true;
+ while (changed) {
+ changed = false;
+ for (const permission of out) {
+ for (const required of requiredByPermission.get(permission) ?? []) {
+ if (!out.has(required)) {
+ out.add(required);
+ changed = true;
+ }
+ }
+ }
+ }
+
+ return [...out];
+}
diff --git a/frontend/src/routes/(app)/account/+page.svelte b/frontend/src/routes/(app)/account/+page.svelte
index c43a94be5..64ceaabf3 100644
--- a/frontend/src/routes/(app)/account/+page.svelte
+++ b/frontend/src/routes/(app)/account/+page.svelte
@@ -5,6 +5,7 @@
import { mode, toggleMode } from 'mode-watcher';
import { format, formatDistanceToNow } from 'date-fns';
import HeaderCard from '$lib/components/header-card.svelte';
+ import ApiKeyFormSheet from '$lib/components/sheets/api-key-form-sheet.svelte';
import { Card } from '$lib/components/ui/card';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label';
@@ -14,11 +15,12 @@
import LocalePicker from '$lib/components/locale-picker.svelte';
import { userService } from '$lib/services/user-service';
import { apiKeyService } from '$lib/services/api-key-service';
+ import { roleService } from '$lib/services/role-service';
import userStore from '$lib/stores/user-store';
import settingsStore from '$lib/stores/config-store';
import { getDefaultProfilePicture } from '$lib/utils/docker';
import { GLOBAL_SCOPE } from '$lib/types/auth';
- import type { ApiKey, ApiKeyCreated } from '$lib/types/auth';
+ import type { ApiKey, ApiKeyCreated, CreateApiKey, PermissionsManifest } from '$lib/types/auth';
import { UserIcon, LogoutIcon, ShieldAlertIcon, SunIcon, MoonIcon, ApiKeyIcon, AddIcon, CopyIcon, TrashIcon } from '$lib/icons';
let { data: _data }: PageProps = $props();
@@ -76,10 +78,9 @@
let apiKeys = $state<ApiKey[]>([]);
let apiKeysLoading = $state(false);
let showCreateKeyForm = $state(false);
- let newKeyName = $state('');
- let newKeyDescription = $state('');
let creatingKey = $state(false);
let createdKey = $state<ApiKeyCreated | null>(null);
+ let permissionsManifest = $state<PermissionsManifest | null>(null);
$effect(() => {
if (!profileLoaded && currentUser) {
@@ -168,18 +169,19 @@
}
}
- async function createApiKey() {
- if (!newKeyName.trim() || creatingKey) return;
+ async function loadPermissionsManifest() {
+ try {
+ permissionsManifest = await roleService.getPermissionsManifest();
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : 'Failed to load available permissions');
+ }
+ }
+
+ async function createApiKey({ apiKey }: { apiKey: CreateApiKey; isEditMode: boolean; apiKeyId?: string }) {
creatingKey = true;
try {
- const created = await apiKeyService.createMine({
- name: newKeyName.trim(),
- description: newKeyDescription.trim() || undefined,
- permissions: []
- });
+ const created = await apiKeyService.createMine(apiKey);
createdKey = created;
- newKeyName = '';
- newKeyDescription = '';
showCreateKeyForm = false;
await loadApiKeys();
} catch (err) {
@@ -207,6 +209,7 @@
onMount(() => {
void loadApiKeys();
+ void loadPermissionsManifest();
});
async function logoutAllOther() {
@@ -285,38 +288,33 @@
/>
</div>
</div>
-
- {#if isOidcUser}
- <p class="text-muted-foreground text-xs">Profile fields are managed by your identity provider.</p>
- {:else}
- <div class="flex flex-col-reverse items-stretch justify-end gap-2 sm:flex-row sm:items-center">
- <ArcaneButton
- action="cancel"
- tone="ghost"
- customLabel="Reset"
- onclick={resetProfile}
- disabled={!profileDirty || profileSaving}
- />
- <ArcaneButton
- action="save"
- customLabel="Save changes"
- onclick={saveProfile}
- loading={profileSaving}
- disabled={!profileDirty || profileSaving}
- />
- </div>
- {/if}
+ <div class="flex justify-end gap-2">
+ <ArcaneButton
+ action="cancel"
+ tone="outline"
+ customLabel="Reset"
+ onclick={resetProfile}
+ disabled={!profileDirty || profileSaving}
+ />
+ <ArcaneButton
+ action="save"
+ customLabel="Save profile"
+ onclick={saveProfile}
+ loading={profileSaving}
+ disabled={!profileDirty || profileSaving || isOidcUser}
+ />
+ </div>
</div>
</Card>
<!-- Password -->
- {#if !isOidcUser && !autoLoginEnabled}
+ {#if !isOidcUser}
<Card class="overflow-hidden">
<div class="border-b p-4 sm:p-6">
<h2 class="text-base font-semibold tracking-tight sm:text-lg">Password</h2>
- <p class="text-muted-foreground mt-1 text-xs sm:text-sm">Changing your password signs out every other session</p>
+ <p class="text-muted-foreground mt-1 text-xs sm:text-sm">Change your account password</p>
</div>
- <div class="space-y-4 p-4 sm:p-6">
+ <div class="space-y-5 p-4 sm:p-6">
<div class="space-y-2">
<Label for="account-current-password">Current password</Label>
<Input
@@ -404,6 +402,7 @@
customLabel="New key"
icon={AddIcon}
onclick={() => (showCreateKeyForm = true)}
+ disabled={!permissionsManifest}
/>
{/if}
</div>
@@ -440,43 +439,6 @@
</div>
{/if}
- {#if showCreateKeyForm}
- <div class="mb-4 space-y-3 rounded-lg border p-4">
- <div class="space-y-2">
- <Label for="api-key-name">Key name</Label>
- <Input id="api-key-name" bind:value={newKeyName} placeholder="e.g. CI deploy bot" />
- </div>
- <div class="space-y-2">
- <Label for="api-key-description">Description (optional)</Label>
- <Input id="api-key-description" bind:value={newKeyDescription} placeholder="What is this key for?" />
- </div>
- <p class="text-muted-foreground text-xs">
- Keys are created without explicit permission scopes. An admin can add scopes later from Settings &rarr; API Keys
- if needed.
- </p>
- <div class="flex justify-end gap-2">
- <ArcaneButton
- action="cancel"
- tone="ghost"
- customLabel="Cancel"
- onclick={() => {
- showCreateKeyForm = false;
- newKeyName = '';
- newKeyDescription = '';
- }}
- disabled={creatingKey}
- />
- <ArcaneButton
- action="create"
- customLabel="Create key"
- onclick={createApiKey}
- loading={creatingKey}
- disabled={!newKeyName.trim() || creatingKey}
- />
- </div>
- </div>
- {/if}
-
{#if apiKeysLoading && apiKeys.length === 0}
<div class="text-muted-foreground py-8 text-center text-sm">Loading keys…</div>
{:else if apiKeys.length === 0}
@@ -647,3 +609,14 @@
<div class="text-muted-foreground py-12 text-center text-sm">Loading account…</div>
{/if}
</div>
+
+{#if permissionsManifest}
+ <ApiKeyFormSheet
+ bind:open={showCreateKeyForm}
+ apiKeyToEdit={null}
+ manifest={permissionsManifest}
+ availablePermissions={[]}
+ onSubmit={createApiKey}
+ isLoading={creatingKey}
+ />
+{/if}
diff --git a/frontend/src/routes/(app)/customize/+page.svelte b/frontend/src/routes/(app)/customize/+page.svelte
index c48721893..0ea3a6529 100644
--- a/frontend/src/routes/(app)/customize/+page.svelte
+++ b/frontend/src/routes/(app)/customize/+page.svelte
@@ -1,13 +1,17 @@
<script lang="ts">
import { goto } from '$app/navigation';
+ import { get } from 'svelte/store';
import { onMount } from 'svelte';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import { Card } from '$lib/components/ui/card';
import { m } from '$lib/paraglide/messages';
import { UiConfigDisabledTag } from '$lib/components/badges/index.js';
import { customizeSearchService } from '$lib/services/customize-search';
+ import userStore from '$lib/stores/user-store';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
import type { CustomizeCategory } from '$lib/types/shared';
import { debounced } from '$lib/utils/ws';
+ import { getAuthRedirectPath } from '$lib/utils/auth';
import * as InputGroup from '$lib/components/ui/input-group/index.js';
import { getCustomizeSubpageUrlsInNavOrder } from '$lib/config/navigation-config';
import {
@@ -38,9 +42,13 @@
'git-branch': GitBranchIcon
};
+ function isAccessibleCategory(category: CustomizeCategory) {
+ return getAuthRedirectPath(category.url, get(userStore), environmentStore.selected?.id) === null;
+ }
+
onMount(async () => {
try {
- customizeCategories = orderCategoriesByNav(await customizeSearchService.getCategories());
+ customizeCategories = orderCategoriesByNav((await customizeSearchService.getCategories()).filter(isAccessibleCategory));
} catch (error) {
console.error('Failed to load categories:', error);
}
@@ -78,7 +86,7 @@
try {
const response = await customizeSearchService.search(trimmedQuery);
if (requestId === currentSearchRequest) {
- searchResults = response.results || [];
+ searchResults = (response.results || []).filter(isAccessibleCategory);
isSearching = false;
}
} catch (error) {
diff --git a/frontend/src/routes/(app)/settings/+page.svelte b/frontend/src/routes/(app)/settings/+page.svelte
index 2eb8ed562..bd3f64baa 100644
--- a/frontend/src/routes/(app)/settings/+page.svelte
+++ b/frontend/src/routes/(app)/settings/+page.svelte
@@ -1,5 +1,6 @@
<script lang="ts">
import { goto } from '$app/navigation';
+ import { get } from 'svelte/store';
import { onMount } from 'svelte';
import {
SearchIcon,
@@ -23,8 +24,11 @@
import { m } from '$lib/paraglide/messages';
import { UiConfigDisabledTag } from '$lib/components/badges/index.js';
import { settingsSearchService } from '$lib/services/settings-search';
+ import userStore from '$lib/stores/user-store';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
import type { SettingsCategory } from '$lib/types/shared';
import { debounced } from '$lib/utils/ws';
+ import { getAuthRedirectPath } from '$lib/utils/auth';
import * as InputGroup from '$lib/components/ui/input-group/index.js';
import { getSettingsSubpageUrlsInNavOrder } from '$lib/config/navigation-config';
import HeaderCard from '$lib/components/header-card.svelte';
@@ -57,7 +61,11 @@
onMount(async () => {
try {
- settingsCategories = orderCategoriesByNav((await settingsSearchService.getCategories()).filter(isVisibleCategory));
+ settingsCategories = orderCategoriesByNav(
+ (await settingsSearchService.getCategories()).filter(
+ (category) => isVisibleCategory(category) && isAccessibleCategory(category)
+ )
+ );
} catch (error) {
console.error('Failed to load categories:', error);
}
@@ -82,7 +90,9 @@
try {
const response = await settingsSearchService.search(trimmedQuery);
if (requestId === currentSearchRequest) {
- searchResults = (response.results || []).filter(isVisibleCategory);
+ searchResults = (response.results || []).filter(
+ (category) => isVisibleCategory(category) && isAccessibleCategory(category)
+ );
isSearching = false;
}
} catch (error) {
@@ -106,6 +116,10 @@
return !hiddenCategoryUrls.has(category.url);
}
+ function isAccessibleCategory(category: SettingsCategory) {
+ return getAuthRedirectPath(category.url, get(userStore), environmentStore.selected?.id) === null;
+ }
+
function orderCategoriesByNav(categories: SettingsCategory[]) {
const navUrls = getSettingsSubpageUrlsInNavOrder();
const categoriesByUrl = new Map(categories.map((category) => [category.url, category]));
diff --git a/frontend/src/routes/(auth)/oidc/callback/+page.svelte b/frontend/src/routes/(auth)/oidc/callback/+page.svelte
index 54dd5328a..0f11ce1c5 100644
--- a/frontend/src/routes/(auth)/oidc/callback/+page.svelte
+++ b/frontend/src/routes/(auth)/oidc/callback/+page.svelte
@@ -102,6 +102,7 @@
m.common_unknown(),
roleAssignments: [],
permissionsByEnv: {},
+ isGlobalAdmin: false,
createdAt: new Date().toISOString()
};
diff --git a/types/role/role.go b/types/role/role.go
index f0c156288..375db3337 100644
--- a/types/role/role.go
+++ b/types/role/role.go
@@ -99,6 +99,7 @@ type UpdateOidcRoleMapping struct {
// picker without hard-coding the taxonomy.
type PermissionsManifest struct {
Resources []PermissionResource `json:"resources" doc:"Resource groups, in display order"`
+ Presets []PermissionPreset `json:"presets,omitempty" doc:"Optional preset permission bundles for bulk selection in the UI"`
}
// PermissionResource is one resource group in the manifest (e.g. "containers").
@@ -111,10 +112,19 @@ type PermissionResource struct {
// PermissionAction is one permission inside a resource group.
type PermissionAction struct {
- Key string `json:"key" doc:"Action verb" example:"start"`
- Permission string `json:"permission" doc:"Fully-qualified permission string used in role definitions" example:"containers:start"`
- Label string `json:"label" doc:"Human-readable label" example:"Start"`
- Description string `json:"description,omitempty" doc:"Optional longer description"`
+ Key string `json:"key" doc:"Action verb" example:"start"`
+ Permission string `json:"permission" doc:"Fully-qualified permission string used in role definitions" example:"containers:start"`
+ Label string `json:"label" doc:"Human-readable label" example:"Start"`
+ Description string `json:"description,omitempty" doc:"Optional longer description"`
+ Requires []string `json:"requires,omitempty" doc:"Permissions that should be auto-selected when this permission is chosen in the UI"`
+}
+
+// PermissionPreset is an optional bulk-selection bundle exposed to the UI.
+type PermissionPreset struct {
+ Key string `json:"key" doc:"Stable preset key" example:"editor"`
+ Label string `json:"label" doc:"Human-readable preset label" example:"All permissions (non-admin)"`
+ Description string `json:"description,omitempty" doc:"Optional longer description for the preset"`
+ Permissions []string `json:"permissions" doc:"Permissions included when the preset is selected"`
}
// ApiKeyPermissionGrant is one permission grant on an API key, optionally
diff --git a/types/user/user.go b/types/user/user.go
index 887fb9954..f0be39d37 100644
--- a/types/user/user.go
+++ b/types/user/user.go
@@ -37,6 +37,7 @@ type User struct {
Email *string `json:"email,omitempty" doc:"Email address of the user" example:"[email protected]"`
RoleAssignments []RoleAssignmentSummary `json:"roleAssignments" doc:"Role assignments held by the user"`
PermissionsByEnv map[string][]string `json:"permissionsByEnv" doc:"Permissions the user effectively holds, keyed by environment ID. The 'global' key holds permissions that apply across every environment (and to org-level endpoints)."`
+ IsGlobalAdmin bool `json:"isGlobalAdmin" doc:"Whether the user effectively holds global administrator access"`
CanDelete bool `json:"canDelete" doc:"Whether the user can currently be deleted"`
OidcSubjectId *string `json:"oidcSubjectId,omitempty" doc:"OIDC subject identifier for SSO users"`
Locale *string `json:"locale,omitempty" doc:"Locale preference of the user" example:"en-US"`