Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: better RBAC layout filters and catalog (#2784)
Kyle Mendellda70b3f140c0
diff --git a/AGENTS.md b/AGENTS.mdindex deb1403f6..057c16c16 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -113,6 +113,17 @@ Domain types shared between backend and CLI. Each domain has its own package (e.The CLI is a Cobra application. Commands live under `cli/pkg/<domain>/`, shared command helpers live under `cli/internal/`, and public API shapes should come from `types/` instead of duplicating structs.+## RBAC Architecture++Keep Arcane RBAC split into three distinct layers:++- Permission catalog: `backend/pkg/authz/catalog.go` and `permissions.go` are the source of truth for raw capabilities, scope taxonomy, labels, permission constants, and built-in bundles.+- Access-surface registry: `backend/pkg/authz/access_policy.go` is the source of truth for page, route, landing, settings category, and customize category reachability metadata. Use it when filtering backend category responses or publishing frontend access policy.+- Frontend UX gates: navigation config owns presentation only: labels, icons, order, grouping, and stable `accessSurfaceId` references. Route redirects, sidebar visibility, mobile nav, and landing cards evaluate backend-published access surfaces instead of duplicating permission arrays.+- Backend enforcement: middleware, handlers, and services remain authoritative. Access surfaces are advisory UI metadata and must not replace `RequirePermission`, `RequireGlobalAdmin`, or service-level validation such as anti-escalation checks.++Admin semantics come from effective permissions: `PermissionSet.IsGlobalAdmin()` on the backend and `isGlobalAdmin` in user DTOs on the frontend. Do not infer global administrator access from built-in role IDs in frontend authorization checks; role IDs may still be used for labels, badge colors, presets, and assignment UX.+## Critical Patterns### Svelte 5 ONLY — No Svelte 4 Syntaxdiff --git a/backend/api/handlers/customize.go b/backend/api/handlers/customize.goindex f03a74077..597ca4262 100644--- a/backend/api/handlers/customize.go+++ b/backend/api/handlers/customize.go@@ -35,13 +35,6 @@ 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{@@ -75,32 +68,13 @@ func RegisterCustomize(api huma.API, customizeSearchService *services.CustomizeS}, 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) {+ if authz.CanAccessCustomizeCategory(ps, cat.ID, "") {filtered = append(filtered, cat)}}diff --git a/backend/api/handlers/roles.go b/backend/api/handlers/roles.goindex 240f04b7b..377895b03 100644--- a/backend/api/handlers/roles.go+++ b/backend/api/handlers/roles.go@@ -418,7 +418,8 @@ func buildPermissionsManifestInternal() roletypes.PermissionsManifest {}}return roletypes.PermissionsManifest{- Resources: resources,+ Resources: resources,+ AccessSurfaces: buildAccessSurfaceManifestInternal(),Presets: []roletypes.PermissionPreset{{Key: "editor",@@ -436,6 +437,26 @@ func buildPermissionsManifestInternal() roletypes.PermissionsManifest {}}+func buildAccessSurfaceManifestInternal() []roletypes.AccessSurface {+ surfaces := authz.AccessSurfaces()+ out := make([]roletypes.AccessSurface, len(surfaces))+ for i, surface := range surfaces {+ out[i] = roletypes.AccessSurface{+ ID: surface.ID,+ Kind: surface.Kind,+ URL: surface.URL,+ Label: surface.Label,+ AccessMode: surface.AccessMode,+ MatchMode: surface.MatchMode,+ ScopeMode: surface.ScopeMode,+ Permissions: append([]string(nil), surface.Permissions...),+ Children: append([]string(nil), surface.Children...),+ FallbackOrder: surface.FallbackOrder,+ }+ }+ return out+}+func requiredPermissionsForPickerInternal(permission string) []string {switch permission {case authz.PermSettingsWrite,diff --git a/backend/api/handlers/roles_access_policy_test.go b/backend/api/handlers/roles_access_policy_test.gonew file mode 100644index 000000000..fcf3a04d2--- /dev/null+++ b/backend/api/handlers/roles_access_policy_test.go@@ -0,0 +1,34 @@+package handlers++import (+ "testing"++ "github.com/getarcaneapp/arcane/backend/pkg/authz"+ "github.com/stretchr/testify/require"+)++func TestBuildPermissionsManifestIncludesAccessSurfaces(t *testing.T) {+ manifest := buildPermissionsManifestInternal()++ require.NotEmpty(t, manifest.Resources)+ require.NotEmpty(t, manifest.AccessSurfaces)++ surfacesByID := make(map[string]struct{}, len(manifest.AccessSurfaces))+ for _, surface := range manifest.AccessSurfaces {+ surfacesByID[surface.ID] = struct{}{}+ }++ for _, id := range []string{+ "landing.settings",+ "landing.customize",+ "settings.category.webhooks",+ "customize.category.templates",+ "route.dashboard",+ } {+ _, ok := surfacesByID[id]+ require.True(t, ok, "expected manifest to include access surface %s", id)+ }++ registrySurfaces := authz.AccessSurfaces()+ require.Len(t, manifest.AccessSurfaces, len(registrySurfaces))+}diff --git a/backend/api/handlers/settings.go b/backend/api/handlers/settings.goindex 84f8e2546..f9caed42a 100644--- a/backend/api/handlers/settings.go+++ b/backend/api/handlers/settings.go@@ -71,20 +71,6 @@ 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:\...)@@ -201,50 +187,34 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s}, h.GetCategories)}-func permissionSetAllowsAtAnyScopeInternal(ps *authz.PermissionSet, perm string) bool {+func filterSettingsCategoriesInternal(ps *authz.PermissionSet, categories []category.Category) []category.Category {if ps == nil {- return false- }- if ps.Allows(perm, "") {- return true+ return []category.Category{}}- for envID := range ps.PerEnv {- if ps.Allows(perm, envID) {- return true+ filtered := make([]category.Category, 0, len(categories))+ for _, cat := range categories {+ if canAccessSettingsCategoryAtAnyScopeInternal(ps, cat.ID) {+ filtered = append(filtered, cat)}}- return false+ return filtered}-func canAccessSettingsCategoryInternal(ps *authz.PermissionSet, categoryID string) bool {+func canAccessSettingsCategoryAtAnyScopeInternal(ps *authz.PermissionSet, categoryID string) bool {if ps == nil {return false}- perms, ok := settingsCategoryPermissionsInternal[categoryID]- if !ok {- return false+ if authz.CanAccessSettingsCategory(ps, categoryID, "") {+ return true}- for _, perm := range perms {- if permissionSetAllowsAtAnyScopeInternal(ps, perm) {+ for envID := range ps.PerEnv {+ if authz.CanAccessSettingsCategory(ps, categoryID, envID) {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 settingsDtodiff --git a/backend/internal/services/settings_search_service.go b/backend/internal/services/settings_search_service.goindex feb14850d..5b9fa414d 100644--- a/backend/internal/services/settings_search_service.go+++ b/backend/internal/services/settings_search_service.go@@ -63,6 +63,10 @@ func (s *SettingsSearchService) buildCategoriesFromModel() []category.Category {desc := metaTag["description"]keywords := utils.ParseKeywords(metaTag["keywords"])categoryID := metaTag["category"]+ if categoryID == "" {+ catMeta := utils.ParseMetaTag(field.Tag.Get("catmeta"))+ categoryID = catMeta["id"]+ }if categoryID == "" {categoryID = "jobs"}diff --git a/backend/pkg/authz/access_policy.go b/backend/pkg/authz/access_policy.gonew file mode 100644index 000000000..8d259cc8c--- /dev/null+++ b/backend/pkg/authz/access_policy.go@@ -0,0 +1,271 @@+package authz++const (+ AccessSurfaceKindRoute = "route"+ AccessSurfaceKindSettingsCategory = "settings-category"+ AccessSurfaceKindCustomizeCategory = "customize-category"+ AccessSurfaceKindLanding = "landing"++ AccessModePermissions = "permissions"+ AccessModeAnyChild = "any-child"++ AccessMatchModeAnyOf = "any-of"+ AccessMatchModeAllOf = "all-of"++ AccessScopeModeGlobalOnly = "global-only"+ AccessScopeModeSelectedEnvPlusGlobal = "selected-env-plus-global"+ AccessScopeModeAnyEffectiveScope = "any-effective-scope"+)++// AccessSurface describes one frontend-visible surface whose reachability is+// derived from backend-owned permission metadata. This is decision metadata for+// UX gating; backend middleware and service checks remain authoritative.+type AccessSurface struct {+ ID string+ Kind string+ URL string+ Label string+ AccessMode string+ MatchMode string+ ScopeMode string+ Permissions []string+ Children []string+ FallbackOrder int+}++var accessSurfacesInternal = []AccessSurface{+ landingSurfaceInternal("landing.customize", "/customize", "Customize", []string{+ "customize.category.templates",+ "customize.category.registries",+ "customize.category.variables",+ "customize.category.git-repositories",+ }, 40),+ landingSurfaceInternal("landing.settings", "/settings", "Settings", []string{+ "settings.category.activity",+ "settings.category.apikeys",+ "settings.category.appearance",+ "settings.category.authentication",+ "settings.category.build",+ "settings.category.jobschedule",+ "settings.category.notifications",+ "settings.category.roles",+ "settings.category.timeouts",+ "settings.category.users",+ "settings.category.webhooks",+ "settings.category.diagnostics",+ }, 120),++ routeSurfaceInternal("route.dashboard", "/dashboard", "Dashboard", AccessScopeModeSelectedEnvPlusGlobal, []string{PermDashboardRead}, 10),+ routeSurfaceInternal("route.projects", "/projects", "Projects", AccessScopeModeSelectedEnvPlusGlobal, []string{PermProjectsList, PermProjectsRead}, 30),+ routeSurfaceInternal("route.environments", "/environments", "Environments", AccessScopeModeGlobalOnly, []string{PermEnvironmentsList, PermEnvironmentsRead}, 130),+ routeSurfaceInternal("route.environments.gitops", "/environments/{id}/gitops", "GitOps Syncs", AccessScopeModeSelectedEnvPlusGlobal, []string{PermGitOpsList, PermGitOpsRead}, 0),+ routeSurfaceInternal("route.containers", "/containers", "Containers", AccessScopeModeSelectedEnvPlusGlobal, []string{PermContainersList, PermContainersRead}, 20),+ routeSurfaceInternal("route.images", "/images", "Images", AccessScopeModeSelectedEnvPlusGlobal, []string{PermImagesList, PermImagesRead}, 50),+ routeSurfaceInternal("route.images.builds", "/images/builds", "Builds", AccessScopeModeSelectedEnvPlusGlobal, []string{PermImagesBuild}, 0),+ routeSurfaceInternal("route.images.vulnerabilities", "/images/vulnerabilities", "Vulnerabilities", AccessScopeModeSelectedEnvPlusGlobal, []string{PermVulnsRead}, 0),+ routeSurfaceInternal("route.updates", "/updates", "Image Updates", AccessScopeModeSelectedEnvPlusGlobal, []string{PermImageUpdatesRead}, 0),+ routeSurfaceInternal("route.networks", "/networks", "Networks", AccessScopeModeSelectedEnvPlusGlobal, []string{PermNetworksList, PermNetworksRead}, 70),+ routeSurfaceInternal("route.ports", "/ports", "Ports", AccessScopeModeSelectedEnvPlusGlobal, []string{PermContainersList}, 0),+ routeSurfaceInternal("route.networks.topology", "/networks/topology", "Network Topology", AccessScopeModeSelectedEnvPlusGlobal, []string{PermNetworksRead}, 0),+ routeSurfaceInternal("route.volumes", "/volumes", "Volumes", AccessScopeModeSelectedEnvPlusGlobal, []string{PermVolumesList, PermVolumesRead}, 60),+ routeSurfaceInternal("route.swarm", "/swarm", "Swarm", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmRead}, 0),+ routeSurfaceInternal("route.swarm.services", "/swarm/services", "Services", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmServices}, 80),+ routeSurfaceInternal("route.swarm.nodes", "/swarm/nodes", "Nodes", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmNodes}, 0),+ routeSurfaceInternal("route.swarm.tasks", "/swarm/tasks", "Tasks", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmRead}, 0),+ routeSurfaceInternal("route.swarm.stacks", "/swarm/stacks", "Stacks", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmStacks}, 90),+ routeSurfaceInternal("route.swarm.cluster", "/swarm/cluster", "Cluster", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmRead}, 100),+ routeSurfaceInternal("route.swarm.configs", "/swarm/configs", "Configs", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmConfigs}, 0),+ routeSurfaceInternal("route.swarm.secrets", "/swarm/secrets", "Secrets", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmSecrets}, 0),+ routeSurfaceInternal("route.events", "/events", "Events", AccessScopeModeGlobalOnly, []string{PermEventsRead}, 110),++ settingsCategorySurfaceInternal("activity", "/settings/activity", "Activity", AccessScopeModeGlobalOnly, []string{PermSettingsRead}),+ settingsCategorySurfaceInternal("apikeys", "/settings/api-keys", "API Keys", AccessScopeModeGlobalOnly, []string{PermApiKeysList, PermApiKeysRead}),+ settingsCategorySurfaceInternal("appearance", "/settings/appearance", "Appearance", AccessScopeModeGlobalOnly, []string{PermSettingsRead}),+ settingsCategorySurfaceInternal("authentication", "/settings/authentication", "Authentication", AccessScopeModeGlobalOnly, []string{PermSettingsRead}),+ settingsCategorySurfaceInternal("build", "/settings/builds", "Builds", AccessScopeModeGlobalOnly, []string{PermSettingsRead}),+ settingsCategorySurfaceInternal("jobschedule", "", "Job Schedule", AccessScopeModeSelectedEnvPlusGlobal, []string{PermJobsManage}),+ settingsCategorySurfaceInternal("notifications", "/settings/notifications", "Notifications", AccessScopeModeSelectedEnvPlusGlobal, []string{PermNotificationsManage}),+ settingsCategorySurfaceInternal("roles", "/settings/roles", "Roles", AccessScopeModeGlobalOnly, []string{PermRolesList, PermRolesRead}),+ settingsCategorySurfaceInternal("timeouts", "/settings/timeouts", "Timeouts", AccessScopeModeGlobalOnly, []string{PermSettingsRead}),+ settingsCategorySurfaceInternal("users", "/settings/users", "Users", AccessScopeModeGlobalOnly, []string{PermUsersList, PermUsersRead}),+ settingsCategorySurfaceInternal("webhooks", "/settings/webhooks", "Webhooks", AccessScopeModeSelectedEnvPlusGlobal, []string{PermWebhooksList}),+ settingsCategorySurfaceInternal("diagnostics", "/settings/diagnostics", "Diagnostics", AccessScopeModeGlobalOnly, []string{PermDiagnosticsRead}),++ customizeCategorySurfaceInternal("templates", "/customize/templates", "Templates", []string{PermCustomizeManage, PermTemplatesList, PermTemplatesRead}),+ customizeCategorySurfaceInternal("registries", "/customize/registries", "Container Registries", []string{PermCustomizeManage, PermRegistriesList, PermRegistriesRead}),+ customizeCategorySurfaceInternal("variables", "/customize/variables", "Variables", []string{PermCustomizeManage, PermTemplatesRead}),+ customizeCategorySurfaceInternal("git-repositories", "/customize/git-repositories", "Git Repositories", []string{PermCustomizeManage, PermGitReposList, PermGitReposRead}),+}++var accessSurfacesByIDInternal = buildAccessSurfaceIndexInternal(accessSurfacesInternal)++// AccessSurfaces returns a defensive copy of every backend-owned access+// surface in stable evaluation order.+func AccessSurfaces() []AccessSurface {+ out := make([]AccessSurface, len(accessSurfacesInternal))+ for i := range accessSurfacesInternal {+ out[i] = copyAccessSurfaceInternal(accessSurfacesInternal[i])+ }+ return out+}++// CanAccessSurface evaluates backend-owned UI reachability metadata for the+// caller. It is for advisory UX only; middleware and handlers still enforce+// permissions on actual API requests.+func CanAccessSurface(ps *PermissionSet, surfaceID, selectedEnvID string) bool {+ return canAccessSurfaceInternal(ps, surfaceID, selectedEnvID, make(map[string]struct{}))+}++// CanAccessSettingsCategory reports whether a settings category is reachable+// for the selected environment.+func CanAccessSettingsCategory(ps *PermissionSet, categoryID, selectedEnvID string) bool {+ return CanAccessSurface(ps, "settings.category."+categoryID, selectedEnvID)+}++// CanAccessCustomizeCategory reports whether a customize category is reachable.+func CanAccessCustomizeCategory(ps *PermissionSet, categoryID, selectedEnvID string) bool {+ return CanAccessSurface(ps, "customize.category."+categoryID, selectedEnvID)+}++func canAccessSurfaceInternal(ps *PermissionSet, surfaceID, selectedEnvID string, visiting map[string]struct{}) bool {+ if ps == nil {+ return false+ }+ if _, ok := visiting[surfaceID]; ok {+ return false+ }+ surface, ok := accessSurfacesByIDInternal[surfaceID]+ if !ok {+ return false+ }++ switch surface.AccessMode {+ case AccessModeAnyChild:+ visiting[surfaceID] = struct{}{}+ defer delete(visiting, surfaceID)+ for _, childID := range surface.Children {+ if canAccessSurfaceInternal(ps, childID, selectedEnvID, visiting) {+ return true+ }+ }+ return false+ case AccessModePermissions:+ return allowsSurfacePermissionsInternal(ps, surface, selectedEnvID)+ default:+ return false+ }+}++func allowsSurfacePermissionsInternal(ps *PermissionSet, surface AccessSurface, selectedEnvID string) bool {+ if len(surface.Permissions) == 0 {+ return false+ }++ switch surface.MatchMode {+ case AccessMatchModeAllOf:+ for _, perm := range surface.Permissions {+ if !allowsPermissionForScopeModeInternal(ps, perm, surface.ScopeMode, selectedEnvID) {+ return false+ }+ }+ return true+ case AccessMatchModeAnyOf:+ for _, perm := range surface.Permissions {+ if allowsPermissionForScopeModeInternal(ps, perm, surface.ScopeMode, selectedEnvID) {+ return true+ }+ }+ return false+ default:+ return false+ }+}++func allowsPermissionForScopeModeInternal(ps *PermissionSet, perm, scopeMode, selectedEnvID string) bool {+ switch scopeMode {+ case AccessScopeModeGlobalOnly:+ return ps.Allows(perm, "")+ case AccessScopeModeSelectedEnvPlusGlobal:+ return ps.Allows(perm, selectedEnvID)+ case AccessScopeModeAnyEffectiveScope:+ if ps.Allows(perm, "") {+ return true+ }+ for envID := range ps.PerEnv {+ if ps.Allows(perm, envID) {+ return true+ }+ }+ return false+ default:+ return false+ }+}++func buildAccessSurfaceIndexInternal(surfaces []AccessSurface) map[string]AccessSurface {+ out := make(map[string]AccessSurface, len(surfaces))+ for _, surface := range surfaces {+ out[surface.ID] = surface+ }+ return out+}++func copyAccessSurfaceInternal(surface AccessSurface) AccessSurface {+ surface.Permissions = append([]string(nil), surface.Permissions...)+ surface.Children = append([]string(nil), surface.Children...)+ return surface+}++func routeSurfaceInternal(id, url, label, scopeMode string, permissions []string, fallbackOrder int) AccessSurface {+ return AccessSurface{+ ID: id,+ Kind: AccessSurfaceKindRoute,+ URL: url,+ Label: label,+ AccessMode: AccessModePermissions,+ MatchMode: AccessMatchModeAnyOf,+ ScopeMode: scopeMode,+ Permissions: append([]string(nil), permissions...),+ FallbackOrder: fallbackOrder,+ }+}++func settingsCategorySurfaceInternal(categoryID, url, label, scopeMode string, permissions []string) AccessSurface {+ return AccessSurface{+ ID: "settings.category." + categoryID,+ Kind: AccessSurfaceKindSettingsCategory,+ URL: url,+ Label: label,+ AccessMode: AccessModePermissions,+ MatchMode: AccessMatchModeAnyOf,+ ScopeMode: scopeMode,+ Permissions: append([]string(nil), permissions...),+ }+}++func customizeCategorySurfaceInternal(categoryID, url, label string, permissions []string) AccessSurface {+ return AccessSurface{+ ID: "customize.category." + categoryID,+ Kind: AccessSurfaceKindCustomizeCategory,+ URL: url,+ Label: label,+ AccessMode: AccessModePermissions,+ MatchMode: AccessMatchModeAnyOf,+ ScopeMode: AccessScopeModeGlobalOnly,+ Permissions: append([]string(nil), permissions...),+ }+}++func landingSurfaceInternal(id, url, label string, children []string, fallbackOrder int) AccessSurface {+ return AccessSurface{+ ID: id,+ Kind: AccessSurfaceKindLanding,+ URL: url,+ Label: label,+ AccessMode: AccessModeAnyChild,+ MatchMode: AccessMatchModeAnyOf,+ ScopeMode: AccessScopeModeSelectedEnvPlusGlobal,+ Children: append([]string(nil), children...),+ FallbackOrder: fallbackOrder,+ }+}diff --git a/backend/pkg/authz/access_policy_test.go b/backend/pkg/authz/access_policy_test.gonew file mode 100644index 000000000..e35879765--- /dev/null+++ b/backend/pkg/authz/access_policy_test.go@@ -0,0 +1,187 @@+package authz_test++import (+ "os"+ "path/filepath"+ "regexp"+ "runtime"+ "strings"+ "testing"++ "github.com/getarcaneapp/arcane/backend/internal/services"+ "github.com/getarcaneapp/arcane/backend/pkg/authz"+ "github.com/stretchr/testify/require"+)++func TestAccessSurfaceRegistryDefinesSettingsCustomizeAndLandingSemantics(t *testing.T) {+ webhooks := requireAccessSurfaceInternal(t, "settings.category.webhooks")+ require.Equal(t, authz.AccessSurfaceKindSettingsCategory, webhooks.Kind)+ require.Equal(t, "/settings/webhooks", webhooks.URL)+ require.Equal(t, authz.AccessModePermissions, webhooks.AccessMode)+ require.Equal(t, authz.AccessMatchModeAnyOf, webhooks.MatchMode)+ require.Equal(t, authz.AccessScopeModeSelectedEnvPlusGlobal, webhooks.ScopeMode)+ require.ElementsMatch(t, []string{authz.PermWebhooksList}, webhooks.Permissions)++ apiKeys := requireAccessSurfaceInternal(t, "settings.category.apikeys")+ require.Equal(t, authz.AccessScopeModeGlobalOnly, apiKeys.ScopeMode)+ require.ElementsMatch(t, []string{authz.PermApiKeysList, authz.PermApiKeysRead}, apiKeys.Permissions)++ jobSchedule := requireAccessSurfaceInternal(t, "settings.category.jobschedule")+ require.Equal(t, authz.AccessScopeModeSelectedEnvPlusGlobal, jobSchedule.ScopeMode)+ require.Empty(t, jobSchedule.URL)+ require.ElementsMatch(t, []string{authz.PermJobsManage}, jobSchedule.Permissions)++ templates := requireAccessSurfaceInternal(t, "customize.category.templates")+ require.Equal(t, authz.AccessSurfaceKindCustomizeCategory, templates.Kind)+ require.Equal(t, authz.AccessScopeModeGlobalOnly, templates.ScopeMode)+ require.ElementsMatch(t, []string{authz.PermCustomizeManage, authz.PermTemplatesList, authz.PermTemplatesRead}, templates.Permissions)++ settingsLanding := requireAccessSurfaceInternal(t, "landing.settings")+ require.Equal(t, authz.AccessSurfaceKindLanding, settingsLanding.Kind)+ require.Equal(t, "/settings", settingsLanding.URL)+ require.Equal(t, authz.AccessModeAnyChild, settingsLanding.AccessMode)+ require.Contains(t, settingsLanding.Children, "settings.category.webhooks")+ require.Contains(t, settingsLanding.Children, "settings.category.apikeys")+ require.Contains(t, settingsLanding.Children, "settings.category.jobschedule")++ dashboard := requireAccessSurfaceInternal(t, "route.dashboard")+ require.Equal(t, authz.AccessSurfaceKindRoute, dashboard.Kind)+ require.Equal(t, "/dashboard", dashboard.URL)+ require.Positive(t, dashboard.FallbackOrder)+}++func TestCanAccessSurfaceEvaluatesScopeModesAndLandingChildren(t *testing.T) {+ ps := authz.NewPermissionSet()+ ps.AddEnv("env-a", authz.PermWebhooksList)++ require.True(t, authz.CanAccessSurface(ps, "settings.category.webhooks", "env-a"))+ require.True(t, authz.CanAccessSurface(ps, "landing.settings", "env-a"))+ require.False(t, authz.CanAccessSurface(ps, "settings.category.webhooks", "env-b"))+ require.False(t, authz.CanAccessSurface(ps, "landing.settings", "env-b"))++ ps.AddGlobal(authz.PermApiKeysRead)+ require.True(t, authz.CanAccessSurface(ps, "settings.category.apikeys", "env-b"))+ require.True(t, authz.CanAccessSurface(ps, "landing.settings", "env-b"))++ jobsPS := authz.NewPermissionSet()+ jobsPS.AddEnv("env-a", authz.PermJobsManage)+ require.True(t, authz.CanAccessSurface(jobsPS, "settings.category.jobschedule", "env-a"))+ require.True(t, authz.CanAccessSurface(jobsPS, "landing.settings", "env-a"))+ require.False(t, authz.CanAccessSurface(jobsPS, "settings.category.jobschedule", "env-b"))++ customizePS := authz.NewPermissionSet()+ customizePS.AddGlobal(authz.PermCustomizeManage)+ require.True(t, authz.CanAccessSurface(customizePS, "customize.category.registries", "env-a"))+ require.True(t, authz.CanAccessSurface(customizePS, "landing.customize", "env-a"))++ require.False(t, authz.CanAccessSurface(authz.NewPermissionSet(), "missing.surface", "env-a"))+}++func TestAccessSurfaceRegistryIsDefensiveAndInternallyConsistent(t *testing.T) {+ surfaces := authz.AccessSurfaces()+ require.NotEmpty(t, surfaces)++ surfaces[0].Permissions = append(surfaces[0].Permissions, "unknown:permission")+ surfaces[0].Children = append(surfaces[0].Children, "missing.child")++ fresh := authz.AccessSurfaces()+ require.NotContains(t, fresh[0].Permissions, "unknown:permission")+ require.NotContains(t, fresh[0].Children, "missing.child")++ for _, surface := range fresh {+ for _, perm := range surface.Permissions {+ require.True(t, authz.IsKnownPermission(perm), "surface %s references unknown permission %s", surface.ID, perm)+ }+ for _, childID := range surface.Children {+ _, ok := findAccessSurfaceInternal(childID)+ require.True(t, ok, "surface %s references unknown child %s", surface.ID, childID)+ }+ }+}++func TestAccessSurfaceCategoryRegistryCoversBackendCategories(t *testing.T) {+ hiddenSettingsCategories := map[string]struct{}{+ "security": {},+ }++ for _, category := range services.NewSettingsSearchService().GetSettingsCategories() {+ if _, hidden := hiddenSettingsCategories[category.ID]; hidden {+ continue+ }+ _, ok := findAccessSurfaceInternal("settings.category." + category.ID)+ require.True(t, ok, "settings category %s must have an access surface", category.ID)+ }++ for _, category := range services.NewCustomizeSearchService().GetCustomizeCategories() {+ _, ok := findAccessSurfaceInternal("customize.category." + category.ID)+ require.True(t, ok, "customize category %s must have an access surface", category.ID)+ }+}++func TestPublishedAccessSurfaceURLsHaveFrontendRoutes(t *testing.T) {+ routesRoot := filepath.Join(repoRootInternal(t), "frontend", "src", "routes", "(app)")++ for _, surface := range authz.AccessSurfaces() {+ if surface.URL == "" {+ continue+ }+ routePath := frontendRoutePathInternal(routesRoot, surface.URL)+ _, err := os.Stat(routePath)+ require.NoError(t, err, "access surface %s URL %s must map to frontend route %s", surface.ID, surface.URL, routePath)+ }+}++func TestFrontendNavigationReferencesKnownAccessSurfaces(t *testing.T) {+ navPath := filepath.Join(repoRootInternal(t), "frontend", "src", "lib", "config", "navigation-config.ts")+ body, err := os.ReadFile(navPath)+ require.NoError(t, err)++ matches := regexp.MustCompile(`accessSurfaceId:\s*'([^']+)'`).FindAllStringSubmatch(string(body), -1)+ require.NotEmpty(t, matches)++ for _, match := range matches {+ require.Len(t, match, 2)+ _, ok := findAccessSurfaceInternal(match[1])+ require.True(t, ok, "frontend navigation references unknown access surface %s", match[1])+ }+}++func requireAccessSurfaceInternal(t *testing.T, id string) authz.AccessSurface {+ t.Helper()++ surface, ok := findAccessSurfaceInternal(id)+ require.True(t, ok, "expected access surface %s to exist", id)++ return surface+}++func findAccessSurfaceInternal(id string) (authz.AccessSurface, bool) {+ for _, surface := range authz.AccessSurfaces() {+ if surface.ID == id {+ return surface, true+ }+ }+ return authz.AccessSurface{}, false+}++func repoRootInternal(t *testing.T) string {+ t.Helper()++ _, filename, _, ok := runtime.Caller(0)+ require.True(t, ok)+ return filepath.Clean(filepath.Join(filepath.Dir(filename), "..", "..", ".."))+}++func frontendRoutePathInternal(routesRoot, url string) string {+ parts := strings.Split(strings.Trim(url, "/"), "/")+ for i, part := range parts {+ if strings.HasPrefix(part, "{") && strings.HasSuffix(part, "}") {+ parts[i] = "[" + strings.Trim(part, "{}") + "]"+ continue+ }+ if strings.HasPrefix(part, ":") {+ parts[i] = "[" + strings.TrimPrefix(part, ":") + "]"+ }+ }+ return filepath.Join(append([]string{routesRoot}, parts...)...)+}diff --git a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelteindex 24539ce4f..5401a3dc9 100644--- a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte+++ b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte@@ -16,6 +16,7 @@import { extractApiErrorMessage } from '$lib/utils/api';import { hasPermission } from '$lib/utils/auth';import type { AppVersionInformation } from '$lib/types/settings';+ import type { PermissionsManifest, User } from '$lib/types/auth';import { createMutation, createQuery } from '@tanstack/svelte-query';let {@@ -23,16 +24,18 @@user = null,versionInformation,swarmItems = [],+ permissionsManifest = null,debug = false}: {open: boolean;- user?: any;+ user?: User | null;versionInformation?: AppVersionInformation;swarmItems?: NavigationItem[];+ permissionsManifest?: PermissionsManifest | null;debug?: boolean;} = $props();- let storeUser: any = $state(null);+ let storeUser = $state<User | null>(null);$effect(() => {const unsub = userStore.subscribe((u) => (storeUser = u));@@ -43,9 +46,15 @@const memoizedUser = $derived.by(() => user ?? storeUser);const currentEnvId = $derived(environmentStore.selected?.id || '0');const managementItemsRaw = $derived(getManagementItems(currentEnvId));- const managementItems = $derived(filterByPermissions(managementItemsRaw, memoizedUser ?? null, currentEnvId));- const resourceItems = $derived(filterByPermissions(navigationItems.resourceItems, memoizedUser ?? null, currentEnvId));- const settingsItems = $derived(filterByPermissions(navigationItems.settingsItems, memoizedUser ?? null, currentEnvId));+ const managementItems = $derived(+ filterByPermissions(managementItemsRaw, memoizedUser ?? null, currentEnvId, permissionsManifest)+ );+ const resourceItems = $derived(+ filterByPermissions(navigationItems.resourceItems, memoizedUser ?? null, currentEnvId, permissionsManifest)+ );+ const settingsItems = $derived(+ filterByPermissions(navigationItems.settingsItems, memoizedUser ?? null, currentEnvId, permissionsManifest)+ );let upgrading = $state(false);let showConfirmDialog = $state(false);diff --git a/frontend/src/lib/components/mobile-nav/mobile-nav.svelte b/frontend/src/lib/components/mobile-nav/mobile-nav.svelteindex 218f24470..0c968f030 100644--- a/frontend/src/lib/components/mobile-nav/mobile-nav.svelte+++ b/frontend/src/lib/components/mobile-nav/mobile-nav.svelte@@ -10,26 +10,31 @@import { MobileNavGestures } from './gestures.svelte';import './styles.css';import type { AppVersionInformation } from '$lib/types/settings';+ import type { PermissionsManifest, User } from '$lib/types/auth';+ import { environmentStore } from '$lib/stores/environment.store.svelte';let {navigationSettings,user = null,versionInformation,swarmEnabled = false,+ permissionsManifest = null,class: className = ''}: {navigationSettings: MobileNavigationSettings;- user?: any;+ user?: User | null;versionInformation?: AppVersionInformation;swarmEnabled?: boolean;+ permissionsManifest?: PermissionsManifest | null;class?: string;} = $props();const swarmItems = $derived(getSwarmNavigationItems(swarmEnabled));+ const currentEnvId = $derived(environmentStore.selected?.id || '0');const pinnedItems = $derived.by(() => {if (!navigationSettings?.pinnedItems) return [];- const availableItems = getAvailableMobileNavItems({ swarmEnabled });+ const availableItems = getAvailableMobileNavItems({ swarmEnabled, user, currentEnvId, accessManifest: permissionsManifest });return navigationSettings.pinnedItems.map((url) => availableItems.find((item) => item.url === url)).filter((item) => item !== undefined);@@ -188,4 +193,4 @@{/if}</nav>-<MobileNavSheet bind:open={menuOpen} {user} {versionInformation} {swarmItems} />+<MobileNavSheet bind:open={menuOpen} {user} {versionInformation} {swarmItems} {permissionsManifest} />diff --git a/frontend/src/lib/components/sidebar/sidebar.svelte b/frontend/src/lib/components/sidebar/sidebar.svelteindex 63e6fb94b..b1035edfd 100644--- a/frontend/src/lib/components/sidebar/sidebar.svelte+++ b/frontend/src/lib/components/sidebar/sidebar.svelte@@ -15,7 +15,7 @@import * as Sidebar from '$lib/components/ui/sidebar/index.js';import { useSidebar } from '$lib/components/ui/sidebar/index.js';import type { ComponentProps } from 'svelte';- import type { User } from '$lib/types/auth';+ import type { PermissionsManifest, User } from '$lib/types/auth';import type { AppVersionInformation } from '$lib/types/settings';import SidebarLogo from './sidebar-logo.svelte';import SidebarUpdatebanner from './sidebar-updatebanner.svelte';@@ -35,11 +35,13 @@user,versionInformation,swarmEnabled = false,+ permissionsManifest = null,...restProps}: ComponentProps<typeof Sidebar.Root> & {versionInformation: AppVersionInformation;user?: User | null;swarmEnabled?: boolean;+ permissionsManifest?: PermissionsManifest | null;} = $props();let autoLoginEnabled = $state(false);@@ -61,10 +63,16 @@const managementItemsRaw = $derived(getManagementItems(currentEnvId));const swarmItemsRaw = $derived(getSwarmNavigationItems(swarmEnabled));- const managementItems = $derived(filterByPermissions(managementItemsRaw, effectiveUser ?? null, currentEnvId));- const resourceItems = $derived(filterByPermissions(navigationItems.resourceItems, effectiveUser ?? null, currentEnvId));- const swarmItems = $derived(filterByPermissions(swarmItemsRaw, effectiveUser ?? null, currentEnvId));- const settingsItems = $derived(filterByPermissions(navigationItems.settingsItems, effectiveUser ?? null, currentEnvId));+ const managementItems = $derived(+ filterByPermissions(managementItemsRaw, effectiveUser ?? null, currentEnvId, permissionsManifest)+ );+ const resourceItems = $derived(+ filterByPermissions(navigationItems.resourceItems, effectiveUser ?? null, currentEnvId, permissionsManifest)+ );+ const swarmItems = $derived(filterByPermissions(swarmItemsRaw, effectiveUser ?? null, currentEnvId, permissionsManifest));+ const settingsItems = $derived(+ filterByPermissions(navigationItems.settingsItems, effectiveUser ?? null, currentEnvId, permissionsManifest)+ );</script><VersionInfoDialogdiff --git a/frontend/src/lib/components/ui/checkbox/checkbox.svelte b/frontend/src/lib/components/ui/checkbox/checkbox.svelteindex d2e990203..7531be2f9 100644--- a/frontend/src/lib/components/ui/checkbox/checkbox.svelte+++ b/frontend/src/lib/components/ui/checkbox/checkbox.svelte@@ -1,7 +1,6 @@<script lang="ts">import { Checkbox as CheckboxPrimitive } from 'bits-ui';import { cn, type WithoutChildrenOrChild } from '$lib/utils.js';- import { CheckIcon, MinusIcon } from '$lib/icons';let {ref = $bindable(null),@@ -16,7 +15,7 @@bind:refdata-slot="checkbox"class={cn(- 'border-input bg-input data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive peer flex size-4 shrink-0 items-center justify-center rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50',+ 'border-input bg-input data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground data-[state=checked]:border-primary data-[state=indeterminate]:bg-primary data-[state=indeterminate]:text-primary-foreground data-[state=indeterminate]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive peer relative flex size-4 shrink-0 items-center justify-center rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50',className)}bind:checked@@ -24,11 +23,27 @@{...restProps}>{#snippet children({ checked, indeterminate })}- <div data-slot="checkbox-indicator" class="text-current transition-none">+ <div+ data-slot="checkbox-indicator"+ class="pointer-events-none absolute inset-0 flex items-center justify-center text-current transition-none"+ >{#if checked}- <CheckIcon class="size-3.5" />+ <svg+ class="absolute top-1/2 left-1/2 size-3 -translate-x-1/2 -translate-y-1/2"+ viewBox="0 0 12 12"+ fill="none"+ aria-hidden="true"+ >+ <path+ d="M3 6.15L5.2 8.25L9 3.85"+ stroke="currentColor"+ stroke-width="1.8"+ stroke-linecap="round"+ stroke-linejoin="round"+ />+ </svg>{:else if indeterminate}- <MinusIcon class="size-3.5" />+ <span class="absolute top-1/2 left-1/2 h-[2px] w-2.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-current"></span>{/if}</div>{/snippet}diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.tsindex 87abdd1cb..a1c542f64 100644--- a/frontend/src/lib/config/navigation-config.ts+++ b/frontend/src/lib/config/navigation-config.ts@@ -30,8 +30,8 @@ import {} from '$lib/icons';import { m } from '$lib/paraglide/messages';import type { ShortcutKey } from '$lib/utils/navigation';-import type { User } from '$lib/types/auth';-import { GLOBAL_SCOPE, SUDO_PERMISSION } from '$lib/types/auth';+import type { PermissionsManifest, User } from '$lib/types/auth';+import { canReachAccessSurface } from '$lib/utils/access-policy';export type NavigationItem = {title: string;@@ -40,24 +40,10 @@ export type NavigationItem = {shortcut?: ShortcutKey[];items?: NavigationItem[];/**- * Permission(s) the user must hold to see this item. ANY-of semantics: if- * the user has at least one of the listed permissions on the relevant- * scope, the item is visible. Omit to make the item visible to every- * authenticated user.+ * Backend-owned access-surface ID that gates this item. Omit to make the+ * item visible to every authenticated user.*/- requiredPermission?: string | string[];- /**- * Scope for the permission check. `'global'` checks the global permission- * set; `'env'` (default for resource items) accepts permissions scoped to- * the currently-selected environment.- */- scope?: 'global' | 'env';-};--export type RouteAccessRule = {- prefix: string;- perms: string[];- scope: 'global' | 'env';+ accessSurfaceId?: string;};export type NavigationSections = {@@ -67,41 +53,6 @@ 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: [{@@ -109,59 +60,52 @@ export const navigationItems: NavigationSections = {url: '/dashboard',icon: DashboardIcon,shortcut: ['mod', '1'],- scope: 'env',- requiredPermission: 'dashboard:read'+ accessSurfaceId: 'route.dashboard'},{title: m.projects_title(),url: '/projects',icon: ProjectsIcon,shortcut: ['mod', '2'],- scope: 'env',- requiredPermission: ['projects:list', 'projects:read']+ accessSurfaceId: 'route.projects'},{title: m.environments_title(),url: '/environments',icon: EnvironmentsIcon,shortcut: ['mod', '3'],- scope: 'global',- requiredPermission: ['environments:list', 'environments:read']+ accessSurfaceId: 'route.environments'},{title: m.customize_title(),url: '/customize',icon: CustomizeIcon,shortcut: ['mod', '4'],- scope: 'global',+ accessSurfaceId: 'landing.customize',items: [{title: m.templates_title(),url: '/customize/templates',icon: TemplateIcon,- scope: 'global',- requiredPermission: ['templates:list', 'templates:read']+ accessSurfaceId: 'customize.category.templates'},{title: m.registries_title(),url: '/customize/registries',icon: RegistryIcon,- scope: 'global',- requiredPermission: ['registries:list', 'registries:read']+ accessSurfaceId: 'customize.category.registries'},{title: m.variables_title(),url: '/customize/variables',icon: VariableIcon,- scope: 'global',- requiredPermission: ['templates:read']+ accessSurfaceId: 'customize.category.variables'},{title: m.git_repositories_title(),url: '/customize/git-repositories',icon: GitBranchIcon,- scope: 'global',- requiredPermission: ['git-repositories:list', 'git-repositories:read']+ accessSurfaceId: 'customize.category.git-repositories'}]}@@ -172,24 +116,21 @@ export const navigationItems: NavigationSections = {url: '/containers',icon: ContainersIcon,shortcut: ['mod', '5'],- scope: 'env',- requiredPermission: ['containers:list', 'containers:read']+ accessSurfaceId: 'route.containers'},{title: m.images_title(),url: '/images',icon: ImagesIcon,shortcut: ['mod', '6'],- scope: 'env',- requiredPermission: ['images:list', 'images:read'],+ accessSurfaceId: 'route.images',items: [- { title: m.builds(), url: '/images/builds', icon: HammerIcon, scope: 'env', requiredPermission: 'images:build' },+ { title: m.builds(), url: '/images/builds', icon: HammerIcon, accessSurfaceId: 'route.images.builds' },{title: m.vuln_title(),url: '/images/vulnerabilities',icon: ShieldAlertIcon,- scope: 'env',- requiredPermission: 'vulnerabilities:read'+ accessSurfaceId: 'route.images.vulnerabilities'}]},@@ -198,24 +139,21 @@ export const navigationItems: NavigationSections = {url: '/updates',icon: UpdateIcon,shortcut: ['mod', 'u'],- scope: 'env',- requiredPermission: 'image-updates:read'+ accessSurfaceId: 'route.updates'},{title: m.networks_title(),url: '/networks',icon: NetworksIcon,shortcut: ['mod', '7'],- scope: 'env',- requiredPermission: ['networks:list', 'networks:read'],+ accessSurfaceId: 'route.networks',items: [- { title: m.ports_title(), url: '/ports', icon: HashIcon, scope: 'env', requiredPermission: 'containers:list' },+ { title: m.ports_title(), url: '/ports', icon: HashIcon, accessSurfaceId: 'route.ports' },{title: m.networks_topology_button(),url: '/networks/topology',icon: GitBranchIcon,- scope: 'env',- requiredPermission: 'networks:read'+ accessSurfaceId: 'route.networks.topology'}]},@@ -224,18 +162,17 @@ export const navigationItems: NavigationSections = {url: '/volumes',icon: VolumesIcon,shortcut: ['mod', '8'],- scope: 'env',- requiredPermission: ['volumes:list', 'volumes:read']+ accessSurfaceId: 'route.volumes'}],swarmItems: [- { title: 'Services', url: '/swarm/services', icon: DockIcon, scope: 'env', requiredPermission: 'swarm:services' },- { title: 'Nodes', url: '/swarm/nodes', icon: UsersIcon, scope: 'env', requiredPermission: 'swarm:nodes' },- { title: 'Tasks', url: '/swarm/tasks', icon: JobsIcon, scope: 'env', requiredPermission: 'swarm:read' },- { title: 'Stacks', url: '/swarm/stacks', icon: LayersIcon, scope: 'env', requiredPermission: 'swarm:stacks' },- { title: 'Cluster', url: '/swarm/cluster', icon: SettingsIcon, scope: 'env', requiredPermission: 'swarm:read' },- { title: 'Configs', url: '/swarm/configs', icon: TemplateIcon, scope: 'env', requiredPermission: 'swarm:configs' },- { title: 'Secrets', url: '/swarm/secrets', icon: LockIcon, scope: 'env', requiredPermission: 'swarm:secrets' }+ { title: 'Services', url: '/swarm/services', icon: DockIcon, accessSurfaceId: 'route.swarm.services' },+ { title: 'Nodes', url: '/swarm/nodes', icon: UsersIcon, accessSurfaceId: 'route.swarm.nodes' },+ { title: 'Tasks', url: '/swarm/tasks', icon: JobsIcon, accessSurfaceId: 'route.swarm.tasks' },+ { title: 'Stacks', url: '/swarm/stacks', icon: LayersIcon, accessSurfaceId: 'route.swarm.stacks' },+ { title: 'Cluster', url: '/swarm/cluster', icon: SettingsIcon, accessSurfaceId: 'route.swarm.cluster' },+ { title: 'Configs', url: '/swarm/configs', icon: TemplateIcon, accessSurfaceId: 'route.swarm.configs' },+ { title: 'Secrets', url: '/swarm/secrets', icon: LockIcon, accessSurfaceId: 'route.swarm.secrets' }],settingsItems: [{@@ -243,98 +180,87 @@ export const navigationItems: NavigationSections = {url: '/events',icon: EventsIcon,shortcut: ['mod', '9'],- scope: 'global',- requiredPermission: 'events:read'+ accessSurfaceId: 'route.events'},{title: m.settings_title(),url: '/settings',icon: SettingsIcon,shortcut: ['mod', '0'],+ accessSurfaceId: 'landing.settings',items: [{title: m.api_key_page_title(),url: '/settings/api-keys',icon: ApiKeyIcon,shortcut: ['mod', 'shift', '1'],- scope: 'global',- requiredPermission: 'apikeys:list'+ accessSurfaceId: 'settings.category.apikeys'},{title: m.appearance_title(),url: '/settings/appearance',icon: AppearanceIcon,shortcut: ['mod', 'shift', '2'],- scope: 'global',- requiredPermission: 'settings:read'+ accessSurfaceId: 'settings.category.appearance'},{title: m.webhook_page_title(),url: '/settings/webhooks',icon: GlobeIcon,- scope: 'env',- requiredPermission: 'webhooks:list'+ accessSurfaceId: 'settings.category.webhooks'},{title: m.authentication_title(),url: '/settings/authentication',icon: LockIcon,shortcut: ['mod', 'shift', '3'],- scope: 'global',- requiredPermission: 'settings:read'+ accessSurfaceId: 'settings.category.authentication'},{title: m.notifications_title(),url: '/settings/notifications',icon: NotificationsIcon,shortcut: ['mod', 'shift', '4'],- scope: 'env',- requiredPermission: 'notifications:manage'+ accessSurfaceId: 'settings.category.notifications'},{title: m.activity_settings_title(),url: '/settings/activity',icon: ActivityIcon,- scope: 'env',- requiredPermission: 'settings:read'+ accessSurfaceId: 'settings.category.activity'},{title: m.builds(),url: '/settings/builds',icon: HammerIcon,shortcut: ['mod', 'shift', '6'],- scope: 'global',- requiredPermission: 'settings:read'+ accessSurfaceId: 'settings.category.build'},{title: m.timeouts_settings(),url: '/settings/timeouts',icon: JobsIcon,shortcut: ['mod', 'shift', '7'],- scope: 'global',- requiredPermission: 'settings:read'+ accessSurfaceId: 'settings.category.timeouts'},{title: m.users_title(),url: '/settings/users',icon: UsersIcon,shortcut: ['mod', 'shift', '8'],- scope: 'global',- requiredPermission: ['users:read', 'users:list']+ accessSurfaceId: 'settings.category.users'},{title: m.roles_title(),url: '/settings/roles',icon: ShieldAlertIcon,- scope: 'global',- requiredPermission: ['roles:read', 'roles:list']+ accessSurfaceId: 'settings.category.roles'},{title: m.diagnostics_title(),url: '/settings/diagnostics',icon: ActivityIcon,- scope: 'global',- requiredPermission: 'diagnostics:read'+ accessSurfaceId: 'settings.category.diagnostics'}]}@@ -357,8 +283,8 @@ export const navigationItems: NavigationSections = {/*** Filter a navigation tree to entries the user can reach. Empty parent groups* (i.e. those whose children were all filtered out and which themselves have- * no required permission) are preserved; empty parent groups whose own- * permission check fails are removed.+ * no access surface) are preserved; empty parent groups whose own access+ * surface check fails are removed.** @param items navigation items to filter* @param user the current user (or null when unauthenticated)@@ -367,15 +293,16 @@ export const navigationItems: NavigationSections = {export function filterByPermissions(items: NavigationItem[] | undefined,user: User | null,- currentEnvId: string | undefined+ currentEnvId: string | undefined,+ accessManifest?: PermissionsManifest | null): NavigationItem[] {if (!items) return [];if (!user) return [];const out: NavigationItem[] = [];for (const item of items) {- if (!canSeeItem(item, user, currentEnvId)) continue;+ if (!canSeeItem(item, user, currentEnvId, accessManifest)) continue;if (item.items && item.items.length > 0) {- const filteredChildren = filterByPermissions(item.items, user, currentEnvId);+ const filteredChildren = filterByPermissions(item.items, user, currentEnvId, accessManifest);// Drop a parent group only when it has children declared but none// survived the filter. A parent with NO children declared (a leaf// link that happens to have an empty items array) stays.@@ -388,24 +315,15 @@ export function filterByPermissions(return out;}-function canSeeItem(item: NavigationItem, user: User, currentEnvId: string | undefined): boolean {- if (!item.requiredPermission) return true;- const required = Array.isArray(item.requiredPermission) ? item.requiredPermission : [item.requiredPermission];- const scope = item.scope ?? 'env';- const set = effectivePermissions(user, scope === 'env' ? currentEnvId : undefined);- if (set.has(SUDO_PERMISSION)) return true;- return required.some((p) => set.has(p));-}--function effectivePermissions(user: User, envId: string | undefined): Set<string> {- const out = new Set<string>();- const global = user.permissionsByEnv?.[GLOBAL_SCOPE];- if (global) for (const p of global) out.add(p);- if (envId && envId !== GLOBAL_SCOPE) {- const env = user.permissionsByEnv?.[envId];- if (env) for (const p of env) out.add(p);- }- return out;+function canSeeItem(+ item: NavigationItem,+ user: User,+ currentEnvId: string | undefined,+ accessManifest: PermissionsManifest | null | undefined+): boolean {+ if (!item.accessSurfaceId) return true;+ if (!accessManifest?.accessSurfaces?.length) return true;+ return canReachAccessSurface(accessManifest, item.accessSurfaceId, user, currentEnvId);}export function getSettingsSubpageUrlsInNavOrder(): string[] {@@ -418,52 +336,6 @@ export function getCustomizeSubpageUrlsInNavOrder(): string[] {return entry?.items?.map((item) => item.url) ?? [];}-function routeAccessRulesForItems(items: NavigationItem[], out: RouteAccessRule[]): void {- for (const item of items) {- if (item.requiredPermission) {- out.push({- prefix: item.url,- perms: Array.isArray(item.requiredPermission) ? item.requiredPermission : [item.requiredPermission],- scope: item.scope ?? 'env'- });- }- if (item.items) {- routeAccessRulesForItems(item.items, out);- }- }-}--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;-}--export function getRouteFallbackRules(): RouteAccessRule[] {- return getRouteAccessRules().filter((rule) => {- return (- rule.prefix === '/dashboard' ||- rule.prefix === '/containers' ||- rule.prefix === '/projects' ||- rule.prefix === '/customize' ||- rule.prefix === '/images' ||- rule.prefix === '/volumes' ||- rule.prefix === '/networks' ||- rule.prefix === '/swarm/services' ||- rule.prefix === '/swarm/stacks' ||- rule.prefix === '/swarm/cluster' ||- rule.prefix === '/events' ||- rule.prefix === '/settings'- );- });-}-export const defaultMobilePinnedItems: NavigationItem[] = [navigationItems.managementItems[0]!,navigationItems.managementItems[1]!,@@ -486,7 +358,12 @@ export type MobileNavigationSettings = {scrollToHide: boolean;};-export function getAvailableMobileNavItems(options?: { swarmEnabled?: boolean }): NavigationItem[] {+export function getAvailableMobileNavItems(options?: {+ swarmEnabled?: boolean;+ user?: User | null;+ currentEnvId?: string;+ accessManifest?: PermissionsManifest | null;+}): NavigationItem[] {const flatItems: NavigationItem[] = [];if (navigationItems.managementItems) {flatItems.push(...navigationItems.managementItems);@@ -511,7 +388,9 @@ export function getAvailableMobileNavItems(options?: { swarmEnabled?: boolean })}}- return flatItems;+ if (options?.user === null) return [];+ if (!options?.user) return flatItems;+ return filterByPermissions(flatItems, options.user, options.currentEnvId, options.accessManifest);}export const defaultMobileNavigationSettings: MobileNavigationSettings = {@@ -526,7 +405,8 @@ export function getManagementItems(environmentId: string): NavigationItem[] {title: m.git_syncs_title(),url: `/environments/${environmentId}/gitops`,icon: GitBranchIcon,- shortcut: ['mod', 'g']+ shortcut: ['mod', 'g'],+ accessSurfaceId: 'route.environments.gitops'};return navigationItems.managementItems.map((item) => {diff --git a/frontend/src/lib/layouts/settings-page-layout.svelte b/frontend/src/lib/layouts/settings-page-layout.svelteindex 6f2e18c06..16acb6a8e 100644--- a/frontend/src/lib/layouts/settings-page-layout.svelte+++ b/frontend/src/lib/layouts/settings-page-layout.svelte@@ -88,11 +88,11 @@<UiConfigDisabledTag />{/if}- {#if pageType === 'form' && formState && !showReadOnlyTag}+ {#if pageType === 'form' && formState?.saveFunction && !showReadOnlyTag}<div class="hidden items-center gap-2 sm:flex">{#if formState.hasChanges}<span class="mr-2 text-xs text-orange-600 dark:text-orange-400">{m.common_unsaved_changes()}</span>- {:else if !formState.hasChanges && formState.saveFunction}+ {:else if !formState.hasChanges}<span class="mr-2 text-xs text-green-600 dark:text-green-400">{m.common_all_changes_saved()}</span>{/if}diff --git a/frontend/src/lib/stores/user-store.ts b/frontend/src/lib/stores/user-store.tsindex be659ea19..1902dd87a 100644--- a/frontend/src/lib/stores/user-store.ts+++ b/frontend/src/lib/stores/user-store.ts@@ -1,5 +1,5 @@import type { User } from '$lib/types/auth';-import { GLOBAL_SCOPE, SUDO_PERMISSION, BUILT_IN_ROLE_ADMIN } from '$lib/types/auth';+import { GLOBAL_SCOPE, SUDO_PERMISSION } from '$lib/types/auth';import { writable, get } from 'svelte/store';import { setLocale } from '$lib/utils/formatting';@@ -58,7 +58,7 @@ const isGlobalAdmin = (): 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);+ return false;};export default {diff --git a/frontend/src/lib/types/auth.ts b/frontend/src/lib/types/auth.tsindex 4034b3605..041cc75f9 100644--- a/frontend/src/lib/types/auth.ts+++ b/frontend/src/lib/types/auth.ts@@ -69,6 +69,7 @@ export type UpdateOidcRoleMapping = CreateOidcRoleMapping;export type PermissionsManifest = {resources: PermissionResource[];presets?: PermissionPreset[];+ accessSurfaces?: AccessSurface[];};export type PermissionResource = {@@ -93,6 +94,24 @@ export type PermissionPreset = {permissions: string[];};+export type AccessSurfaceKind = 'route' | 'settings-category' | 'customize-category' | 'landing';+export type AccessMode = 'permissions' | 'any-child';+export type AccessMatchMode = 'any-of' | 'all-of';+export type AccessScopeMode = 'global-only' | 'selected-env-plus-global' | 'any-effective-scope';++export type AccessSurface = {+ id: string;+ kind: AccessSurfaceKind;+ url?: string;+ label: string;+ accessMode: AccessMode;+ matchMode: AccessMatchMode;+ scopeMode: AccessScopeMode;+ permissions?: string[];+ children?: string[];+ fallbackOrder?: number;+};+export type ApiKeyPermissionGrant = {permission: string;environmentId?: string;diff --git a/frontend/src/lib/utils/access-policy.ts b/frontend/src/lib/utils/access-policy.tsnew file mode 100644index 000000000..82f51a176--- /dev/null+++ b/frontend/src/lib/utils/access-policy.ts@@ -0,0 +1,151 @@+import type { AccessSurface, PermissionsManifest, User } from '$lib/types/auth';+import { GLOBAL_SCOPE, SUDO_PERMISSION } from '$lib/types/auth';++type SurfaceIndex = Map<string, AccessSurface>;++let cachedSurfacesInternal: AccessSurface[] | undefined;+let cachedSurfaceIndexInternal: SurfaceIndex | undefined;++export function canReachAccessSurface(+ manifest: PermissionsManifest | null | undefined,+ surfaceId: string | undefined,+ user: User | null | undefined,+ selectedEnvId?: string+): boolean {+ if (!surfaceId || !user) return false;+ const surfaces = manifest?.accessSurfaces;+ if (!surfaces?.length) return false;++ return canReachSurfaceInternal(getSurfaceIndexInternal(surfaces), surfaceId, user, selectedEnvId, new Set());+}++export function canReachAccessSurfaceUrl(+ manifest: PermissionsManifest | null | undefined,+ url: string,+ user: User | null | undefined,+ selectedEnvId?: string+): boolean {+ const surface = manifest?.accessSurfaces?.find((entry) => entry.url === url);+ if (!surface) return false;+ return canReachAccessSurface(manifest, surface.id, user, selectedEnvId);+}++export function getRouteAccessSurfaces(manifest: PermissionsManifest | null | undefined): AccessSurface[] {+ return (manifest?.accessSurfaces ?? [])+ .filter((surface) => !!surface.url)+ .slice()+ .sort((a, b) => (b.url?.length ?? 0) - (a.url?.length ?? 0));+}++export function getFallbackAccessSurfaces(manifest: PermissionsManifest | null | undefined): AccessSurface[] {+ return (manifest?.accessSurfaces ?? [])+ .filter((surface) => !!surface.url && !!surface.fallbackOrder)+ .slice()+ .sort((a, b) => (a.fallbackOrder ?? 0) - (b.fallbackOrder ?? 0));+}++export function pathMatchesAccessSurface(path: string, surface: AccessSurface): boolean {+ const template = surface.url;+ if (!template) return false;++ const pathSegments = splitPathInternal(path);+ const templateSegments = splitPathInternal(template);+ if (templateSegments.length > pathSegments.length) return false;++ for (let i = 0; i < templateSegments.length; i++) {+ const expected = templateSegments[i];+ const actual = pathSegments[i];+ if (!expected || !actual) return false;+ if (isTemplateSegmentInternal(expected)) continue;+ if (expected !== actual) return false;+ }++ return true;+}++function canReachSurfaceInternal(+ surfaces: SurfaceIndex,+ surfaceId: string,+ user: User,+ selectedEnvId: string | undefined,+ visiting: Set<string>+): boolean {+ if (visiting.has(surfaceId)) return false;++ const surface = surfaces.get(surfaceId);+ if (!surface) return false;++ if (surface.accessMode === 'any-child') {+ visiting.add(surfaceId);+ const reachable = (surface.children ?? []).some((childId) =>+ canReachSurfaceInternal(surfaces, childId, user, selectedEnvId, visiting)+ );+ visiting.delete(surfaceId);+ return reachable;+ }++ const permissions = surface.permissions ?? [];+ if (permissions.length === 0) return false;++ if (surface.matchMode === 'all-of') {+ return permissions.every((permission) => hasPermissionForScopeInternal(user, permission, surface.scopeMode, selectedEnvId));+ }++ return permissions.some((permission) => hasPermissionForScopeInternal(user, permission, surface.scopeMode, selectedEnvId));+}++function hasPermissionForScopeInternal(+ user: User,+ permission: string,+ scopeMode: AccessSurface['scopeMode'],+ selectedEnvId: string | undefined+): boolean {+ const global = user.permissionsByEnv?.[GLOBAL_SCOPE] ?? [];+ if (global.includes(SUDO_PERMISSION)) return true;++ switch (scopeMode) {+ case 'global-only':+ return global.includes(permission);+ case 'selected-env-plus-global':+ return permissionsForEnvInternal(user, selectedEnvId).has(permission);+ case 'any-effective-scope':+ return Object.values(user.permissionsByEnv ?? {}).some((permissions) => permissions.includes(permission));+ default:+ return false;+ }+}++function permissionsForEnvInternal(user: User, envId: string | undefined): Set<string> {+ const out = new Set<string>();+ const global = user.permissionsByEnv?.[GLOBAL_SCOPE];+ if (global) for (const permission of global) out.add(permission);+ if (envId && envId !== GLOBAL_SCOPE) {+ const scoped = user.permissionsByEnv?.[envId];+ if (scoped) for (const permission of scoped) out.add(permission);+ }+ return out;+}++function buildSurfaceIndexInternal(surfaces: AccessSurface[]): SurfaceIndex {+ return new Map(surfaces.map((surface) => [surface.id, surface]));+}++function getSurfaceIndexInternal(surfaces: AccessSurface[]): SurfaceIndex {+ if (cachedSurfacesInternal === surfaces && cachedSurfaceIndexInternal) {+ return cachedSurfaceIndexInternal;+ }++ cachedSurfacesInternal = surfaces;+ cachedSurfaceIndexInternal = buildSurfaceIndexInternal(surfaces);+ return cachedSurfaceIndexInternal;+}++function splitPathInternal(path: string): string[] {+ const withoutQuery = path.split('?')[0] ?? '';+ const withoutHash = withoutQuery.split('#')[0] ?? '';+ return withoutHash.split('/').filter(Boolean);+}++function isTemplateSegmentInternal(segment: string): boolean {+ return segment.startsWith(':') || (segment.startsWith('{') && segment.endsWith('}'));+}diff --git a/frontend/src/lib/utils/auth.ts b/frontend/src/lib/utils/auth.tsindex 8a7256be8..51199ca00 100644--- a/frontend/src/lib/utils/auth.ts+++ b/frontend/src/lib/utils/auth.ts@@ -1,9 +1,14 @@import { get } from 'svelte/store';import userStore from '$lib/stores/user-store';import { environmentStore } from '$lib/stores/environment.store.svelte';-import { getRouteAccessRules, getRouteFallbackRules, type RouteAccessRule } from '$lib/config/navigation-config';-import { BUILT_IN_ROLE_ADMIN, GLOBAL_SCOPE, SUDO_PERMISSION } from '$lib/types/auth';-import type { User } from '$lib/types/auth';+import {+ canReachAccessSurface,+ getFallbackAccessSurfaces,+ getRouteAccessSurfaces,+ pathMatchesAccessSurface+} from '$lib/utils/access-policy';+import { GLOBAL_SCOPE, SUDO_PERMISSION } from '$lib/types/auth';+import type { PermissionsManifest, User } from '$lib/types/auth';// --- Store-backed permission checks (for .svelte / runtime) ---@@ -65,7 +70,7 @@ 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);+ return false;}export function userIsGlobalAdmin(user: User | null | undefined): boolean {@@ -79,23 +84,6 @@ function isAdminOnlyRoute(path: string): boolean {const matchesAny = (path: string, prefixes: string[]) =>prefixes.some((prefix) => path === prefix || path.startsWith(`${prefix}/`));-function permissionsForEnv(user: User, envId?: string): Set<string> {- const out = new Set<string>();- const global = user.permissionsByEnv?.[GLOBAL_SCOPE];- if (global) for (const p of global) out.add(p);- if (envId && envId !== GLOBAL_SCOPE) {- const env = user.permissionsByEnv?.[envId];- if (env) for (const p of env) out.add(p);- }- return out;-}--function userCanReach(user: User, perms: string[], scope: 'global' | 'env', envId?: string): boolean {- const set = permissionsForEnv(user, scope === 'env' ? envId : undefined);- if (set.has(SUDO_PERMISSION)) return true;- return perms.some((p) => set.has(p));-}-function userHasAnyAccess(user: User): boolean {if (!user.permissionsByEnv) return false;for (const perms of Object.values(user.permissionsByEnv)) {@@ -104,16 +92,25 @@ function userHasAnyAccess(user: User): boolean {return false;}-function pickFallbackRoute(user: User, envId?: string): string {- for (const rule of getRouteFallbackRules()) {- if (userCanReach(user, rule.perms, rule.scope, envId)) {- return rule.prefix;+function pickFallbackRoute(+ user: User,+ envId: string | undefined,+ accessManifest: PermissionsManifest | null | undefined+): string {+ for (const surface of getFallbackAccessSurfaces(accessManifest)) {+ if (canReachAccessSurface(accessManifest, surface.id, user, envId)) {+ return surface.url ?? '/no-access';}}return '/no-access';}-export function getAuthRedirectPath(path: string, user: User | null, envId?: string): string | null {+export function getAuthRedirectPath(+ path: string,+ user: User | null,+ envId?: string,+ accessManifest?: PermissionsManifest | null+): string | null {const isSignedIn = !!user;if (path === '/') {@@ -138,11 +135,10 @@ export function getAuthRedirectPath(path: string, user: User | null, envId?: strreturn '/settings/roles';}- const sorted: RouteAccessRule[] = [...getRouteAccessRules()].sort((a, b) => b.prefix.length - a.prefix.length);- for (const rule of sorted) {- if (matchesAny(path, [rule.prefix])) {- if (!userCanReach(user, rule.perms, rule.scope, envId)) {- const fallback = pickFallbackRoute(user, envId);+ for (const surface of getRouteAccessSurfaces(accessManifest)) {+ if (pathMatchesAccessSurface(path, surface)) {+ if (!canReachAccessSurface(accessManifest, surface.id, user, envId)) {+ const fallback = pickFallbackRoute(user, envId, accessManifest);return fallback === path ? '/no-access' : fallback;}break;diff --git a/frontend/src/routes/(app)/+layout.svelte b/frontend/src/routes/(app)/+layout.svelteindex 75f85858d..fc4679c26 100644--- a/frontend/src/routes/(app)/+layout.svelte+++ b/frontend/src/routes/(app)/+layout.svelte@@ -19,6 +19,7 @@const versionInformation = $derived(data.versionInformation);const user = $derived(data.user);const settings = $derived(data.settings);+ const permissionsManifest = $derived(data.permissionsManifest);const swarmEnabled = $derived(data.swarmEnabled === true);const isMobile = new IsMobile();@@ -31,15 +32,21 @@});const navigationMode = $derived(navigationSettings.mode);const currentEnvId = $derived(environmentStore.selected?.id || '0');- const managementItems = $derived(getManagementItems(currentEnvId));- const settingsShortcutItems = $derived(filterByPermissions(navigationItems.settingsItems, user ?? null, currentEnvId));+ const managementItemsRaw = $derived(getManagementItems(currentEnvId));+ const managementItems = $derived(filterByPermissions(managementItemsRaw, user ?? null, currentEnvId, permissionsManifest));+ const resourceItems = $derived(+ filterByPermissions(navigationItems.resourceItems, user ?? null, currentEnvId, permissionsManifest)+ );+ const settingsShortcutItems = $derived(+ filterByPermissions(navigationItems.settingsItems, user ?? null, currentEnvId, permissionsManifest)+ );const shortcutItems = $derived.by(() => {- const items: NavigationItem[] = [...managementItems, ...navigationItems.resourceItems, ...settingsShortcutItems];+ const items: NavigationItem[] = [...managementItems, ...resourceItems, ...settingsShortcutItems];return flattenNavigationItems(items).filter((item) => item.shortcut?.length);});$effect(() => {- const redirectPath = getAuthRedirectPath(page.url.pathname, user, currentEnvId);+ const redirectPath = getAuthRedirectPath(page.url.pathname, user, currentEnvId, permissionsManifest);if (redirectPath) {goto(redirectPath);}@@ -95,10 +102,10 @@{@render children()}</section></main>- <MobileNav {navigationSettings} {user} {versionInformation} {swarmEnabled} />+ <MobileNav {navigationSettings} {user} {versionInformation} {swarmEnabled} {permissionsManifest} />{:else}<Sidebar.Provider>- <AppSidebar {versionInformation} {user} {swarmEnabled} />+ <AppSidebar {versionInformation} {user} {swarmEnabled} {permissionsManifest} /><main class="h-dvh flex-1"><section class="h-full p-3 sm:p-5">{@render children()}diff --git a/frontend/src/routes/(app)/customize/+page.svelte b/frontend/src/routes/(app)/customize/+page.svelteindex 0ea3a6529..5c8aa0893 100644--- a/frontend/src/routes/(app)/customize/+page.svelte+++ b/frontend/src/routes/(app)/customize/+page.svelte@@ -1,17 +1,15 @@<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 { canReachAccessSurfaceUrl } from '$lib/utils/access-policy';import * as InputGroup from '$lib/components/ui/input-group/index.js';import { getCustomizeSubpageUrlsInNavOrder } from '$lib/config/navigation-config';import {@@ -26,13 +24,15 @@} from '$lib/icons';import HeaderCard from '$lib/components/header-card.svelte';- let {}: PageProps = $props();+ let { data }: PageProps = $props();let searchQuery = $state('');let showSearchResults = $state(false);let searchResults = $state<CustomizeCategory[]>([]);let isSearching = $state(false);let customizeCategories = $state<CustomizeCategory[]>([]);let currentSearchRequest = $state(0);+ const user = $derived(data.user);+ const permissionsManifest = $derived(data.permissionsManifest);const iconMap: Record<string, any> = {'file-text': FileTextIcon,@@ -43,7 +43,8 @@};function isAccessibleCategory(category: CustomizeCategory) {- return getAuthRedirectPath(category.url, get(userStore), environmentStore.selected?.id) === null;+ if (!permissionsManifest?.accessSurfaces?.length) return true;+ return canReachAccessSurfaceUrl(permissionsManifest, category.url, user, environmentStore.selected?.id);}onMount(async () => {diff --git a/frontend/src/routes/(app)/settings/+page.svelte b/frontend/src/routes/(app)/settings/+page.svelteindex bd3f64baa..2ddf90b07 100644--- a/frontend/src/routes/(app)/settings/+page.svelte+++ b/frontend/src/routes/(app)/settings/+page.svelte@@ -1,6 +1,5 @@<script lang="ts">import { goto } from '$app/navigation';- import { get } from 'svelte/store';import { onMount } from 'svelte';import {SearchIcon,@@ -24,17 +23,16 @@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 { canReachAccessSurface, canReachAccessSurfaceUrl } from '$lib/utils/access-policy';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';import { Spinner } from '$lib/components/ui/spinner/index.js';- let {}: PageProps = $props();+ let { data }: PageProps = $props();let searchQuery = $state('');let showSearchResults = $state(false);@@ -42,7 +40,8 @@let isSearching = $state(false);let settingsCategories = $state<SettingsCategory[]>([]);let currentSearchRequest = $state(0);- const hiddenCategoryUrls = new Set(['/settings/security']);+ const user = $derived(data.user);+ const permissionsManifest = $derived(data.permissionsManifest);const iconMap: Record<string, any> = {settings: SettingsIcon,@@ -61,11 +60,7 @@onMount(async () => {try {- settingsCategories = orderCategoriesByNav(- (await settingsSearchService.getCategories()).filter(- (category) => isVisibleCategory(category) && isAccessibleCategory(category)- )- );+ settingsCategories = orderCategoriesByNav((await settingsSearchService.getCategories()).filter(isAccessibleCategory));} catch (error) {console.error('Failed to load categories:', error);}@@ -90,9 +85,7 @@try {const response = await settingsSearchService.search(trimmedQuery);if (requestId === currentSearchRequest) {- searchResults = (response.results || []).filter(- (category) => isVisibleCategory(category) && isAccessibleCategory(category)- );+ searchResults = (response.results || []).filter(isAccessibleCategory);isSearching = false;}} catch (error) {@@ -112,12 +105,19 @@goto(categoryUrl);}- function isVisibleCategory(category: SettingsCategory) {- return !hiddenCategoryUrls.has(category.url);+ function isAccessibleCategory(category: SettingsCategory) {+ if (!permissionsManifest?.accessSurfaces?.length) return true;+ if (category.id === 'jobschedule') {+ return canReachAccessSurface(permissionsManifest, 'settings.category.jobschedule', user, environmentStore.selected?.id);+ }+ return canReachAccessSurfaceUrl(permissionsManifest, category.url, user, environmentStore.selected?.id);}- function isAccessibleCategory(category: SettingsCategory) {- return getAuthRedirectPath(category.url, get(userStore), environmentStore.selected?.id) === null;+ function getCategoryUrl(category: SettingsCategory) {+ if (category.id === 'jobschedule') {+ return `/environments/${environmentStore.selected?.id ?? '0'}?tab=jobs`;+ }+ return category.url;}function orderCategoriesByNav(categories: SettingsCategory[]) {@@ -205,7 +205,7 @@{#each settingsCategories as category (category.id)}{@const Icon = getIconComponent(category.icon)}<Card class="hover:border-primary/30 group cursor-pointer transition-colors duration-200">- <button onclick={() => navigateToCategory(category.url)} class="w-full p-4 text-left sm:p-6">+ <button onclick={() => navigateToCategory(getCategoryUrl(category))} class="w-full p-4 text-left sm:p-6"><div class="flex items-start justify-between gap-3"><div class="flex min-w-0 flex-1 items-start gap-3 sm:gap-4"><div@@ -261,7 +261,7 @@action="base"tone="outline"size="sm"- onclick={() => navigateToCategory(result.url)}+ onclick={() => navigateToCategory(getCategoryUrl(result))}class="shrink-0"customLabel={m.settings_go_to_page()}/>diff --git a/frontend/src/routes/(app)/settings/users/user-table.svelte b/frontend/src/routes/(app)/settings/users/user-table.svelteindex 311c500e8..8e427a6b0 100644--- a/frontend/src/routes/(app)/settings/users/user-table.svelte+++ b/frontend/src/routes/(app)/settings/users/user-table.svelte@@ -127,9 +127,9 @@type BadgeVariant = 'red' | 'blue' | 'purple' | 'gray' | 'green';- /** True when the user holds the built-in Admin role globally. */+ /** True when the backend reports effective global administrator access. */function isGlobalAdmin(user: User): boolean {- return !!user.roleAssignments?.some((a) => a.roleId === BUILT_IN_ROLE_ADMIN && !a.environmentId);+ return user.isGlobalAdmin === true;}/** Color variant for a role badge keyed off the role ID (not its localized name). */diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.tsindex 82d42c2d4..258bc149e 100644--- a/frontend/src/routes/+layout.ts+++ b/frontend/src/routes/+layout.ts@@ -1,6 +1,7 @@import { browser } from '$app/environment';import { environmentManagementService } from '$lib/services/env-mgmt-service';import { settingsService } from '$lib/services/settings-service';+import { roleService } from '$lib/services/role-service';import { swarmService } from '$lib/services/swarm-service';import { userService } from '$lib/services/user-service';import versionService from '$lib/services/version-service';@@ -63,6 +64,7 @@ export const load = async () => {// Step 2: Only fetch authenticated data if user is logged inlet settings = null;let swarmEnabled = false;+ let permissionsManifest = null;if (user) {// Initialize environment store (required for settings service)const environmentRequestOptions: SearchPaginationSortRequest = {@@ -81,12 +83,14 @@ export const load = async () => {// Fetch settings after environment store is initialized// Settings service depends on environmentStore.getCurrentEnvironmentId()- const [loadedSettings, loadedSwarmStatus] = await Promise.all([+ const [loadedSettings, loadedSwarmStatus, loadedPermissionsManifest] = await Promise.all([settingsService.getSettings().catch(() => null),- swarmService.getSwarmStatus().catch(() => null)+ swarmService.getSwarmStatus().catch(() => null),+ roleService.getPermissionsManifest().catch(() => null)]);settings = loadedSettings;swarmEnabled = loadedSwarmStatus?.enabled === true;+ permissionsManifest = loadedPermissionsManifest;} else {// Initialize empty environment store for unauthenticated usersawait environmentStore.initialize([]);@@ -140,6 +144,7 @@ export const load = async () => {return {user,settings,+ permissionsManifest,versionInformation,queryClient,swarmEnableddiff --git a/types/role/role.go b/types/role/role.goindex 375db3337..5ad31db51 100644--- a/types/role/role.go+++ b/types/role/role.go@@ -98,8 +98,9 @@ type UpdateOidcRoleMapping struct {// grouped by resource. The frontend uses this to render the permission// 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"`+ 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"`+ AccessSurfaces []AccessSurface `json:"accessSurfaces,omitempty" doc:"Backend-owned route, landing, and category access metadata for frontend UX gating"`}// PermissionResource is one resource group in the manifest (e.g. "containers").@@ -127,6 +128,22 @@ type PermissionPreset struct {Permissions []string `json:"permissions" doc:"Permissions included when the preset is selected"`}+// AccessSurface describes one UI surface whose visibility is driven by+// backend-owned RBAC metadata. It is advisory UX metadata; backend handlers and+// middleware remain authoritative for actual enforcement.+type AccessSurface struct {+ ID string `json:"id" doc:"Stable surface identifier" example:"settings.category.webhooks"`+ Kind string `json:"kind" enum:"route,settings-category,customize-category,landing" doc:"Surface type"`+ URL string `json:"url,omitempty" doc:"Route URL or prefix represented by this surface" example:"/settings/webhooks"`+ Label string `json:"label" doc:"Human-readable surface label" example:"Webhooks"`+ AccessMode string `json:"accessMode" enum:"permissions,any-child" doc:"How reachability is evaluated"`+ MatchMode string `json:"matchMode" enum:"any-of,all-of" doc:"How permissions are combined when accessMode is permissions"`+ ScopeMode string `json:"scopeMode" enum:"global-only,selected-env-plus-global,any-effective-scope" doc:"Which effective permission scope is considered"`+ Permissions []string `json:"permissions,omitempty" doc:"Permissions used by permission-based surfaces"`+ Children []string `json:"children,omitempty" doc:"Child surface IDs used by aggregate landing surfaces"`+ FallbackOrder int `json:"fallbackOrder,omitempty" doc:"Positive ordering hint for route fallback selection"`+}+// ApiKeyPermissionGrant is one permission grant on an API key, optionally// scoped to a single environment. Used by the API key create/update flow.type ApiKeyPermissionGrant struct {