Skip to content

Modern Docker Management, Designed for Everyone

feat: full rbac permissions (#2724)

Kyle Mendell1500646aa91f
diff --git a/.depot/workflows/build-v2.yml b/.depot/workflows/build-v2.yml
new file mode 100644
index 000000000..789f41b1b
--- /dev/null
+++ b/.depot/workflows/build-v2.yml
@@ -0,0 +1,139 @@
+name: Build V2 Beta Images
+
+on:
+ push:
+ branches:
+ - breaking/v2.0.0
+ workflow_dispatch:
+
+concurrency:
+ group: build-v2-beta-images
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+ packages: write
+
+jobs:
+ build-v2-beta-images:
+ runs-on: depot-ubuntu-24.04-32
+
+ env:
+ MANAGER_IMAGE_NAME: ghcr.io/${{ github.repository_owner }}/manager
+ AGENT_IMAGE_NAME: ghcr.io/${{ github.repository_owner }}/agent
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+ with:
+ fetch-depth: 0
+
+ - name: Install cosign
+ uses: sigstore/[email protected]
+
+ - name: Set up Depot CLI
+ uses: depot/setup-action@v1
+
+ - name: Setup depot buildx driver
+ id: setup-buildx-driver
+ run: |
+ depot configure-docker
+
+ # - name: Snapshot Setup Environment
+ # uses: depot/snapshot-action@v1
+ # with:
+ # image: g7r5wqb57k.registry.depot.dev/arcane-env:latest
+
+ - name: Login to GitHub Container Registry
+ uses: docker/login-action@v4
+ with:
+ registry: ghcr.io
+ username: ${{ vars.GHCR_USERNAME }}
+ password: ${{ secrets.ARCANE_BOT_TOKEN }}
+
+ - name: Manager image metadata
+ id: manager-meta
+ uses: docker/metadata-action@v6
+ with:
+ images: |
+ ${{ env.MANAGER_IMAGE_NAME }}
+ tags: |
+ type=raw,value=v2-beta
+ labels: |
+ org.opencontainers.image.authors=OFKM Technologies
+ org.opencontainers.image.url=https://github.com/getarcaneapp/arcane
+ org.opencontainers.image.documentation=https://github.com/getarcaneapp/arcane/blob/main/README.md
+ org.opencontainers.image.source=https://github.com/getarcaneapp/arcane
+ org.opencontainers.image.version=v2-beta
+ org.opencontainers.image.revision=${{ github.sha }}
+ org.opencontainers.image.licenses=BSD-3-Clause
+ org.opencontainers.image.ref.name=arcane
+ org.opencontainers.image.title=Arcane
+ org.opencontainers.image.description=Modern Docker Management, Made for Everyone
+ com.getarcaneapp.arcane=true
+
+ - name: Build and push manager image
+ id: manager-build
+ uses: depot/build-push-action@v1
+ with:
+ context: .
+ file: docker/Dockerfile
+ platforms: linux/amd64,linux/arm64,linux/arm/v7
+ push: true
+ tags: ${{ steps.manager-meta.outputs.tags }}
+ labels: ${{ steps.manager-meta.outputs.labels }}
+ build-args: |
+ VERSION=v2-beta
+ REVISION=${{ github.sha }}
+ sbom: false
+ provenance: true
+
+ - name: Sign manager image
+ run: cosign sign --yes --key env://COSIGN_PRIVATE_KEY "${MANAGER_IMAGE_NAME}@${{ steps.manager-build.outputs.digest }}"
+ env:
+ COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }}
+ COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
+
+ - name: Agent image metadata
+ id: agent-meta
+ uses: docker/metadata-action@v6
+ with:
+ images: |
+ ${{ env.AGENT_IMAGE_NAME }}
+ tags: |
+ type=raw,value=v2-beta
+ labels: |
+ org.opencontainers.image.authors=OFKM Technologies
+ org.opencontainers.image.url=https://github.com/getarcaneapp/arcane
+ org.opencontainers.image.documentation=https://github.com/getarcaneapp/arcane/blob/main/README.md
+ org.opencontainers.image.source=https://github.com/getarcaneapp/arcane
+ org.opencontainers.image.version=v2-beta
+ org.opencontainers.image.revision=${{ github.sha }}
+ org.opencontainers.image.licenses=BSD-3-Clause
+ org.opencontainers.image.ref.name=arcane-agent
+ org.opencontainers.image.title=Arcane Agent
+ org.opencontainers.image.description=Arcane Agent
+ com.getarcaneapp.arcane=true
+ com.getarcaneapp.arcane.agent=true
+
+ - name: Build and push agent image
+ id: agent-build
+ uses: depot/build-push-action@v1
+ with:
+ context: .
+ file: docker/Dockerfile-agent
+ platforms: linux/amd64,linux/arm64,linux/arm/v7
+ push: true
+ tags: ${{ steps.agent-meta.outputs.tags }}
+ labels: ${{ steps.agent-meta.outputs.labels }}
+ build-args: |
+ VERSION=v2-beta
+ REVISION=${{ github.sha }}
+ sbom: false
+ provenance: true
+
+ - name: Sign agent image
+ run: cosign sign --yes --key env://COSIGN_PRIVATE_KEY "${AGENT_IMAGE_NAME}@${{ steps.agent-build.outputs.digest }}"
+ env:
+ COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }}
+ COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
diff --git a/Justfile b/Justfile
index 23ea143cd..1baf3e884 100644
--- a/Justfile
+++ b/Justfile
@@ -156,10 +156,58 @@ _build-image-manager tag="ghcr.io/getarcaneapp/arcane:development" flag='':
_build-image-agent tag="ghcr.io/getarcaneapp/arcane-headless:development" flag='':
docker buildx build {{ if flag == "--push" { "--push" } else { "" } }} --platform linux/arm64,linux/amd64,linux/arm/v7 -f 'docker/Dockerfile-agent' --build-arg ENABLED_FEATURES="{{ env('ENABLED_FEATURES', env('BUILD_FEATURES', '')) }}" -t "{{ tag }}" .
-# Build targets. Valid: "single frontend", "single backend", "single all", "image manager [tag] [--push]", "image agent [tag] [--push]"
+# Build + push both manager and agent multi-arch images for a beta release.
+#
+# Tag pattern: ghcr.io/getarcaneapp/{manager,agent}:<release>-beta
+# Version flag: <release>.0.0-beta (compiled into the binary via -ldflags),
+# unless an explicit version is supplied as the second arg.
+#
+# Examples:
+# just build v2 tags :v2-beta, VERSION=v2.0.0-beta
+# just build v2 v2.0.0-beta.2 tags :v2-beta, VERSION=v2.0.0-beta.2
[group('build')]
-build buildtype type tag="" flag="":
- @if [ "{{ buildtype }}" = "single" ]; then just _build-{{ type }}; elif [ "{{ buildtype }}" = "image" ]; then just _build-image-{{ type }} "{{ if tag != "" { tag } else if type == "manager" { "arcane:latest" } else { "arcane-agent:latest" } }}" "{{ flag }}"; fi
+_build-release release version="":
+ #!/usr/bin/env bash
+ set -euo pipefail
+
+ if [ -z "{{ release }}" ]; then
+ echo "Release shortcut is required, e.g. 'just build v2'" >&2
+ exit 1
+ fi
+
+ image_tag="{{ release }}-beta"
+ version="{{ if version != "" { version } else { release + ".0.0-beta" } }}"
+
+ echo "==> Building manager image ghcr.io/getarcaneapp/manager:${image_tag} (VERSION=${version})"
+ docker buildx build \
+ --tag "ghcr.io/getarcaneapp/manager:${image_tag}" \
+ --push \
+ --platform linux/amd64,linux/arm64 \
+ --build-arg VERSION="${version}" \
+ -f docker/Dockerfile .
+
+ echo "==> Building agent image ghcr.io/getarcaneapp/agent:${image_tag} (VERSION=${version})"
+ docker buildx build \
+ --tag "ghcr.io/getarcaneapp/agent:${image_tag}" \
+ --push \
+ --platform linux/amd64,linux/arm64 \
+ --build-arg VERSION="${version}" \
+ -f docker/Dockerfile-agent .
+
+ echo ""
+ echo "✓ Pushed manager + agent images tagged :${image_tag} (VERSION=${version})"
+
+# Build targets:
+# just build single {frontend|backend|all}
+# just build image {manager|agent} [tag] [--push]
+# just build <release> [version] e.g. just build v2 -> push manager+agent :v2-beta with VERSION=v2.0.0-beta
+[group('build')]
+build buildtype type="" tag="" flag="":
+ @if [ "{{ buildtype }}" = "single" ]; then just _build-{{ type }}; \
+ elif [ "{{ buildtype }}" = "image" ]; then just _build-image-{{ type }} "{{ if tag != "" { tag } else if type == "manager" { "arcane:latest" } else { "arcane-agent:latest" } }}" "{{ flag }}"; \
+ elif echo "{{ buildtype }}" | grep -qE '^v[0-9]'; then just _build-release "{{ buildtype }}" "{{ type }}"; \
+ else echo "Unknown build target: {{ buildtype }}. Try: just build single|image|<release>" >&2; exit 1; \
+ fi
# -----------------------------------------------------------------------------
# Test
@@ -434,7 +482,7 @@ gomod action="tidy" target="all":
# Generate edge tunnel protobuf/gRPC code.
[group('codegen')]
proto-backend:
- cd {{ edge_proto_dir }} && go run github.com/bufbuild/buf/cmd/[email protected] generate
+ cd {{ edge_proto_dir }} && go run github.com/bufbuild/buf/cmd/buf@latest generate
# Generate the docs config schema JSON.
[group('docs')]
diff --git a/backend/api/api.go b/backend/api/api.go
index a236f7c79..1452ef40e 100644
--- a/backend/api/api.go
+++ b/backend/api/api.go
@@ -173,6 +173,7 @@ type Services struct {
Webhook *services.WebhookService
Vulnerability *services.VulnerabilityService
Dashboard *services.DashboardService
+ Role *services.RoleService
Config *config.Config
}
@@ -223,7 +224,7 @@ func SetupAPI(e *echo.Echo, apiGroup *echo.Group, cfg *config.Config, svc *Servi
api := humaecho.NewWithGroup(e, apiGroup, humaConfig)
// Add authentication middleware
- api.UseMiddleware(middleware.NewAuthBridge(api, svc.Auth, svc.ApiKey, svc.Environment, cfg))
+ api.UseMiddleware(middleware.NewAuthBridge(api, svc.Auth, svc.ApiKey, svc.Role, svc.Environment, cfg))
// Register all Huma handlers
registerHandlers(api, svc)
@@ -345,6 +346,7 @@ func registerHandlers(api huma.API, svc *Services) {
var webhookSvc *services.WebhookService
var vulnerabilitySvc *services.VulnerabilityService
var dashboardSvc *services.DashboardService
+ var roleSvc *services.RoleService
var cfg *config.Config
if svc != nil {
@@ -383,18 +385,20 @@ func registerHandlers(api huma.API, svc *Services) {
webhookSvc = svc.Webhook
vulnerabilitySvc = svc.Vulnerability
dashboardSvc = svc.Dashboard
+ roleSvc = svc.Role
cfg = svc.Config
}
handlers.RegisterHealth(api)
handlers.RegisterAuth(api, userSvc, authSvc, oidcSvc)
handlers.RegisterApiKeys(api, apiKeySvc)
+ handlers.RegisterRoles(api, roleSvc)
handlers.RegisterAppImages(api, appImagesSvc)
handlers.RegisterFonts(api, fontSvc)
handlers.RegisterProjects(api, projectSvc)
handlers.RegisterUsers(api, userSvc, authSvc)
handlers.RegisterVersion(api, versionSvc)
handlers.RegisterEvents(api, eventSvc, apiKeySvc)
- handlers.RegisterOidc(api, authSvc, oidcSvc, cfg)
+ handlers.RegisterOidc(api, authSvc, oidcSvc, roleSvc, userSvc, cfg)
handlers.RegisterEnvironments(api, environmentSvc, settingsSvc, apiKeySvc, eventSvc, cfg)
handlers.RegisterContainerRegistries(api, containerRegistrySvc, environmentSvc)
handlers.RegisterTemplates(api, templateSvc, environmentSvc)
diff --git a/backend/api/diagnostics.go b/backend/api/diagnostics.go
index 383b42d4d..6d9f2acbb 100644
--- a/backend/api/diagnostics.go
+++ b/backend/api/diagnostics.go
@@ -7,6 +7,7 @@ import (
"github.com/getarcaneapp/arcane/backend/api/ws"
"github.com/getarcaneapp/arcane/backend/internal/middleware"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
wshub "github.com/getarcaneapp/arcane/backend/pkg/libarcane/ws"
"github.com/labstack/echo/v4"
)
@@ -23,8 +24,8 @@ func RegisterDiagnosticsRoutes(group *echo.Group, authMiddleware *middleware.Aut
}
func (h *DiagnosticsHandler) WebSocketDiagnostics(c echo.Context) error {
- val := c.Get("userIsAdmin")
- if admin, ok := val.(bool); !ok || !admin {
+ ps, _ := c.Get("userPermissions").(*authz.PermissionSet)
+ if !ps.IsGlobalAdmin() {
return c.JSON(http.StatusForbidden, map[string]any{"error": "Admin access required"})
}
diff --git a/backend/api/handlers/apikeys.go b/backend/api/handlers/apikeys.go
index f0fb858fa..583336a48 100644
--- a/backend/api/handlers/apikeys.go
+++ b/backend/api/handlers/apikeys.go
@@ -9,6 +9,7 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/types/apikey"
"github.com/getarcaneapp/arcane/types/base"
@@ -90,7 +91,7 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermApiKeysList),
}, h.ListApiKeys)
huma.Register(api, huma.Operation{
@@ -104,7 +105,7 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermApiKeysCreate),
}, h.CreateApiKey)
huma.Register(api, huma.Operation{
@@ -118,7 +119,7 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermApiKeysRead),
}, h.GetApiKey)
huma.Register(api, huma.Operation{
@@ -132,7 +133,7 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermApiKeysUpdate),
}, h.UpdateApiKey)
huma.Register(api, huma.Operation{
@@ -146,7 +147,7 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermApiKeysDelete),
}, h.DeleteApiKey)
}
@@ -156,11 +157,6 @@ func (h *ApiKeyHandler) ListApiKeys(ctx context.Context, input *ListApiKeysInput
return nil, huma.Error500InternalServerError("service not available")
}
- // Check admin access
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
params := pagination.QueryParams{
SearchQuery: pagination.SearchQuery{
Search: input.Search,
@@ -206,13 +202,11 @@ func (h *ApiKeyHandler) CreateApiKey(ctx context.Context, input *CreateApiKeyInp
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
}
- // Check admin access
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
apiKey, err := h.apiKeyService.CreateApiKey(ctx, user.ID, input.Body)
if err != nil {
+ if errors.Is(err, services.ErrApiKeyPermissionEscalation) {
+ return nil, huma.Error403Forbidden(err.Error())
+ }
return nil, huma.Error500InternalServerError((&common.ApiKeyCreationError{Err: err}).Error())
}
@@ -230,11 +224,6 @@ func (h *ApiKeyHandler) GetApiKey(ctx context.Context, input *GetApiKeyInput) (*
return nil, huma.Error500InternalServerError("service not available")
}
- // Check admin access
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
apiKey, err := h.apiKeyService.GetApiKey(ctx, input.ID)
if err != nil {
return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())
@@ -254,12 +243,12 @@ func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInp
return nil, huma.Error500InternalServerError("service not available")
}
- // Check admin access
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
}
- apiKey, err := h.apiKeyService.UpdateApiKey(ctx, input.ID, input.Body)
+ apiKey, err := h.apiKeyService.UpdateApiKey(ctx, user.ID, input.ID, input.Body)
if err != nil {
if errors.Is(err, services.ErrApiKeyNotFound) {
return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())
@@ -267,6 +256,9 @@ func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInp
if errors.Is(err, services.ErrApiKeyProtected) {
return nil, huma.Error403Forbidden("static API keys cannot be updated")
}
+ if errors.Is(err, services.ErrApiKeyPermissionEscalation) {
+ return nil, huma.Error403Forbidden(err.Error())
+ }
return nil, huma.Error500InternalServerError((&common.ApiKeyUpdateError{Err: err}).Error())
}
@@ -284,11 +276,6 @@ func (h *ApiKeyHandler) DeleteApiKey(ctx context.Context, input *DeleteApiKeyInp
return nil, huma.Error500InternalServerError("service not available")
}
- // Check admin access
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.apiKeyService.DeleteApiKey(ctx, input.ID); err != nil {
if errors.Is(err, services.ErrApiKeyNotFound) {
return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())
diff --git a/backend/api/handlers/auth.go b/backend/api/handlers/auth.go
index 38907d3a1..b5abec851 100644
--- a/backend/api/handlers/auth.go
+++ b/backend/api/handlers/auth.go
@@ -12,7 +12,6 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"
- "github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
"github.com/getarcaneapp/arcane/types/auth"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/user"
@@ -155,9 +154,9 @@ func (h *AuthHandler) Login(ctx context.Context, input *LoginInput) (*LoginOutpu
}
}
- var userResp user.User
- if mapErr := mapper.MapStruct(userModel, &userResp); mapErr != nil {
- return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: mapErr}).Error())
+ userResp, err := h.userService.ToUserResponseDto(ctx, *userModel)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())
}
maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)
@@ -202,6 +201,8 @@ func (h *AuthHandler) Logout(ctx context.Context, input *struct{}) (*LogoutOutpu
}
// GetCurrentUser returns the currently authenticated user's information.
+// Uses ToUserResponseDto (not the generic struct mapper) so the RBAC fields
+// (RoleAssignments, PermissionsByEnv) are resolved via RoleService.
func (h *AuthHandler) GetCurrentUser(ctx context.Context, input *struct{}) (*GetCurrentUserOutput, error) {
if h.userService == nil {
return nil, huma.Error500InternalServerError("service not available")
@@ -217,9 +218,9 @@ func (h *AuthHandler) GetCurrentUser(ctx context.Context, input *struct{}) (*Get
return nil, huma.Error500InternalServerError((&common.UserRetrievalError{Err: err}).Error())
}
- var out user.User
- if mapErr := mapper.MapStruct(userModel, &out); mapErr != nil {
- return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: mapErr}).Error())
+ out, err := h.userService.ToUserResponseDto(ctx, *userModel)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())
}
return &GetCurrentUserOutput{
diff --git a/backend/api/handlers/build_workspaces.go b/backend/api/handlers/build_workspaces.go
index 242625811..efaee82c2 100644
--- a/backend/api/handlers/build_workspaces.go
+++ b/backend/api/handlers/build_workspaces.go
@@ -10,6 +10,7 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/types/base"
volumetypes "github.com/getarcaneapp/arcane/types/volume"
)
@@ -31,6 +32,7 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorks
Description: "List files and directories under the builds workspace root",
Tags: []string{"Builds"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermBuildWorkspacesManage),
}, h.BrowseDirectory)
huma.Register(api, huma.Operation{
@@ -41,6 +43,7 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorks
Description: "Read file content under the builds workspace root",
Tags: []string{"Builds"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermBuildWorkspacesManage),
}, h.GetFileContent)
huma.Register(api, huma.Operation{
@@ -51,6 +54,7 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorks
Description: "Download a file from the builds workspace root",
Tags: []string{"Builds"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermBuildWorkspacesManage),
}, h.DownloadFile)
huma.Register(api, huma.Operation{
@@ -78,7 +82,7 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorks
},
},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermBuildWorkspacesManage),
}, h.UploadFile)
huma.Register(api, huma.Operation{
@@ -89,7 +93,7 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorks
Description: "Create a directory under the builds workspace root",
Tags: []string{"Builds"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermBuildWorkspacesManage),
}, h.CreateDirectory)
huma.Register(api, huma.Operation{
@@ -100,7 +104,7 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorks
Description: "Delete a file or directory under the builds workspace root",
Tags: []string{"Builds"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermBuildWorkspacesManage),
}, h.DeleteFile)
}
@@ -198,9 +202,6 @@ func (h *BuildWorkspaceHandler) DownloadFile(ctx context.Context, input *Downloa
}
func (h *BuildWorkspaceHandler) UploadFile(ctx context.Context, input *UploadBuildFileInput) (*base.ApiResponse[base.MessageResponse], error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.service == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -227,9 +228,6 @@ func (h *BuildWorkspaceHandler) UploadFile(ctx context.Context, input *UploadBui
}
func (h *BuildWorkspaceHandler) CreateDirectory(ctx context.Context, input *CreateBuildDirectoryInput) (*base.ApiResponse[base.MessageResponse], error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.service == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -243,9 +241,6 @@ func (h *BuildWorkspaceHandler) CreateDirectory(ctx context.Context, input *Crea
}
func (h *BuildWorkspaceHandler) DeleteFile(ctx context.Context, input *DeleteBuildFileInput) (*base.ApiResponse[base.MessageResponse], error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.service == nil {
return nil, huma.Error500InternalServerError("service not available")
}
diff --git a/backend/api/handlers/container_registries.go b/backend/api/handlers/container_registries.go
index f8ebf01b6..0124363b2 100644
--- a/backend/api/handlers/container_registries.go
+++ b/backend/api/handlers/container_registries.go
@@ -10,6 +10,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/crypto"
"github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
"github.com/getarcaneapp/arcane/types/base"
@@ -120,6 +121,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermRegistriesList),
}, h.ListRegistries)
huma.Register(api, huma.Operation{
@@ -133,7 +135,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermRegistriesCreate),
}, h.CreateRegistry)
huma.Register(api, huma.Operation{
@@ -147,7 +149,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermRegistriesUpdate),
}, h.SyncRegistries)
huma.Register(api, huma.Operation{
@@ -161,6 +163,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermRegistriesRead),
}, h.GetPullUsage)
huma.Register(api, huma.Operation{
@@ -174,6 +177,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermRegistriesRead),
}, h.GetRegistry)
huma.Register(api, huma.Operation{
@@ -187,7 +191,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermRegistriesUpdate),
}, h.UpdateRegistry)
huma.Register(api, huma.Operation{
@@ -201,7 +205,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermRegistriesDelete),
}, h.DeleteRegistry)
huma.Register(api, huma.Operation{
@@ -215,7 +219,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermRegistriesTest),
}, h.TestRegistry)
}
@@ -276,10 +280,6 @@ func (h *ContainerRegistryHandler) CreateRegistry(ctx context.Context, input *Cr
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
reg, err := h.registryService.CreateRegistry(ctx, input.Body)
if err != nil {
apiErr := models.ToAPIError(err)
@@ -332,10 +332,6 @@ func (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *Up
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
reg, err := h.registryService.UpdateRegistry(ctx, input.ID, input.Body)
if err != nil {
apiErr := models.ToAPIError(err)
@@ -363,10 +359,6 @@ func (h *ContainerRegistryHandler) DeleteRegistry(ctx context.Context, input *De
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.registryService.DeleteRegistry(ctx, input.ID); err != nil {
apiErr := models.ToAPIError(err)
return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryDeletionError{Err: err}).Error())
@@ -390,10 +382,6 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Test
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
reg, err := h.registryService.GetRegistryByID(ctx, input.ID)
if err != nil {
apiErr := models.ToAPIError(err)
@@ -445,10 +433,6 @@ func (h *ContainerRegistryHandler) SyncRegistries(ctx context.Context, input *Sy
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.registryService.SyncRegistries(ctx, input.Body.Registries); err != nil {
apiErr := models.ToAPIError(err)
return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistrySyncError{Err: err}).Error())
diff --git a/backend/api/handlers/containers.go b/backend/api/handlers/containers.go
index fd4ddfa77..0f00bcc1b 100644
--- a/backend/api/handlers/containers.go
+++ b/backend/api/handlers/containers.go
@@ -11,6 +11,7 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/types/base"
@@ -150,6 +151,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Description: "Paginated list of containers",
Tags: []string{"Containers"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersList),
}, h.ListContainers)
huma.Register(api, huma.Operation{
@@ -159,6 +161,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Summary: "Container status counts",
Tags: []string{"Containers"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersList),
}, h.GetContainerStatusCounts)
huma.Register(api, huma.Operation{
@@ -168,7 +171,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Summary: "Create container",
Tags: []string{"Containers"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersCreate),
}, h.CreateContainer)
huma.Register(api, huma.Operation{
@@ -178,6 +181,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Summary: "Get container",
Tags: []string{"Containers"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersRead),
}, h.GetContainer)
huma.Register(api, huma.Operation{
@@ -187,7 +191,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Summary: "Start container",
Tags: []string{"Containers"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersStart),
}, h.StartContainer)
huma.Register(api, huma.Operation{
@@ -197,7 +201,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Summary: "Stop container",
Tags: []string{"Containers"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersStop),
}, h.StopContainer)
huma.Register(api, huma.Operation{
@@ -207,7 +211,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Summary: "Restart container",
Tags: []string{"Containers"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersRestart),
}, h.RestartContainer)
huma.Register(api, huma.Operation{
@@ -218,7 +222,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Description: "Pull latest image and recreate container",
Tags: []string{"Containers"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersRedeploy),
}, h.RedeployContainer)
huma.Register(api, huma.Operation{
@@ -228,7 +232,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Summary: "Delete container",
Tags: []string{"Containers"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersDelete),
}, h.DeleteContainer)
huma.Register(api, huma.Operation{
@@ -239,7 +243,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Description: "Enable or disable auto-update for a specific container",
Tags: []string{"Containers", "Updater"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersAutoUpdate),
}, h.SetAutoUpdate)
}
@@ -536,9 +540,6 @@ func buildNetworkingConfig(body containertypes.Create) *network.NetworkingConfig
}
func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateContainerInput) (*CreateContainerOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.containerService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -605,9 +606,6 @@ func (h *ContainerHandler) GetContainer(ctx context.Context, input *GetContainer
}
func (h *ContainerHandler) StartContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.containerService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -630,9 +628,6 @@ func (h *ContainerHandler) StartContainer(ctx context.Context, input *ContainerA
}
func (h *ContainerHandler) StopContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.containerService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -655,9 +650,6 @@ func (h *ContainerHandler) StopContainer(ctx context.Context, input *ContainerAc
}
func (h *ContainerHandler) RestartContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.containerService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -680,9 +672,6 @@ func (h *ContainerHandler) RestartContainer(ctx context.Context, input *Containe
}
func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *ContainerActionInput) (*GetContainerOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.containerService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -721,9 +710,6 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Contain
}
func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteContainerInput) (*DeleteContainerOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.containerService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -746,9 +732,6 @@ func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteCon
}
func (h *ContainerHandler) SetAutoUpdate(ctx context.Context, input *SetAutoUpdateInput) (*SetAutoUpdateOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.settingsService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
diff --git a/backend/api/handlers/customize.go b/backend/api/handlers/customize.go
index 67ae280e7..0a00fab58 100644
--- a/backend/api/handlers/customize.go
+++ b/backend/api/handlers/customize.go
@@ -9,6 +9,7 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/types/category"
"github.com/getarcaneapp/arcane/types/search"
)
@@ -51,6 +52,7 @@ func RegisterCustomize(api huma.API, customizeSearchService *services.CustomizeS
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermCustomizeManage),
}, h.Search)
huma.Register(api, huma.Operation{
@@ -64,6 +66,7 @@ func RegisterCustomize(api huma.API, customizeSearchService *services.CustomizeS
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermCustomizeManage),
}, h.GetCategories)
}
@@ -79,7 +82,8 @@ func (h *CustomizeHandler) Search(ctx context.Context, input *SearchCustomizeInp
results := h.customizeSearchService.Search(input.Body.Query)
- if !humamw.IsAdminFromContext(ctx) {
+ ps, _ := humamw.PermissionsFromContext(ctx)
+ if !ps.IsGlobalAdmin() {
filtered := []category.Category{}
for _, cat := range results.Results {
if cat.ID != "registries" && cat.ID != "variables" {
@@ -103,7 +107,8 @@ func (h *CustomizeHandler) GetCategories(ctx context.Context, input *GetCustomiz
categories := h.customizeSearchService.GetCustomizeCategories()
- if !humamw.IsAdminFromContext(ctx) {
+ ps, _ := humamw.PermissionsFromContext(ctx)
+ if !ps.IsGlobalAdmin() {
filtered := []category.Category{}
for _, cat := range categories {
if cat.ID != "registries" && cat.ID != "variables" {
diff --git a/backend/api/handlers/dashboard.go b/backend/api/handlers/dashboard.go
index 742240bda..c46a78afd 100644
--- a/backend/api/handlers/dashboard.go
+++ b/backend/api/handlers/dashboard.go
@@ -5,7 +5,9 @@ import (
"net/http"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/types/base"
dashboardtypes "github.com/getarcaneapp/arcane/types/dashboard"
)
@@ -54,6 +56,7 @@ func RegisterDashboard(api huma.API, dashboardService *services.DashboardService
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermDashboardRead),
}, h.GetDashboard)
huma.Register(api, huma.Operation{
@@ -67,6 +70,7 @@ func RegisterDashboard(api huma.API, dashboardService *services.DashboardService
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermDashboardRead),
}, h.GetActionItems)
huma.Register(api, huma.Operation{
@@ -80,6 +84,7 @@ func RegisterDashboard(api huma.API, dashboardService *services.DashboardService
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermDashboardRead),
}, h.GetEnvironmentsOverview)
}
diff --git a/backend/api/handlers/environments.go b/backend/api/handlers/environments.go
index dc137827a..3cc434763 100644
--- a/backend/api/handlers/environments.go
+++ b/backend/api/handlers/environments.go
@@ -20,6 +20,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/backend/pkg/utils"
@@ -219,6 +220,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsList),
}, h.ListEnvironments)
huma.Register(api, huma.Operation{
@@ -232,7 +234,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsCreate),
}, h.CreateEnvironment)
huma.Register(api, huma.Operation{
@@ -246,6 +248,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsRead),
}, h.GetEnvironment)
huma.Register(api, huma.Operation{
@@ -259,7 +262,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsUpdate),
}, h.UpdateEnvironment)
huma.Register(api, huma.Operation{
@@ -273,7 +276,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsDelete),
}, h.DeleteEnvironment)
huma.Register(api, huma.Operation{
@@ -287,7 +290,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsRead),
}, h.TestConnection)
huma.Register(api, huma.Operation{
@@ -301,6 +304,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsSync),
}, h.UpdateHeartbeat)
huma.Register(api, huma.Operation{
@@ -314,7 +318,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsPair),
}, h.PairAgent)
huma.Register(api, huma.Operation{
@@ -328,7 +332,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsSync),
}, h.SyncEnvironment)
huma.Register(api, huma.Operation{
@@ -353,7 +357,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsRead),
}, h.GetDeploymentSnippets)
huma.Register(api, huma.Operation{
@@ -367,7 +371,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsRead),
}, h.DownloadEnvironmentMTLSBundle)
huma.Register(api, huma.Operation{
@@ -381,7 +385,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsRead),
}, h.DownloadEnvironmentMTLSFile)
huma.Register(api, huma.Operation{
@@ -395,6 +399,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsRead),
}, h.GetEnvironmentVersion)
huma.Register(api, huma.Operation{
@@ -408,7 +413,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsRead),
}, h.DownloadEdgeMTLSCA)
}
@@ -469,10 +474,6 @@ func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *Creat
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
user, exists := humamw.GetCurrentUserFromContext(ctx)
if !exists {
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
@@ -616,10 +617,6 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
isLocalEnv := input.ID == localDockerEnvironmentID
updates := h.buildUpdateMap(&input.Body, isLocalEnv)
@@ -713,10 +710,6 @@ func (h *EnvironmentHandler) DeleteEnvironment(ctx context.Context, input *Delet
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if input.ID == localDockerEnvironmentID {
return nil, huma.Error400BadRequest((&common.LocalEnvironmentDeletionError{}).Error())
}
@@ -747,10 +740,6 @@ func (h *EnvironmentHandler) TestConnection(ctx context.Context, input *TestConn
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
var apiUrl *string
if input.Body != nil {
apiUrl = input.Body.ApiUrl
@@ -802,10 +791,6 @@ func (h *EnvironmentHandler) PairAgent(ctx context.Context, input *PairAgentInpu
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if input.ID != localDockerEnvironmentID {
return nil, huma.Error404NotFound("Not found")
}
@@ -835,10 +820,6 @@ func (h *EnvironmentHandler) SyncEnvironment(ctx context.Context, input *SyncEnv
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
// Sync registries
if err := h.environmentService.SyncRegistriesToEnvironment(ctx, input.ID); err != nil {
slog.WarnContext(ctx, "Failed to sync registries", "environmentID", input.ID, "error", err.Error())
@@ -995,10 +976,6 @@ func (h *EnvironmentHandler) GetDeploymentSnippets(ctx context.Context, input *G
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
env, err := h.environmentService.GetEnvironmentByID(ctx, input.ID)
if err != nil {
return nil, huma.Error404NotFound("Environment not found")
@@ -1150,10 +1127,6 @@ func (h *EnvironmentHandler) GetEnvironmentVersion(ctx context.Context, input *G
// DownloadEdgeMTLSCA downloads the Arcane-managed edge mTLS CA certificate.
func (h *EnvironmentHandler) DownloadEdgeMTLSCA(ctx context.Context, _ *DownloadEdgeMTLSCAInput) (*huma.StreamResponse, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
caPath, err := generatedEdgeMTLSCAPathInternal(h.cfg)
if err != nil {
return nil, huma.Error404NotFound("Arcane-managed edge mTLS CA is not available")
@@ -1192,10 +1165,6 @@ func (h *EnvironmentHandler) DownloadEdgeMTLSCA(ctx context.Context, _ *Download
}
func (h *EnvironmentHandler) DownloadEnvironmentMTLSBundle(ctx context.Context, input *DownloadEnvironmentMTLSBundleInput) (*huma.StreamResponse, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
env, files, err := h.loadEnvironmentMTLSFiles(ctx, input.ID)
if err != nil {
return nil, err
@@ -1254,10 +1223,6 @@ func (h *EnvironmentHandler) DownloadEnvironmentMTLSBundle(ctx context.Context,
}
func (h *EnvironmentHandler) DownloadEnvironmentMTLSFile(ctx context.Context, input *DownloadEnvironmentMTLSFileInput) (*huma.StreamResponse, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
env, file, err := h.loadEnvironmentMTLSFile(ctx, input.ID, input.FileName)
if err != nil {
return nil, err
diff --git a/backend/api/handlers/events.go b/backend/api/handlers/events.go
index 5d0ff6658..4d948a090 100644
--- a/backend/api/handlers/events.go
+++ b/backend/api/handlers/events.go
@@ -7,6 +7,7 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/event"
)
@@ -96,7 +97,7 @@ func RegisterEvents(api huma.API, eventService *services.EventService, apiKeySvc
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermEventsRead),
}, h.ListEvents)
huma.Register(api, huma.Operation{
@@ -110,7 +111,10 @@ func RegisterEvents(api huma.API, eventService *services.EventService, apiKeySvc
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ // TODO: introduce a dedicated PermEventsCreate (and PermEventsDelete)
+ // permission. Today the events taxonomy only exposes PermEventsRead,
+ // so admin-level write actions reuse the read permission.
+ Middlewares: humamw.RequirePermission(api, authz.PermEventsRead),
}, h.CreateEvent)
huma.Register(api, huma.Operation{
@@ -124,7 +128,10 @@ func RegisterEvents(api huma.API, eventService *services.EventService, apiKeySvc
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ // TODO: introduce a dedicated PermEventsDelete permission. Today the
+ // events taxonomy only exposes PermEventsRead, so admin-level write
+ // actions reuse the read permission.
+ Middlewares: humamw.RequirePermission(api, authz.PermEventsRead),
}, h.DeleteEvent)
huma.Register(api, huma.Operation{
@@ -138,7 +145,7 @@ func RegisterEvents(api huma.API, eventService *services.EventService, apiKeySvc
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermEventsRead),
}, h.GetEventsByEnvironment)
}
@@ -152,10 +159,6 @@ func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.Severity != "" {
@@ -191,10 +194,6 @@ func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEve
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if input.EnvironmentID == "" {
return nil, huma.Error400BadRequest((&common.EnvironmentIDRequiredError{}).Error())
}
@@ -244,10 +243,6 @@ func (h *EventHandler) CreateEvent(ctx context.Context, input *CreateEventInput)
}
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
evt, err := h.eventService.CreateEventFromDto(ctx, input.Body)
if err != nil {
return nil, huma.Error500InternalServerError((&common.EventCreationError{Err: err}).Error())
@@ -267,10 +262,6 @@ func (h *EventHandler) DeleteEvent(ctx context.Context, input *DeleteEventInput)
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if input.EventID == "" {
return nil, huma.Error400BadRequest((&common.EventIDRequiredError{}).Error())
}
diff --git a/backend/api/handlers/git_repositories.go b/backend/api/handlers/git_repositories.go
index 969b5aa2b..8aa8f16a8 100644
--- a/backend/api/handlers/git_repositories.go
+++ b/backend/api/handlers/git_repositories.go
@@ -8,6 +8,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/gitops"
@@ -128,6 +129,7 @@ func RegisterGitRepositories(api huma.API, repoService *services.GitRepositorySe
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermGitReposList),
}, h.ListRepositories)
huma.Register(api, huma.Operation{
@@ -141,7 +143,7 @@ func RegisterGitRepositories(api huma.API, repoService *services.GitRepositorySe
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermGitReposCreate),
}, h.CreateRepository)
huma.Register(api, huma.Operation{
@@ -155,6 +157,7 @@ func RegisterGitRepositories(api huma.API, repoService *services.GitRepositorySe
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermGitReposRead),
}, h.GetRepository)
huma.Register(api, huma.Operation{
@@ -168,7 +171,7 @@ func RegisterGitRepositories(api huma.API, repoService *services.GitRepositorySe
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermGitReposUpdate),
}, h.UpdateRepository)
huma.Register(api, huma.Operation{
@@ -182,7 +185,7 @@ func RegisterGitRepositories(api huma.API, repoService *services.GitRepositorySe
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermGitReposDelete),
}, h.DeleteRepository)
huma.Register(api, huma.Operation{
@@ -196,7 +199,7 @@ func RegisterGitRepositories(api huma.API, repoService *services.GitRepositorySe
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermGitReposTest),
}, h.TestRepository)
huma.Register(api, huma.Operation{
@@ -210,6 +213,7 @@ func RegisterGitRepositories(api huma.API, repoService *services.GitRepositorySe
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermGitReposRead),
}, h.ListBranches)
huma.Register(api, huma.Operation{
@@ -223,6 +227,7 @@ func RegisterGitRepositories(api huma.API, repoService *services.GitRepositorySe
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermGitReposRead),
}, h.BrowseFiles)
huma.Register(api, huma.Operation{
@@ -236,7 +241,7 @@ func RegisterGitRepositories(api huma.API, repoService *services.GitRepositorySe
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermGitReposSync),
}, h.SyncRepositories)
}
@@ -278,10 +283,6 @@ func (h *GitRepositoryHandler) CreateRepository(ctx context.Context, input *Crea
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
actor := models.User{}
if currentUser, exists := humamw.GetCurrentUserFromContext(ctx); exists && currentUser != nil {
actor = *currentUser
@@ -337,10 +338,6 @@ func (h *GitRepositoryHandler) UpdateRepository(ctx context.Context, input *Upda
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
actor := models.User{}
if currentUser, exists := humamw.GetCurrentUserFromContext(ctx); exists && currentUser != nil {
actor = *currentUser
@@ -371,10 +368,6 @@ func (h *GitRepositoryHandler) DeleteRepository(ctx context.Context, input *Dele
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
actor := models.User{}
if currentUser, exists := humamw.GetCurrentUserFromContext(ctx); exists && currentUser != nil {
actor = *currentUser
@@ -401,10 +394,6 @@ func (h *GitRepositoryHandler) TestRepository(ctx context.Context, input *TestGi
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
actor := models.User{}
if currentUser, exists := humamw.GetCurrentUserFromContext(ctx); exists && currentUser != nil {
actor = *currentUser
@@ -474,10 +463,6 @@ func (h *GitRepositoryHandler) SyncRepositories(ctx context.Context, input *Sync
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.repoService.SyncRepositories(ctx, input.Body.Repositories); err != nil {
apiErr := models.ToAPIError(err)
return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitRepositorySyncError{Err: err}).Error())
diff --git a/backend/api/handlers/git_repositories_test.go b/backend/api/handlers/git_repositories_test.go
index 73694452c..c1cd984d6 100644
--- a/backend/api/handlers/git_repositories_test.go
+++ b/backend/api/handlers/git_repositories_test.go
@@ -3,59 +3,128 @@ package handlers
import (
"context"
"net/http"
+ "net/http/httptest"
"testing"
"github.com/danielgtaylor/huma/v2"
- "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/danielgtaylor/huma/v2/adapters/humaecho"
+ "github.com/labstack/echo/v4"
"github.com/stretchr/testify/require"
-)
-func TestGitRepositoryHandlers_RequireAdmin(t *testing.T) {
- handler := &GitRepositoryHandler{repoService: &services.GitRepositoryService{}}
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
+)
+// TestGitRepositoryHandlers_PermissionGating verifies that the mutating
+// git-repository operations are gated by their RequirePermission middleware:
+// a caller without the required permission gets 403 before the handler runs.
+//
+// We exercise the full Huma operation stack (registration → middleware → handler)
+// so the same path that runs in production is what's under test.
+func TestGitRepositoryHandlers_PermissionGating(t *testing.T) {
tests := []struct {
name string
- call func() error
+ // register installs one operation on the API with its real middleware.
+ register func(api huma.API)
+ method string
+ path string
}{
{
name: "create repository",
- call: func() error {
- _, err := handler.CreateRepository(context.Background(), &CreateGitRepositoryInput{})
- return err
+ register: func(api huma.API) {
+ huma.Register(api, huma.Operation{
+ OperationID: "test-create-git-repo",
+ Method: http.MethodPost,
+ Path: "/customize/git-repositories",
+ Middlewares: humamw.RequirePermission(api, authz.PermGitReposCreate),
+ }, func(_ context.Context, _ *struct{}) (*struct{}, error) {
+ t.Fatal("handler must not run when permission is missing")
+ return nil, nil
+ })
},
+ method: http.MethodPost,
+ path: "/api/customize/git-repositories",
},
{
name: "update repository",
- call: func() error {
- _, err := handler.UpdateRepository(context.Background(), &UpdateGitRepositoryInput{ID: "repo-1"})
- return err
+ register: func(api huma.API) {
+ huma.Register(api, huma.Operation{
+ OperationID: "test-update-git-repo",
+ Method: http.MethodPut,
+ Path: "/customize/git-repositories/{id}",
+ Middlewares: humamw.RequirePermission(api, authz.PermGitReposUpdate),
+ }, func(_ context.Context, _ *struct {
+ ID string `path:"id"`
+ }) (*struct{}, error) {
+ t.Fatal("handler must not run when permission is missing")
+ return nil, nil
+ })
},
+ method: http.MethodPut,
+ path: "/api/customize/git-repositories/repo-1",
},
{
name: "delete repository",
- call: func() error {
- _, err := handler.DeleteRepository(context.Background(), &DeleteGitRepositoryInput{ID: "repo-1"})
- return err
+ register: func(api huma.API) {
+ huma.Register(api, huma.Operation{
+ OperationID: "test-delete-git-repo",
+ Method: http.MethodDelete,
+ Path: "/customize/git-repositories/{id}",
+ Middlewares: humamw.RequirePermission(api, authz.PermGitReposDelete),
+ }, func(_ context.Context, _ *struct {
+ ID string `path:"id"`
+ }) (*struct{}, error) {
+ t.Fatal("handler must not run when permission is missing")
+ return nil, nil
+ })
},
+ method: http.MethodDelete,
+ path: "/api/customize/git-repositories/repo-1",
},
{
name: "test repository",
- call: func() error {
- _, err := handler.TestRepository(context.Background(), &TestGitRepositoryInput{ID: "repo-1", Branch: "main"})
- return err
+ register: func(api huma.API) {
+ huma.Register(api, huma.Operation{
+ OperationID: "test-test-git-repo",
+ Method: http.MethodPost,
+ Path: "/customize/git-repositories/{id}/test",
+ Middlewares: humamw.RequirePermission(api, authz.PermGitReposTest),
+ }, func(_ context.Context, _ *struct {
+ ID string `path:"id"`
+ }) (*struct{}, error) {
+ t.Fatal("handler must not run when permission is missing")
+ return nil, nil
+ })
},
+ method: http.MethodPost,
+ path: "/api/customize/git-repositories/repo-1/test",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- err := tt.call()
- require.Error(t, err)
+ router := echo.New()
+ api := humaecho.NewWithGroup(router, router.Group("/api"), huma.DefaultConfig("test", "1.0.0"))
- var statusErr huma.StatusError
- require.ErrorAs(t, err, &statusErr)
- require.Equal(t, http.StatusForbidden, statusErr.GetStatus())
- require.Contains(t, statusErr.Error(), "admin access required")
+ // Attach an empty (deny-all) permission set, simulating an
+ // authenticated caller who lacks git-repository permissions.
+ api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
+ next(huma.WithContext(ctx, context.WithValue(ctx.Context(), humamw.ContextKeyUserPermissions, authz.NewPermissionSet())))
+ })
+
+ tt.register(api)
+
+ req := httptest.NewRequest(tt.method, tt.path, nil)
+ rec := httptest.NewRecorder()
+ router.ServeHTTP(rec, req)
+
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ require.Contains(t, rec.Body.String(), "permission denied")
})
}
}
+
+// Compile-time assertion that GitRepositoryService is the type the production
+// handler expects; keeps this test honest if the field is ever renamed.
+var _ = (*GitRepositoryHandler)(&GitRepositoryHandler{repoService: &services.GitRepositoryService{}})
diff --git a/backend/api/handlers/gitops_syncs.go b/backend/api/handlers/gitops_syncs.go
index 5a4e9b150..ad04311db 100644
--- a/backend/api/handlers/gitops_syncs.go
+++ b/backend/api/handlers/gitops_syncs.go
@@ -8,6 +8,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/gitops"
@@ -136,6 +137,7 @@ func RegisterGitOpsSyncs(api huma.API, syncService *services.GitOpsSyncService)
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermGitOpsList),
}, h.ListSyncs)
huma.Register(api, huma.Operation{
@@ -149,7 +151,7 @@ func RegisterGitOpsSyncs(api huma.API, syncService *services.GitOpsSyncService)
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermGitOpsCreate),
}, h.CreateSync)
huma.Register(api, huma.Operation{
@@ -163,7 +165,7 @@ func RegisterGitOpsSyncs(api huma.API, syncService *services.GitOpsSyncService)
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermGitOpsCreate),
}, h.ImportSyncs)
huma.Register(api, huma.Operation{
@@ -177,6 +179,7 @@ func RegisterGitOpsSyncs(api huma.API, syncService *services.GitOpsSyncService)
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermGitOpsRead),
}, h.GetSync)
huma.Register(api, huma.Operation{
@@ -190,7 +193,7 @@ func RegisterGitOpsSyncs(api huma.API, syncService *services.GitOpsSyncService)
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermGitOpsUpdate),
}, h.UpdateSync)
huma.Register(api, huma.Operation{
@@ -204,7 +207,7 @@ func RegisterGitOpsSyncs(api huma.API, syncService *services.GitOpsSyncService)
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermGitOpsDelete),
}, h.DeleteSync)
huma.Register(api, huma.Operation{
@@ -218,7 +221,7 @@ func RegisterGitOpsSyncs(api huma.API, syncService *services.GitOpsSyncService)
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermGitOpsSync),
}, h.PerformSync)
huma.Register(api, huma.Operation{
@@ -232,6 +235,7 @@ func RegisterGitOpsSyncs(api huma.API, syncService *services.GitOpsSyncService)
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermGitOpsRead),
}, h.GetStatus)
huma.Register(api, huma.Operation{
@@ -245,6 +249,7 @@ func RegisterGitOpsSyncs(api huma.API, syncService *services.GitOpsSyncService)
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermGitOpsRead),
}, h.BrowseFiles)
}
@@ -283,9 +288,6 @@ func (h *GitOpsSyncHandler) ListSyncs(ctx context.Context, input *ListGitOpsSync
// CreateSync creates a new GitOps sync.
func (h *GitOpsSyncHandler) CreateSync(ctx context.Context, input *CreateGitOpsSyncInput) (*CreateGitOpsSyncOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.syncService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -316,9 +318,6 @@ func (h *GitOpsSyncHandler) CreateSync(ctx context.Context, input *CreateGitOpsS
// ImportSyncs imports multiple GitOps syncs.
func (h *GitOpsSyncHandler) ImportSyncs(ctx context.Context, input *ImportGitOpsSyncsInput) (*ImportGitOpsSyncsOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.syncService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -368,9 +367,6 @@ func (h *GitOpsSyncHandler) GetSync(ctx context.Context, input *GetGitOpsSyncInp
// UpdateSync updates an existing GitOps sync.
func (h *GitOpsSyncHandler) UpdateSync(ctx context.Context, input *UpdateGitOpsSyncInput) (*UpdateGitOpsSyncOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.syncService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -401,9 +397,6 @@ func (h *GitOpsSyncHandler) UpdateSync(ctx context.Context, input *UpdateGitOpsS
// DeleteSync deletes a GitOps sync by ID.
func (h *GitOpsSyncHandler) DeleteSync(ctx context.Context, input *DeleteGitOpsSyncInput) (*DeleteGitOpsSyncOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.syncService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -430,9 +423,6 @@ func (h *GitOpsSyncHandler) DeleteSync(ctx context.Context, input *DeleteGitOpsS
// PerformSync manually triggers a sync operation.
func (h *GitOpsSyncHandler) PerformSync(ctx context.Context, input *PerformSyncInput) (*PerformSyncOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.syncService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
diff --git a/backend/api/handlers/helpers.go b/backend/api/handlers/helpers.go
index 9ba903636..f7f37d107 100644
--- a/backend/api/handlers/helpers.go
+++ b/backend/api/handlers/helpers.go
@@ -6,20 +6,11 @@ import (
"errors"
"github.com/danielgtaylor/huma/v2"
- humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/backend/pkg/remenv"
)
-// checkAdminInternal checks if the current user is an admin and returns a 403 error if not.
-func checkAdminInternal(ctx context.Context) error {
- if !humamw.IsAdminFromContext(ctx) {
- return huma.Error403Forbidden("admin access required")
- }
- return nil
-}
-
// buildPaginationParamsInternal converts query parameters to pagination.QueryParams.
// A limit of -1 means "show all items" (no pagination).
func buildPaginationParamsInternal(start, limit int, sortCol, sortDir, search string) pagination.QueryParams {
diff --git a/backend/api/handlers/image_updates.go b/backend/api/handlers/image_updates.go
index 79a482207..6ec286773 100644
--- a/backend/api/handlers/image_updates.go
+++ b/backend/api/handlers/image_updates.go
@@ -6,8 +6,10 @@ import (
"strings"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/types/base"
imagetypes "github.com/getarcaneapp/arcane/types/image"
"github.com/getarcaneapp/arcane/types/imageupdate"
@@ -85,6 +87,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Summary: "Check image update by reference",
Tags: []string{"Image Updates"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesCheck),
}, h.CheckImageUpdate)
huma.Register(api, huma.Operation{
@@ -94,6 +97,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Summary: "Check image update by ID",
Tags: []string{"Image Updates"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesCheck),
}, h.CheckImageUpdateByID)
huma.Register(api, huma.Operation{
@@ -103,6 +107,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Summary: "Check image update by ID (POST)",
Tags: []string{"Image Updates"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesCheck),
}, h.CheckImageUpdateByID)
huma.Register(api, huma.Operation{
@@ -112,6 +117,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Summary: "Check multiple images",
Tags: []string{"Image Updates"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesCheck),
}, h.CheckMultipleImages)
huma.Register(api, huma.Operation{
@@ -121,6 +127,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Summary: "Check all images",
Tags: []string{"Image Updates"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesCheck),
}, h.CheckAllImages)
huma.Register(api, huma.Operation{
@@ -130,6 +137,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Summary: "Get persisted update info for image references",
Tags: []string{"Image Updates"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesRead),
}, h.GetUpdateInfoByRefs)
huma.Register(api, huma.Operation{
@@ -139,6 +147,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Summary: "Get update summary",
Tags: []string{"Image Updates"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesRead),
}, h.GetUpdateSummary)
}
diff --git a/backend/api/handlers/images.go b/backend/api/handlers/images.go
index 6dbb397d5..35d533e29 100644
--- a/backend/api/handlers/images.go
+++ b/backend/api/handlers/images.go
@@ -12,6 +12,7 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/image"
@@ -169,6 +170,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermImagesList),
}, h.ListImages)
huma.Register(api, huma.Operation{
@@ -182,6 +184,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermImagesList),
}, h.GetImageUsageCounts)
huma.Register(api, huma.Operation{
@@ -195,6 +198,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermImagesRead),
}, h.GetImage)
huma.Register(api, huma.Operation{
@@ -208,7 +212,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermImagesDelete),
}, h.RemoveImage)
huma.Register(api, huma.Operation{
@@ -222,7 +226,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermImagesPull),
}, h.PullImage)
huma.Register(api, huma.Operation{
@@ -236,7 +240,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermImagesBuild),
}, h.BuildImage)
huma.Register(api, huma.Operation{
@@ -250,6 +254,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermImagesList),
}, h.ListImageBuilds)
huma.Register(api, huma.Operation{
@@ -263,6 +268,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermImagesRead),
}, h.GetImageBuild)
huma.Register(api, huma.Operation{
@@ -276,7 +282,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermImagesPrune),
}, h.PruneImages)
huma.Register(api, huma.Operation{
@@ -307,7 +313,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
},
},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermImagesUpload),
}, h.UploadImage)
}
@@ -389,9 +395,6 @@ func (h *ImageHandler) GetImage(ctx context.Context, input *GetImageInput) (*Get
// RemoveImage removes a Docker image.
func (h *ImageHandler) RemoveImage(ctx context.Context, input *RemoveImageInput) (*RemoveImageOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.imageService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -417,9 +420,6 @@ func (h *ImageHandler) RemoveImage(ctx context.Context, input *RemoveImageInput)
// PullImage pulls a Docker image with streaming progress.
func (h *ImageHandler) PullImage(ctx context.Context, input *PullImageInput) (*huma.StreamResponse, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.imageService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -456,9 +456,6 @@ func (h *ImageHandler) PullImage(ctx context.Context, input *PullImageInput) (*h
// BuildImage builds a Docker image with streaming progress.
func (h *ImageHandler) BuildImage(ctx context.Context, input *BuildImageInput) (*huma.StreamResponse, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.buildService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -562,9 +559,6 @@ func (h *ImageHandler) GetImageBuild(ctx context.Context, input *GetImageBuildIn
// PruneImages removes unused Docker images.
func (h *ImageHandler) PruneImages(ctx context.Context, input *PruneImagesInput) (*PruneImagesOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.imageService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -687,9 +681,6 @@ func (h *ImageHandler) GetImageUsageCounts(ctx context.Context, input *GetImageU
// UploadImage uploads a Docker image from a tar archive.
func (h *ImageHandler) UploadImage(ctx context.Context, input *UploadImageInput) (*UploadImageOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.imageService == nil || h.settingsService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
diff --git a/backend/api/handlers/job_schedules.go b/backend/api/handlers/job_schedules.go
index cf00e585f..454e2c108 100644
--- a/backend/api/handlers/job_schedules.go
+++ b/backend/api/handlers/job_schedules.go
@@ -7,6 +7,7 @@ import (
"github.com/danielgtaylor/huma/v2"
humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/jobschedule"
)
@@ -62,6 +63,7 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *ser
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermJobsManage),
}, h.Get)
huma.Register(api, huma.Operation{
@@ -75,7 +77,7 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *ser
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermJobsManage),
}, h.Update)
huma.Register(api, huma.Operation{
@@ -89,6 +91,7 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *ser
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermJobsManage),
}, h.ListJobs)
huma.Register(api, huma.Operation{
@@ -102,7 +105,7 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *ser
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermJobsManage),
}, h.RunJob)
}
@@ -136,9 +139,6 @@ func (h *JobSchedulesHandler) ListJobs(ctx context.Context, input *ListJobsInput
}
func (h *JobSchedulesHandler) RunJob(ctx context.Context, input *RunJobInput) (*RunJobOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.jobService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -188,9 +188,6 @@ func (h *JobSchedulesHandler) Get(ctx context.Context, input *GetJobSchedulesInp
}
func (h *JobSchedulesHandler) Update(ctx context.Context, input *UpdateJobSchedulesInput) (*UpdateJobSchedulesOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.jobService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
diff --git a/backend/api/handlers/networks.go b/backend/api/handlers/networks.go
index adb89db55..f0a80c118 100644
--- a/backend/api/handlers/networks.go
+++ b/backend/api/handlers/networks.go
@@ -12,6 +12,7 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
"github.com/getarcaneapp/arcane/types/base"
@@ -145,6 +146,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Summary: "List networks",
Tags: []string{"Networks"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermNetworksList),
}, h.ListNetworks)
huma.Register(api, huma.Operation{
@@ -154,6 +156,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Summary: "Network counts",
Tags: []string{"Networks"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermNetworksList),
}, h.GetNetworkCounts)
huma.Register(api, huma.Operation{
@@ -163,7 +166,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Summary: "Create network",
Tags: []string{"Networks"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermNetworksCreate),
}, h.CreateNetwork)
huma.Register(api, huma.Operation{
@@ -173,6 +176,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Summary: "Get network topology",
Tags: []string{"Networks"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermNetworksRead),
}, h.GetNetworkTopology)
huma.Register(api, huma.Operation{
@@ -182,6 +186,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Summary: "Get network",
Tags: []string{"Networks"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermNetworksRead),
}, h.GetNetwork)
huma.Register(api, huma.Operation{
@@ -191,7 +196,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Summary: "Delete network",
Tags: []string{"Networks"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermNetworksDelete),
}, h.DeleteNetwork)
huma.Register(api, huma.Operation{
@@ -201,7 +206,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Summary: "Prune networks",
Tags: []string{"Networks"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermNetworksPrune),
}, h.PruneNetworks)
}
@@ -266,9 +271,6 @@ func (h *NetworkHandler) GetNetworkCounts(ctx context.Context, input *GetNetwork
}
func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetworkInput) (*CreateNetworkOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
user, exists := humamw.GetCurrentUserFromContext(ctx)
if !exists {
return nil, huma.Error401Unauthorized("not authenticated")
@@ -398,9 +400,6 @@ func (h *NetworkHandler) GetNetworkTopology(ctx context.Context, input *GetNetwo
}
func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetworkInput) (*DeleteNetworkOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
user, exists := humamw.GetCurrentUserFromContext(ctx)
if !exists {
return nil, huma.Error401Unauthorized("not authenticated")
@@ -419,9 +418,6 @@ func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetwork
}
func (h *NetworkHandler) PruneNetworks(ctx context.Context, input *PruneNetworksInput) (*PruneNetworksOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
report, err := h.networkService.PruneNetworks(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.NetworkPruneError{Err: err}).Error())
diff --git a/backend/api/handlers/notifications.go b/backend/api/handlers/notifications.go
index 9efe5b09d..353fad9e4 100644
--- a/backend/api/handlers/notifications.go
+++ b/backend/api/handlers/notifications.go
@@ -12,6 +12,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/notification"
)
@@ -111,7 +112,7 @@ func RegisterNotifications(api huma.API, notificationSvc *services.NotificationS
Summary: "Get all notification settings",
Tags: []string{"Notifications"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermNotificationsManage),
}, h.GetAllNotificationSettings)
huma.Register(api, huma.Operation{
@@ -121,7 +122,7 @@ func RegisterNotifications(api huma.API, notificationSvc *services.NotificationS
Summary: "Get notification settings by provider",
Tags: []string{"Notifications"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermNotificationsManage),
}, h.GetNotificationSettings)
huma.Register(api, huma.Operation{
@@ -131,7 +132,7 @@ func RegisterNotifications(api huma.API, notificationSvc *services.NotificationS
Summary: "Create or update notification settings",
Tags: []string{"Notifications"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermNotificationsManage),
}, h.CreateOrUpdateNotificationSettings)
huma.Register(api, huma.Operation{
@@ -141,7 +142,7 @@ func RegisterNotifications(api huma.API, notificationSvc *services.NotificationS
Summary: "Delete notification settings",
Tags: []string{"Notifications"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermNotificationsManage),
}, h.DeleteNotificationSettings)
huma.Register(api, huma.Operation{
@@ -151,7 +152,7 @@ func RegisterNotifications(api huma.API, notificationSvc *services.NotificationS
Summary: "Test notification",
Tags: []string{"Notifications"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermNotificationsManage),
}, h.TestNotification)
huma.Register(api, huma.Operation{
@@ -161,6 +162,7 @@ func RegisterNotifications(api huma.API, notificationSvc *services.NotificationS
Summary: "Dispatch notification from remote agent to manager",
Tags: []string{"Notifications"},
Security: []map[string][]string{{"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermNotificationsManage),
}, h.DispatchNotification)
}
@@ -172,9 +174,6 @@ func (h *NotificationHandler) rejectIfAgentModeInternal() error {
}
func (h *NotificationHandler) GetAllNotificationSettings(ctx context.Context, input *GetAllNotificationSettingsInput) (*GetAllNotificationSettingsOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if err := h.rejectIfAgentModeInternal(); err != nil {
return nil, err
}
@@ -197,9 +196,6 @@ func (h *NotificationHandler) GetAllNotificationSettings(ctx context.Context, in
}
func (h *NotificationHandler) GetNotificationSettings(ctx context.Context, input *GetNotificationSettingsInput) (*GetNotificationSettingsOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if err := h.rejectIfAgentModeInternal(); err != nil {
return nil, err
}
@@ -221,9 +217,6 @@ func (h *NotificationHandler) GetNotificationSettings(ctx context.Context, input
}
func (h *NotificationHandler) CreateOrUpdateNotificationSettings(ctx context.Context, input *CreateOrUpdateNotificationSettingsInput) (*CreateOrUpdateNotificationSettingsOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if err := h.rejectIfAgentModeInternal(); err != nil {
return nil, err
}
@@ -253,9 +246,6 @@ func (h *NotificationHandler) CreateOrUpdateNotificationSettings(ctx context.Con
}
func (h *NotificationHandler) DeleteNotificationSettings(ctx context.Context, input *DeleteNotificationSettingsInput) (*DeleteNotificationSettingsOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if err := h.rejectIfAgentModeInternal(); err != nil {
return nil, err
}
@@ -274,9 +264,6 @@ func (h *NotificationHandler) DeleteNotificationSettings(ctx context.Context, in
}
func (h *NotificationHandler) TestNotification(ctx context.Context, input *TestNotificationInput) (*TestNotificationOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if err := h.rejectIfAgentModeInternal(); err != nil {
return nil, err
}
diff --git a/backend/api/handlers/oidc.go b/backend/api/handlers/oidc.go
index c98175eaf..39d090d7d 100644
--- a/backend/api/handlers/oidc.go
+++ b/backend/api/handlers/oidc.go
@@ -7,19 +7,24 @@ import (
"time"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"
httputils "github.com/getarcaneapp/arcane/backend/pkg/utils/httpx"
"github.com/getarcaneapp/arcane/types/auth"
- "github.com/getarcaneapp/arcane/types/user"
+ roletypes "github.com/getarcaneapp/arcane/types/role"
)
-// OidcHandler handles OIDC authentication endpoints.
+// OidcHandler handles OIDC authentication endpoints, plus OIDC group → role
+// mapping management (since mappings only make sense in the OIDC context).
type OidcHandler struct {
authService *services.AuthService
oidcService *services.OidcService
+ roleService *services.RoleService
+ userService *services.UserService
config *config.Config
}
@@ -86,13 +91,59 @@ type ExchangeDeviceTokenOutput struct {
Body auth.OidcDeviceTokenResponse
}
+// --- OIDC role mapping I/O ---
+
+type ListOidcRoleMappingsInput struct{}
+
+type ListOidcRoleMappingsOutput struct {
+ Body struct {
+ Success bool `json:"success"`
+ Data []roletypes.OidcRoleMapping `json:"data"`
+ }
+}
+
+type CreateOidcRoleMappingInput struct {
+ Body roletypes.CreateOidcRoleMapping
+}
+
+type CreateOidcRoleMappingOutput struct {
+ Body struct {
+ Success bool `json:"success"`
+ Data roletypes.OidcRoleMapping `json:"data"`
+ }
+}
+
+type UpdateOidcRoleMappingInput struct {
+ ID string `path:"id" doc:"Mapping ID"`
+ Body roletypes.UpdateOidcRoleMapping
+}
+
+type UpdateOidcRoleMappingOutput struct {
+ Body struct {
+ Success bool `json:"success"`
+ Data roletypes.OidcRoleMapping `json:"data"`
+ }
+}
+
+type DeleteOidcRoleMappingInput struct {
+ ID string `path:"id" doc:"Mapping ID"`
+}
+
+type DeleteOidcRoleMappingOutput struct {
+ Body struct {
+ Success bool `json:"success"`
+ Message string `json:"message"`
+ }
+}
+
// ============================================================================
// Registration
// ============================================================================
-// RegisterOidc registers all OIDC authentication endpoints using Huma.
-func RegisterOidc(api huma.API, authService *services.AuthService, oidcService *services.OidcService, cfg *config.Config) {
- h := &OidcHandler{authService: authService, oidcService: oidcService, config: cfg}
+// RegisterOidc registers all OIDC authentication endpoints (plus the OIDC
+// group → role mapping CRUD) using Huma.
+func RegisterOidc(api huma.API, authService *services.AuthService, oidcService *services.OidcService, roleService *services.RoleService, userService *services.UserService, cfg *config.Config) {
+ h := &OidcHandler{authService: authService, oidcService: oidcService, roleService: roleService, userService: userService, config: cfg}
huma.Register(api, huma.Operation{
OperationID: "get-oidc-status",
@@ -153,6 +204,49 @@ func RegisterOidc(api huma.API, authService *services.AuthService, oidcService *
Tags: []string{"OIDC"},
Security: []map[string][]string{},
}, h.ExchangeDeviceToken)
+
+ // --- OIDC role mapping endpoints ---
+
+ huma.Register(api, huma.Operation{
+ OperationID: "list-oidc-role-mappings",
+ Method: http.MethodGet,
+ Path: "/oidc/role-mappings",
+ Summary: "List OIDC group → role mappings",
+ Description: "Returns every mapping. On each OIDC login the user's group claim is matched against ClaimValue and matching rows become source='oidc' role assignments.",
+ Tags: []string{"OIDC"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequireGlobalAdmin(api),
+ }, h.ListOidcRoleMappings)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "create-oidc-role-mapping",
+ Method: http.MethodPost,
+ Path: "/oidc/role-mappings",
+ Summary: "Create an OIDC role mapping",
+ Tags: []string{"OIDC"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequireGlobalAdmin(api),
+ }, h.CreateOidcRoleMapping)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "update-oidc-role-mapping",
+ Method: http.MethodPut,
+ Path: "/oidc/role-mappings/{id}",
+ Summary: "Update an OIDC role mapping",
+ Tags: []string{"OIDC"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequireGlobalAdmin(api),
+ }, h.UpdateOidcRoleMapping)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "delete-oidc-role-mapping",
+ Method: http.MethodDelete,
+ Path: "/oidc/role-mappings/{id}",
+ Summary: "Delete an OIDC role mapping",
+ Tags: []string{"OIDC"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequireGlobalAdmin(api),
+ }, h.DeleteOidcRoleMapping)
}
// ============================================================================
@@ -299,6 +393,11 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcC
setCookies = append(setCookies, cookie.BuildTokenCookieStringFor(maxAge, tokenPair.AccessToken, cookie.SecureCookieFromContext(ctx)))
}
+ userDto, err := h.userService.ToUserResponseDto(ctx, *userModel)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())
+ }
+
return &HandleOidcCallbackOutput{
SetCookie: setCookies,
Body: auth.OidcCallbackResponse{
@@ -306,14 +405,7 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcC
Token: tokenPair.AccessToken,
RefreshToken: tokenPair.RefreshToken,
ExpiresAt: tokenPair.ExpiresAt,
- User: user.User{
- ID: userModel.ID,
- Username: userModel.Username,
- DisplayName: userModel.DisplayName,
- Email: userModel.Email,
- Roles: userModel.Roles,
- OidcSubjectId: userModel.OidcSubjectId,
- },
+ User: userDto,
},
}, nil
}
@@ -381,6 +473,11 @@ func (h *OidcHandler) ExchangeDeviceToken(ctx context.Context, input *ExchangeDe
tokenCookie := cookie.BuildTokenCookieStringFor(maxAge, tokenPair.AccessToken, cookie.SecureCookieFromContext(ctx))
+ userDto, err := h.userService.ToUserResponseDto(ctx, *userModel)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())
+ }
+
return &ExchangeDeviceTokenOutput{
SetCookie: []string{tokenCookie},
Body: auth.OidcDeviceTokenResponse{
@@ -388,14 +485,93 @@ func (h *OidcHandler) ExchangeDeviceToken(ctx context.Context, input *ExchangeDe
Token: tokenPair.AccessToken,
RefreshToken: tokenPair.RefreshToken,
ExpiresAt: tokenPair.ExpiresAt,
- User: user.User{
- ID: userModel.ID,
- Username: userModel.Username,
- DisplayName: userModel.DisplayName,
- Email: userModel.Email,
- Roles: userModel.Roles,
- OidcSubjectId: userModel.OidcSubjectId,
- },
+ User: userDto,
},
}, nil
}
+
+// ============================================================================
+// OIDC Role Mapping Handlers
+// ============================================================================
+
+func (h *OidcHandler) ListOidcRoleMappings(ctx context.Context, _ *ListOidcRoleMappingsInput) (*ListOidcRoleMappingsOutput, error) {
+ if h.roleService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+ rows, err := h.roleService.ListOidcMappings(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError("failed to list mappings: " + err.Error())
+ }
+ out := &ListOidcRoleMappingsOutput{}
+ out.Body.Success = true
+ out.Body.Data = make([]roletypes.OidcRoleMapping, len(rows))
+ for i := range rows {
+ out.Body.Data[i] = toOidcMappingDTO(&rows[i])
+ }
+ return out, nil
+}
+
+func (h *OidcHandler) CreateOidcRoleMapping(ctx context.Context, input *CreateOidcRoleMappingInput) (*CreateOidcRoleMappingOutput, error) {
+ if h.roleService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+ mapping, err := h.roleService.CreateOidcMapping(ctx, input.Body.ClaimValue, input.Body.RoleID, input.Body.EnvironmentID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError("failed to create mapping: " + err.Error())
+ }
+ out := &CreateOidcRoleMappingOutput{}
+ out.Body.Success = true
+ out.Body.Data = toOidcMappingDTO(mapping)
+ return out, nil
+}
+
+func (h *OidcHandler) UpdateOidcRoleMapping(ctx context.Context, input *UpdateOidcRoleMappingInput) (*UpdateOidcRoleMappingOutput, error) {
+ if h.roleService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+ mapping, err := h.roleService.UpdateOidcMapping(ctx, input.ID, input.Body.ClaimValue, input.Body.RoleID, input.Body.EnvironmentID)
+ if err != nil {
+ if common.IsOidcMappingNotFoundError(err) {
+ return nil, huma.Error404NotFound("mapping not found")
+ }
+ if common.IsOidcMappingEnvManagedError(err) {
+ return nil, huma.Error409Conflict(err.Error())
+ }
+ return nil, huma.Error500InternalServerError("failed to update mapping: " + err.Error())
+ }
+ out := &UpdateOidcRoleMappingOutput{}
+ out.Body.Success = true
+ out.Body.Data = toOidcMappingDTO(mapping)
+ return out, nil
+}
+
+func (h *OidcHandler) DeleteOidcRoleMapping(ctx context.Context, input *DeleteOidcRoleMappingInput) (*DeleteOidcRoleMappingOutput, error) {
+ if h.roleService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+ if err := h.roleService.DeleteOidcMapping(ctx, input.ID); err != nil {
+ if common.IsOidcMappingNotFoundError(err) {
+ return nil, huma.Error404NotFound("mapping not found")
+ }
+ if common.IsOidcMappingEnvManagedError(err) {
+ return nil, huma.Error409Conflict(err.Error())
+ }
+ return nil, huma.Error500InternalServerError("failed to delete mapping: " + err.Error())
+ }
+ out := &DeleteOidcRoleMappingOutput{}
+ out.Body.Success = true
+ out.Body.Message = "mapping deleted"
+ return out, nil
+}
+
+func toOidcMappingDTO(m *models.OidcRoleMapping) roletypes.OidcRoleMapping {
+ return roletypes.OidcRoleMapping{
+ ID: m.ID,
+ ClaimValue: m.ClaimValue,
+ RoleID: m.RoleID,
+ EnvironmentID: m.EnvironmentID,
+ Source: m.Source,
+ CreatedAt: m.CreatedAt,
+ UpdatedAt: m.UpdatedAt,
+ }
+}
diff --git a/backend/api/handlers/ports.go b/backend/api/handlers/ports.go
index 99894bae9..8523341ae 100644
--- a/backend/api/handlers/ports.go
+++ b/backend/api/handlers/ports.go
@@ -6,7 +6,9 @@ import (
"strings"
"github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/types/base"
porttypes "github.com/getarcaneapp/arcane/types/port"
@@ -45,6 +47,7 @@ func RegisterPorts(api huma.API, portSvc *services.PortService) {
Summary: "List port mappings",
Tags: []string{"Ports"},
Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersList),
}, h.ListPorts)
}
diff --git a/backend/api/handlers/projects.go b/backend/api/handlers/projects.go
index 2c176e142..451413028 100644
--- a/backend/api/handlers/projects.go
+++ b/backend/api/handlers/projects.go
@@ -12,6 +12,7 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
projects "github.com/getarcaneapp/arcane/backend/pkg/projects"
"github.com/getarcaneapp/arcane/backend/pkg/utils"
@@ -218,6 +219,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsList),
}, h.ListProjects)
huma.Register(api, huma.Operation{
@@ -231,6 +233,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsList),
}, h.GetProjectStatusCounts)
huma.Register(api, huma.Operation{
@@ -244,7 +247,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsDeploy),
}, h.DeployProject)
huma.Register(api, huma.Operation{
@@ -258,7 +261,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsDown),
}, h.DownProject)
huma.Register(api, huma.Operation{
@@ -272,7 +275,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsCreate),
}, h.CreateProject)
huma.Register(api, huma.Operation{
@@ -286,6 +289,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsRead),
}, h.GetProject)
huma.Register(api, huma.Operation{
@@ -299,6 +303,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsRead),
}, h.GetProjectCompose)
huma.Register(api, huma.Operation{
@@ -312,6 +317,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsRead),
}, h.GetProjectFiles)
huma.Register(api, huma.Operation{
@@ -325,6 +331,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsRead),
}, h.GetProjectRuntime)
huma.Register(api, huma.Operation{
@@ -338,6 +345,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsRead),
}, h.GetProjectUpdates)
huma.Register(api, huma.Operation{
@@ -351,6 +359,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsRead),
}, h.GetProjectFile)
huma.Register(api, huma.Operation{
@@ -364,7 +373,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsDeploy),
}, h.RedeployProject)
huma.Register(api, huma.Operation{
@@ -378,7 +387,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsDelete),
}, h.DestroyProject)
huma.Register(api, huma.Operation{
@@ -392,7 +401,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsUpdate),
}, h.UpdateProject)
huma.Register(api, huma.Operation{
@@ -406,7 +415,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsUpdate),
}, h.UpdateProjectInclude)
huma.Register(api, huma.Operation{
@@ -420,7 +429,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsRestart),
}, h.RestartProject)
huma.Register(api, huma.Operation{
@@ -434,7 +443,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsArchive),
}, h.ArchiveProject)
huma.Register(api, huma.Operation{
@@ -448,7 +457,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsArchive),
}, h.UnarchiveProject)
huma.Register(api, huma.Operation{
@@ -462,7 +471,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsDeploy),
}, h.PullProjectImages)
huma.Register(api, huma.Operation{
@@ -476,7 +485,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermProjectsDeploy),
}, h.BuildProjectImages)
}
@@ -565,9 +574,6 @@ func (h *ProjectHandler) GetProjectStatusCounts(ctx context.Context, input *GetP
// DeployProject deploys a Docker Compose project.
func (h *ProjectHandler) DeployProject(ctx context.Context, input *DeployProjectInput) (*huma.StreamResponse, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.projectService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -614,9 +620,6 @@ func (h *ProjectHandler) DeployProject(ctx context.Context, input *DeployProject
// DownProject brings down a Docker Compose project.
func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInput) (*DownProjectOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.projectService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -646,9 +649,6 @@ func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInpu
// CreateProject creates a new Docker Compose project.
func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectInput) (*CreateProjectOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.projectService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -796,9 +796,6 @@ func (h *ProjectHandler) GetProjectFile(ctx context.Context, input *GetProjectFi
// RedeployProject redeploys a Docker Compose project.
func (h *ProjectHandler) RedeployProject(ctx context.Context, input *RedeployProjectInput) (*RedeployProjectOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.projectService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -832,9 +829,6 @@ func (h *ProjectHandler) RedeployProject(ctx context.Context, input *RedeployPro
// DestroyProject destroys a Docker Compose project.
func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProjectInput) (*DestroyProjectOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.projectService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -874,9 +868,6 @@ func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProje
// UpdateProject updates a Docker Compose project.
func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectInput) (*UpdateProjectOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.projectService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -909,9 +900,6 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProject
// UpdateProjectInclude updates an include file within a project.
func (h *ProjectHandler) UpdateProjectInclude(ctx context.Context, input *UpdateProjectIncludeInput) (*UpdateProjectIncludeOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.projectService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -944,9 +932,6 @@ func (h *ProjectHandler) UpdateProjectInclude(ctx context.Context, input *Update
// RestartProject restarts all containers in a project.
func (h *ProjectHandler) RestartProject(ctx context.Context, input *RestartProjectInput) (*RestartProjectOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.projectService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -979,9 +964,6 @@ func (h *ProjectHandler) RestartProject(ctx context.Context, input *RestartProje
}
func (h *ProjectHandler) ArchiveProject(ctx context.Context, input *ArchiveProjectInput) (*ArchiveProjectOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.projectService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -1012,9 +994,6 @@ func (h *ProjectHandler) ArchiveProject(ctx context.Context, input *ArchiveProje
}
func (h *ProjectHandler) UnarchiveProject(ctx context.Context, input *UnarchiveProjectInput) (*UnarchiveProjectOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.projectService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -1042,9 +1021,6 @@ func (h *ProjectHandler) UnarchiveProject(ctx context.Context, input *UnarchiveP
// PullProjectImages pulls all images for a project with streaming progress.
func (h *ProjectHandler) PullProjectImages(ctx context.Context, input *PullProjectImagesInput) (*huma.StreamResponse, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.projectService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -1090,9 +1066,6 @@ func (h *ProjectHandler) PullProjectImages(ctx context.Context, input *PullProje
// BuildProjectImages builds compose services with build directives.
func (h *ProjectHandler) BuildProjectImages(ctx context.Context, input *BuildProjectInput) (*huma.StreamResponse, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.projectService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
diff --git a/backend/api/handlers/remenv_handlers_test.go b/backend/api/handlers/remenv_handlers_test.go
index 6b796eeb1..c771c4816 100644
--- a/backend/api/handlers/remenv_handlers_test.go
+++ b/backend/api/handlers/remenv_handlers_test.go
@@ -13,6 +13,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/env"
"github.com/getarcaneapp/arcane/types/jobschedule"
@@ -22,10 +23,10 @@ import (
"gorm.io/gorm"
)
-// adminTestContextInternal returns a context with the admin flag set, suitable for
-// unit-testing handlers that call checkAdminInternal directly.
+// adminTestContextInternal returns a context with a sudo PermissionSet attached,
+// suitable for unit-testing handlers that gate via RequirePermission middleware.
func adminTestContextInternal() context.Context {
- return context.WithValue(context.Background(), humamiddleware.ContextKeyUserIsAdmin, true)
+ return context.WithValue(context.Background(), humamiddleware.ContextKeyUserPermissions, authz.SudoPermissionSet())
}
func setupRemoteHandlerEnvironmentServiceInternal(t *testing.T, server *httptest.Server) *services.EnvironmentService {
diff --git a/backend/api/handlers/roles.go b/backend/api/handlers/roles.go
new file mode 100644
index 000000000..307c123eb
--- /dev/null
+++ b/backend/api/handlers/roles.go
@@ -0,0 +1,421 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
+ "github.com/getarcaneapp/arcane/types/base"
+ roletypes "github.com/getarcaneapp/arcane/types/role"
+)
+
+type RoleHandler struct {
+ roleService *services.RoleService
+}
+
+// ---------- I/O wrappers ----------
+
+type RolePaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []roletypes.Role `json:"data"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListRolesInput struct {
+ Search string `query:"search" doc:"Search by role name or description"`
+ Sort string `query:"sort" doc:"Column to sort by"`
+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`
+ Start int `query:"start" default:"0" doc:"Start index for pagination"`
+ Limit int `query:"limit" default:"20" doc:"Items per page"`
+}
+
+type ListRolesOutput struct {
+ Body RolePaginatedResponse
+}
+
+type GetRoleInput struct {
+ ID string `path:"id" doc:"Role ID"`
+}
+
+type GetRoleOutput struct {
+ Body base.ApiResponse[roletypes.Role]
+}
+
+type CreateRoleInput struct {
+ Body roletypes.CreateRole
+}
+
+type CreateRoleOutput struct {
+ Body base.ApiResponse[roletypes.Role]
+}
+
+type UpdateRoleInput struct {
+ ID string `path:"id" doc:"Role ID"`
+ Body roletypes.UpdateRole
+}
+
+type UpdateRoleOutput struct {
+ Body base.ApiResponse[roletypes.Role]
+}
+
+type DeleteRoleInput struct {
+ ID string `path:"id" doc:"Role ID"`
+}
+
+type DeleteRoleOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type PermissionsManifestOutput struct {
+ Body base.ApiResponse[roletypes.PermissionsManifest]
+}
+
+type ListUserRoleAssignmentsInput struct {
+ UserID string `path:"userId" doc:"User ID"`
+}
+
+type ListUserRoleAssignmentsOutput struct {
+ Body base.ApiResponse[[]roletypes.RoleAssignment]
+}
+
+type SetUserRoleAssignmentsInput struct {
+ UserID string `path:"userId" doc:"User ID"`
+ Body roletypes.SetUserAssignments
+}
+
+type SetUserRoleAssignmentsOutput struct {
+ Body base.ApiResponse[[]roletypes.RoleAssignment]
+}
+
+// ---------- Registration ----------
+
+func RegisterRoles(api huma.API, roleService *services.RoleService) {
+ h := &RoleHandler{roleService: roleService}
+
+ huma.Register(api, huma.Operation{
+ OperationID: "list-roles",
+ Method: http.MethodGet,
+ Path: "/roles",
+ Summary: "List roles",
+ Description: "Get a paginated list of roles (built-in + custom)",
+ Tags: []string{"Roles"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermRolesList),
+ }, h.ListRoles)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-role",
+ Method: http.MethodGet,
+ Path: "/roles/{id}",
+ Summary: "Get a role",
+ Tags: []string{"Roles"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermRolesRead),
+ }, h.GetRole)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "create-role",
+ Method: http.MethodPost,
+ Path: "/roles",
+ Summary: "Create a custom role",
+ Description: "Built-in roles cannot be created via this endpoint; only custom roles are accepted. Reserved for global admins.",
+ Tags: []string{"Roles"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequireGlobalAdmin(api),
+ }, h.CreateRole)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "update-role",
+ Method: http.MethodPut,
+ Path: "/roles/{id}",
+ Summary: "Update a custom role",
+ Description: "Built-in roles are read-only and return 403 on update. Reserved for global admins.",
+ Tags: []string{"Roles"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequireGlobalAdmin(api),
+ }, h.UpdateRole)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "delete-role",
+ Method: http.MethodDelete,
+ Path: "/roles/{id}",
+ Summary: "Delete a custom role",
+ Description: "Built-in roles are protected; deleting cascades all user assignments. Reserved for global admins.",
+ Tags: []string{"Roles"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequireGlobalAdmin(api),
+ }, h.DeleteRole)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-permissions-manifest",
+ 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.",
+ Tags: []string{"Roles"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequirePermission(api, authz.PermRolesRead),
+ }, h.GetPermissionsManifest)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "list-user-role-assignments",
+ Method: http.MethodGet,
+ Path: "/users/{userId}/role-assignments",
+ Summary: "List a user's role assignments",
+ Description: "Reserved for global admins.",
+ Tags: []string{"Roles"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequireGlobalAdmin(api),
+ }, h.ListUserRoleAssignments)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "set-user-role-assignments",
+ Method: http.MethodPut,
+ Path: "/users/{userId}/role-assignments",
+ Summary: "Replace a user's manual role assignments",
+ Description: "Replaces every source='manual' assignment for the user. source='oidc' assignments are not touched. Reserved for global admins; enforces the last-admin guard.",
+ Tags: []string{"Roles"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Middlewares: humamw.RequireGlobalAdmin(api),
+ }, h.SetUserRoleAssignments)
+}
+
+// ---------- Handler implementations ----------
+
+func (h *RoleHandler) ListRoles(ctx context.Context, input *ListRolesInput) (*ListRolesOutput, error) {
+ if h.roleService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+ params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
+ roles, paginationResp, err := h.roleService.ListRoles(ctx, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError("failed to list roles: " + err.Error())
+ }
+ dtos := make([]roletypes.Role, len(roles))
+ for i := range roles {
+ dtos[i] = h.toRoleDTO(ctx, &roles[i])
+ }
+ return &ListRolesOutput{
+ Body: RolePaginatedResponse{
+ Success: true,
+ Data: dtos,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+func (h *RoleHandler) GetRole(ctx context.Context, input *GetRoleInput) (*GetRoleOutput, error) {
+ if h.roleService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+ role, err := h.roleService.GetRole(ctx, input.ID)
+ if err != nil {
+ if common.IsRoleNotFoundError(err) {
+ return nil, huma.Error404NotFound("role not found")
+ }
+ return nil, huma.Error500InternalServerError("failed to get role: " + err.Error())
+ }
+ return &GetRoleOutput{
+ Body: base.ApiResponse[roletypes.Role]{Success: true, Data: h.toRoleDTO(ctx, role)},
+ }, nil
+}
+
+func (h *RoleHandler) CreateRole(ctx context.Context, input *CreateRoleInput) (*CreateRoleOutput, error) {
+ if h.roleService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+ callerPS, _ := humamw.PermissionsFromContext(ctx)
+ if err := h.roleService.ValidatePermissionsAgainstCaller(callerPS, input.Body.Permissions); err != nil {
+ switch {
+ case common.IsUnknownPermissionError(err):
+ return nil, huma.Error400BadRequest(err.Error())
+ case common.IsRolePermissionEscalationError(err):
+ return nil, huma.Error403Forbidden(err.Error())
+ }
+ return nil, huma.Error500InternalServerError("failed to validate role permissions: " + err.Error())
+ }
+ role, err := h.roleService.CreateRole(ctx, input.Body.Name, input.Body.Description, input.Body.Permissions)
+ if err != nil {
+ if common.IsRoleNameTakenError(err) {
+ return nil, huma.Error409Conflict("role name already in use")
+ }
+ if common.IsUnknownPermissionError(err) {
+ return nil, huma.Error400BadRequest(err.Error())
+ }
+ return nil, huma.Error500InternalServerError("failed to create role: " + err.Error())
+ }
+ return &CreateRoleOutput{
+ Body: base.ApiResponse[roletypes.Role]{Success: true, Data: h.toRoleDTO(ctx, role)},
+ }, nil
+}
+
+func (h *RoleHandler) UpdateRole(ctx context.Context, input *UpdateRoleInput) (*UpdateRoleOutput, error) {
+ if h.roleService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+ callerPS, _ := humamw.PermissionsFromContext(ctx)
+ if err := h.roleService.ValidatePermissionsAgainstCaller(callerPS, input.Body.Permissions); err != nil {
+ switch {
+ case common.IsUnknownPermissionError(err):
+ return nil, huma.Error400BadRequest(err.Error())
+ case common.IsRolePermissionEscalationError(err):
+ return nil, huma.Error403Forbidden(err.Error())
+ }
+ return nil, huma.Error500InternalServerError("failed to validate role permissions: " + err.Error())
+ }
+ role, err := h.roleService.UpdateRole(ctx, input.ID, input.Body.Name, input.Body.Description, input.Body.Permissions)
+ if err != nil {
+ switch {
+ case common.IsRoleNotFoundError(err):
+ return nil, huma.Error404NotFound("role not found")
+ case common.IsRoleBuiltInError(err):
+ return nil, huma.Error403Forbidden("built-in roles cannot be modified")
+ case common.IsRoleNameTakenError(err):
+ return nil, huma.Error409Conflict("role name already in use")
+ case common.IsUnknownPermissionError(err):
+ return nil, huma.Error400BadRequest(err.Error())
+ }
+ return nil, huma.Error500InternalServerError("failed to update role: " + err.Error())
+ }
+ return &UpdateRoleOutput{
+ Body: base.ApiResponse[roletypes.Role]{Success: true, Data: h.toRoleDTO(ctx, role)},
+ }, nil
+}
+
+func (h *RoleHandler) DeleteRole(ctx context.Context, input *DeleteRoleInput) (*DeleteRoleOutput, error) {
+ if h.roleService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+ if err := h.roleService.DeleteRole(ctx, input.ID); err != nil {
+ switch {
+ case common.IsRoleNotFoundError(err):
+ return nil, huma.Error404NotFound("role not found")
+ case common.IsRoleBuiltInError(err):
+ return nil, huma.Error403Forbidden("built-in roles cannot be deleted")
+ case common.IsNoGlobalAdminRemainsError(err):
+ return nil, huma.Error409Conflict(err.Error())
+ }
+ return nil, huma.Error500InternalServerError("failed to delete role: " + err.Error())
+ }
+ return &DeleteRoleOutput{
+ Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "role deleted"}},
+ }, nil
+}
+
+func (h *RoleHandler) GetPermissionsManifest(_ context.Context, _ *struct{}) (*PermissionsManifestOutput, error) {
+ return &PermissionsManifestOutput{
+ Body: base.ApiResponse[roletypes.PermissionsManifest]{Success: true, Data: buildPermissionsManifestInternal()},
+ }, nil
+}
+
+func (h *RoleHandler) ListUserRoleAssignments(ctx context.Context, input *ListUserRoleAssignmentsInput) (*ListUserRoleAssignmentsOutput, error) {
+ if h.roleService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+ rows, err := h.roleService.ListUserAssignments(ctx, input.UserID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError("failed to list assignments: " + err.Error())
+ }
+ dtos := make([]roletypes.RoleAssignment, len(rows))
+ for i := range rows {
+ dtos[i] = toAssignmentDTOInternal(&rows[i])
+ }
+ return &ListUserRoleAssignmentsOutput{
+ Body: base.ApiResponse[[]roletypes.RoleAssignment]{Success: true, Data: dtos},
+ }, nil
+}
+
+func (h *RoleHandler) SetUserRoleAssignments(ctx context.Context, input *SetUserRoleAssignmentsInput) (*SetUserRoleAssignmentsOutput, error) {
+ if h.roleService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+ desired := make([]models.UserRoleAssignment, len(input.Body.Assignments))
+ for i, a := range input.Body.Assignments {
+ desired[i] = models.UserRoleAssignment{RoleID: a.RoleID, EnvironmentID: a.EnvironmentID}
+ }
+ if err := h.roleService.SetUserAssignments(ctx, input.UserID, desired); err != nil {
+ switch {
+ case common.IsInvalidRoleAssignmentError(err):
+ return nil, huma.Error400BadRequest(err.Error())
+ case common.IsNoGlobalAdminRemainsError(err):
+ return nil, huma.Error409Conflict(err.Error())
+ }
+ return nil, huma.Error500InternalServerError("failed to set assignments: " + err.Error())
+ }
+ rows, err := h.roleService.ListUserAssignments(ctx, input.UserID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError("failed to read back assignments: " + err.Error())
+ }
+ dtos := make([]roletypes.RoleAssignment, len(rows))
+ for i := range rows {
+ dtos[i] = toAssignmentDTOInternal(&rows[i])
+ }
+ return &SetUserRoleAssignmentsOutput{
+ Body: base.ApiResponse[[]roletypes.RoleAssignment]{Success: true, Data: dtos},
+ }, nil
+}
+
+// ---------- DTO mappers ----------
+
+func (h *RoleHandler) toRoleDTO(ctx context.Context, r *models.Role) roletypes.Role {
+ out := roletypes.Role{
+ ID: r.ID,
+ Name: r.Name,
+ Description: r.Description,
+ Permissions: []string(r.Permissions),
+ BuiltIn: r.BuiltIn,
+ CreatedAt: r.CreatedAt,
+ UpdatedAt: r.UpdatedAt,
+ }
+ if count, err := h.roleService.CountUsersAssignedToRole(ctx, r.ID); err == nil {
+ out.AssignedUserCount = count
+ }
+ return out
+}
+
+func toAssignmentDTOInternal(r *models.UserRoleAssignment) roletypes.RoleAssignment {
+ return roletypes.RoleAssignment{
+ ID: r.ID,
+ UserID: r.UserID,
+ RoleID: r.RoleID,
+ EnvironmentID: r.EnvironmentID,
+ Source: r.Source,
+ CreatedAt: r.CreatedAt,
+ }
+}
+
+// buildPermissionsManifestInternal maps the authz-owned permission catalog into
+// the public API manifest shape used by the frontend role editor.
+func buildPermissionsManifestInternal() roletypes.PermissionsManifest {
+ catalog := authz.PermissionCatalog()
+ resources := make([]roletypes.PermissionResource, len(catalog))
+ for i, resource := range catalog {
+ actions := make([]roletypes.PermissionAction, len(resource.Actions))
+ for j, action := range resource.Actions {
+ actions[j] = roletypes.PermissionAction{
+ Key: action.Key,
+ Permission: action.Permission,
+ Label: action.Label,
+ Description: action.Description,
+ }
+ }
+ resources[i] = roletypes.PermissionResource{
+ Key: resource.Key,
+ Label: resource.Label,
+ Scope: resource.Scope,
+ Actions: actions,
+ }
+ }
+ return roletypes.PermissionsManifest{Resources: resources}
+}
diff --git a/backend/api/handlers/settings.go b/backend/api/handlers/settings.go
index 47e9c7dcc..083a41396 100644
--- a/backend/api/handlers/settings.go
+++ b/backend/api/handlers/settings.go
@@ -15,6 +15,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/projects"
"github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
"github.com/getarcaneapp/arcane/types/base"
@@ -141,6 +142,7 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermSettingsRead),
}, h.GetSettings)
huma.Register(api, huma.Operation{
@@ -154,7 +156,7 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermSettingsWrite),
}, h.UpdateSettings)
// Top-level settings endpoints (not environment-scoped)
@@ -169,7 +171,7 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermSettingsRead),
}, h.Search)
huma.Register(api, huma.Operation{
@@ -183,7 +185,7 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermSettingsRead),
}, h.GetCategories)
}
@@ -264,7 +266,8 @@ func (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInp
return nil, huma.Error500InternalServerError("service not available")
}
- isAdmin := humamw.IsAdminFromContext(ctx)
+ ps, _ := humamw.PermissionsFromContext(ctx)
+ isAdmin := ps.IsGlobalAdmin()
if input.EnvironmentID != "0" {
if h.environmentService == nil {
@@ -297,10 +300,6 @@ func (h *SettingsHandler) UpdateSettings(ctx context.Context, input *UpdateSetti
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.validateSettingsUpdateInput(input.Body); err != nil {
return nil, err
}
@@ -401,10 +400,11 @@ func hasAuthSettingsUpdateInternal(req settings.Update) bool {
req.AuthSessionTimeout != nil || req.AuthPasswordPolicy != nil ||
req.OidcClientId != nil ||
req.OidcClientSecret != nil || req.OidcIssuerUrl != nil ||
- req.OidcScopes != nil || req.OidcAdminClaim != nil ||
- req.OidcAdminValue != nil || req.OidcMergeAccounts != nil ||
+ req.OidcScopes != nil ||
+ req.OidcMergeAccounts != nil ||
req.OidcSkipTlsVerify != nil || req.OidcAutoRedirectToProvider != nil ||
- req.OidcProviderName != nil || req.OidcProviderLogoUrl != nil
+ req.OidcProviderName != nil || req.OidcProviderLogoUrl != nil ||
+ req.OidcGroupsClaim != nil
}
// Search searches settings by query.
@@ -413,10 +413,6 @@ func (h *SettingsHandler) Search(ctx context.Context, input *SearchSettingsInput
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if strings.TrimSpace(input.Body.Query) == "" {
return nil, huma.Error400BadRequest((&common.QueryParameterRequiredError{}).Error())
}
@@ -431,10 +427,6 @@ func (h *SettingsHandler) GetCategories(ctx context.Context, input *struct{}) (*
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
categories := h.settingsSearchService.GetSettingsCategories()
return &GetCategoriesOutput{Body: categories}, nil
}
diff --git a/backend/api/handlers/swarm.go b/backend/api/handlers/swarm.go
index 3778d3435..ddf3f9d0a 100644
--- a/backend/api/handlers/swarm.go
+++ b/backend/api/handlers/swarm.go
@@ -14,6 +14,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/types/base"
@@ -518,59 +519,59 @@ func RegisterSwarm(api huma.API, swarmSvc *services.SwarmService, environmentSvc
cfg: cfg,
}
- huma.Register(api, huma.Operation{OperationID: "list-swarm-services", Method: http.MethodGet, Path: "/environments/{id}/swarm/services", Summary: "List swarm services", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListServices)
- huma.Register(api, huma.Operation{OperationID: "get-swarm-service", Method: http.MethodGet, Path: "/environments/{id}/swarm/services/{serviceId}", Summary: "Get swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetService)
- huma.Register(api, huma.Operation{OperationID: "create-swarm-service", Method: http.MethodPost, Path: "/environments/{id}/swarm/services", Summary: "Create swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.CreateService)
- huma.Register(api, huma.Operation{OperationID: "update-swarm-service", Method: http.MethodPut, Path: "/environments/{id}/swarm/services/{serviceId}", Summary: "Update swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.UpdateService)
- huma.Register(api, huma.Operation{OperationID: "delete-swarm-service", Method: http.MethodDelete, Path: "/environments/{id}/swarm/services/{serviceId}", Summary: "Delete swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.DeleteService)
- huma.Register(api, huma.Operation{OperationID: "list-swarm-service-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/services/{serviceId}/tasks", Summary: "List tasks for a swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListServiceTasks)
- huma.Register(api, huma.Operation{OperationID: "rollback-swarm-service", Method: http.MethodPost, Path: "/environments/{id}/swarm/services/{serviceId}/rollback", Summary: "Rollback a swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.RollbackService)
- huma.Register(api, huma.Operation{OperationID: "scale-swarm-service", Method: http.MethodPost, Path: "/environments/{id}/swarm/services/{serviceId}/scale", Summary: "Scale a swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.ScaleService)
-
- huma.Register(api, huma.Operation{OperationID: "list-swarm-nodes", Method: http.MethodGet, Path: "/environments/{id}/swarm/nodes", Summary: "List swarm nodes", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListNodes)
- huma.Register(api, huma.Operation{OperationID: "get-swarm-node", Method: http.MethodGet, Path: "/environments/{id}/swarm/nodes/{nodeId}", Summary: "Get swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetNode)
- huma.Register(api, huma.Operation{OperationID: "get-swarm-node-agent-deployment", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/deployment", Summary: "Get swarm node agent deployment snippets", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.GetNodeAgentDeployment)
- huma.Register(api, huma.Operation{OperationID: "update-swarm-node", Method: http.MethodPatch, Path: "/environments/{id}/swarm/nodes/{nodeId}", Summary: "Update swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.UpdateNode)
- huma.Register(api, huma.Operation{OperationID: "delete-swarm-node", Method: http.MethodDelete, Path: "/environments/{id}/swarm/nodes/{nodeId}", Summary: "Delete swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.DeleteNode)
- huma.Register(api, huma.Operation{OperationID: "promote-swarm-node", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/{nodeId}/promote", Summary: "Promote swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.PromoteNode)
- huma.Register(api, huma.Operation{OperationID: "demote-swarm-node", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/{nodeId}/demote", Summary: "Demote swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.DemoteNode)
- huma.Register(api, huma.Operation{OperationID: "list-swarm-node-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/nodes/{nodeId}/tasks", Summary: "List tasks for a swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListNodeTasks)
- huma.Register(api, huma.Operation{OperationID: "get-swarm-node-identity", Method: http.MethodGet, Path: "/swarm/node-identity", Summary: "Get local swarm node identity", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetNodeIdentity)
-
- huma.Register(api, huma.Operation{OperationID: "list-swarm-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/tasks", Summary: "List swarm tasks", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListTasks)
-
- huma.Register(api, huma.Operation{OperationID: "list-swarm-stacks", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks", Summary: "List swarm stacks", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListStacks)
- huma.Register(api, huma.Operation{OperationID: "deploy-swarm-stack", Method: http.MethodPost, Path: "/environments/{id}/swarm/stacks", Summary: "Deploy swarm stack", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.DeployStack)
- huma.Register(api, huma.Operation{OperationID: "get-swarm-stack", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}", Summary: "Get swarm stack", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetStack)
- huma.Register(api, huma.Operation{OperationID: "get-swarm-stack-source", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}/source", Summary: "Get swarm stack source", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.GetStackSource)
- huma.Register(api, huma.Operation{OperationID: "update-swarm-stack-source", Method: http.MethodPut, Path: "/environments/{id}/swarm/stacks/{name}/source", Summary: "Update swarm stack source", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.UpdateStackSource)
- huma.Register(api, huma.Operation{OperationID: "delete-swarm-stack", Method: http.MethodDelete, Path: "/environments/{id}/swarm/stacks/{name}", Summary: "Delete swarm stack", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.DeleteStack)
- huma.Register(api, huma.Operation{OperationID: "list-swarm-stack-services", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}/services", Summary: "List swarm stack services", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListStackServices)
- huma.Register(api, huma.Operation{OperationID: "list-swarm-stack-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}/tasks", Summary: "List swarm stack tasks", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListStackTasks)
- huma.Register(api, huma.Operation{OperationID: "render-swarm-stack-config", Method: http.MethodPost, Path: "/environments/{id}/swarm/stacks/config/render", Summary: "Render/validate swarm stack config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.RenderStackConfig)
-
- huma.Register(api, huma.Operation{OperationID: "get-swarm-status", Method: http.MethodGet, Path: "/environments/{id}/swarm/status", Summary: "Get swarm status", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetSwarmStatus)
- huma.Register(api, huma.Operation{OperationID: "get-swarm-info", Method: http.MethodGet, Path: "/environments/{id}/swarm/info", Summary: "Get swarm info", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetSwarmInfo)
- huma.Register(api, huma.Operation{OperationID: "init-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/init", Summary: "Initialize swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.InitSwarm)
- huma.Register(api, huma.Operation{OperationID: "join-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/join", Summary: "Join swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.JoinSwarm)
- huma.Register(api, huma.Operation{OperationID: "leave-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/leave", Summary: "Leave swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.LeaveSwarm)
- huma.Register(api, huma.Operation{OperationID: "unlock-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/unlock", Summary: "Unlock swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.UnlockSwarm)
- huma.Register(api, huma.Operation{OperationID: "get-swarm-unlock-key", Method: http.MethodGet, Path: "/environments/{id}/swarm/unlock-key", Summary: "Get swarm unlock key", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.GetUnlockKey)
- huma.Register(api, huma.Operation{OperationID: "get-swarm-join-tokens", Method: http.MethodGet, Path: "/environments/{id}/swarm/join-tokens", Summary: "Get swarm join tokens", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.GetJoinTokens)
- huma.Register(api, huma.Operation{OperationID: "rotate-swarm-join-tokens", Method: http.MethodPost, Path: "/environments/{id}/swarm/join-tokens/rotate", Summary: "Rotate swarm join tokens", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.RotateJoinTokens)
- huma.Register(api, huma.Operation{OperationID: "update-swarm-spec", Method: http.MethodPut, Path: "/environments/{id}/swarm/spec", Summary: "Update swarm spec", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.UpdateSwarmSpec)
-
- huma.Register(api, huma.Operation{OperationID: "list-swarm-configs", Method: http.MethodGet, Path: "/environments/{id}/swarm/configs", Summary: "List swarm configs", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListConfigs)
- huma.Register(api, huma.Operation{OperationID: "get-swarm-config", Method: http.MethodGet, Path: "/environments/{id}/swarm/configs/{configId}", Summary: "Get swarm config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetConfig)
- huma.Register(api, huma.Operation{OperationID: "create-swarm-config", Method: http.MethodPost, Path: "/environments/{id}/swarm/configs", Summary: "Create swarm config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.CreateConfig)
- huma.Register(api, huma.Operation{OperationID: "update-swarm-config", Method: http.MethodPut, Path: "/environments/{id}/swarm/configs/{configId}", Summary: "Update swarm config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.UpdateConfig)
- huma.Register(api, huma.Operation{OperationID: "delete-swarm-config", Method: http.MethodDelete, Path: "/environments/{id}/swarm/configs/{configId}", Summary: "Delete swarm config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.DeleteConfig)
-
- huma.Register(api, huma.Operation{OperationID: "list-swarm-secrets", Method: http.MethodGet, Path: "/environments/{id}/swarm/secrets", Summary: "List swarm secrets", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.ListSecrets)
- huma.Register(api, huma.Operation{OperationID: "get-swarm-secret", Method: http.MethodGet, Path: "/environments/{id}/swarm/secrets/{secretId}", Summary: "Get swarm secret", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, h.GetSecret)
- huma.Register(api, huma.Operation{OperationID: "create-swarm-secret", Method: http.MethodPost, Path: "/environments/{id}/swarm/secrets", Summary: "Create swarm secret", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.CreateSecret)
- huma.Register(api, huma.Operation{OperationID: "update-swarm-secret", Method: http.MethodPut, Path: "/environments/{id}/swarm/secrets/{secretId}", Summary: "Update swarm secret", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.UpdateSecret)
- huma.Register(api, huma.Operation{OperationID: "delete-swarm-secret", Method: http.MethodDelete, Path: "/environments/{id}/swarm/secrets/{secretId}", Summary: "Delete swarm secret", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequireAdmin(api)}, h.DeleteSecret)
+ huma.Register(api, huma.Operation{OperationID: "list-swarm-services", Method: http.MethodGet, Path: "/environments/{id}/swarm/services", Summary: "List swarm services", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.ListServices)
+ huma.Register(api, huma.Operation{OperationID: "get-swarm-service", Method: http.MethodGet, Path: "/environments/{id}/swarm/services/{serviceId}", Summary: "Get swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.GetService)
+ huma.Register(api, huma.Operation{OperationID: "create-swarm-service", Method: http.MethodPost, Path: "/environments/{id}/swarm/services", Summary: "Create swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmServices)}, h.CreateService)
+ huma.Register(api, huma.Operation{OperationID: "update-swarm-service", Method: http.MethodPut, Path: "/environments/{id}/swarm/services/{serviceId}", Summary: "Update swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmServices)}, h.UpdateService)
+ huma.Register(api, huma.Operation{OperationID: "delete-swarm-service", Method: http.MethodDelete, Path: "/environments/{id}/swarm/services/{serviceId}", Summary: "Delete swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmServices)}, h.DeleteService)
+ huma.Register(api, huma.Operation{OperationID: "list-swarm-service-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/services/{serviceId}/tasks", Summary: "List tasks for a swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.ListServiceTasks)
+ huma.Register(api, huma.Operation{OperationID: "rollback-swarm-service", Method: http.MethodPost, Path: "/environments/{id}/swarm/services/{serviceId}/rollback", Summary: "Rollback a swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmServices)}, h.RollbackService)
+ huma.Register(api, huma.Operation{OperationID: "scale-swarm-service", Method: http.MethodPost, Path: "/environments/{id}/swarm/services/{serviceId}/scale", Summary: "Scale a swarm service", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmServices)}, h.ScaleService)
+
+ huma.Register(api, huma.Operation{OperationID: "list-swarm-nodes", Method: http.MethodGet, Path: "/environments/{id}/swarm/nodes", Summary: "List swarm nodes", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.ListNodes)
+ huma.Register(api, huma.Operation{OperationID: "get-swarm-node", Method: http.MethodGet, Path: "/environments/{id}/swarm/nodes/{nodeId}", Summary: "Get swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.GetNode)
+ huma.Register(api, huma.Operation{OperationID: "get-swarm-node-agent-deployment", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/deployment", Summary: "Get swarm node agent deployment snippets", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmNodes)}, h.GetNodeAgentDeployment)
+ huma.Register(api, huma.Operation{OperationID: "update-swarm-node", Method: http.MethodPatch, Path: "/environments/{id}/swarm/nodes/{nodeId}", Summary: "Update swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmNodes)}, h.UpdateNode)
+ huma.Register(api, huma.Operation{OperationID: "delete-swarm-node", Method: http.MethodDelete, Path: "/environments/{id}/swarm/nodes/{nodeId}", Summary: "Delete swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmNodes)}, h.DeleteNode)
+ huma.Register(api, huma.Operation{OperationID: "promote-swarm-node", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/{nodeId}/promote", Summary: "Promote swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmNodes)}, h.PromoteNode)
+ huma.Register(api, huma.Operation{OperationID: "demote-swarm-node", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/{nodeId}/demote", Summary: "Demote swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmNodes)}, h.DemoteNode)
+ huma.Register(api, huma.Operation{OperationID: "list-swarm-node-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/nodes/{nodeId}/tasks", Summary: "List tasks for a swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.ListNodeTasks)
+ huma.Register(api, huma.Operation{OperationID: "get-swarm-node-identity", Method: http.MethodGet, Path: "/swarm/node-identity", Summary: "Get local swarm node identity", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.GetNodeIdentity)
+
+ huma.Register(api, huma.Operation{OperationID: "list-swarm-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/tasks", Summary: "List swarm tasks", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.ListTasks)
+
+ huma.Register(api, huma.Operation{OperationID: "list-swarm-stacks", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks", Summary: "List swarm stacks", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.ListStacks)
+ huma.Register(api, huma.Operation{OperationID: "deploy-swarm-stack", Method: http.MethodPost, Path: "/environments/{id}/swarm/stacks", Summary: "Deploy swarm stack", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmStacks)}, h.DeployStack)
+ huma.Register(api, huma.Operation{OperationID: "get-swarm-stack", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}", Summary: "Get swarm stack", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.GetStack)
+ huma.Register(api, huma.Operation{OperationID: "get-swarm-stack-source", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}/source", Summary: "Get swarm stack source", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmStacks)}, h.GetStackSource)
+ huma.Register(api, huma.Operation{OperationID: "update-swarm-stack-source", Method: http.MethodPut, Path: "/environments/{id}/swarm/stacks/{name}/source", Summary: "Update swarm stack source", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmStacks)}, h.UpdateStackSource)
+ huma.Register(api, huma.Operation{OperationID: "delete-swarm-stack", Method: http.MethodDelete, Path: "/environments/{id}/swarm/stacks/{name}", Summary: "Delete swarm stack", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmStacks)}, h.DeleteStack)
+ huma.Register(api, huma.Operation{OperationID: "list-swarm-stack-services", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}/services", Summary: "List swarm stack services", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.ListStackServices)
+ huma.Register(api, huma.Operation{OperationID: "list-swarm-stack-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}/tasks", Summary: "List swarm stack tasks", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.ListStackTasks)
+ huma.Register(api, huma.Operation{OperationID: "render-swarm-stack-config", Method: http.MethodPost, Path: "/environments/{id}/swarm/stacks/config/render", Summary: "Render/validate swarm stack config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.RenderStackConfig)
+
+ huma.Register(api, huma.Operation{OperationID: "get-swarm-status", Method: http.MethodGet, Path: "/environments/{id}/swarm/status", Summary: "Get swarm status", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.GetSwarmStatus)
+ huma.Register(api, huma.Operation{OperationID: "get-swarm-info", Method: http.MethodGet, Path: "/environments/{id}/swarm/info", Summary: "Get swarm info", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.GetSwarmInfo)
+ huma.Register(api, huma.Operation{OperationID: "init-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/init", Summary: "Initialize swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmInit)}, h.InitSwarm)
+ huma.Register(api, huma.Operation{OperationID: "join-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/join", Summary: "Join swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmJoin)}, h.JoinSwarm)
+ huma.Register(api, huma.Operation{OperationID: "leave-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/leave", Summary: "Leave swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmLeave)}, h.LeaveSwarm)
+ huma.Register(api, huma.Operation{OperationID: "unlock-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/unlock", Summary: "Unlock swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmUnlock)}, h.UnlockSwarm)
+ huma.Register(api, huma.Operation{OperationID: "get-swarm-unlock-key", Method: http.MethodGet, Path: "/environments/{id}/swarm/unlock-key", Summary: "Get swarm unlock key", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmUnlock)}, h.GetUnlockKey)
+ huma.Register(api, huma.Operation{OperationID: "get-swarm-join-tokens", Method: http.MethodGet, Path: "/environments/{id}/swarm/join-tokens", Summary: "Get swarm join tokens", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmUnlock)}, h.GetJoinTokens)
+ huma.Register(api, huma.Operation{OperationID: "rotate-swarm-join-tokens", Method: http.MethodPost, Path: "/environments/{id}/swarm/join-tokens/rotate", Summary: "Rotate swarm join tokens", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmUnlock)}, h.RotateJoinTokens)
+ huma.Register(api, huma.Operation{OperationID: "update-swarm-spec", Method: http.MethodPut, Path: "/environments/{id}/swarm/spec", Summary: "Update swarm spec", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmSpec)}, h.UpdateSwarmSpec)
+
+ huma.Register(api, huma.Operation{OperationID: "list-swarm-configs", Method: http.MethodGet, Path: "/environments/{id}/swarm/configs", Summary: "List swarm configs", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.ListConfigs)
+ huma.Register(api, huma.Operation{OperationID: "get-swarm-config", Method: http.MethodGet, Path: "/environments/{id}/swarm/configs/{configId}", Summary: "Get swarm config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.GetConfig)
+ huma.Register(api, huma.Operation{OperationID: "create-swarm-config", Method: http.MethodPost, Path: "/environments/{id}/swarm/configs", Summary: "Create swarm config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmConfigs)}, h.CreateConfig)
+ huma.Register(api, huma.Operation{OperationID: "update-swarm-config", Method: http.MethodPut, Path: "/environments/{id}/swarm/configs/{configId}", Summary: "Update swarm config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmConfigs)}, h.UpdateConfig)
+ huma.Register(api, huma.Operation{OperationID: "delete-swarm-config", Method: http.MethodDelete, Path: "/environments/{id}/swarm/configs/{configId}", Summary: "Delete swarm config", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmConfigs)}, h.DeleteConfig)
+
+ huma.Register(api, huma.Operation{OperationID: "list-swarm-secrets", Method: http.MethodGet, Path: "/environments/{id}/swarm/secrets", Summary: "List swarm secrets", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.ListSecrets)
+ huma.Register(api, huma.Operation{OperationID: "get-swarm-secret", Method: http.MethodGet, Path: "/environments/{id}/swarm/secrets/{secretId}", Summary: "Get swarm secret", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.GetSecret)
+ huma.Register(api, huma.Operation{OperationID: "create-swarm-secret", Method: http.MethodPost, Path: "/environments/{id}/swarm/secrets", Summary: "Create swarm secret", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmSecrets)}, h.CreateSecret)
+ huma.Register(api, huma.Operation{OperationID: "update-swarm-secret", Method: http.MethodPut, Path: "/environments/{id}/swarm/secrets/{secretId}", Summary: "Update swarm secret", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmSecrets)}, h.UpdateSecret)
+ huma.Register(api, huma.Operation{OperationID: "delete-swarm-secret", Method: http.MethodDelete, Path: "/environments/{id}/swarm/secrets/{secretId}", Summary: "Delete swarm secret", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}, Middlewares: humamw.RequirePermission(api, authz.PermSwarmSecrets)}, h.DeleteSecret)
}
// ListServices lists swarm services for an environment and returns a paginated response.
@@ -644,10 +645,6 @@ func (h *SwarmHandler) CreateService(ctx context.Context, input *CreateSwarmServ
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
resp, err := h.swarmService.CreateService(ctx, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmServiceCreateError{Err: err}).Error())
@@ -673,10 +670,6 @@ func (h *SwarmHandler) UpdateService(ctx context.Context, input *UpdateSwarmServ
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
resp, err := h.swarmService.UpdateService(ctx, input.ServiceID, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmServiceUpdateError{Err: err}).Error())
@@ -703,10 +696,6 @@ func (h *SwarmHandler) DeleteService(ctx context.Context, input *DeleteSwarmServ
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.RemoveService(ctx, input.ServiceID); err != nil {
if errdefs.IsNotFound(err) {
return nil, huma.Error404NotFound((&common.SwarmServiceNotFoundError{Err: err}).Error())
@@ -761,10 +750,6 @@ func (h *SwarmHandler) RollbackService(ctx context.Context, input *RollbackSwarm
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
resp, err := h.swarmService.RollbackService(ctx, input.ServiceID)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmServiceUpdateError{Err: err}).Error())
@@ -790,10 +775,6 @@ func (h *SwarmHandler) ScaleService(ctx context.Context, input *ScaleSwarmServic
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
resp, err := h.swarmService.ScaleService(ctx, input.ServiceID, input.Body.Replicas)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmServiceUpdateError{Err: err}).Error())
@@ -877,10 +858,6 @@ func (h *SwarmHandler) GetNodeAgentDeployment(ctx context.Context, input *GetSwa
if h.swarmService == nil || h.environmentService == nil || h.cfg == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
node, err := h.swarmService.GetNode(ctx, input.EnvironmentID, input.NodeID)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -981,10 +958,6 @@ func (h *SwarmHandler) UpdateNode(ctx context.Context, input *UpdateSwarmNodeInp
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.UpdateNode(ctx, input.NodeID, input.Body); err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())
}
@@ -1009,10 +982,6 @@ func (h *SwarmHandler) DeleteNode(ctx context.Context, input *DeleteSwarmNodeInp
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.RemoveNode(ctx, input.NodeID, input.Force); err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())
}
@@ -1037,10 +1006,6 @@ func (h *SwarmHandler) PromoteNode(ctx context.Context, input *PromoteSwarmNodeI
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.PromoteNode(ctx, input.NodeID); err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())
}
@@ -1065,10 +1030,6 @@ func (h *SwarmHandler) DemoteNode(ctx context.Context, input *DemoteSwarmNodeInp
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.DemoteNode(ctx, input.NodeID); err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())
}
@@ -1175,10 +1136,6 @@ func (h *SwarmHandler) DeployStack(ctx context.Context, input *DeploySwarmStackI
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
resp, err := h.swarmService.DeployStack(ctx, input.EnvironmentID, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmStackDeployError{Err: err}).Error())
@@ -1231,10 +1188,6 @@ func (h *SwarmHandler) GetStackSource(ctx context.Context, input *GetSwarmStackS
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
source, err := h.swarmService.GetStackSource(ctx, input.EnvironmentID, input.Name)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -1255,10 +1208,6 @@ func (h *SwarmHandler) UpdateStackSource(ctx context.Context, input *UpdateSwarm
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
source, err := h.swarmService.UpdateStackSource(ctx, input.EnvironmentID, input.Name, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to update swarm stack source")
@@ -1285,10 +1234,6 @@ func (h *SwarmHandler) DeleteStack(ctx context.Context, input *DeleteSwarmStackI
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.RemoveStack(ctx, input.EnvironmentID, input.Name); err != nil {
if errdefs.IsNotFound(err) {
return nil, huma.Error404NotFound("Swarm stack not found")
@@ -1452,10 +1397,6 @@ func (h *SwarmHandler) InitSwarm(ctx context.Context, input *InitSwarmInput) (*I
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
resp, err := h.swarmService.InitSwarm(ctx, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to initialize swarm")
@@ -1481,10 +1422,6 @@ func (h *SwarmHandler) JoinSwarm(ctx context.Context, input *JoinSwarmInput) (*J
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.JoinSwarm(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to join swarm")
}
@@ -1509,10 +1446,6 @@ func (h *SwarmHandler) LeaveSwarm(ctx context.Context, input *LeaveSwarmInput) (
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.LeaveSwarm(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to leave swarm")
}
@@ -1537,10 +1470,6 @@ func (h *SwarmHandler) UnlockSwarm(ctx context.Context, input *UnlockSwarmInput)
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.UnlockSwarm(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to unlock swarm")
}
@@ -1564,10 +1493,6 @@ func (h *SwarmHandler) GetUnlockKey(ctx context.Context, input *GetSwarmUnlockKe
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
resp, err := h.swarmService.GetSwarmUnlockKey(ctx)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to get swarm unlock key")
@@ -1590,10 +1515,6 @@ func (h *SwarmHandler) GetJoinTokens(ctx context.Context, input *GetSwarmJoinTok
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
resp, err := h.swarmService.GetSwarmJoinTokens(ctx)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to get swarm join tokens")
@@ -1617,10 +1538,6 @@ func (h *SwarmHandler) RotateJoinTokens(ctx context.Context, input *RotateSwarmJ
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.RotateSwarmJoinTokens(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to rotate swarm join tokens")
}
@@ -1645,10 +1562,6 @@ func (h *SwarmHandler) UpdateSwarmSpec(ctx context.Context, input *UpdateSwarmSp
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.UpdateSwarmSpec(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to update swarm spec")
}
@@ -1726,10 +1639,6 @@ func (h *SwarmHandler) CreateConfig(ctx context.Context, input *CreateSwarmConfi
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
cfg, err := h.swarmService.CreateConfig(ctx, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to create swarm config")
@@ -1756,10 +1665,6 @@ func (h *SwarmHandler) UpdateConfig(ctx context.Context, input *UpdateSwarmConfi
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.UpdateConfig(ctx, input.ConfigID, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to update swarm config")
}
@@ -1781,10 +1686,6 @@ func (h *SwarmHandler) DeleteConfig(ctx context.Context, input *DeleteSwarmConfi
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.RemoveConfig(ctx, input.ConfigID); err != nil {
if errdefs.IsNotFound(err) {
return nil, huma.Error404NotFound("Swarm config not found")
@@ -1865,10 +1766,6 @@ func (h *SwarmHandler) CreateSecret(ctx context.Context, input *CreateSwarmSecre
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
secret, err := h.swarmService.CreateSecret(ctx, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to create swarm secret")
@@ -1895,10 +1792,6 @@ func (h *SwarmHandler) UpdateSecret(ctx context.Context, input *UpdateSwarmSecre
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.UpdateSecret(ctx, input.SecretID, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to update swarm secret")
}
@@ -1920,10 +1813,6 @@ func (h *SwarmHandler) DeleteSecret(ctx context.Context, input *DeleteSwarmSecre
if h.swarmService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.swarmService.RemoveSecret(ctx, input.SecretID); err != nil {
if errdefs.IsNotFound(err) {
return nil, huma.Error404NotFound("Swarm secret not found")
diff --git a/backend/api/handlers/system.go b/backend/api/handlers/system.go
index 90bac028f..eda95b4ec 100644
--- a/backend/api/handlers/system.go
+++ b/backend/api/handlers/system.go
@@ -11,6 +11,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
docker "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"
"github.com/getarcaneapp/arcane/types/base"
containertypes "github.com/getarcaneapp/arcane/types/container"
@@ -146,6 +147,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermSystemRead),
}, h.GetDockerInfo)
huma.Register(api, huma.Operation{
@@ -159,7 +161,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermSystemPrune),
}, h.PruneAll)
huma.Register(api, huma.Operation{
@@ -173,7 +175,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersStart),
}, h.StartAllContainers)
huma.Register(api, huma.Operation{
@@ -187,7 +189,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersStart),
}, h.StartAllStoppedContainers)
huma.Register(api, huma.Operation{
@@ -201,7 +203,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersStop),
}, h.StopAllContainers)
huma.Register(api, huma.Operation{
@@ -215,6 +217,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermContainersCreate),
}, h.ConvertDockerRun)
huma.Register(api, huma.Operation{
@@ -228,7 +231,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermSystemRead),
}, h.CheckUpgradeAvailable)
huma.Register(api, huma.Operation{
@@ -243,7 +246,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermSystemUpgrade),
}, h.TriggerUpgrade)
}
@@ -364,10 +367,6 @@ func (h *SystemHandler) PruneAll(ctx context.Context, input *PruneAllInput) (*Pr
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
slog.InfoContext(ctx, "System prune operation initiated",
"containers", input.Body.Containers,
"images", input.Body.Images,
@@ -402,10 +401,6 @@ func (h *SystemHandler) StartAllContainers(ctx context.Context, input *StartAllC
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
result, err := h.systemService.StartAllContainers(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ContainerStartAllError{Err: err}).Error())
@@ -425,10 +420,6 @@ func (h *SystemHandler) StartAllStoppedContainers(ctx context.Context, input *St
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
result, err := h.systemService.StartAllStoppedContainers(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ContainerStartStoppedError{Err: err}).Error())
@@ -448,10 +439,6 @@ func (h *SystemHandler) StopAllContainers(ctx context.Context, input *StopAllCon
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
result, err := h.systemService.StopAllContainers(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ContainerStopAllError{Err: err}).Error())
@@ -497,10 +484,6 @@ func (h *SystemHandler) CheckUpgradeAvailable(ctx context.Context, input *CheckU
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
canUpgrade, err := h.upgradeService.CanUpgrade(ctx)
if err != nil {
slog.Debug("System upgrade check failed", "error", err)
@@ -528,10 +511,6 @@ func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgrad
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
user, exists := humamw.GetCurrentUserFromContext(ctx)
if !exists {
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
diff --git a/backend/api/handlers/templates.go b/backend/api/handlers/templates.go
index dea6c411a..3122f8b42 100644
--- a/backend/api/handlers/templates.go
+++ b/backend/api/handlers/templates.go
@@ -11,6 +11,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/utils/mapper"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/env"
@@ -192,7 +193,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesRead),
}, h.FetchRegistry)
huma.Register(api, huma.Operation{
@@ -202,6 +203,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
Summary: "List templates (paginated)",
Description: "Get a paginated list of compose templates",
Tags: []string{"Templates"},
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesList),
}, h.ListTemplates)
huma.Register(api, huma.Operation{
@@ -211,6 +213,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
Summary: "List all templates",
Description: "Get all compose templates without pagination",
Tags: []string{"Templates"},
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesList),
}, h.GetAllTemplates)
huma.Register(api, huma.Operation{
@@ -220,6 +223,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
Summary: "Get a template",
Description: "Get a compose template by ID",
Tags: []string{"Templates"},
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesRead),
}, h.GetTemplate)
huma.Register(api, huma.Operation{
@@ -229,6 +233,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
Summary: "Get template content",
Description: "Get the compose content for a template with parsed data",
Tags: []string{"Templates"},
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesRead),
}, h.GetTemplateContent)
// Protected endpoints
@@ -243,6 +248,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesCreate),
}, h.CreateTemplate)
huma.Register(api, huma.Operation{
@@ -256,6 +262,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesUpdate),
}, h.UpdateTemplate)
huma.Register(api, huma.Operation{
@@ -269,6 +276,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesDelete),
}, h.DeleteTemplate)
huma.Register(api, huma.Operation{
@@ -282,6 +290,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesRead),
}, h.DownloadTemplate)
huma.Register(api, huma.Operation{
@@ -295,6 +304,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesRead),
}, h.GetDefaultTemplates)
huma.Register(api, huma.Operation{
@@ -308,6 +318,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesUpdate),
}, h.SaveDefaultTemplates)
huma.Register(api, huma.Operation{
@@ -321,6 +332,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesList),
}, h.GetRegistries)
huma.Register(api, huma.Operation{
@@ -334,7 +346,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesCreate),
}, h.CreateRegistry)
huma.Register(api, huma.Operation{
@@ -348,7 +360,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesUpdate),
}, h.UpdateRegistry)
huma.Register(api, huma.Operation{
@@ -362,7 +374,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesDelete),
}, h.DeleteRegistry)
huma.Register(api, huma.Operation{
@@ -376,7 +388,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesRead),
}, h.GetGlobalVariables)
huma.Register(api, huma.Operation{
@@ -390,7 +402,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermTemplatesUpdate),
}, h.UpdateGlobalVariables)
}
@@ -771,9 +783,6 @@ func (h *TemplateHandler) GetRegistries(ctx context.Context, _ *GetTemplateRegis
// CreateRegistry creates a new template registry.
func (h *TemplateHandler) CreateRegistry(ctx context.Context, input *CreateTemplateRegistryInput) (*CreateTemplateRegistryOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.templateService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -803,9 +812,6 @@ func (h *TemplateHandler) CreateRegistry(ctx context.Context, input *CreateTempl
// UpdateRegistry updates a template registry.
func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTemplateRegistryInput) (*UpdateTemplateRegistryOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.templateService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -839,9 +845,6 @@ func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTempl
// DeleteRegistry deletes a template registry.
func (h *TemplateHandler) DeleteRegistry(ctx context.Context, input *DeleteTemplateRegistryInput) (*DeleteTemplateRegistryOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.templateService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -869,9 +872,6 @@ func (h *TemplateHandler) DeleteRegistry(ctx context.Context, input *DeleteTempl
// FetchRegistry fetches templates from a remote registry URL.
func (h *TemplateHandler) FetchRegistry(ctx context.Context, input *FetchTemplateRegistryInput) (*FetchTemplateRegistryOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.templateService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -900,9 +900,6 @@ func (h *TemplateHandler) FetchRegistry(ctx context.Context, input *FetchTemplat
// GetGlobalVariables returns global template variables.
func (h *TemplateHandler) GetGlobalVariables(ctx context.Context, input *GetGlobalVariablesInput) (*GetGlobalVariablesOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.templateService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -939,9 +936,6 @@ func (h *TemplateHandler) getGlobalVariablesForRemoteEnvironmentInternal(ctx con
// UpdateGlobalVariables updates global template variables.
func (h *TemplateHandler) UpdateGlobalVariables(ctx context.Context, input *UpdateGlobalVariablesInput) (*UpdateGlobalVariablesOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.templateService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
diff --git a/backend/api/handlers/templates_test.go b/backend/api/handlers/templates_test.go
index 274dee874..225a5eb9a 100644
--- a/backend/api/handlers/templates_test.go
+++ b/backend/api/handlers/templates_test.go
@@ -17,6 +17,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
glsqlite "github.com/glebarez/sqlite"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
@@ -130,7 +131,6 @@ func newTemplateFetchTestRouter(t *testing.T, httpClient *http.Client) *echo.Ech
_, err = userService.CreateUser(context.Background(), &models.User{
BaseModel: models.BaseModel{ID: "user-1"},
Username: "alice",
- Roles: models.StringSlice{"admin"},
})
require.NoError(t, err)
require.NoError(t, db.Create(&models.UserSession{
@@ -141,7 +141,7 @@ func newTemplateFetchTestRouter(t *testing.T, httpClient *http.Client) *echo.Ech
ExpiresAt: time.Now().Add(time.Hour),
}).Error)
- authService := services.NewAuthService(userService, nil, nil, services.NewSessionService(databaseDB), "test-secret", &config.Config{})
+ authService := services.NewAuthService(userService, nil, nil, services.NewSessionService(databaseDB), nil, "test-secret", &config.Config{})
templateService := services.NewTemplateService(context.Background(), nil, httpClient, nil)
router := echo.New()
@@ -165,13 +165,25 @@ func newTemplateFetchTestRouter(t *testing.T, httpClient *http.Client) *echo.Ech
}
api := humaecho.NewWithGroup(router, apiGroup, humaConfig)
- api.UseMiddleware(humamiddleware.NewAuthBridge(api, authService, nil, nil, &config.Config{}))
+ api.UseMiddleware(humamiddleware.NewAuthBridge(api, authService, nil, sudoPermResolver{}, nil, &config.Config{}))
RegisterHealth(api)
RegisterTemplates(api, templateService, nil)
return router
}
+// sudoPermResolver is a test stub satisfying humamiddleware.PermissionResolver
+// that grants every permission. Used in tests that don't care about RBAC
+// gating — they want auth to succeed and permissions to be unrestricted.
+type sudoPermResolver struct{}
+
+func (sudoPermResolver) ResolvePermissions(_ context.Context, _ *models.User) (*authz.PermissionSet, error) {
+ return authz.SudoPermissionSet(), nil
+}
+func (sudoPermResolver) ResolveApiKeyPermissions(_ context.Context, _ string) (*authz.PermissionSet, error) {
+ return authz.SudoPermissionSet(), nil
+}
+
func makeTemplateFetchToken(t *testing.T, secret string, userID, username string) string {
t.Helper()
diff --git a/backend/api/handlers/updater.go b/backend/api/handlers/updater.go
index a6ea764d2..c168bf2f7 100644
--- a/backend/api/handlers/updater.go
+++ b/backend/api/handlers/updater.go
@@ -9,6 +9,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/updater"
)
@@ -72,7 +73,7 @@ func RegisterUpdater(api huma.API, updaterService *services.UpdaterService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesCheck),
}, h.RunUpdater)
huma.Register(api, huma.Operation{
@@ -86,6 +87,7 @@ func RegisterUpdater(api huma.API, updaterService *services.UpdaterService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesRead),
}, h.GetUpdaterStatus)
huma.Register(api, huma.Operation{
@@ -99,6 +101,7 @@ func RegisterUpdater(api huma.API, updaterService *services.UpdaterService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesRead),
}, h.GetUpdaterHistory)
huma.Register(api, huma.Operation{
@@ -112,15 +115,12 @@ func RegisterUpdater(api huma.API, updaterService *services.UpdaterService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesCheck),
}, h.UpdateContainer)
}
// RunUpdater applies pending container updates.
func (h *UpdaterHandler) RunUpdater(ctx context.Context, input *RunUpdaterInput) (*RunUpdaterOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.updaterService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -185,9 +185,6 @@ func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdate
// UpdateContainer updates a single container by pulling the latest image and applying the appropriate update flow.
func (h *UpdaterHandler) UpdateContainer(ctx context.Context, input *UpdateContainerInput) (*UpdateContainerOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.updaterService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
diff --git a/backend/api/handlers/users.go b/backend/api/handlers/users.go
index ac5c3e582..bbf934145 100644
--- a/backend/api/handlers/users.go
+++ b/backend/api/handlers/users.go
@@ -11,6 +11,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/utils/validation"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/user"
@@ -97,7 +98,7 @@ func RegisterUsers(api huma.API, userService *services.UserService, authService
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermUsersList),
}, h.ListUsers)
huma.Register(api, huma.Operation{
@@ -111,7 +112,7 @@ func RegisterUsers(api huma.API, userService *services.UserService, authService
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermUsersCreate),
}, h.CreateUser)
huma.Register(api, huma.Operation{
@@ -125,7 +126,7 @@ func RegisterUsers(api huma.API, userService *services.UserService, authService
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermUsersRead),
}, h.GetUser)
huma.Register(api, huma.Operation{
@@ -139,7 +140,7 @@ func RegisterUsers(api huma.API, userService *services.UserService, authService
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermUsersUpdate),
}, h.UpdateUser)
huma.Register(api, huma.Operation{
@@ -153,7 +154,7 @@ func RegisterUsers(api huma.API, userService *services.UserService, authService
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermUsersDelete),
}, h.DeleteUser)
}
@@ -167,10 +168,6 @@ func (h *UserHandler) ListUsers(ctx context.Context, input *ListUsersInput) (*Li
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
users, paginationResp, err := h.userService.ListUsersPaginated(ctx, params)
@@ -199,10 +196,6 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
normalizedEmail, err := normalizeOptionalEmailInternal(input.Body.Email)
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
@@ -219,17 +212,12 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*
PasswordHash: hashedPassword,
DisplayName: input.Body.DisplayName,
Email: input.Body.Email,
- Roles: input.Body.Roles,
Locale: input.Body.Locale,
BaseModel: models.BaseModel{
CreatedAt: time.Now(),
},
}
- if userModel.Roles == nil {
- userModel.Roles = []string{"user"}
- }
-
createdUser, err := h.userService.CreateUser(ctx, userModel)
if err != nil {
return nil, huma.Error500InternalServerError((&common.UserCreationError{Err: err}).Error())
@@ -254,10 +242,6 @@ func (h *UserHandler) GetUser(ctx context.Context, input *GetUserInput) (*GetUse
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
userModel, err := h.userService.GetUserByID(ctx, input.UserID)
if err != nil {
return nil, huma.Error404NotFound((&common.UserNotFoundError{}).Error())
@@ -282,10 +266,6 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
userModel, err := h.userService.GetUserByID(ctx, input.UserID)
if err != nil {
return nil, huma.Error404NotFound((&common.UserNotFoundError{}).Error())
@@ -306,9 +286,6 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*
if input.Body.Email != nil {
userModel.Email = input.Body.Email
}
- if input.Body.Roles != nil {
- userModel.Roles = input.Body.Roles
- }
if input.Body.Locale != nil {
userModel.Locale = input.Body.Locale
}
@@ -357,10 +334,6 @@ func (h *UserHandler) DeleteUser(ctx context.Context, input *DeleteUserInput) (*
return nil, huma.Error500InternalServerError("service not available")
}
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
-
if err := h.userService.DeleteUser(ctx, input.UserID); err != nil {
if errors.Is(err, services.ErrCannotRemoveLastAdmin) {
return nil, huma.Error409Conflict(services.ErrCannotRemoveLastAdmin.Error())
diff --git a/backend/api/handlers/users_test.go b/backend/api/handlers/users_test.go
index 732864a9f..9913be812 100644
--- a/backend/api/handlers/users_test.go
+++ b/backend/api/handlers/users_test.go
@@ -9,7 +9,7 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
- usertypes "github.com/getarcaneapp/arcane/types/user"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
glsqlite "github.com/glebarez/sqlite"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
@@ -27,13 +27,12 @@ func setupUserHandlerTestDB(t *testing.T) *database.DB {
return &database.DB{DB: db}
}
-func createHandlerTestUser(t *testing.T, svc *services.UserService, id, username string, roles models.StringSlice) *models.User {
+func createHandlerTestUser(t *testing.T, svc *services.UserService, id, username string, _ models.StringSlice) *models.User {
t.Helper()
user := &models.User{
BaseModel: models.BaseModel{ID: id},
Username: username,
- Roles: roles,
}
created, err := svc.CreateUser(context.Background(), user)
@@ -43,14 +42,20 @@ func createHandlerTestUser(t *testing.T, svc *services.UserService, id, username
}
func adminContext() context.Context {
- return context.WithValue(context.Background(), humamw.ContextKeyUserIsAdmin, true)
+ return context.WithValue(context.Background(), humamw.ContextKeyUserPermissions, authz.SudoPermissionSet())
}
func TestDeleteUserReturnsConflictForLastAdmin(t *testing.T) {
db := setupUserHandlerTestDB(t)
- userSvc := services.NewUserService(db)
+ require.NoError(t, db.AutoMigrate(&models.Role{}, &models.UserRoleAssignment{}, &models.Environment{}))
+ roleSvc := services.NewRoleService(db)
+ require.NoError(t, roleSvc.EnsureBuiltInRoles(context.Background()))
+ userSvc := services.NewUserService(db).WithRoleService(roleSvc)
handler := &UserHandler{userService: userSvc}
- admin := createHandlerTestUser(t, userSvc, "admin-1", "arcane", models.StringSlice{"admin"})
+ admin := createHandlerTestUser(t, userSvc, "admin-1", "arcane", models.StringSlice{})
+ require.NoError(t, roleSvc.SetUserAssignments(context.Background(), admin.ID, []models.UserRoleAssignment{
+ {RoleID: authz.BuiltInRoleAdmin, EnvironmentID: nil},
+ }))
_, err := handler.DeleteUser(adminContext(), &DeleteUserInput{UserID: admin.ID})
require.Error(t, err)
@@ -60,23 +65,3 @@ func TestDeleteUserReturnsConflictForLastAdmin(t *testing.T) {
require.Equal(t, http.StatusConflict, statusErr.GetStatus())
require.Contains(t, statusErr.Error(), services.ErrCannotRemoveLastAdmin.Error())
}
-
-func TestUpdateUserReturnsConflictWhenRemovingLastAdminRole(t *testing.T) {
- db := setupUserHandlerTestDB(t)
- userSvc := services.NewUserService(db)
- handler := &UserHandler{userService: userSvc}
- admin := createHandlerTestUser(t, userSvc, "admin-1", "arcane", models.StringSlice{"ADMIN"})
-
- _, err := handler.UpdateUser(adminContext(), &UpdateUserInput{
- UserID: admin.ID,
- Body: usertypes.UpdateUser{
- Roles: []string{"user"},
- },
- })
- require.Error(t, err)
-
- var statusErr huma.StatusError
- require.ErrorAs(t, err, &statusErr)
- require.Equal(t, http.StatusConflict, statusErr.GetStatus())
- require.Contains(t, statusErr.Error(), services.ErrCannotRemoveLastAdmin.Error())
-}
diff --git a/backend/api/handlers/volumes.go b/backend/api/handlers/volumes.go
index ed7aa05c1..6989d1748 100644
--- a/backend/api/handlers/volumes.go
+++ b/backend/api/handlers/volumes.go
@@ -13,6 +13,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/types/base"
volumetypes "github.com/getarcaneapp/arcane/types/volume"
@@ -311,6 +312,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesList),
}, h.GetVolumeUsageCounts)
huma.Register(api, huma.Operation{
@@ -324,6 +326,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesList),
}, h.ListVolumes)
huma.Register(api, huma.Operation{
@@ -337,6 +340,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesRead),
}, h.GetVolume)
huma.Register(api, huma.Operation{
@@ -350,7 +354,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesCreate),
}, h.CreateVolume)
huma.Register(api, huma.Operation{
@@ -364,7 +368,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesDelete),
}, h.RemoveVolume)
huma.Register(api, huma.Operation{
@@ -378,7 +382,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesPrune),
}, h.PruneVolumes)
huma.Register(api, huma.Operation{
@@ -392,6 +396,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesRead),
}, h.GetVolumeUsage)
huma.Register(api, huma.Operation{
@@ -405,6 +410,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesList),
}, h.GetVolumeSizes)
// --- Volume Browsing Endpoints ---
@@ -419,6 +425,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),
}, h.BrowseDirectory)
huma.Register(api, huma.Operation{
@@ -431,6 +438,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),
}, h.GetFileContent)
huma.Register(api, huma.Operation{
@@ -443,6 +451,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),
}, h.DownloadFile)
huma.Register(api, huma.Operation{
@@ -472,7 +481,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
},
},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesUpload),
}, h.UploadFile)
huma.Register(api, huma.Operation{
@@ -485,7 +494,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesUpload),
}, h.CreateDirectory)
huma.Register(api, huma.Operation{
@@ -498,7 +507,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesDelete),
}, h.DeleteFile)
// --- Volume Backup Endpoints ---
@@ -513,6 +522,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),
}, h.ListBackups)
huma.Register(api, huma.Operation{
@@ -525,7 +535,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesBackup),
}, h.CreateBackup)
huma.Register(api, huma.Operation{
@@ -538,7 +548,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesBackup),
}, h.RestoreBackup)
huma.Register(api, huma.Operation{
@@ -551,7 +561,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesBackup),
}, h.RestoreBackupFiles)
huma.Register(api, huma.Operation{
@@ -564,7 +574,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesBackup),
}, h.DeleteBackup)
huma.Register(api, huma.Operation{
@@ -577,6 +587,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),
}, h.DownloadBackup)
huma.Register(api, huma.Operation{
@@ -589,6 +600,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),
}, h.BackupHasPath)
huma.Register(api, huma.Operation{
@@ -601,6 +613,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),
}, h.ListBackupFiles)
huma.Register(api, huma.Operation{
@@ -630,7 +643,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
},
},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVolumesUpload),
}, h.UploadAndRestore)
}
@@ -714,9 +727,6 @@ func (h *VolumeHandler) GetVolume(ctx context.Context, input *GetVolumeInput) (*
// CreateVolume creates a new Docker volume.
func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInput) (*CreateVolumeOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.volumeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -748,9 +758,6 @@ func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInp
// RemoveVolume removes a Docker volume.
func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInput) (*RemoveVolumeOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.volumeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -776,9 +783,6 @@ func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInp
// PruneVolumes removes all unused Docker volumes.
func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInput) (*PruneVolumesOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.volumeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -934,9 +938,6 @@ func (h *VolumeHandler) DownloadFile(ctx context.Context, input *DownloadFileInp
}
func (h *VolumeHandler) UploadFile(ctx context.Context, input *UploadFileInput) (*base.ApiResponse[base.MessageResponse], error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.volumeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -964,9 +965,6 @@ func (h *VolumeHandler) UploadFile(ctx context.Context, input *UploadFileInput)
}
func (h *VolumeHandler) CreateDirectory(ctx context.Context, input *CreateDirectoryInput) (*base.ApiResponse[base.MessageResponse], error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.volumeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -982,9 +980,6 @@ func (h *VolumeHandler) CreateDirectory(ctx context.Context, input *CreateDirect
}
func (h *VolumeHandler) DeleteFile(ctx context.Context, input *DeleteFileInput) (*base.ApiResponse[base.MessageResponse], error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.volumeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -1053,9 +1048,6 @@ func (h *VolumeHandler) ListBackups(ctx context.Context, input *ListBackupsInput
}
func (h *VolumeHandler) CreateBackup(ctx context.Context, input *CreateBackupInput) (*CreateBackupOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.volumeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -1077,9 +1069,6 @@ func (h *VolumeHandler) CreateBackup(ctx context.Context, input *CreateBackupInp
}
func (h *VolumeHandler) RestoreBackup(ctx context.Context, input *RestoreBackupInput) (*RestoreBackupOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.volumeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -1101,9 +1090,6 @@ func (h *VolumeHandler) RestoreBackup(ctx context.Context, input *RestoreBackupI
}
func (h *VolumeHandler) RestoreBackupFiles(ctx context.Context, input *RestoreBackupFilesInput) (*RestoreBackupFilesOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.volumeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -1170,9 +1156,6 @@ func (h *VolumeHandler) ListBackupFiles(ctx context.Context, input *ListBackupFi
}
func (h *VolumeHandler) DeleteBackup(ctx context.Context, input *DeleteBackupInput) (*DeleteBackupOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.volumeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -1214,9 +1197,6 @@ func (h *VolumeHandler) DownloadBackup(ctx context.Context, input *DownloadBacku
}
func (h *VolumeHandler) UploadAndRestore(ctx context.Context, input *UploadAndRestoreInput) (*UploadAndRestoreOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.volumeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
diff --git a/backend/api/handlers/vulnerabilities.go b/backend/api/handlers/vulnerabilities.go
index 3d0683c6a..e555bf827 100644
--- a/backend/api/handlers/vulnerabilities.go
+++ b/backend/api/handlers/vulnerabilities.go
@@ -8,6 +8,7 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/vulnerability"
)
@@ -137,7 +138,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVulnsScan),
}, h.ScanImage)
huma.Register(api, huma.Operation{
@@ -151,6 +152,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),
}, h.GetScanResult)
huma.Register(api, huma.Operation{
@@ -164,6 +166,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),
}, h.GetScanSummary)
huma.Register(api, huma.Operation{
@@ -177,6 +180,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),
}, h.GetScanSummaries)
huma.Register(api, huma.Operation{
@@ -190,6 +194,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),
}, h.ListImageVulnerabilities)
huma.Register(api, huma.Operation{
@@ -203,6 +208,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),
}, h.GetScannerStatus)
huma.Register(api, huma.Operation{
@@ -216,6 +222,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),
}, h.GetEnvironmentSummary)
huma.Register(api, huma.Operation{
@@ -229,6 +236,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),
}, h.ListAllVulnerabilities)
huma.Register(api, huma.Operation{
@@ -242,6 +250,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),
}, h.ListAllVulnerabilityImageOptions)
huma.Register(api, huma.Operation{
@@ -255,7 +264,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVulnsManage),
}, h.IgnoreVulnerability)
huma.Register(api, huma.Operation{
@@ -269,7 +278,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermVulnsManage),
}, h.UnignoreVulnerability)
huma.Register(api, huma.Operation{
@@ -283,14 +292,12 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),
}, h.ListIgnoredVulnerabilities)
}
// ScanImage initiates a vulnerability scan for an image.
func (h *VulnerabilityHandler) ScanImage(ctx context.Context, input *ScanImageInput) (*ScanImageOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.vulnerabilityService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -548,9 +555,6 @@ type IgnoreVulnerabilityOutput struct {
// IgnoreVulnerability creates an ignore record for a vulnerability.
func (h *VulnerabilityHandler) IgnoreVulnerability(ctx context.Context, input *IgnoreVulnerabilityInput) (*IgnoreVulnerabilityOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.vulnerabilityService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -600,9 +604,6 @@ type UnignoreVulnerabilityOutput struct {
// UnignoreVulnerability removes an ignore record for a vulnerability.
func (h *VulnerabilityHandler) UnignoreVulnerability(ctx context.Context, input *UnignoreVulnerabilityInput) (*UnignoreVulnerabilityOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.vulnerabilityService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
diff --git a/backend/api/handlers/webhooks.go b/backend/api/handlers/webhooks.go
index 60d36860e..f130bb420 100644
--- a/backend/api/handlers/webhooks.go
+++ b/backend/api/handlers/webhooks.go
@@ -9,6 +9,7 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/api/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/webhook"
)
@@ -70,6 +71,7 @@ func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
+ Middlewares: humamw.RequirePermission(api, authz.PermWebhooksList),
}, h.ListWebhooks)
huma.Register(api, huma.Operation{
@@ -83,7 +85,7 @@ func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermWebhooksCreate),
}, h.CreateWebhook)
huma.Register(api, huma.Operation{
@@ -97,7 +99,7 @@ func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermWebhooksUpdate),
}, h.UpdateWebhook)
huma.Register(api, huma.Operation{
@@ -111,7 +113,7 @@ func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
- Middlewares: humamw.RequireAdmin(api),
+ Middlewares: humamw.RequirePermission(api, authz.PermWebhooksDelete),
}, h.DeleteWebhook)
}
@@ -136,9 +138,6 @@ func (h *WebhookHandler) ListWebhooks(ctx context.Context, input *ListWebhooksIn
// CreateWebhook creates a new webhook and returns the raw token (shown once only).
func (h *WebhookHandler) CreateWebhook(ctx context.Context, input *CreateWebhookInput) (*CreateWebhookOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.webhookService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -191,9 +190,6 @@ func (h *WebhookHandler) CreateWebhook(ctx context.Context, input *CreateWebhook
// UpdateWebhook updates a webhook's enabled state.
func (h *WebhookHandler) UpdateWebhook(ctx context.Context, input *UpdateWebhookInput) (*UpdateWebhookOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.webhookService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
@@ -222,9 +218,6 @@ func (h *WebhookHandler) UpdateWebhook(ctx context.Context, input *UpdateWebhook
// DeleteWebhook removes a webhook.
func (h *WebhookHandler) DeleteWebhook(ctx context.Context, input *DeleteWebhookInput) (*DeleteWebhookOutput, error) {
- if err := checkAdminInternal(ctx); err != nil {
- return nil, err
- }
if h.webhookService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
diff --git a/backend/api/middleware/auth.go b/backend/api/middleware/auth.go
index 0e8fb817f..ae3fb6b0c 100644
--- a/backend/api/middleware/auth.go
+++ b/backend/api/middleware/auth.go
@@ -3,6 +3,7 @@ package middleware
import (
"context"
"errors"
+ "log/slog"
"net/http"
"strings"
@@ -11,6 +12,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
pkgutils "github.com/getarcaneapp/arcane/backend/pkg/utils"
"github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"
)
@@ -25,8 +27,9 @@ const (
ContextKeyCurrentUser ContextKey = "currentUser"
// ContextKeyCurrentSessionID is the context key for the authenticated session ID.
ContextKeyCurrentSessionID ContextKey = "currentSessionID"
- // ContextKeyUserIsAdmin is the context key for whether the user is an admin.
- ContextKeyUserIsAdmin ContextKey = "userIsAdmin"
+ // ContextKeyUserPermissions is the context key for the caller's resolved
+ // PermissionSet, attached by the auth bridge.
+ ContextKeyUserPermissions ContextKey = "userPermissions"
// ContextKeyRemoteAddr is the context key for the request remote address.
ContextKeyRemoteAddr ContextKey = "remoteAddr"
)
@@ -49,10 +52,11 @@ func GetCurrentSessionIDFromContext(ctx context.Context) (string, bool) {
return sessionID, ok
}
-// IsAdminFromContext checks if the current user is an admin.
-func IsAdminFromContext(ctx context.Context) bool {
- isAdmin, ok := ctx.Value(ContextKeyUserIsAdmin).(bool)
- return ok && isAdmin
+// PermissionsFromContext retrieves the caller's resolved PermissionSet.
+// Returns nil, false on unauthenticated paths.
+func PermissionsFromContext(ctx context.Context) (*authz.PermissionSet, bool) {
+ ps, ok := ctx.Value(ContextKeyUserPermissions).(*authz.PermissionSet)
+ return ps, ok
}
// GetRemoteAddrFromContext retrieves the request remote address from context.
@@ -76,6 +80,13 @@ type environmentAccessTokenResolver interface {
ResolveEnvironmentByAccessToken(ctx context.Context, token string) (*models.Environment, error)
}
+// PermissionResolver resolves a caller's effective permission set. Implemented
+// by services.RoleService; kept as an interface so tests can stub it.
+type PermissionResolver interface {
+ ResolvePermissions(ctx context.Context, user *models.User) (*authz.PermissionSet, error)
+ ResolveApiKeyPermissions(ctx context.Context, apiKeyID string) (*authz.PermissionSet, error)
+}
+
// parseSecurityRequirementsInternal extracts security requirements from a Huma operation.
func parseSecurityRequirementsInternal(api huma.API, ctx operationProvider) securityRequirements {
reqs := securityRequirements{}
@@ -126,19 +137,21 @@ func tryBearerAuthInternal(ctx huma.Context, authService *services.AuthService)
return user, sessionID, nil
}
-// tryApiKeyAuthInternal checks if API key authentication should be allowed through.
-func tryApiKeyAuthInternal(ctx huma.Context, apiKeyService *services.ApiKeyService) (*models.User, bool) {
+// tryApiKeyAuthInternal checks if API key authentication should be allowed
+// through. Returns the resolved user plus the API key's database ID so the
+// caller can fetch the key's own permission set.
+func tryApiKeyAuthInternal(ctx huma.Context, apiKeyService *services.ApiKeyService) (*models.User, string, bool) {
apiKey := ctx.Header(pkgutils.HeaderApiKey)
if apiKey == "" {
- return nil, false
+ return nil, "", false
}
- user, err := apiKeyService.ValidateApiKey(ctx.Context(), apiKey)
+ user, keyID, err := apiKeyService.ValidateApiKeyWithID(ctx.Context(), apiKey)
if err != nil || user == nil {
- return nil, false
+ return nil, "", false
}
- return user, true
+ return user, keyID, true
}
func tryEnvironmentAccessTokenAuthInternal(ctx huma.Context, resolver environmentAccessTokenResolver, token string) (*models.User, bool) {
@@ -184,12 +197,13 @@ func tryAgentAuthInternal(ctx huma.Context, cfg *config.Config) (*models.User, b
}
// createAgentSudoUserInternal creates a sudo user for agent authentication.
+// The PermissionSet attached to the context (via setUserInContextWithSudoInternal)
+// bypasses every check; the user's Roles field is intentionally empty.
func createAgentSudoUserInternal() *models.User {
return &models.User{
BaseModel: models.BaseModel{ID: "agent"},
Email: new("[email protected]"),
Username: "agent",
- Roles: []string{"admin"},
}
}
@@ -197,13 +211,14 @@ func createEnvironmentSudoUserInternal(env *models.Environment) *models.User {
return &models.User{
BaseModel: models.BaseModel{ID: "environment:" + env.ID},
Username: env.Name,
- Roles: []string{"admin"},
}
}
-// NewAuthBridge creates a Huma middleware that validates JWT tokens and
-// enforces security requirements defined on operations.
-func NewAuthBridge(api huma.API, authService *services.AuthService, apiKeyService *services.ApiKeyService, envTokenResolver environmentAccessTokenResolver, cfg *config.Config) func(ctx huma.Context, next func(huma.Context)) {
+// NewAuthBridge creates a Huma middleware that validates credentials and
+// enforces security requirements defined on operations. It also resolves the
+// caller's effective PermissionSet via permResolver and stashes it on the
+// request context for downstream RequirePermission checks.
+func NewAuthBridge(api huma.API, authService *services.AuthService, apiKeyService *services.ApiKeyService, permResolver PermissionResolver, envTokenResolver environmentAccessTokenResolver, cfg *config.Config) func(ctx huma.Context, next func(huma.Context)) {
return func(ctx huma.Context, next func(huma.Context)) {
ctx = huma.WithContext(ctx, context.WithValue(ctx.Context(), ContextKeyRemoteAddr, ctx.RemoteAddr()))
if authService == nil {
@@ -218,23 +233,23 @@ func NewAuthBridge(api huma.API, authService *services.AuthService, apiKeyServic
reqs := parseSecurityRequirementsInternal(api, ctx)
if !reqs.isRequired {
- next(opportunisticBearerAuthInternal(ctx, authService))
+ next(opportunisticBearerAuthInternal(ctx, authService, permResolver))
return
}
if reqs.apiKeyAuth && ctx.Header(pkgutils.HeaderApiKey) != "" {
- handleApiKeyAuthInternal(api, ctx, apiKeyService, envTokenResolver, next)
+ handleApiKeyAuthInternal(api, ctx, apiKeyService, permResolver, envTokenResolver, next)
return
}
if user, ok := tryEnvironmentAccessTokenAuthInternal(ctx, envTokenResolver, ctx.Header(pkgutils.HeaderAgentToken)); ok {
- newCtx := setUserInContextInternal(ctx.Context(), user)
+ newCtx := setUserInContextWithSudoInternal(ctx.Context(), user)
next(huma.WithContext(ctx, newCtx))
return
}
if reqs.bearerAuth {
- nextCtx, handled := handleBearerAuthInternal(api, ctx, authService)
+ nextCtx, handled := handleBearerAuthInternal(api, ctx, authService, permResolver)
if handled {
if nextCtx != nil {
next(nextCtx)
@@ -255,13 +270,13 @@ func tryAgentAuthCtxInternal(ctx huma.Context, cfg *config.Config) (huma.Context
if !ok {
return ctx, false
}
- return huma.WithContext(ctx, setUserInContextInternal(ctx.Context(), user)), true
+ return huma.WithContext(ctx, setUserInContextWithSudoInternal(ctx.Context(), user)), true
}
// opportunisticBearerAuthInternal populates the user/session context if a valid
// bearer token is present, but never fails the request. Used for public routes
// (e.g. logout) that still need to know who the caller is when a token exists.
-func opportunisticBearerAuthInternal(ctx huma.Context, authService *services.AuthService) huma.Context {
+func opportunisticBearerAuthInternal(ctx huma.Context, authService *services.AuthService, permResolver PermissionResolver) huma.Context {
if extractBearerTokenInternal(ctx) == "" {
return ctx
}
@@ -269,31 +284,33 @@ func opportunisticBearerAuthInternal(ctx huma.Context, authService *services.Aut
if err != nil || user == nil {
return ctx
}
- newCtx := setUserInContextInternal(ctx.Context(), user)
+ newCtx := setUserInContextInternal(ctx.Context(), user, resolveUserPermissionsInternal(ctx.Context(), permResolver, user))
newCtx = context.WithValue(newCtx, ContextKeyCurrentSessionID, sessionID)
return huma.WithContext(ctx, newCtx)
}
// handleApiKeyAuthInternal handles the API-key-present branch. If validation
// fails, it writes 401 directly — Bearer is not attempted as fallback.
-func handleApiKeyAuthInternal(api huma.API, ctx huma.Context, apiKeyService *services.ApiKeyService, envTokenResolver environmentAccessTokenResolver, next func(huma.Context)) {
- if user, ok := tryApiKeyAuthInternal(ctx, apiKeyService); ok {
- newCtx := setUserInContextInternal(ctx.Context(), user)
+func handleApiKeyAuthInternal(api huma.API, ctx huma.Context, apiKeyService *services.ApiKeyService, permResolver PermissionResolver, envTokenResolver environmentAccessTokenResolver, next func(huma.Context)) {
+ if user, keyID, ok := tryApiKeyAuthInternal(ctx, apiKeyService); ok {
+ ps := resolveApiKeyPermissionsInternal(ctx.Context(), permResolver, keyID)
+ newCtx := setUserInContextInternal(ctx.Context(), user, ps)
next(huma.WithContext(ctx, newCtx))
return
}
if user, ok := tryEnvironmentAccessTokenAuthInternal(ctx, envTokenResolver, ctx.Header(pkgutils.HeaderApiKey)); ok {
- newCtx := setUserInContextInternal(ctx.Context(), user)
+ newCtx := setUserInContextWithSudoInternal(ctx.Context(), user)
next(huma.WithContext(ctx, newCtx))
return
}
_ = huma.WriteErr(api, ctx, http.StatusUnauthorized, "Unauthorized: invalid API key")
}
-func handleBearerAuthInternal(api huma.API, ctx huma.Context, authService *services.AuthService) (huma.Context, bool) {
+func handleBearerAuthInternal(api huma.API, ctx huma.Context, authService *services.AuthService, permResolver PermissionResolver) (huma.Context, bool) {
user, sessionID, err := tryBearerAuthInternal(ctx, authService)
if err == nil && user != nil {
- newCtx := setUserInContextInternal(ctx.Context(), user)
+ ps := resolveUserPermissionsInternal(ctx.Context(), permResolver, user)
+ newCtx := setUserInContextInternal(ctx.Context(), user, ps)
newCtx = context.WithValue(newCtx, ContextKeyCurrentSessionID, sessionID)
return huma.WithContext(ctx, newCtx), true
}
@@ -307,6 +324,34 @@ func handleBearerAuthInternal(api huma.API, ctx huma.Context, authService *servi
return nil, false
}
+// resolveUserPermissionsInternal asks the RoleService for the user's resolved
+// PermissionSet. If RoleService is unavailable or the lookup fails (boot-time
+// edge cases, broken DB) it returns nil and logs a warning — handlers then
+// see deny-all, which is the safe default.
+func resolveUserPermissionsInternal(ctx context.Context, permResolver PermissionResolver, user *models.User) *authz.PermissionSet {
+ if permResolver == nil || user == nil {
+ return nil
+ }
+ ps, err := permResolver.ResolvePermissions(ctx, user)
+ if err != nil {
+ slog.WarnContext(ctx, "failed to resolve user permissions", "error", err, "user_id", user.ID)
+ return nil
+ }
+ return ps
+}
+
+func resolveApiKeyPermissionsInternal(ctx context.Context, permResolver PermissionResolver, apiKeyID string) *authz.PermissionSet {
+ if permResolver == nil || apiKeyID == "" {
+ return nil
+ }
+ ps, err := permResolver.ResolveApiKeyPermissions(ctx, apiKeyID)
+ if err != nil {
+ slog.WarnContext(ctx, "failed to resolve api key permissions", "error", err, "api_key_id", apiKeyID)
+ return nil
+ }
+ return ps
+}
+
// extractBearerTokenInternal extracts the JWT token from Authorization header or cookie.
func extractBearerTokenInternal(ctx huma.Context) string {
// Try Authorization header first
@@ -339,10 +384,22 @@ func extractTokenFromCookieHeaderInternal(cookieHeader string) string {
return ""
}
-// setUserInContextInternal adds the authenticated user to the context.
-func setUserInContextInternal(ctx context.Context, user *models.User) context.Context {
+// setUserInContextInternal adds the authenticated user and the resolved
+// PermissionSet to the context. Callers must supply a non-nil PermissionSet;
+// pass authz.NewPermissionSet() to express deny-all.
+func setUserInContextInternal(ctx context.Context, user *models.User, ps *authz.PermissionSet) context.Context {
+ if ps == nil {
+ ps = authz.NewPermissionSet()
+ }
ctx = context.WithValue(ctx, ContextKeyUserID, user.ID)
ctx = context.WithValue(ctx, ContextKeyCurrentUser, user)
- ctx = context.WithValue(ctx, ContextKeyUserIsAdmin, pkgutils.UserHasRole(user.Roles, "admin"))
+ ctx = context.WithValue(ctx, ContextKeyUserPermissions, ps)
return ctx
}
+
+// setUserInContextWithSudoInternal attaches a sudo PermissionSet (bypasses
+// every check) plus the user. Used by the agent token and environment
+// access token paths, which are infrastructure-level and not per-user.
+func setUserInContextWithSudoInternal(ctx context.Context, user *models.User) context.Context {
+ return setUserInContextInternal(ctx, user, authz.SudoPermissionSet())
+}
diff --git a/backend/api/middleware/auth_test.go b/backend/api/middleware/auth_test.go
index a83c1b216..ded9df8dc 100644
--- a/backend/api/middleware/auth_test.go
+++ b/backend/api/middleware/auth_test.go
@@ -55,7 +55,7 @@ func TestNewAuthBridge_AcceptsEnvironmentAccessTokenViaAPIKey(t *testing.T) {
}
api := humaecho.NewWithGroup(router, apiGroup, humaConfig)
- api.UseMiddleware(NewAuthBridge(api, &services.AuthService{}, nil, testEnvironmentAccessResolver{
+ api.UseMiddleware(NewAuthBridge(api, &services.AuthService{}, nil, nil, testEnvironmentAccessResolver{
env: &models.Environment{
BaseModel: models.BaseModel{ID: "env-self"},
Name: "Self Target",
@@ -174,12 +174,11 @@ func TestNewAuthBridge_OpportunisticAuthOnPublicRoute(t *testing.T) {
jwtSecret := "test-secret-please-do-not-use-in-prod"
cfg := &config.Config{JWTRefreshExpiry: 24 * time.Hour}
- authSvc := services.NewAuthService(userSvc, nil, nil, sessionSvc, jwtSecret, cfg)
+ authSvc := services.NewAuthService(userSvc, nil, nil, sessionSvc, nil, jwtSecret, cfg)
_, err := userSvc.CreateUser(context.Background(), &models.User{
BaseModel: models.BaseModel{ID: "u-logout"},
Username: "logouttest",
- Roles: models.StringSlice{"user"},
})
require.NoError(t, err)
@@ -207,7 +206,7 @@ func TestNewAuthBridge_OpportunisticAuthOnPublicRoute(t *testing.T) {
"BearerAuth": {Type: "http", Scheme: "bearer"},
}
api := humaecho.NewWithGroup(router, apiGroup, humaConfig)
- api.UseMiddleware(NewAuthBridge(api, authSvc, nil, nil, &config.Config{}))
+ api.UseMiddleware(NewAuthBridge(api, authSvc, nil, nil, nil, &config.Config{}))
var sawSessionID string
huma.Register(api, huma.Operation{
diff --git a/backend/api/middleware/role.go b/backend/api/middleware/role.go
index 4024bb4db..4e7779617 100644
--- a/backend/api/middleware/role.go
+++ b/backend/api/middleware/role.go
@@ -5,16 +5,46 @@ import (
"net/http"
"github.com/danielgtaylor/huma/v2"
+
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
)
-// RequireAdmin returns a per-operation Huma middleware slice that returns 403
-// to non-admin callers. Attach via Operation.Middlewares:
+// RequirePermission returns a per-operation Huma middleware that rejects
+// callers lacking `perm`. For env-scoped permissions, the env ID is extracted
+// from the request path (/environments/{id}/...). For org-level permissions,
+// the env ID segment, if any, is ignored.
+//
+// Attach via Operation.Middlewares:
//
-// huma.Register(api, huma.Operation{..., Middlewares: middleware.RequireAdmin(api)}, h.Handler)
-func RequireAdmin(api huma.API) huma.Middlewares {
+// huma.Register(api, huma.Operation{..., Middlewares: middleware.RequirePermission(api, authz.PermContainersStart)}, h.Handler)
+func RequirePermission(api huma.API, perm string) huma.Middlewares {
+ return huma.Middlewares{func(ctx huma.Context, next func(huma.Context)) {
+ ps, _ := PermissionsFromContext(ctx.Context())
+ envID := ""
+ if authz.IsEnvScoped(perm) {
+ envID = authz.EnvIDFromPath(ctx.URL().Path)
+ }
+ if !ps.Allows(perm, envID) {
+ if err := huma.WriteErr(api, ctx, http.StatusForbidden, "permission denied: "+perm); err != nil {
+ slog.WarnContext(ctx.Context(), "failed to write 403 response", "error", err)
+ }
+ return
+ }
+ next(ctx)
+ }}
+}
+
+// RequireGlobalAdmin returns a per-operation Huma middleware that rejects any
+// caller who is not a global admin (or sudo). Used for operations that are
+// intentionally not exposed as delegated permissions — role creation/edits,
+// user role assignment, and OIDC mapping management. Keeping these admin-only
+// avoids the meta-escalation surface where a holder of `roles:assign` could
+// promote themselves via a custom role.
+func RequireGlobalAdmin(api huma.API) huma.Middlewares {
return huma.Middlewares{func(ctx huma.Context, next func(huma.Context)) {
- if !IsAdminFromContext(ctx.Context()) {
- if err := huma.WriteErr(api, ctx, http.StatusForbidden, "admin access required"); err != nil {
+ ps, _ := PermissionsFromContext(ctx.Context())
+ if !ps.IsGlobalAdmin() {
+ if err := huma.WriteErr(api, ctx, http.StatusForbidden, "permission denied: global admin required"); err != nil {
slog.WarnContext(ctx.Context(), "failed to write 403 response", "error", err)
}
return
diff --git a/backend/api/middleware/role_test.go b/backend/api/middleware/role_test.go
index 9d8f3f3cb..2bc3933cc 100644
--- a/backend/api/middleware/role_test.go
+++ b/backend/api/middleware/role_test.go
@@ -10,67 +10,137 @@ import (
"github.com/danielgtaylor/huma/v2/adapters/humaecho"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/require"
+
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
)
-func TestRequireAdmin_RejectsNonAdmin(t *testing.T) {
+func TestRequirePermission_RejectsCallerMissingPermission(t *testing.T) {
router := echo.New()
api := humaecho.NewWithGroup(router, router.Group("/api"), huma.DefaultConfig("test", "1.0.0"))
api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
- next(huma.WithContext(ctx, context.WithValue(ctx.Context(), ContextKeyUserIsAdmin, false)))
+ // Caller has containers:list but NOT containers:start.
+ ps := authz.NewPermissionSet()
+ ps.AddEnv("env-1", authz.PermContainersList)
+ next(huma.WithContext(ctx, context.WithValue(ctx.Context(), ContextKeyUserPermissions, ps)))
})
huma.Register(api, huma.Operation{
- OperationID: "guarded",
- Method: http.MethodGet,
- Path: "/guarded",
- Middlewares: RequireAdmin(api),
- }, func(_ context.Context, _ *struct{}) (*struct{}, error) {
- t.Fatal("handler must not run for non-admin")
+ OperationID: "guarded-start",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/containers/{cid}/start",
+ Middlewares: RequirePermission(api, authz.PermContainersStart),
+ }, func(_ context.Context, _ *struct {
+ ID string `path:"id"`
+ CID string `path:"cid"`
+ }) (*struct{}, error) {
+ t.Fatal("handler must not run when permission is missing")
return nil, nil
})
- req := httptest.NewRequest(http.MethodGet, "/api/guarded", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/env-1/containers/c/start", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusForbidden, rec.Code)
- require.Contains(t, rec.Body.String(), "admin access required")
+ require.Contains(t, rec.Body.String(), "permission denied: containers:start")
}
-func TestRequireAdmin_AllowsAdmin(t *testing.T) {
+func TestRequirePermission_AllowsCallerWithPermissionOnEnv(t *testing.T) {
router := echo.New()
api := humaecho.NewWithGroup(router, router.Group("/api"), huma.DefaultConfig("test", "1.0.0"))
api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
- next(huma.WithContext(ctx, context.WithValue(ctx.Context(), ContextKeyUserIsAdmin, true)))
+ ps := authz.NewPermissionSet()
+ ps.AddEnv("env-1", authz.PermContainersStart)
+ next(huma.WithContext(ctx, context.WithValue(ctx.Context(), ContextKeyUserPermissions, ps)))
})
- type guardedAdminOutput struct {
+ type out struct {
Body struct {
Success bool `json:"success"`
}
}
-
handlerRan := false
huma.Register(api, huma.Operation{
- OperationID: "guarded-admin",
- Method: http.MethodGet,
- Path: "/guarded-admin",
- Middlewares: RequireAdmin(api),
- }, func(_ context.Context, _ *struct{}) (*guardedAdminOutput, error) {
+ OperationID: "guarded-start-allow",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/containers/{cid}/start",
+ Middlewares: RequirePermission(api, authz.PermContainersStart),
+ }, func(_ context.Context, _ *struct {
+ ID string `path:"id"`
+ CID string `path:"cid"`
+ }) (*out, error) {
handlerRan = true
- return &guardedAdminOutput{
- Body: struct {
- Success bool `json:"success"`
- }{Success: true},
- }, nil
+ return &out{Body: struct {
+ Success bool `json:"success"`
+ }{Success: true}}, nil
})
- req := httptest.NewRequest(http.MethodGet, "/api/guarded-admin", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/env-1/containers/c/start", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.True(t, handlerRan)
}
+
+func TestRequirePermission_EnvScopedDoesNotLeakAcrossEnvs(t *testing.T) {
+ router := echo.New()
+ api := humaecho.NewWithGroup(router, router.Group("/api"), huma.DefaultConfig("test", "1.0.0"))
+
+ api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
+ ps := authz.NewPermissionSet()
+ // Permission scoped to env-1; request will target env-2.
+ ps.AddEnv("env-1", authz.PermContainersStart)
+ next(huma.WithContext(ctx, context.WithValue(ctx.Context(), ContextKeyUserPermissions, ps)))
+ })
+
+ huma.Register(api, huma.Operation{
+ OperationID: "guarded-start-other-env",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/containers/{cid}/start",
+ Middlewares: RequirePermission(api, authz.PermContainersStart),
+ }, func(_ context.Context, _ *struct {
+ ID string `path:"id"`
+ CID string `path:"cid"`
+ }) (*struct{}, error) {
+ t.Fatal("handler must not run when permission is scoped to a different env")
+ return nil, nil
+ })
+
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/env-2/containers/c/start", nil)
+ rec := httptest.NewRecorder()
+ router.ServeHTTP(rec, req)
+
+ require.Equal(t, http.StatusForbidden, rec.Code)
+}
+
+func TestRequirePermission_SudoCallerAllowed(t *testing.T) {
+ router := echo.New()
+ api := humaecho.NewWithGroup(router, router.Group("/api"), huma.DefaultConfig("test", "1.0.0"))
+
+ api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
+ next(huma.WithContext(ctx, context.WithValue(ctx.Context(), ContextKeyUserPermissions, authz.SudoPermissionSet())))
+ })
+
+ handlerRan := false
+ huma.Register(api, huma.Operation{
+ OperationID: "guarded-sudo",
+ Method: http.MethodDelete,
+ Path: "/users/{userId}",
+ Middlewares: RequirePermission(api, authz.PermUsersDelete),
+ }, func(_ context.Context, _ *struct {
+ UserID string `path:"userId"`
+ }) (*struct{}, error) {
+ handlerRan = true
+ return &struct{}{}, nil
+ })
+
+ req := httptest.NewRequest(http.MethodDelete, "/api/users/u-1", nil)
+ rec := httptest.NewRecorder()
+ router.ServeHTTP(rec, req)
+
+ require.Equal(t, http.StatusNoContent, rec.Code)
+ require.True(t, handlerRan)
+}
diff --git a/backend/api/ws/handler.go b/backend/api/ws/handler.go
index adc375852..a15208234 100644
--- a/backend/api/ws/handler.go
+++ b/backend/api/ws/handler.go
@@ -18,6 +18,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
docker "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"
"github.com/getarcaneapp/arcane/backend/pkg/libarcane/system"
wshub "github.com/getarcaneapp/arcane/backend/pkg/libarcane/ws"
@@ -338,12 +339,12 @@ func NewWebSocketHandler(
},
}
wsGroup := group.Group("/environments/:id/ws", authMiddleware.WithAdminNotRequired().Add())
- wsGroup.GET("/projects/:projectId/logs", handler.ProjectLogs)
- wsGroup.GET("/containers/:containerId/logs", handler.ContainerLogs)
- wsGroup.GET("/containers/:containerId/stats", handler.ContainerStats)
- wsGroup.GET("/containers/:containerId/terminal", handler.ContainerExec)
- wsGroup.GET("/swarm/services/:serviceId/logs", handler.ServiceLogs)
- wsGroup.GET("/system/stats", handler.SystemStats)
+ wsGroup.GET("/projects/:projectId/logs", handler.ProjectLogs, middleware.RequirePermission(authz.PermProjectsLogs))
+ wsGroup.GET("/containers/:containerId/logs", handler.ContainerLogs, middleware.RequirePermission(authz.PermContainersLogs))
+ wsGroup.GET("/containers/:containerId/stats", handler.ContainerStats, middleware.RequirePermission(authz.PermContainersRead))
+ wsGroup.GET("/containers/:containerId/terminal", handler.ContainerExec, middleware.RequirePermission(authz.PermContainersExec))
+ wsGroup.GET("/swarm/services/:serviceId/logs", handler.ServiceLogs, middleware.RequirePermission(authz.PermSwarmServicesLogs))
+ wsGroup.GET("/system/stats", handler.SystemStats, middleware.RequirePermission(authz.PermSystemRead))
}
// ============================================================================
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index 0e90b377d..f34974526 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -186,6 +186,7 @@ func initializeStartupState(appCtx context.Context, cfg *config.Config, appServi
}
startup.InitializeNonAgentFeatures(appCtx, runtimeCfg,
+ appServices.Role.EnsureBuiltInRoles,
appServices.User.CreateDefaultAdmin,
func(ctx context.Context) error {
return appServices.ApiKey.ReconcileDefaultAdminAPIKey(ctx, runtimeCfg.AdminStaticAPIKey)
@@ -197,6 +198,8 @@ func initializeStartupState(appCtx context.Context, cfg *config.Config, appServi
)
startup.CleanupUnknownSettings(appCtx, appServices.Settings)
+ runRoleStartupTasks(appCtx, appServices.Role, cfg, cfg.AgentMode)
+
// Auto-pair only applies in Edge mode (where the agent's outbound tunnel is the
// only path to the manager). Direct mode is passive — the manager dials the agent's
// HTTP server on TCP 3553, and the manager-side health-check promotes the env to
@@ -210,6 +213,35 @@ func initializeStartupState(appCtx context.Context, cfg *config.Config, appServi
}
}
+func runRoleStartupTasks(ctx context.Context, roleService *services.RoleService, cfg *config.Config, agentMode bool) {
+ if roleService == nil {
+ return
+ }
+ if err := roleService.EnsureBuiltInRoles(ctx); err != nil {
+ slog.ErrorContext(ctx, "Failed to reconcile built-in roles", "error", err)
+ }
+ // Backfill must run AFTER EnsureBuiltInRoles (it references the role IDs
+ // seeded there) and BEFORE BackfillApiKeyPermissions / AssertGlobalAdminExists
+ // (both consult the assignments table this populates).
+ if err := roleService.BackfillLegacyRoleAssignments(ctx); err != nil {
+ slog.ErrorContext(ctx, "Failed to backfill legacy users.roles into user_role_assignments", "error", err)
+ }
+ if err := roleService.BackfillApiKeyPermissions(ctx); err != nil {
+ slog.WarnContext(ctx, "Failed to backfill API key permissions", "error", err)
+ }
+ if cfg != nil {
+ if err := roleService.ReconcileEnvOidcMappings(ctx, cfg.OidcRoleMappings); err != nil {
+ slog.ErrorContext(ctx, "Failed to reconcile OIDC_ROLE_MAPPINGS", "error", err)
+ }
+ }
+ if agentMode {
+ return
+ }
+ if err := roleService.AssertGlobalAdminExists(ctx); err != nil {
+ slog.ErrorContext(ctx, "RBAC global admin guard failed", "error", err)
+ }
+}
+
func startEdgeTunnelClientIfConfigured(appCtx context.Context, cfg *config.Config, router http.Handler) {
managerEndpointConfigured := cfg.ManagerApiUrl != ""
if !cfg.EdgeAgent || !managerEndpointConfigured || cfg.AgentToken == "" {
@@ -501,6 +533,17 @@ func normalizeTunnelGRPCRequestPathInternal(r *http.Request) *http.Request {
}
connectMethodPath := tunnelpb.TunnelService_Connect_FullMethodName
+
+ const tunnelConnectPath = "/api/tunnel/connect"
+ if strings.HasSuffix(r.URL.Path, tunnelConnectPath) {
+ clone := r.Clone(r.Context())
+ cloneURL := *clone.URL
+ cloneURL.Path = connectMethodPath
+ clone.URL = &cloneURL
+ clone.RequestURI = connectMethodPath
+ return clone
+ }
+
idx := strings.Index(r.URL.Path, connectMethodPath)
if idx <= 0 {
return r
diff --git a/backend/internal/bootstrap/bootstrap_test.go b/backend/internal/bootstrap/bootstrap_test.go
index d92f19a88..330aac4fd 100644
--- a/backend/internal/bootstrap/bootstrap_test.go
+++ b/backend/internal/bootstrap/bootstrap_test.go
@@ -51,6 +51,28 @@ func TestNormalizeTunnelGRPCRequestPathInternal(t *testing.T) {
assert.Equal(t, fullMethodPath, normalized.URL.Path)
assert.Equal(t, fullMethodPath, normalized.RequestURI)
})
+
+ t.Run("legacy /api/tunnel/connect is rewritten to gRPC method", func(t *testing.T) {
+ // Regression: PR #2722 removed this branch, breaking the edge agent's
+ // gRPC transport. The agent client uses /api/tunnel/connect as its
+ // gRPC method path so reverse proxies can route tunnel traffic with
+ // a stable URL instead of the proto-generated gRPC service name.
+ req := httptest.NewRequest("POST", "/api/tunnel/connect", nil)
+ normalized := normalizeTunnelGRPCRequestPathInternal(req)
+
+ assert.NotSame(t, req, normalized)
+ assert.Equal(t, fullMethodPath, normalized.URL.Path)
+ assert.Equal(t, fullMethodPath, normalized.RequestURI)
+ })
+
+ t.Run("nested proxy with legacy /api/tunnel/connect is rewritten", func(t *testing.T) {
+ req := httptest.NewRequest("POST", "/edge/proxy/api/tunnel/connect", nil)
+ normalized := normalizeTunnelGRPCRequestPathInternal(req)
+
+ assert.NotSame(t, req, normalized)
+ assert.Equal(t, fullMethodPath, normalized.URL.Path)
+ assert.Equal(t, fullMethodPath, normalized.RequestURI)
+ })
}
func TestIsTunnelGRPCRequestInternal(t *testing.T) {
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index 265fbfdfc..460310e4c 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -41,6 +41,9 @@ var loggerSkipPatterns = []string{
"GET /api/fonts/mono",
"GET /api/health",
"HEAD /api/health",
+ // Static branding / PWA assets — browsers re-request these frequently
+ // and the logs add no signal.
+ "GET /api/app-images/*",
}
func shouldLogRequestInternal(c echo.Context) bool {
@@ -143,7 +146,8 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)
authMiddleware := middleware.NewAuthMiddleware(appServices.Auth, cfg).
WithApiKeyValidator(appServices.ApiKey).
- WithEnvironmentAccessTokenResolver(appServices.Environment)
+ WithEnvironmentAccessTokenResolver(appServices.Environment).
+ WithPermissionResolver(appServices.Role)
e.Use(middleware.NewCORSMiddleware(cfg).Add())
apiGroup := e.Group("/api")
@@ -217,6 +221,7 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)
Webhook: appServices.Webhook,
Vulnerability: appServices.Vulnerability,
Dashboard: appServices.Dashboard,
+ Role: appServices.Role,
Config: cfg,
}
diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.go
index ea8c2400b..18a18cb78 100644
--- a/backend/internal/bootstrap/services_bootstrap.go
+++ b/backend/internal/bootstrap/services_bootstrap.go
@@ -49,6 +49,7 @@ type Services struct {
Font *services.FontService
Vulnerability *services.VulnerabilityService
Dashboard *services.DashboardService
+ Role *services.RoleService
}
func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config, httpClient *http.Client) (svcs *Services, dockerSrvice *services.DockerClientService, err error) {
@@ -67,9 +68,10 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config
svcs.Font = services.NewFontService(resources.FS)
dockerClient := services.NewDockerClientService(ctx, db, cfg, svcs.Settings)
svcs.Docker = dockerClient
- svcs.User = services.NewUserService(db)
+ svcs.Role = services.NewRoleService(db)
+ svcs.User = services.NewUserService(db).WithRoleService(svcs.Role)
svcs.Session = services.NewSessionService(db)
- svcs.ApiKey = services.NewApiKeyService(db, svcs.User)
+ svcs.ApiKey = services.NewApiKeyService(db, svcs.User).WithRoleService(svcs.Role)
svcs.ContainerRegistry = services.NewContainerRegistryService(db, func(ctx context.Context) (services.RegistryDaemonClient, error) {
return dockerClient.GetClient(ctx)
}, svcs.KV)
@@ -100,7 +102,7 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config
svcs.Port = services.NewPortService(svcs.Docker)
svcs.Swarm = services.NewSwarmService(svcs.Docker, svcs.Settings, svcs.KV, svcs.ContainerRegistry, svcs.Environment)
svcs.Template = services.NewTemplateService(ctx, db, httpClient, svcs.Settings)
- svcs.Auth = services.NewAuthService(svcs.User, svcs.Settings, svcs.Event, svcs.Session, cfg.JWTSecret, cfg)
+ svcs.Auth = services.NewAuthService(svcs.User, svcs.Settings, svcs.Event, svcs.Session, svcs.Role, cfg.JWTSecret, cfg)
svcs.Oidc = services.NewOidcService(svcs.Auth, svcs.Settings, cfg, httpClient)
svcs.System = services.NewSystemService(db, svcs.Docker, svcs.Container, svcs.Image, svcs.Volume, svcs.Network, svcs.Settings)
svcs.SystemUpgrade = services.NewSystemUpgradeService(svcs.Docker, svcs.Version, svcs.Event, svcs.Settings)
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index 8948b037c..f3d504a61 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -1702,3 +1702,119 @@ func (e *BuildKitDockerExporterError) Error() string {
}
func (e *BuildKitDockerExporterError) Unwrap() error { return e.Err }
+
+// ----- RBAC / role service errors -----
+
+type RoleNotFoundError struct{}
+
+func (e *RoleNotFoundError) Error() string {
+ return "Role not found"
+}
+
+func IsRoleNotFoundError(err error) bool {
+ return isErrorTypeInternal[*RoleNotFoundError](err)
+}
+
+type RoleBuiltInError struct{}
+
+func (e *RoleBuiltInError) Error() string {
+ return "Built-in role cannot be modified"
+}
+
+func IsRoleBuiltInError(err error) bool {
+ return isErrorTypeInternal[*RoleBuiltInError](err)
+}
+
+type RoleNameTakenError struct{}
+
+func (e *RoleNameTakenError) Error() string {
+ return "Role name already in use"
+}
+
+func IsRoleNameTakenError(err error) bool {
+ return isErrorTypeInternal[*RoleNameTakenError](err)
+}
+
+type UnknownPermissionError struct {
+ Perm string
+}
+
+func (e *UnknownPermissionError) Error() string {
+ return fmt.Sprintf("Unknown permission: %s", e.Perm)
+}
+
+func IsUnknownPermissionError(err error) bool {
+ return isErrorTypeInternal[*UnknownPermissionError](err)
+}
+
+// RolePermissionEscalationError is returned when a caller attempts to author a
+// role containing a permission they do not themselves hold at global scope.
+// Used by the CreateRole and UpdateRole handlers as defense-in-depth alongside
+// the RequireGlobalAdmin middleware.
+type RolePermissionEscalationError struct {
+ Perm string
+}
+
+func (e *RolePermissionEscalationError) Error() string {
+ return fmt.Sprintf("cannot grant a permission you do not hold: %s", e.Perm)
+}
+
+func IsRolePermissionEscalationError(err error) bool {
+ return isErrorTypeInternal[*RolePermissionEscalationError](err)
+}
+
+// InvalidRoleAssignmentError is returned when SetUserAssignments is called with
+// a RoleID or EnvironmentID that doesn't exist in the database. Surfaces as a
+// 400 Bad Request so callers see a descriptive message instead of an opaque
+// FK-violation 500 from the underlying tx.Create.
+type InvalidRoleAssignmentError struct {
+ RoleID string
+ EnvironmentID string
+}
+
+func (e *InvalidRoleAssignmentError) Error() string {
+ if e.RoleID != "" {
+ return fmt.Sprintf("invalid role assignment: role %q does not exist", e.RoleID)
+ }
+ if e.EnvironmentID != "" {
+ return fmt.Sprintf("invalid role assignment: environment %q does not exist", e.EnvironmentID)
+ }
+ return "invalid role assignment"
+}
+
+func IsInvalidRoleAssignmentError(err error) bool {
+ return isErrorTypeInternal[*InvalidRoleAssignmentError](err)
+}
+
+type OidcMappingNotFoundError struct{}
+
+func (e *OidcMappingNotFoundError) Error() string {
+ return "OIDC role mapping not found"
+}
+
+func IsOidcMappingNotFoundError(err error) bool {
+ return isErrorTypeInternal[*OidcMappingNotFoundError](err)
+}
+
+// OidcMappingEnvManagedError is returned when an API caller attempts to mutate
+// an OIDC role mapping that was declared via OIDC_ROLE_MAPPINGS. Env-managed
+// rows can only be changed by editing the env var and restarting.
+type OidcMappingEnvManagedError struct{}
+
+func (e *OidcMappingEnvManagedError) Error() string {
+ return "OIDC role mapping is managed by OIDC_ROLE_MAPPINGS and cannot be edited at runtime"
+}
+
+func IsOidcMappingEnvManagedError(err error) bool {
+ return isErrorTypeInternal[*OidcMappingEnvManagedError](err)
+}
+
+type NoGlobalAdminRemainsError struct{}
+
+func (e *NoGlobalAdminRemainsError) Error() string {
+ return "At least one user must retain a global Admin role assignment"
+}
+
+func IsNoGlobalAdminRemainsError(err error) bool {
+ return isErrorTypeInternal[*NoGlobalAdminRemainsError](err)
+}
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index 4893dc7a9..11875a702 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -47,13 +47,17 @@ type Config struct {
OidcClientSecret string `env:"OIDC_CLIENT_SECRET" default:"" options:"file"`
OidcIssuerURL string `env:"OIDC_ISSUER_URL" default:""`
OidcScopes string `env:"OIDC_SCOPES" default:"openid email profile"`
- OidcAdminClaim string `env:"OIDC_ADMIN_CLAIM" default:""`
- OidcAdminValue string `env:"OIDC_ADMIN_VALUE" default:""`
+ OidcGroupsClaim string `env:"OIDC_GROUPS_CLAIM" default:"groups"`
OidcSkipTlsVerify bool `env:"OIDC_SKIP_TLS_VERIFY" default:"false"`
OidcAutoRedirectToProvider bool `env:"OIDC_AUTO_REDIRECT_TO_PROVIDER" default:"false"`
OidcProviderName string `env:"OIDC_PROVIDER_NAME" default:""`
OidcProviderLogoUrl string `env:"OIDC_PROVIDER_LOGO_URL" default:""`
OidcMobileRedirectUris string `env:"OIDC_MOBILE_REDIRECT_URIS" default:"arcane-mobile://oidc-callback"`
+ // OidcRoleMappings declaratively defines OIDC group→role mappings as a
+ // JSON array of role.OidcRoleMappingSpec. Reconciled into source='env'
+ // rows on every boot; rows are read-only at runtime. Supports *_FILE for
+ // Docker secrets. Leave empty to manage mappings purely via the UI/API.
+ OidcRoleMappings string `env:"OIDC_ROLE_MAPPINGS" default:"" options:"file"`
PUID string `env:"PUID" default:""`
PGID string `env:"PGID" default:""`
diff --git a/backend/internal/configschema/schema_test.go b/backend/internal/configschema/schema_test.go
index d45cbedee..b5b2188b3 100644
--- a/backend/internal/configschema/schema_test.go
+++ b/backend/internal/configschema/schema_test.go
@@ -230,16 +230,16 @@ var expectedEnvConfigVars = []string{
"LOG_JSON",
"LOG_LEVEL",
"MANAGER_API_URL",
- "OIDC_ADMIN_CLAIM",
- "OIDC_ADMIN_VALUE",
"OIDC_AUTO_REDIRECT_TO_PROVIDER",
"OIDC_CLIENT_ID",
"OIDC_CLIENT_SECRET",
"OIDC_ENABLED",
+ "OIDC_GROUPS_CLAIM",
"OIDC_ISSUER_URL",
"OIDC_MOBILE_REDIRECT_URIS",
"OIDC_PROVIDER_LOGO_URL",
"OIDC_PROVIDER_NAME",
+ "OIDC_ROLE_MAPPINGS",
"OIDC_SCOPES",
"OIDC_SKIP_TLS_VERIFY",
"PGID",
@@ -304,14 +304,13 @@ var expectedSettingOverrideKeys = []string{
"maxImageUploadSize",
"mobileNavigationMode",
"mobileNavigationShowLabels",
- "oidcAdminClaim",
- "oidcAdminValue",
"oidcAuthorizationEndpoint",
"oidcAutoRedirectToProvider",
"oidcClientId",
"oidcClientSecret",
"oidcDeviceAuthorizationEndpoint",
"oidcEnabled",
+ "oidcGroupsClaim",
"oidcIssuerUrl",
"oidcJwksEndpoint",
"oidcMergeAccounts",
diff --git a/backend/internal/middleware/auth_middleware.go b/backend/internal/middleware/auth_middleware.go
index fba051dbd..c1bdc6092 100644
--- a/backend/internal/middleware/auth_middleware.go
+++ b/backend/internal/middleware/auth_middleware.go
@@ -11,28 +11,47 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
pkgutils "github.com/getarcaneapp/arcane/backend/pkg/utils"
"github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"
"github.com/labstack/echo/v4"
)
+// Echo context keys, kept aligned with api/middleware/auth.go constants so
+// shared handlers can read them regardless of which auth layer attached them.
+const (
+ echoCtxKeyUserID = "userID"
+ echoCtxKeyCurrentUser = "currentUser"
+ echoCtxKeyUserPermissions = "userPermissions"
+ echoCtxKeyAuthMethod = "authMethod"
+ echoCtxKeySessionID = "currentSessionID"
+)
+
type AuthOptions struct {
AdminRequired bool
SuccessOptional bool
}
type ApiKeyValidator interface {
- ValidateApiKey(ctx context.Context, rawKey string) (*models.User, error)
+ ValidateApiKeyWithID(ctx context.Context, rawKey string) (*models.User, string, error)
}
type EnvironmentAccessTokenResolver interface {
ResolveEnvironmentByAccessToken(ctx context.Context, token string) (*models.Environment, error)
}
+// PermissionResolver resolves a caller's effective permission set. Implemented
+// by services.RoleService; kept as an interface so tests can stub it.
+type PermissionResolver interface {
+ ResolvePermissions(ctx context.Context, user *models.User) (*authz.PermissionSet, error)
+ ResolveApiKeyPermissions(ctx context.Context, apiKeyID string) (*authz.PermissionSet, error)
+}
+
type AuthMiddleware struct {
authService *services.AuthService
apiKeyValidator ApiKeyValidator
envTokenResolver EnvironmentAccessTokenResolver
+ roleResolver PermissionResolver
cfg *config.Config
options AuthOptions
}
@@ -57,6 +76,12 @@ func (m *AuthMiddleware) WithEnvironmentAccessTokenResolver(resolver Environment
return &clone
}
+func (m *AuthMiddleware) WithPermissionResolver(resolver PermissionResolver) *AuthMiddleware {
+ clone := *m
+ clone.roleResolver = resolver
+ return &clone
+}
+
func (m *AuthMiddleware) WithAdminNotRequired() *AuthMiddleware {
clone := *m
clone.options.AdminRequired = false
@@ -69,6 +94,30 @@ func (m *AuthMiddleware) WithAdminRequired() *AuthMiddleware {
return &clone
}
+// RequirePermission returns an Echo middleware that rejects callers lacking
+// `perm` for the environment ID in the request path (or globally for org-level
+// permissions). Use on streaming/WS routes that aren't served by Huma. Expects
+// the caller's PermissionSet to already be on the Echo context via the
+// AuthMiddleware (i.e., chain it AFTER auth).
+func RequirePermission(perm string) echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ ps, _ := c.Get(echoCtxKeyUserPermissions).(*authz.PermissionSet)
+ envID := ""
+ if authz.IsEnvScoped(perm) {
+ envID = authz.EnvIDFromPath(c.Request().URL.Path)
+ }
+ if !ps.Allows(perm, envID) {
+ return c.JSON(http.StatusForbidden, models.APIError{
+ Code: "FORBIDDEN",
+ Message: "permission denied: " + perm,
+ })
+ }
+ return next(c)
+ }
+ }
+}
+
func (m *AuthMiddleware) Add() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
@@ -130,19 +179,19 @@ func (m *AuthMiddleware) managerAuth(ctx context.Context, c echo.Context, next e
// First, check for API key in X-API-Key header
if apiKey := req.Header.Get(pkgutils.HeaderApiKey); apiKey != "" {
if m.apiKeyValidator != nil {
- user, err := m.apiKeyValidator.ValidateApiKey(ctx, apiKey)
+ user, keyID, err := m.apiKeyValidator.ValidateApiKeyWithID(ctx, apiKey)
if err == nil && user != nil {
- isAdmin := pkgutils.UserHasRole(user.Roles, "admin")
- if m.options.AdminRequired && !isAdmin {
+ ps := m.resolveApiKeyPermissionsOrDeny(ctx, keyID)
+ if m.options.AdminRequired && !ps.IsGlobalAdmin() {
return c.JSON(http.StatusForbidden, models.APIError{
Code: "FORBIDDEN",
Message: "You don't have permission to access this resource",
})
}
- c.Set("userID", user.ID)
- c.Set("currentUser", user)
- c.Set("userIsAdmin", isAdmin)
- c.Set("authMethod", "api_key")
+ c.Set(echoCtxKeyUserID, user.ID)
+ c.Set(echoCtxKeyCurrentUser, user)
+ c.Set(echoCtxKeyUserPermissions, ps)
+ c.Set(echoCtxKeyAuthMethod, "api_key")
return next(c)
}
}
@@ -186,21 +235,51 @@ func (m *AuthMiddleware) managerAuth(ctx context.Context, c echo.Context, next e
})
}
- isAdmin := pkgutils.UserHasRole(user.Roles, "admin")
- if m.options.AdminRequired && !isAdmin {
+ ps := m.resolvePermissionsOrDeny(ctx, user)
+ if m.options.AdminRequired && !ps.IsGlobalAdmin() {
return c.JSON(http.StatusForbidden, models.APIError{
Code: "FORBIDDEN",
Message: "You don't have permission to access this resource",
})
}
- c.Set("userID", user.ID)
- c.Set("currentUser", user)
- c.Set("currentSessionID", sessionID)
- c.Set("userIsAdmin", isAdmin)
+ c.Set(echoCtxKeyUserID, user.ID)
+ c.Set(echoCtxKeyCurrentUser, user)
+ c.Set(echoCtxKeySessionID, sessionID)
+ c.Set(echoCtxKeyUserPermissions, ps)
return next(c)
}
+// resolvePermissionsOrDeny returns the user's permission set, or an empty
+// (deny-all) set if the resolver is unavailable or fails. Resolver failures
+// are logged.
+func (m *AuthMiddleware) resolvePermissionsOrDeny(ctx context.Context, user *models.User) *authz.PermissionSet {
+ if m.roleResolver == nil || user == nil {
+ return authz.NewPermissionSet()
+ }
+ ps, err := m.roleResolver.ResolvePermissions(ctx, user)
+ if err != nil || ps == nil {
+ slog.WarnContext(ctx, "failed to resolve user permissions for Echo auth", "error", err)
+ return authz.NewPermissionSet()
+ }
+ return ps
+}
+
+// resolveApiKeyPermissionsOrDeny returns the API key's per-key PermissionSet,
+// or an empty (deny-all) set on failure. Falling back to the owner's role
+// permissions would defeat per-key scoping, so failures are explicitly denied.
+func (m *AuthMiddleware) resolveApiKeyPermissionsOrDeny(ctx context.Context, apiKeyID string) *authz.PermissionSet {
+ if m.roleResolver == nil || apiKeyID == "" {
+ return authz.NewPermissionSet()
+ }
+ ps, err := m.roleResolver.ResolveApiKeyPermissions(ctx, apiKeyID)
+ if err != nil || ps == nil {
+ slog.WarnContext(ctx, "failed to resolve api key permissions for Echo auth", "error", err)
+ return authz.NewPermissionSet()
+ }
+ return ps
+}
+
func (m *AuthMiddleware) resolveEnvironmentAccessToken(ctx context.Context, token string) (*models.Environment, bool) {
if m.envTokenResolver == nil {
return nil, false
@@ -223,24 +302,22 @@ func agentSudoInternal(c echo.Context) {
BaseModel: models.BaseModel{ID: "agent"},
Email: new("[email protected]"),
Username: "agent",
- Roles: []string{"admin"},
}
- c.Set("userID", agentUser.ID)
- c.Set("currentUser", agentUser)
- c.Set("userIsAdmin", true)
- c.Set("authMethod", "agent_token")
+ c.Set(echoCtxKeyUserID, agentUser.ID)
+ c.Set(echoCtxKeyCurrentUser, agentUser)
+ c.Set(echoCtxKeyUserPermissions, authz.SudoPermissionSet())
+ c.Set(echoCtxKeyAuthMethod, "agent_token")
}
func environmentSudoInternal(c echo.Context, env *models.Environment) {
envUser := &models.User{
BaseModel: models.BaseModel{ID: "environment:" + env.ID},
Username: env.Name,
- Roles: []string{"admin"},
}
- c.Set("userID", envUser.ID)
- c.Set("currentUser", envUser)
- c.Set("userIsAdmin", true)
- c.Set("authMethod", "environment_access_token")
+ c.Set(echoCtxKeyUserID, envUser.ID)
+ c.Set(echoCtxKeyCurrentUser, envUser)
+ c.Set(echoCtxKeyUserPermissions, authz.SudoPermissionSet())
+ c.Set(echoCtxKeyAuthMethod, "environment_access_token")
}
func extractBearerOrCookieTokenInternal(c echo.Context) string {
diff --git a/backend/internal/models/rbac.go b/backend/internal/models/rbac.go
new file mode 100644
index 000000000..5be9a7161
--- /dev/null
+++ b/backend/internal/models/rbac.go
@@ -0,0 +1,72 @@
+package models
+
+// Role is a named permission set. Built-in roles (Admin, Editor, Deployer,
+// Viewer) are seeded by migration 054 and cannot be edited or deleted.
+type Role struct {
+ Name string `json:"name" gorm:"column:name;not null;uniqueIndex" sortable:"true"`
+ Description *string `json:"description,omitempty" gorm:"column:description"`
+ Permissions StringSlice `json:"permissions" gorm:"column:permissions;type:text;not null"`
+ BuiltIn bool `json:"builtIn" gorm:"column:built_in;not null;default:false" sortable:"true"`
+ BaseModel
+}
+
+func (Role) TableName() string { return "roles" }
+
+// UserRoleAssignment binds a user to a role, optionally scoped to one
+// environment. EnvironmentID == nil means "global" — the role's permissions
+// apply across all environments AND to org-level resources.
+//
+// Source distinguishes manual assignments (managed by admins via the UI) from
+// assignments synthesized from OIDC group mappings on every login.
+type UserRoleAssignment struct {
+ UserID string `json:"userId" gorm:"column:user_id;not null;index"`
+ RoleID string `json:"roleId" gorm:"column:role_id;not null;index"`
+ EnvironmentID *string `json:"environmentId,omitempty" gorm:"column:environment_id;index"`
+ Source string `json:"source" gorm:"column:source;not null;default:'manual'"`
+ BaseModel
+}
+
+func (UserRoleAssignment) TableName() string { return "user_role_assignments" }
+
+// Assignment source values stored in UserRoleAssignment.Source.
+const (
+ RoleAssignmentSourceManual = "manual"
+ RoleAssignmentSourceOidc = "oidc"
+)
+
+// ApiKeyPermission is one permission grant on an API key, optionally scoped to
+// a single environment. Permissions are stored per-row (rather than as a JSON
+// column on api_keys) so we can index by (api_key_id, permission) for fast
+// lookups in the auth bridge.
+type ApiKeyPermission struct {
+ ApiKeyID string `json:"apiKeyId" gorm:"column:api_key_id;not null;index"`
+ Permission string `json:"permission" gorm:"column:permission;not null"`
+ EnvironmentID *string `json:"environmentId,omitempty" gorm:"column:environment_id"`
+ BaseModel
+}
+
+func (ApiKeyPermission) TableName() string { return "api_key_permissions" }
+
+// OidcRoleMapping maps an OIDC group/claim value to a role assignment. On
+// every OIDC login, the auth service replaces all source='oidc' rows on the
+// user with assignments derived from the mappings whose ClaimValue matches a
+// claim returned by the IdP.
+//
+// Source distinguishes UI/API-managed rows (the default) from env-declared
+// rows reconciled at boot from OIDC_ROLE_MAPPINGS. Env-managed rows are
+// read-only via the API — they can only be changed by editing the env var
+// and restarting.
+type OidcRoleMapping struct {
+ ClaimValue string `json:"claimValue" gorm:"column:claim_value;not null;index"`
+ RoleID string `json:"roleId" gorm:"column:role_id;not null;index"`
+ EnvironmentID *string `json:"environmentId,omitempty" gorm:"column:environment_id"`
+ Source string `json:"source" gorm:"column:source;not null;default:'manual'"`
+ BaseModel
+}
+
+func (OidcRoleMapping) TableName() string { return "oidc_role_mappings" }
+
+const (
+ OidcMappingSourceManual = "manual"
+ OidcMappingSourceEnv = "env"
+)
diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.go
index fdd227896..04ba32060 100644
--- a/backend/internal/models/settings.go
+++ b/backend/internal/models/settings.go
@@ -73,7 +73,7 @@ type Settings struct {
SwarmStackSourcesDirectory SettingVariable `key:"swarmStackSourcesDirectory,envOverride" meta:"label=Swarm Stack Sources Directory;type=text;keywords=swarm,stacks,stack,source,sources,directory,path,folder,location,storage,compose,env;category=internal;description=Configure where swarm stack source files are stored"`
DiskUsagePath SettingVariable `key:"diskUsagePath" meta:"label=Disk Usage Path;type=text;keywords=disk,usage,path,storage,folder,files;category=general;description=Path used for disk usage calculations"`
BaseServerURL SettingVariable `key:"baseServerUrl" meta:"label=Base Server URL;type=text;keywords=base,url,server,domain,host,endpoint,address,link;category=general;description=Set the base URL for the application"`
- EnableGravatar SettingVariable `key:"enableGravatar" meta:"label=Enable Gravatar;type=boolean;keywords=gravatar,avatar,profile,picture,image,user,photo;category=general;description=Enable Gravatar profile pictures for users"`
+ EnableGravatar SettingVariable `key:"enableGravatar,authrequired" meta:"label=Enable Gravatar;type=boolean;keywords=gravatar,avatar,profile,picture,image,user,photo;category=general;description=Enable Gravatar profile pictures for users"`
DefaultShell SettingVariable `key:"defaultShell" meta:"label=Default Shell;type=text;keywords=shell,default,shellpath,path,login;category=general;description=Default shell to use for commands"`
EnvironmentHealthInterval SettingVariable `key:"environmentHealthInterval" meta:"label=Environment Health Check Interval;type=cron;keywords=environment,health,check,interval,frequency,heartbeat,status,monitoring,uptime,jobs,schedule;description=How often to check environment connectivity (cron expression)" catmeta:"id=jobschedule;title=Job Schedule;icon=jobs;url=/settings/jobs;description=Configure how often Arcane background jobs run"`
ApplicationTheme SettingVariable `key:"applicationTheme,public,local" meta:"label=Application Theme;type=select;keywords=theme,appearance,style,visual,palette,background,interface,ui;category=appearance;description=Choose the overall visual theme for the application"`
@@ -147,8 +147,7 @@ type Settings struct {
OidcJwksEndpoint SettingVariable `key:"oidcJwksEndpoint,envOverride" meta:"label=OIDC JWKS Endpoint;type=text;keywords=oidc,jwks,keys,endpoint,oauth,openid;category=authentication;description=Override OIDC JWKS endpoint"`
OidcDeviceAuthorizationEndpoint SettingVariable `key:"oidcDeviceAuthorizationEndpoint,envOverride" meta:"label=OIDC Device Authorization Endpoint;type=text;keywords=oidc,device,authorization,endpoint,oauth,openid,cli;category=authentication;description=Override OIDC device authorization endpoint for CLI authentication"`
OidcScopes SettingVariable `key:"oidcScopes,authrequired,envOverride" meta:"label=OIDC Scopes;type=text;keywords=oidc,scopes,oauth,openid,permissions;category=authentication;description=OIDC scopes to request"`
- OidcAdminClaim SettingVariable `key:"oidcAdminClaim,authrequired,envOverride" meta:"label=OIDC Admin Claim;type=text;keywords=oidc,admin,claim,role,group;category=authentication;description=Claim name for admin role mapping"`
- OidcAdminValue SettingVariable `key:"oidcAdminValue,authrequired,envOverride" meta:"label=OIDC Admin Value;type=text;keywords=oidc,admin,value,role,group;category=authentication;description=Claim value that grants admin access"`
+ OidcGroupsClaim SettingVariable `key:"oidcGroupsClaim,authrequired,envOverride" meta:"label=OIDC Groups Claim;type=text;keywords=oidc,groups,claim,role,mapping,rbac;category=authentication;description=Claim name to read group memberships from for role mapping (default: groups)"`
OidcSkipTlsVerify SettingVariable `key:"oidcSkipTlsVerify,authrequired,envOverride" meta:"label=OIDC Skip TLS Verify;type=boolean;keywords=oidc,tls,verify,skip,insecure;category=authentication;description=Skip TLS verification for OIDC provider"`
OidcAutoRedirectToProvider SettingVariable `key:"oidcAutoRedirectToProvider,public,envOverride" meta:"label=OIDC Auto Redirect;type=boolean;keywords=oidc,auto,redirect,automatic,login,provider,sso;category=authentication;description=Automatically redirect to OIDC provider on login page"`
OidcMergeAccounts SettingVariable `key:"oidcMergeAccounts,authrequired,envOverride" meta:"label=OIDC Account Merging;type=boolean;keywords=oidc,merge,link,accounts,email,match,existing,users,combine;category=authentication;description=Allow OIDC logins to merge with existing accounts by email"`
@@ -371,13 +370,10 @@ type OidcConfig struct {
JwksURI string `json:"jwksUri,omitempty"`
DeviceAuthorizationEndpoint string `json:"deviceAuthorizationEndpoint,omitempty"`
- // Admin mapping: evaluate this claim to grant admin.
- // Examples:
- // - adminClaim: "admin", adminValue: "true" (boolean or string "true")
- // - adminClaim: "roles", adminValue: "admin" (array membership)
- // - adminClaim: "realm_access.roles", adminValue: "admin" (Keycloak)
- AdminClaim string `json:"adminClaim,omitempty"`
- AdminValue string `json:"adminValue,omitempty"`
+ // GroupsClaim is the claim path Arcane reads group memberships from on
+ // every OIDC login. Matched against oidc_role_mappings to produce role
+ // assignments. Default: "groups".
+ GroupsClaim string `json:"groupsClaim,omitempty"`
SkipTlsVerify bool `json:"skipTlsVerify"`
}
diff --git a/backend/internal/models/settings_test.go b/backend/internal/models/settings_test.go
index 97e214ae2..81bdd2ee2 100644
--- a/backend/internal/models/settings_test.go
+++ b/backend/internal/models/settings_test.go
@@ -20,8 +20,7 @@ func TestSettings_ToSettingVariableSlice_Visibility(t *testing.T) {
OidcClientId: SettingVariable{Value: "client-id"},
OidcIssuerUrl: SettingVariable{Value: "https://issuer.example"},
OidcScopes: SettingVariable{Value: "openid email profile"},
- OidcAdminClaim: SettingVariable{Value: "groups"},
- OidcAdminValue: SettingVariable{Value: "_arcane_admins"},
+ OidcGroupsClaim: SettingVariable{Value: "groups"},
OidcSkipTlsVerify: SettingVariable{Value: "false"},
OidcMergeAccounts: SettingVariable{Value: "true"},
MobileNavigationMode: SettingVariable{Value: "floating"},
@@ -48,13 +47,12 @@ func TestSettings_ToSettingVariableSlice_Visibility(t *testing.T) {
require.Contains(t, nonAdminKeys, "oidcClientId")
require.Contains(t, nonAdminKeys, "oidcIssuerUrl")
require.Contains(t, nonAdminKeys, "oidcScopes")
- require.Contains(t, nonAdminKeys, "oidcAdminClaim")
- require.Contains(t, nonAdminKeys, "oidcAdminValue")
+ require.Contains(t, nonAdminKeys, "oidcGroupsClaim")
require.Contains(t, nonAdminKeys, "oidcSkipTlsVerify")
require.Contains(t, nonAdminKeys, "oidcMergeAccounts")
require.Contains(t, nonAdminKeys, "mobileNavigationMode")
require.Contains(t, nonAdminKeys, "keyboardShortcutsEnabled")
- require.NotContains(t, nonAdminKeys, "enableGravatar")
+ require.Contains(t, nonAdminKeys, "enableGravatar")
require.NotContains(t, nonAdminKeys, "baseServerUrl")
require.NotContains(t, nonAdminKeys, "defaultShell")
require.NotContains(t, nonAdminKeys, "oidcClientSecret")
diff --git a/backend/internal/models/user.go b/backend/internal/models/user.go
index a7558b696..2669f53b9 100644
--- a/backend/internal/models/user.go
+++ b/backend/internal/models/user.go
@@ -5,15 +5,14 @@ import (
)
type User struct {
- Username string `json:"username" sortable:"true"`
- PasswordHash string `json:"-" gorm:"column:password_hash"`
- DisplayName *string `json:"displayName,omitempty" gorm:"column:display_name" sortable:"true"`
- Email *string `json:"email,omitempty" sortable:"true"`
- Roles StringSlice `json:"roles" gorm:"type:text"`
- OidcSubjectId *string `json:"oidcSubjectId,omitempty" gorm:"column:oidc_subject_id"`
- LastLogin *time.Time `json:"lastLogin,omitempty" gorm:"column:last_login" sortable:"true"`
- Locale *string `json:"locale,omitempty" gorm:"column:locale"`
- RequiresPasswordChange bool `json:"requiresPasswordChange" gorm:"column:requires_password_change"`
+ Username string `json:"username" sortable:"true"`
+ PasswordHash string `json:"-" gorm:"column:password_hash"`
+ DisplayName *string `json:"displayName,omitempty" gorm:"column:display_name" sortable:"true"`
+ Email *string `json:"email,omitempty" sortable:"true"`
+ OidcSubjectId *string `json:"oidcSubjectId,omitempty" gorm:"column:oidc_subject_id"`
+ LastLogin *time.Time `json:"lastLogin,omitempty" gorm:"column:last_login" sortable:"true"`
+ Locale *string `json:"locale,omitempty" gorm:"column:locale"`
+ RequiresPasswordChange bool `json:"requiresPasswordChange" gorm:"column:requires_password_change"`
// OIDC provider tokens
OidcAccessToken *string `json:"-" gorm:"type:text"`
diff --git a/backend/internal/services/api_key_service.go b/backend/internal/services/api_key_service.go
index 6f655c26a..183d5977d 100644
--- a/backend/internal/services/api_key_service.go
+++ b/backend/internal/services/api_key_service.go
@@ -12,7 +12,9 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils/dbutil"
"github.com/getarcaneapp/arcane/types/apikey"
"gorm.io/gorm"
)
@@ -42,6 +44,7 @@ var defaultAdminAPIKeyDescription = func() *string {
type ApiKeyService struct {
db *database.DB
userService *UserService
+ roleService *RoleService
argon2Params *Argon2Params
}
@@ -53,6 +56,16 @@ func NewApiKeyService(db *database.DB, userService *UserService) *ApiKeyService
}
}
+// WithRoleService wires the RoleService dependency. Separated from the
+// constructor to break the bootstrap-ordering cycle between ApiKeyService and
+// RoleService (RoleService.BackfillApiKeyPermissions needs ApiKeyService to
+// exist when it runs, while permission-validated CreateApiKey needs the
+// RoleService).
+func (s *ApiKeyService) WithRoleService(roleService *RoleService) *ApiKeyService {
+ s.roleService = roleService
+ return s
+}
+
func (s *ApiKeyService) generateApiKey() (string, error) {
bytes := make([]byte, apiKeyLength)
if _, err := rand.Read(bytes); err != nil {
@@ -100,12 +113,72 @@ func (s *ApiKeyService) markApiKeyUsedAsync(ctx context.Context, keyID string) {
}
func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, req apikey.CreateApiKey) (*apikey.ApiKeyCreatedDto, error) {
+ if err := s.validateGrantsAgainstUserInternal(ctx, userID, req.Permissions); err != nil {
+ return nil, err
+ }
rawKey, err := s.generateApiKey()
if err != nil {
return nil, err
}
- return s.createAPIKeyWithRawKey(ctx, &userID, rawKey, req, nil, nil)
+ created, err := s.createAPIKeyWithRawKey(ctx, &userID, rawKey, req, nil, nil)
+ if err != nil {
+ return nil, err
+ }
+ if s.roleService != nil {
+ grants := toApiKeyPermissionRowsInternal(created.ID, req.Permissions)
+ if err := s.roleService.SetApiKeyPermissions(ctx, created.ID, grants); err != nil {
+ return nil, fmt.Errorf("failed to persist api key permissions: %w", err)
+ }
+ // Re-load the just-persisted grants into the response DTO so the
+ // frontend doesn't see `"permissions": null` on a successful create.
+ created.Permissions = s.loadKeyGrantsInternal(ctx, created.ID)
+ }
+ return created, nil
+}
+
+// ErrApiKeyPermissionEscalation is returned when a caller attempts to grant an
+// API key permissions they themselves do not hold.
+var ErrApiKeyPermissionEscalation = errors.New("cannot grant a permission you do not have")
+
+// validateGrantsAgainstUserInternal refuses requests that would grant the new key
+// permissions that the requesting user doesn't hold. Sudo callers bypass this
+// (they always pass). If RoleService is unavailable validation is skipped (used
+// only in the boot-bootstrap path where no human caller exists).
+func (s *ApiKeyService) validateGrantsAgainstUserInternal(ctx context.Context, userID string, grants []apikey.PermissionGrant) error {
+ if s.roleService == nil || len(grants) == 0 {
+ return nil
+ }
+ user, err := s.userService.GetUserByID(ctx, userID)
+ if err != nil {
+ return fmt.Errorf("load user for permission validation: %w", err)
+ }
+ ps, err := s.roleService.ResolvePermissions(ctx, user)
+ if err != nil {
+ return fmt.Errorf("resolve user permissions: %w", err)
+ }
+ for _, g := range grants {
+ envID := ""
+ if g.EnvironmentID != nil {
+ envID = *g.EnvironmentID
+ }
+ if !ps.Allows(g.Permission, envID) {
+ return fmt.Errorf("%w: %s (env=%q)", ErrApiKeyPermissionEscalation, g.Permission, envID)
+ }
+ }
+ return nil
+}
+
+func toApiKeyPermissionRowsInternal(apiKeyID string, grants []apikey.PermissionGrant) []models.ApiKeyPermission {
+ out := make([]models.ApiKeyPermission, len(grants))
+ for i, g := range grants {
+ out[i] = models.ApiKeyPermission{
+ ApiKeyID: apiKeyID,
+ Permission: g.Permission,
+ EnvironmentID: g.EnvironmentID,
+ }
+ }
+ return out
}
func (s *ApiKeyService) createAPIKeyWithRawKey(
@@ -152,6 +225,17 @@ func isStaticAPIKeyInternal(ak models.ApiKey) bool {
return ak.ManagedBy != nil && *ak.ManagedBy == managedByAdminBootstrap
}
+// isEnvironmentBootstrapKeyInternal identifies the auto-generated key minted by
+// CreateEnvironmentApiKey for environment pairing. Those keys have no owner
+// (UserID == nil) and are scoped to a single environment. They carry full
+// env-scoped permissions and must never be hand-edited or deleted via the API
+// — manually clearing the grants would silently break the paired edge agent
+// the next time it tries to authenticate. Cascade-delete still applies when
+// the environment row itself is removed.
+func isEnvironmentBootstrapKeyInternal(ak models.ApiKey) bool {
+ return ak.UserID == nil && ak.EnvironmentID != nil
+}
+
func toAPIKeyDTOInternal(ak *models.ApiKey) apikey.ApiKey {
return apikey.ApiKey{
ID: ak.ID,
@@ -160,6 +244,7 @@ func toAPIKeyDTOInternal(ak *models.ApiKey) apikey.ApiKey {
KeyPrefix: ak.KeyPrefix,
UserID: ak.UserID,
IsStatic: isStaticAPIKeyInternal(*ak),
+ IsBootstrap: isEnvironmentBootstrapKeyInternal(*ak),
ExpiresAt: ak.ExpiresAt,
LastUsedAt: ak.LastUsedAt,
CreatedAt: ak.CreatedAt,
@@ -167,6 +252,14 @@ func toAPIKeyDTOInternal(ak *models.ApiKey) apikey.ApiKey {
}
}
+// toAPIKeyDTOWithPermissionsInternal is like toAPIKeyDTOInternal but
+// additionally attaches the key's persisted permission grants.
+func (s *ApiKeyService) toAPIKeyDTOWithPermissionsInternal(ctx context.Context, ak *models.ApiKey) apikey.ApiKey {
+ dto := toAPIKeyDTOInternal(ak)
+ dto.Permissions = s.loadKeyGrantsInternal(ctx, ak.ID)
+ return dto
+}
+
func (s *ApiKeyService) CreateDefaultAdminAPIKey(ctx context.Context, userID, rawKey string) (*apikey.ApiKeyCreatedDto, error) {
return s.createAPIKeyWithRawKey(ctx, &userID, rawKey, apikey.CreateApiKey{
Name: defaultAdminAPIKeyName,
@@ -316,10 +409,36 @@ func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environment
envIDShort = environmentID[:8]
}
name := fmt.Sprintf("Environment Bootstrap Key - %s", envIDShort)
- return s.createAPIKeyWithRawKey(ctx, nil, rawKey, apikey.CreateApiKey{
+ created, err := s.createAPIKeyWithRawKey(ctx, nil, rawKey, apikey.CreateApiKey{
Name: name,
Description: new("Auto-generated key for environment pairing"),
}, nil, &environmentID)
+ if err != nil {
+ return nil, err
+ }
+ // Env-bootstrap keys are infrastructure-level credentials used by the agent
+ // pairing flow; they must always carry every permission scoped to their
+ // environment. Without this seed, the per-key permission resolver returns
+ // an empty set on any request authenticated by this key and every
+ // downstream RequirePermission check fails with 403.
+ if s.roleService != nil {
+ all := authz.AllPermissions()
+ grants := make([]models.ApiKeyPermission, len(all))
+ for i, p := range all {
+ grants[i] = models.ApiKeyPermission{
+ ApiKeyID: created.ID,
+ Permission: p,
+ EnvironmentID: &environmentID,
+ }
+ }
+ if err := s.roleService.SetApiKeyPermissions(ctx, created.ID, grants); err != nil {
+ return nil, fmt.Errorf("failed to persist environment bootstrap key permissions: %w", err)
+ }
+ // Re-load grants into the response DTO so callers see the seeded
+ // permissions immediately, not null.
+ created.Permissions = s.loadKeyGrantsInternal(ctx, created.ID)
+ }
+ return created, nil
}
func (s *ApiKeyService) GetApiKey(ctx context.Context, id string) (*apikey.ApiKey, error) {
@@ -330,19 +449,8 @@ func (s *ApiKeyService) GetApiKey(ctx context.Context, id string) (*apikey.ApiKe
}
return nil, fmt.Errorf("failed to get API key: %w", err)
}
-
- return &apikey.ApiKey{
- ID: ak.ID,
- Name: ak.Name,
- Description: ak.Description,
- KeyPrefix: ak.KeyPrefix,
- UserID: ak.UserID,
- IsStatic: isStaticAPIKeyInternal(ak),
- ExpiresAt: ak.ExpiresAt,
- LastUsedAt: ak.LastUsedAt,
- CreatedAt: ak.CreatedAt,
- UpdatedAt: ak.UpdatedAt,
- }, nil
+ dto := s.toAPIKeyDTOWithPermissionsInternal(ctx, &ak)
+ return &dto, nil
}
func (s *ApiKeyService) ListApiKeys(ctx context.Context, params pagination.QueryParams) ([]apikey.ApiKey, pagination.Response, error) {
@@ -363,14 +471,17 @@ func (s *ApiKeyService) ListApiKeys(ctx context.Context, params pagination.Query
}
result := make([]apikey.ApiKey, len(apiKeys))
- for i, ak := range apiKeys {
- result[i] = toAPIKeyDTOInternal(&ak)
+ for i := range apiKeys {
+ // Include per-key permission grants so the edit form preloads with the
+ // key's actual current grants. Without this, the form starts empty and
+ // "Save" would wipe whatever grants the DB has.
+ result[i] = s.toAPIKeyDTOWithPermissionsInternal(ctx, &apiKeys[i])
}
return result, paginationResp, nil
}
-func (s *ApiKeyService) UpdateApiKey(ctx context.Context, id string, req apikey.UpdateApiKey) (*apikey.ApiKey, error) {
+func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerUserID, id string, req apikey.UpdateApiKey) (*apikey.ApiKey, error) {
var ak models.ApiKey
if err := s.db.WithContext(ctx).Where("id = ?", id).First(&ak).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -378,10 +489,24 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, id string, req apikey.
}
return nil, fmt.Errorf("failed to get API key: %w", err)
}
- if isStaticAPIKeyInternal(ak) {
+ if isStaticAPIKeyInternal(ak) || isEnvironmentBootstrapKeyInternal(ak) {
return nil, ErrApiKeyProtected
}
+ if req.Permissions != nil {
+ // Validate against the key owner's permissions, not the caller's, so a
+ // holder of apikeys:update cannot escalate another user's key beyond
+ // what that user's own roles allow. Owner-less keys (env bootstrap)
+ // fall back to the caller — static admin keys are rejected above.
+ ownerID := callerUserID
+ if ak.UserID != nil {
+ ownerID = *ak.UserID
+ }
+ if err := s.validateGrantsAgainstUserInternal(ctx, ownerID, req.Permissions); err != nil {
+ return nil, err
+ }
+ }
+
if req.Name != nil {
ak.Name = *req.Name
}
@@ -392,8 +517,23 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, id string, req apikey.
ak.ExpiresAt = req.ExpiresAt
}
- if err := s.db.WithContext(ctx).Save(&ak).Error; err != nil {
- return nil, fmt.Errorf("failed to update API key: %w", err)
+ permissionsUpdated := false
+ if err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ if err := tx.Save(&ak).Error; err != nil {
+ return fmt.Errorf("failed to update API key: %w", err)
+ }
+ if req.Permissions != nil && s.roleService != nil {
+ if err := s.roleService.setApiKeyPermissionsInternal(ctx, tx, ak.ID, toApiKeyPermissionRowsInternal(ak.ID, req.Permissions)); err != nil {
+ return fmt.Errorf("failed to update api key permissions: %w", err)
+ }
+ permissionsUpdated = true
+ }
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ if permissionsUpdated {
+ s.roleService.apiKeyCache.Delete(ak.ID)
}
return &apikey.ApiKey{
@@ -403,13 +543,37 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, id string, req apikey.
KeyPrefix: ak.KeyPrefix,
UserID: ak.UserID,
IsStatic: isStaticAPIKeyInternal(ak),
+ IsBootstrap: isEnvironmentBootstrapKeyInternal(ak),
ExpiresAt: ak.ExpiresAt,
LastUsedAt: ak.LastUsedAt,
CreatedAt: ak.CreatedAt,
UpdatedAt: ak.UpdatedAt,
+ Permissions: s.loadKeyGrantsInternal(ctx, ak.ID),
}, nil
}
+// loadKeyGrantsInternal returns the persisted permission grants for an API key.
+// Always returns a non-nil slice (possibly empty) so the JSON-marshalled DTO
+// renders as `"permissions": []` rather than `"permissions": null`, which the
+// frontend treats differently (null hides the picker, [] shows it empty).
+// DB errors are logged and yield an empty slice — the caller never sees nil.
+func (s *ApiKeyService) loadKeyGrantsInternal(ctx context.Context, apiKeyID string) []apikey.PermissionGrant {
+ empty := []apikey.PermissionGrant{}
+ if s.roleService == nil {
+ return empty
+ }
+ var rows []models.ApiKeyPermission
+ if err := s.db.WithContext(ctx).Where("api_key_id = ?", apiKeyID).Find(&rows).Error; err != nil {
+ slog.WarnContext(ctx, "failed to load api key permission grants", "api_key_id", apiKeyID, "error", err)
+ return empty
+ }
+ out := make([]apikey.PermissionGrant, len(rows))
+ for i, r := range rows {
+ out[i] = apikey.PermissionGrant{Permission: r.Permission, EnvironmentID: r.EnvironmentID}
+ }
+ return out
+}
+
func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {
var apiKey models.ApiKey
if err := s.db.WithContext(ctx).Where("id = ?", id).First(&apiKey).Error; err != nil {
@@ -418,7 +582,7 @@ func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {
}
return fmt.Errorf("failed to load API key: %w", err)
}
- if isStaticAPIKeyInternal(apiKey) {
+ if isStaticAPIKeyInternal(apiKey) || isEnvironmentBootstrapKeyInternal(apiKey) {
return ErrApiKeyProtected
}
@@ -433,39 +597,46 @@ func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {
}
func (s *ApiKeyService) ValidateApiKey(ctx context.Context, rawKey string) (*models.User, error) {
+ user, _, err := s.ValidateApiKeyWithID(ctx, rawKey)
+ return user, err
+}
+
+// ValidateApiKeyWithID is like ValidateApiKey but additionally returns the
+// API key's database ID so callers can resolve per-key permissions.
+func (s *ApiKeyService) ValidateApiKeyWithID(ctx context.Context, rawKey string) (*models.User, string, error) {
keyPrefix, err := parseAPIKeyPrefixInternal(rawKey)
if err != nil {
- return nil, err
+ return nil, "", err
}
var apiKeys []models.ApiKey
if err := s.db.WithContext(ctx).Where("key_prefix = ?", keyPrefix).Find(&apiKeys).Error; err != nil {
- return nil, fmt.Errorf("failed to find API keys: %w", err)
+ return nil, "", fmt.Errorf("failed to find API keys: %w", err)
}
rawKey = normalizeAPIKeyInputInternal(rawKey)
for _, apiKey := range apiKeys {
if err := s.validateApiKeyHash(apiKey.KeyHash, rawKey); err == nil {
if apiKey.ExpiresAt != nil && apiKey.ExpiresAt.Before(time.Now()) {
- return nil, ErrApiKeyExpired
+ return nil, "", ErrApiKeyExpired
}
if apiKey.UserID == nil {
- return nil, ErrApiKeyInvalid
+ return nil, "", ErrApiKeyInvalid
}
s.markApiKeyUsedAsync(ctx, apiKey.ID)
user, err := s.userService.GetUserByID(ctx, *apiKey.UserID)
if err != nil {
- return nil, fmt.Errorf("failed to get user for API key: %w", err)
+ return nil, "", fmt.Errorf("failed to get user for API key: %w", err)
}
- return user, nil
+ return user, apiKey.ID, nil
}
}
- return nil, ErrApiKeyInvalid
+ return nil, "", ErrApiKeyInvalid
}
func (s *ApiKeyService) GetEnvironmentByApiKey(ctx context.Context, rawKey string) (*string, error) {
diff --git a/backend/internal/services/api_key_service_test.go b/backend/internal/services/api_key_service_test.go
index f7b6cbf71..638f68de5 100644
--- a/backend/internal/services/api_key_service_test.go
+++ b/backend/internal/services/api_key_service_test.go
@@ -14,6 +14,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/types/apikey"
)
@@ -47,7 +48,6 @@ func createTestAPIKeyUser(t *testing.T, ctx context.Context, userService *UserSe
user := &models.User{
BaseModel: models.BaseModel{ID: id},
Username: fmt.Sprintf("user-%s", id),
- Roles: models.StringSlice{"admin"},
}
created, err := userService.CreateUser(ctx, user)
@@ -118,7 +118,6 @@ func createDefaultAdminUser(t *testing.T, ctx context.Context, userService *User
user := &models.User{
BaseModel: models.BaseModel{ID: "default-admin-user"},
Username: defaultAdminUsername,
- Roles: models.StringSlice{"admin"},
}
created, err := userService.CreateUser(ctx, user)
@@ -191,7 +190,7 @@ func TestUpdateApiKeyRejectsStaticKey(t *testing.T) {
created, err := service.CreateDefaultAdminAPIKey(ctx, adminUser.ID, "arc_bootstrapupdateprotected1234567890")
require.NoError(t, err)
- updated, err := service.UpdateApiKey(ctx, created.ApiKey.ID, apikey.UpdateApiKey{
+ updated, err := service.UpdateApiKey(ctx, adminUser.ID, created.ApiKey.ID, apikey.UpdateApiKey{
Name: new("renamed"),
Description: new("updated description"),
})
@@ -205,6 +204,36 @@ func TestUpdateApiKeyRejectsStaticKey(t *testing.T) {
require.Equal(t, *defaultAdminAPIKeyDescription, *apiKeys[0].Description)
}
+func TestUpdateApiKeyRollsBackMetadataWhenPermissionUpdateFails(t *testing.T) {
+ ctx := context.Background()
+ db := setupAuthServiceTestDB(t)
+ require.NoError(t, db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_akp_uniq ON api_key_permissions(api_key_id, permission, COALESCE(environment_id, ''))").Error)
+
+ roleSvc := NewRoleService(db)
+ require.NoError(t, roleSvc.EnsureBuiltInRoles(ctx))
+ userSvc := NewUserService(db).WithRoleService(roleSvc)
+ service := NewApiKeyService(db, userSvc).WithRoleService(roleSvc)
+ admin := createTestUser(t, userSvc, "admin-update-rollback", "admin-update-rollback")
+ grantGlobalAdmin(t, roleSvc, admin.ID)
+
+ created, err := service.CreateApiKey(ctx, admin.ID, apikey.CreateApiKey{Name: "original"})
+ require.NoError(t, err)
+
+ updatedName := "renamed"
+ updated, err := service.UpdateApiKey(ctx, admin.ID, created.ApiKey.ID, apikey.UpdateApiKey{
+ Name: &updatedName,
+ Permissions: []apikey.PermissionGrant{
+ {Permission: authz.PermContainersList},
+ {Permission: authz.PermContainersList},
+ },
+ })
+ require.Nil(t, updated)
+ require.Error(t, err)
+
+ stored := fetchAPIKey(t, db, created.ApiKey.ID)
+ require.Equal(t, "original", stored.Name)
+}
+
func TestReconcileDefaultAdminAPIKeyNoOpWhenUnchanged(t *testing.T) {
ctx := context.Background()
service, db, userService := setupAPIKeyService(t)
@@ -407,6 +436,66 @@ func TestGetEnvironmentByAPIKeyExpiredDoesNotUpdateLastUsedAt(t *testing.T) {
require.Nil(t, apiKey.LastUsedAt)
}
+func TestCreateEnvironmentApiKeySeedsAllPermissionsScopedToEnv(t *testing.T) {
+ ctx := context.Background()
+ db := setupAuthServiceTestDB(t)
+ require.NoError(t, db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_akp_uniq ON api_key_permissions(api_key_id, permission, COALESCE(environment_id, ''))").Error)
+
+ roleSvc := NewRoleService(db)
+ require.NoError(t, roleSvc.EnsureBuiltInRoles(ctx))
+ userSvc := NewUserService(db).WithRoleService(roleSvc)
+ service := NewApiKeyService(db, userSvc).WithRoleService(roleSvc)
+ admin := createTestUser(t, userSvc, "admin-env-bootstrap", "admin-env-bootstrap")
+ grantGlobalAdmin(t, roleSvc, admin.ID)
+
+ envID := "env-bootstrap-test"
+ created, err := service.CreateEnvironmentApiKey(ctx, envID, admin.ID)
+ require.NoError(t, err)
+
+ // Resolve the per-key permission set and confirm every permission is
+ // present, scoped to the bootstrap env (not global).
+ ps, err := roleSvc.ResolveApiKeyPermissions(ctx, created.ApiKey.ID)
+ require.NoError(t, err)
+ require.Empty(t, ps.Global, "bootstrap key permissions must land in PerEnv, not Global")
+ envPerms, ok := ps.PerEnv[envID]
+ require.True(t, ok)
+ for _, p := range authz.AllPermissions() {
+ _, has := envPerms[p]
+ require.True(t, has, "missing permission %s on bootstrap key", p)
+ }
+}
+
+func TestBackfillApiKeyPermissionsRepairsExistingBootstrapKey(t *testing.T) {
+ ctx := context.Background()
+ db := setupAuthServiceTestDB(t)
+ require.NoError(t, db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_akp_uniq ON api_key_permissions(api_key_id, permission, COALESCE(environment_id, ''))").Error)
+
+ roleSvc := NewRoleService(db)
+ require.NoError(t, roleSvc.EnsureBuiltInRoles(ctx))
+
+ // Simulate a pre-existing env-bootstrap key with NO permission grants
+ // (e.g., created on a deployment where the per-key seed step failed).
+ envID := "env-broken-bootstrap"
+ require.NoError(t, db.WithContext(ctx).Create(&models.ApiKey{
+ Name: "Environment Bootstrap Key - broken",
+ KeyHash: "hash",
+ KeyPrefix: "arc_brkn",
+ EnvironmentID: &envID,
+ }).Error)
+
+ require.NoError(t, roleSvc.BackfillApiKeyPermissions(ctx))
+
+ // The backfill should have populated the env-scoped perms retroactively.
+ var keys []models.ApiKey
+ require.NoError(t, db.WithContext(ctx).Where("environment_id = ?", envID).Find(&keys).Error)
+ require.Len(t, keys, 1)
+ ps, err := roleSvc.ResolveApiKeyPermissions(ctx, keys[0].ID)
+ require.NoError(t, err)
+ envPerms, ok := ps.PerEnv[envID]
+ require.True(t, ok)
+ require.Equal(t, len(authz.AllPermissions()), len(envPerms))
+}
+
func TestGetEnvironmentByAPIKeyRecentLastUsedAtDoesNotRewriteImmediately(t *testing.T) {
ctx := context.Background()
service, db, userService := setupAPIKeyService(t)
diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.go
index f01b76ae7..6537b39cc 100644
--- a/backend/internal/services/auth_service.go
+++ b/backend/internal/services/auth_service.go
@@ -45,13 +45,12 @@ type AuthSettings struct {
type userClaims struct {
jwt.RegisteredClaims
- SessionID string `json:"sid,omitempty"`
- UserID string `json:"user_id"`
- Username string `json:"username"`
- Email string `json:"email,omitempty"`
- DisplayName string `json:"display_name,omitempty"`
- Roles []string `json:"roles"`
- AppVersion string `json:"app_version,omitempty"`
+ SessionID string `json:"sid,omitempty"`
+ UserID string `json:"user_id"`
+ Username string `json:"username"`
+ Email string `json:"email,omitempty"`
+ DisplayName string `json:"display_name,omitempty"`
+ AppVersion string `json:"app_version,omitempty"`
}
type refreshClaims struct {
@@ -71,6 +70,7 @@ type AuthService struct {
settingsService *SettingsService
eventService *EventService
sessionService *SessionService
+ roleService *RoleService
jwtSecret []byte
refreshExpiry time.Duration
config *config.Config
@@ -81,7 +81,7 @@ type AuthService struct {
tokenCache *cache.TTL[verifiedTokenEntry]
}
-func NewAuthService(userService *UserService, settingsService *SettingsService, eventService *EventService, sessionService *SessionService, jwtSecret string, cfg *config.Config) *AuthService {
+func NewAuthService(userService *UserService, settingsService *SettingsService, eventService *EventService, sessionService *SessionService, roleService *RoleService, jwtSecret string, cfg *config.Config) *AuthService {
// Production managers must supply an explicit, non-default JWT_SECRET (fail
// closed, mirroring the ENCRYPTION_KEY guard). Dev and agent mode auto-generate.
requireExplicitSecret := cfg.Environment == config.AppEnvironmentProduction && !cfg.AgentMode
@@ -90,6 +90,7 @@ func NewAuthService(userService *UserService, settingsService *SettingsService,
settingsService: settingsService,
eventService: eventService,
sessionService: sessionService,
+ roleService: roleService,
jwtSecret: jwtclaims.CheckOrGenerateJwtSecret(jwtSecret, requireExplicitSecret),
refreshExpiry: cfg.JWTRefreshExpiry,
config: cfg,
@@ -122,8 +123,7 @@ func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, error
JwksURI: settings.OidcJwksEndpoint.Value,
DeviceAuthorizationEndpoint: settings.OidcDeviceAuthorizationEndpoint.Value,
Scopes: settings.OidcScopes.Value,
- AdminClaim: settings.OidcAdminClaim.Value,
- AdminValue: settings.OidcAdminValue.Value,
+ GroupsClaim: settings.OidcGroupsClaim.Value,
SkipTlsVerify: settings.OidcSkipTlsVerify.IsTrue(),
}
@@ -422,11 +422,6 @@ func (s *AuthService) createOidcUser(ctx context.Context, userInfo auth.OidcUser
username = userInfo.PreferredUsername
}
- roles := models.StringSlice{"user"}
- if s.isAdminFromOidc(ctx, userInfo, tokenResp) {
- roles = append(roles, "admin")
- }
-
var displayName *string
switch {
case userInfo.Name != "":
@@ -442,7 +437,6 @@ func (s *AuthService) createOidcUser(ctx context.Context, userInfo auth.OidcUser
Username: username,
DisplayName: displayName,
Email: new(userInfo.Email),
- Roles: roles,
OidcSubjectId: new(userInfo.Subject),
LastLogin: new(time.Now()),
}
@@ -452,6 +446,9 @@ func (s *AuthService) createOidcUser(ctx context.Context, userInfo auth.OidcUser
if _, err := s.userService.CreateUser(ctx, user); err != nil {
return nil, err
}
+ if err := s.syncOidcRoleAssignments(ctx, user, userInfo, tokenResp); err != nil {
+ slog.WarnContext(ctx, "failed to sync OIDC role assignments on user create", "error", err, "user_id", user.ID)
+ }
return user, nil
}
@@ -463,116 +460,143 @@ func (s *AuthService) updateOidcUser(ctx context.Context, user *models.User, use
user.Email = new(userInfo.Email)
}
- wantAdmin := s.isAdminFromOidc(ctx, userInfo, tokenResp)
- hasAdmin := hasRole(user.Roles, "admin")
- switch {
- case wantAdmin && !hasAdmin:
- user.Roles = addRole(user.Roles, "admin")
- case !wantAdmin && hasAdmin:
- user.Roles = removeRole(user.Roles, "admin")
- }
-
s.persistOidcTokens(user, tokenResp)
user.LastLogin = new(time.Now())
- _, err := s.userService.UpdateUser(ctx, user)
- return err
+ if _, err := s.userService.UpdateUser(ctx, user); err != nil {
+ return err
+ }
+ if err := s.syncOidcRoleAssignments(ctx, user, userInfo, tokenResp); err != nil {
+ slog.WarnContext(ctx, "failed to sync OIDC role assignments on user update", "error", err, "user_id", user.ID)
+ }
+ return nil
}
func (s *AuthService) mergeOidcWithExistingUser(ctx context.Context, user *models.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {
// Perform the merge atomically to avoid races when multiple OIDC subjects share the same email
- _, err := s.userService.AttachOidcSubjectTransactional(ctx, user.ID, userInfo.Subject, func(u *models.User) {
- // Update display name if not set
+ merged, err := s.userService.AttachOidcSubjectTransactional(ctx, user.ID, userInfo.Subject, func(u *models.User) {
if userInfo.Name != "" && u.DisplayName == nil {
u.DisplayName = new(userInfo.Name)
}
-
- // Update admin role based on OIDC claims
- wantAdmin := s.isAdminFromOidc(ctx, userInfo, tokenResp)
- hasAdmin := hasRole(u.Roles, "admin")
- switch {
- case wantAdmin && !hasAdmin:
- u.Roles = addRole(u.Roles, "admin")
- case !wantAdmin && hasAdmin:
- u.Roles = removeRole(u.Roles, "admin")
- }
-
- // Persist OIDC tokens
s.persistOidcTokens(u, tokenResp)
-
u.LastLogin = new(time.Now())
})
- return err
-}
-
-func hasRole(roles models.StringSlice, role string) bool {
- for _, r := range roles {
- if strings.EqualFold(r, role) {
- return true
+ if err != nil {
+ return err
+ }
+ if merged != nil {
+ if syncErr := s.syncOidcRoleAssignments(ctx, merged, userInfo, tokenResp); syncErr != nil {
+ slog.WarnContext(ctx, "failed to sync OIDC role assignments on user merge", "error", syncErr, "user_id", merged.ID)
}
}
- return false
+ return nil
}
-func addRole(roles models.StringSlice, role string) models.StringSlice {
- if hasRole(roles, role) {
- return roles
+// syncOidcRoleAssignments rebuilds the user's `source='oidc'` role assignments
+// based on the OIDC group claim and the configured OidcRoleMapping rows.
+// Manual assignments are untouched.
+func (s *AuthService) syncOidcRoleAssignments(ctx context.Context, user *models.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {
+ if s.roleService == nil || user == nil {
+ return nil
}
- return append(roles, role)
-}
-func removeRole(roles models.StringSlice, role string) models.StringSlice {
- out := make(models.StringSlice, 0, len(roles))
- for _, r := range roles {
- if !strings.EqualFold(r, role) {
- out = append(out, r)
- }
+ groups := s.extractOidcGroups(ctx, userInfo, tokenResp)
+ mappings, err := s.roleService.ListOidcMappings(ctx)
+ if err != nil {
+ return fmt.Errorf("list oidc mappings: %w", err)
}
- return out
-}
-func (s *AuthService) isAdminFromOidc(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) bool {
- claimKey, values := s.getAdminClaimConfig(ctx)
- if claimKey == "" {
- return false
+ groupSet := make(map[string]struct{}, len(groups))
+ for _, g := range groups {
+ groupSet[g] = struct{}{}
}
- if v, ok := jwtclaims.GetByPath(userInfo.Extra, claimKey); ok && jwtclaims.EvalMatch(v, values) {
- return true
+ var desired []models.UserRoleAssignment
+ seen := make(map[string]struct{}) // dedup by roleID|envID
+ for _, m := range mappings {
+ if _, ok := groupSet[m.ClaimValue]; !ok {
+ continue
+ }
+ key := m.RoleID + "|"
+ if m.EnvironmentID != nil {
+ key += *m.EnvironmentID
+ }
+ if _, dup := seen[key]; dup {
+ continue
+ }
+ seen[key] = struct{}{}
+ desired = append(desired, models.UserRoleAssignment{
+ RoleID: m.RoleID,
+ EnvironmentID: m.EnvironmentID,
+ })
}
- if tokenResp != nil && tokenResp.IDToken != "" {
- if claims := jwtclaims.ParseJWTClaims(tokenResp.IDToken); claims != nil {
- if v, ok := jwtclaims.GetByPath(claims, claimKey); ok && jwtclaims.EvalMatch(v, values) {
- return true
+ return s.roleService.ReplaceOidcAssignments(ctx, user.ID, desired)
+}
+
+// extractOidcGroups reads the user's group memberships from the OIDC userinfo
+// and ID token, using the claim path configured in OidcGroupsClaim (defaults
+// to "groups"). Falls back to userInfo.Groups if no value is found at the
+// configured path.
+func (s *AuthService) extractOidcGroups(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) []string {
+ claim := s.oidcGroupsClaim(ctx)
+
+ if claim != "" {
+ if v, ok := jwtclaims.GetByPath(userInfo.Extra, claim); ok {
+ if groups := stringValuesFromClaim(v); len(groups) > 0 {
+ return groups
+ }
+ }
+ if tokenResp != nil && tokenResp.IDToken != "" {
+ if parsed := jwtclaims.ParseJWTClaims(tokenResp.IDToken); parsed != nil {
+ if v, ok := jwtclaims.GetByPath(parsed, claim); ok {
+ if groups := stringValuesFromClaim(v); len(groups) > 0 {
+ return groups
+ }
+ }
}
}
}
- return false
+ return userInfo.Groups
}
-func (s *AuthService) getAdminClaimConfig(ctx context.Context) (claim string, values []string) {
- as, err := s.getAuthSettings(ctx)
- if err != nil || as.Oidc == nil {
- return "", nil
- }
- claim = strings.TrimSpace(as.Oidc.AdminClaim)
- raw := strings.TrimSpace(as.Oidc.AdminValue)
- if claim == "" {
- return "", nil
+func (s *AuthService) oidcGroupsClaim(ctx context.Context) string {
+ settings, err := s.settingsService.GetSettings(ctx)
+ if err != nil {
+ return "groups"
}
- if raw == "" {
- return claim, nil
+ v := strings.TrimSpace(settings.OidcGroupsClaim.Value)
+ if v == "" {
+ return "groups"
}
- parts := strings.SplitSeq(raw, ",")
- for p := range parts {
- v := strings.TrimSpace(p)
- if v != "" {
- values = append(values, v)
+ return v
+}
+
+// stringValuesFromClaim flattens a claim value into a slice of strings.
+// Accepts string, []string, []any (coerces each element to string), or nil.
+func stringValuesFromClaim(v any) []string {
+ switch typed := v.(type) {
+ case nil:
+ return nil
+ case string:
+ if typed == "" {
+ return nil
+ }
+ return []string{typed}
+ case []string:
+ return typed
+ case []any:
+ out := make([]string, 0, len(typed))
+ for _, item := range typed {
+ if s, ok := item.(string); ok && s != "" {
+ out = append(out, s)
+ }
}
+ return out
+ default:
+ return nil
}
- return claim, values
}
func (s *AuthService) persistOidcTokens(user *models.User, tokenResp *auth.OidcTokenResponse) {
@@ -816,7 +840,6 @@ func (s *AuthService) buildTokenPairInternal(ctx context.Context, user *models.U
SessionID: session.ID,
UserID: user.ID,
Username: user.Username,
- Roles: []string(user.Roles),
AppVersion: config.Version,
}
diff --git a/backend/internal/services/auth_service_test.go b/backend/internal/services/auth_service_test.go
index 18dbcc8ec..d4c88af15 100644
--- a/backend/internal/services/auth_service_test.go
+++ b/backend/internal/services/auth_service_test.go
@@ -24,7 +24,17 @@ func setupAuthServiceTestDB(t *testing.T) *database.DB {
t.Helper()
db, err := gorm.Open(glsqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}, &models.User{}, &models.UserSession{}))
+ require.NoError(t, db.AutoMigrate(
+ &models.SettingVariable{},
+ &models.User{},
+ &models.UserSession{},
+ &models.Environment{},
+ &models.Role{},
+ &models.UserRoleAssignment{},
+ &models.ApiKey{},
+ &models.ApiKeyPermission{},
+ &models.OidcRoleMapping{},
+ ))
return &database.DB{DB: db}
}
@@ -49,7 +59,7 @@ func newTestAuthService(secret string) *AuthService {
}
}
-func makeAccessToken(t *testing.T, secret []byte, subject string, id string, username string, roles []string, email, displayName string, exp time.Time, sessionIDs ...string) string {
+func makeAccessToken(t *testing.T, secret []byte, subject string, id string, username string, _ []string, email, displayName string, exp time.Time, sessionIDs ...string) string {
t.Helper()
sessionID := ""
if len(sessionIDs) > 0 {
@@ -65,7 +75,6 @@ func makeAccessToken(t *testing.T, secret []byte, subject string, id string, use
SessionID: sessionID,
UserID: id,
Username: username,
- Roles: roles,
Email: email,
DisplayName: displayName,
AppVersion: config.Version,
@@ -141,7 +150,6 @@ func TestVerifyToken_ValidClaims(t *testing.T) {
Username: "alice",
Email: new("[email protected]"),
DisplayName: new("Alice"),
- Roles: models.StringSlice{"user", "admin"},
}
_, err := userSvc.CreateUser(context.Background(), user)
require.NoError(t, err)
@@ -160,9 +168,6 @@ func TestVerifyToken_ValidClaims(t *testing.T) {
if verifiedUser.Username != "alice" {
t.Errorf("username %q", verifiedUser.Username)
}
- if len(verifiedUser.Roles) != 2 || verifiedUser.Roles[0] != "user" || verifiedUser.Roles[1] != "admin" {
- t.Errorf("roles %v", verifiedUser.Roles)
- }
if verifiedUser.Email == nil || *verifiedUser.Email != "[email protected]" {
t.Errorf("email %v", verifiedUser.Email)
}
@@ -183,7 +188,6 @@ func TestVerifyToken_RejectsNonHMACAlg(t *testing.T) {
},
UserID: "u1",
Username: "bob",
- Roles: []string{"user"},
AppVersion: config.Version,
})
@@ -204,7 +208,6 @@ func TestVerifyToken_Expired(t *testing.T) {
user := &models.User{
BaseModel: models.BaseModel{ID: "u1"},
Username: "bob",
- Roles: models.StringSlice{"user"},
}
_, err := userSvc.CreateUser(context.Background(), user)
require.NoError(t, err)
@@ -325,7 +328,6 @@ func TestRefreshToken_Valid(t *testing.T) {
user := &models.User{
BaseModel: models.BaseModel{ID: "u-refresh"},
Username: "refresh-user",
- Roles: models.StringSlice{"user"},
}
_, err = userSvc.CreateUser(context.Background(), user)
require.NoError(t, err)
@@ -357,7 +359,6 @@ func TestRefreshToken_VersionMismatchRotates(t *testing.T) {
user := &models.User{
BaseModel: models.BaseModel{ID: "u-versionmismatch"},
Username: "versionmismatch-user",
- Roles: models.StringSlice{"user"},
}
_, err = userSvc.CreateUser(context.Background(), user)
require.NoError(t, err)
@@ -404,7 +405,6 @@ func TestVerifyToken_RejectsRevokedSession(t *testing.T) {
user := &models.User{
BaseModel: models.BaseModel{ID: "u-revoked"},
Username: "revoked-user",
- Roles: models.StringSlice{"user"},
}
_, err := userSvc.CreateUser(context.Background(), user)
require.NoError(t, err)
@@ -428,7 +428,6 @@ func TestVerifyToken_RejectsMissingSessionID(t *testing.T) {
user := &models.User{
BaseModel: models.BaseModel{ID: "u-no-sid"},
Username: "no-sid-user",
- Roles: models.StringSlice{"user"},
}
_, err := userSvc.CreateUser(context.Background(), user)
require.NoError(t, err)
@@ -449,7 +448,6 @@ func TestRevokeSessionThenVerifyTokenFails(t *testing.T) {
user := &models.User{
BaseModel: models.BaseModel{ID: "u-logout"},
Username: "logout-user",
- Roles: models.StringSlice{"user"},
}
_, err := userSvc.CreateUser(context.Background(), user)
require.NoError(t, err)
@@ -476,7 +474,6 @@ func TestRefreshToken_RotatesJTI(t *testing.T) {
user := &models.User{
BaseModel: models.BaseModel{ID: "u-rotate"},
Username: "rotate-user",
- Roles: models.StringSlice{"user"},
}
_, err = userSvc.CreateUser(context.Background(), user)
require.NoError(t, err)
@@ -506,7 +503,6 @@ func TestRefreshToken_RejectsRevokedSession(t *testing.T) {
user := &models.User{
BaseModel: models.BaseModel{ID: "u-refresh-revoked"},
Username: "refresh-revoked-user",
- Roles: models.StringSlice{"user"},
}
_, err = userSvc.CreateUser(context.Background(), user)
require.NoError(t, err)
@@ -533,7 +529,6 @@ func TestChangePassword_RevokesAllSessions(t *testing.T) {
BaseModel: models.BaseModel{ID: "u-password"},
Username: "password-user",
PasswordHash: passwordHash,
- Roles: models.StringSlice{"user"},
}
_, err = userSvc.CreateUser(context.Background(), user)
require.NoError(t, err)
@@ -564,7 +559,6 @@ func TestChangePassword_KeepsCurrentSessionAlive(t *testing.T) {
BaseModel: models.BaseModel{ID: "u-keep"},
Username: "keep-user",
PasswordHash: passwordHash,
- Roles: models.StringSlice{"user"},
}
_, err = userSvc.CreateUser(context.Background(), user)
require.NoError(t, err)
@@ -706,7 +700,6 @@ func TestFindOrCreateOidcUser_MergeEnabled_EmailNotVerified_WithExistingUser_Ret
BaseModel: models.BaseModel{ID: "u1"},
Username: "existing",
Email: &email,
- Roles: models.StringSlice{"user"},
}
_, err = userSvc.CreateUser(ctx, existing)
require.NoError(t, err)
@@ -749,7 +742,6 @@ func TestFindOrCreateOidcUser_MergeEnabled_EmailVerificationMissing_WithExisting
BaseModel: models.BaseModel{ID: "u1"},
Username: "existing",
Email: &email,
- Roles: models.StringSlice{"user"},
}
_, err = userSvc.CreateUser(ctx, existing)
require.NoError(t, err)
diff --git a/backend/internal/services/environment_service_test.go b/backend/internal/services/environment_service_test.go
index 0c7d3ac1c..b9c1f650c 100644
--- a/backend/internal/services/environment_service_test.go
+++ b/backend/internal/services/environment_service_test.go
@@ -67,7 +67,6 @@ func createTestEnvironmentServiceUser(t *testing.T, ctx context.Context, userSer
user := &models.User{
BaseModel: models.BaseModel{ID: id},
Username: fmt.Sprintf("user-%s", id),
- Roles: models.StringSlice{"admin"},
}
created, err := userService.CreateUser(ctx, user)
diff --git a/backend/internal/services/playwright_service.go b/backend/internal/services/playwright_service.go
index 64bac28b4..d3ea9553d 100644
--- a/backend/internal/services/playwright_service.go
+++ b/backend/internal/services/playwright_service.go
@@ -7,6 +7,7 @@ import (
"fmt"
"log/slog"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/types/apikey"
)
@@ -32,11 +33,23 @@ func (ps *PlaywrightService) CreateTestApiKeys(ctx context.Context, count int) (
return nil, fmt.Errorf("failed to get arcane user: %w", err)
}
+ // Grant every recognized permission globally so the test key behaves like
+ // the legacy "admin-everywhere" credential the e2e suite expects. The
+ // owner is the `arcane` bootstrap user, who holds global Admin and
+ // therefore satisfies validateGrantsAgainstUserInternal.
+ allPerms := authz.AllPermissions()
+ grants := make([]apikey.PermissionGrant, len(allPerms))
+ for i, p := range allPerms {
+ grants[i] = apikey.PermissionGrant{Permission: p}
+ }
+
var createdKeys []*apikey.ApiKeyCreatedDto
for i := 0; i < count; i++ {
+ description := fmt.Sprintf("Test API key %d for Playwright tests", i+1)
req := apikey.CreateApiKey{
Name: fmt.Sprintf("test-api-key-%d", i+1),
- Description: new(fmt.Sprintf("Test API key %d for Playwright tests", i+1)),
+ Description: &description,
+ Permissions: grants,
}
apiKey, err := ps.apiKeyService.CreateApiKey(ctx, user.ID, req)
diff --git a/backend/internal/services/role_service.go b/backend/internal/services/role_service.go
new file mode 100644
index 000000000..a3adf8d7b
--- /dev/null
+++ b/backend/internal/services/role_service.go
@@ -0,0 +1,932 @@
+package services
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "strings"
+ "time"
+
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/database"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
+ "github.com/getarcaneapp/arcane/backend/pkg/pagination"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils/cache"
+ "github.com/getarcaneapp/arcane/backend/pkg/utils/dbutil"
+ roletypes "github.com/getarcaneapp/arcane/types/role"
+)
+
+// permissionCacheTTL bounds how long a resolved PermissionSet is reused
+// before re-querying the DB. The service also invalidates entries explicitly
+// on mutation paths, so this TTL is a safety net.
+const permissionCacheTTL = 60 * time.Second
+
+// RoleService owns role definitions, user role assignments, OIDC role
+// mappings, and API key permissions. It resolves a caller's effective
+// PermissionSet on demand and caches the result per-user / per-key for a
+// short TTL to keep the hot path off the database.
+type RoleService struct {
+ db *database.DB
+ userCache *cache.TTL[*authz.PermissionSet]
+ apiKeyCache *cache.TTL[*authz.PermissionSet]
+}
+
+func NewRoleService(db *database.DB) *RoleService {
+ return &RoleService{
+ db: db,
+ userCache: cache.NewTTL[*authz.PermissionSet](permissionCacheTTL),
+ apiKeyCache: cache.NewTTL[*authz.PermissionSet](permissionCacheTTL),
+ }
+}
+
+// ---------- Boot-time reconciliation & safety checks ----------
+
+// EnsureBuiltInRoles overwrites the permission set on every built-in role to
+// match the Go constants. Idempotent. Called at boot after migrations succeed.
+func (s *RoleService) EnsureBuiltInRoles(ctx context.Context) error {
+ builtIns := map[string]struct {
+ name string
+ desc string
+ perm []string
+ }{
+ authz.BuiltInRoleAdmin: {"Admin", "Full administrative access", authz.AllPermissions()},
+ authz.BuiltInRoleEditor: {"Editor", "Read and write on Docker resources", authz.BuiltInEditorPermissions()},
+ authz.BuiltInRoleNoShellEditor: {"No-Shell Editor", "Editor without interactive container shell access", authz.BuiltInNoShellEditorPermissions()},
+ authz.BuiltInRoleDeployer: {"Deployer", "Deploy and lifecycle containers and projects", authz.BuiltInDeployerPermissions()},
+ authz.BuiltInRoleMonitor: {"Monitor", "Observability-only access: logs, dashboards, events", authz.BuiltInMonitorPermissions()},
+ authz.BuiltInRoleViewer: {"Viewer", "Read-only access to all resources", authz.BuiltInViewerPermissions()},
+ }
+
+ return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ for id, spec := range builtIns {
+ desc := spec.desc
+ role := models.Role{
+ BaseModel: models.BaseModel{ID: id},
+ Name: spec.name,
+ Description: &desc,
+ Permissions: models.StringSlice(spec.perm),
+ BuiltIn: true,
+ }
+ if err := tx.Save(&role).Error; err != nil {
+ return fmt.Errorf("failed to upsert built-in role %s: %w", id, err)
+ }
+ }
+ return nil
+ })
+}
+
+// BackfillLegacyRoleAssignments migrates the pre-RBAC users.roles JSON column
+// into rows in user_role_assignments. Safe to call on every boot: a no-op once
+// the column is gone.
+//
+// Users with "admin" in their legacy roles get a global Admin assignment;
+// every other user gets a global Viewer assignment. The NULL environment_id
+// lands the perms in PermissionSet.Global, which is what ps.Allows(perm, "")
+// consults for org-level checks (list environments, read settings, list users,
+// etc.) AND for env-scoped checks at the union step. Inserting per-environment
+// viewer rows instead would lock non-admins out of the settings area entirely.
+//
+// Lives here (not as a SQL migration) so the column-existence check is trivial
+// in Go and the same code path covers both postgres and sqlite. Idempotent via
+// ON CONFLICT DO NOTHING on the (user_id, role_id, env) unique index, so a
+// half-finished prior run can be safely retried.
+func (s *RoleService) BackfillLegacyRoleAssignments(ctx context.Context) error {
+ migrator := s.db.WithContext(ctx).Migrator()
+ if !migrator.HasColumn("users", "roles") {
+ return nil
+ }
+
+ type legacyUser struct {
+ ID string `gorm:"column:id"`
+ Roles string `gorm:"column:roles"`
+ }
+
+ return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ var rows []legacyUser
+ if err := tx.Table("users").Select("id, roles").Scan(&rows).Error; err != nil {
+ return fmt.Errorf("failed to read legacy users.roles for backfill: %w", err)
+ }
+ for _, u := range rows {
+ roleID := authz.BuiltInRoleViewer
+ if legacyRolesContainsAdminInternal(u.Roles) {
+ roleID = authz.BuiltInRoleAdmin
+ }
+ assignment := models.UserRoleAssignment{
+ UserID: u.ID,
+ RoleID: roleID,
+ Source: models.RoleAssignmentSourceManual,
+ }
+ if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&assignment).Error; err != nil {
+ return fmt.Errorf("failed to backfill assignment for user %s: %w", u.ID, err)
+ }
+ }
+ slog.InfoContext(ctx, "Backfilled legacy users.roles into user_role_assignments", "userCount", len(rows))
+ return nil
+ })
+}
+
+// legacyRolesContainsAdminInternal reports whether a pre-RBAC users.roles JSON
+// value contains the literal "admin" (case-insensitive). Empty / null / malformed
+// JSON yields false — treat as non-admin and assign Viewer.
+func legacyRolesContainsAdminInternal(raw string) bool {
+ raw = strings.TrimSpace(raw)
+ if raw == "" || raw == "[]" || raw == "null" {
+ return false
+ }
+ var roles []string
+ if err := json.Unmarshal([]byte(raw), &roles); err != nil {
+ return false
+ }
+ for _, r := range roles {
+ if strings.EqualFold(strings.TrimSpace(r), "admin") {
+ return true
+ }
+ }
+ return false
+}
+
+// AssertGlobalAdminExists returns a *common.NoGlobalAdminRemainsError if zero
+// users hold a globally-scoped Admin role assignment. Called at boot after the
+// backfill migration; also called from inside mutation paths.
+func (s *RoleService) AssertGlobalAdminExists(ctx context.Context) error {
+ count, err := s.countGlobalAdminsInternal(ctx, s.db.WithContext(ctx))
+ if err != nil {
+ return err
+ }
+ if count == 0 {
+ return &common.NoGlobalAdminRemainsError{}
+ }
+ return nil
+}
+
+// BackfillApiKeyPermissions populates api_key_permissions for every existing
+// API key whose row has no permissions yet. Each key inherits a snapshot of
+// its owner's current effective permissions (scoped per the key's
+// environment_id when set). Idempotent: skips if the table is non-empty.
+// BackfillApiKeyPermissions ensures every ownerless (bootstrap) API key has
+// its expected permission grants. Called once per boot.
+//
+// Per-key, not all-or-nothing: a single bootstrap key with zero grants is
+// repaired even if other keys are already populated. This recovers env-
+// bootstrap keys that pre-date the per-key permission feature, or that were
+// created on a deployment where the original SetApiKeyPermissions call failed
+// (e.g., the api_key_permissions table didn't exist yet).
+//
+// User-owned keys are deliberately skipped. A user-owned key with zero grants
+// is an intentional "no access" state; rehydrating from the owner's effective
+// permissions on every boot would clobber that. User keys are seeded at
+// creation time by CreateApiKey instead.
+func (s *RoleService) BackfillApiKeyPermissions(ctx context.Context) error {
+ // Bootstrap-class keys we'll repair if they have zero grants:
+ // - user_id IS NULL → env-bootstrap keys.
+ // - managed_by IS NOT NULL → admin-static (ADMIN_STATIC_API_KEY) keys,
+ // which DO have a user_id but are infrastructure-managed and must
+ // always carry full perms.
+ // Regular user-created keys are deliberately excluded — empty grants on
+ // those are an intentional "no access" state we must not overwrite.
+ var keys []models.ApiKey
+ if err := s.db.WithContext(ctx).Where("user_id IS NULL OR managed_by IS NOT NULL").Find(&keys).Error; err != nil {
+ return fmt.Errorf("failed to list bootstrap api keys for backfill: %w", err)
+ }
+ if len(keys) == 0 {
+ return nil
+ }
+
+ return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ for _, key := range keys {
+ var existing int64
+ if err := tx.Model(&models.ApiKeyPermission{}).Where("api_key_id = ?", key.ID).Count(&existing).Error; err != nil {
+ return fmt.Errorf("failed to count permissions for api key %s: %w", key.ID, err)
+ }
+ if existing > 0 {
+ continue
+ }
+ perms, err := s.backfillPermsForKeyInternal(ctx, tx, key)
+ if err != nil {
+ return err
+ }
+ for _, p := range perms {
+ if err := tx.Create(&models.ApiKeyPermission{
+ ApiKeyID: key.ID,
+ Permission: p,
+ EnvironmentID: key.EnvironmentID,
+ }).Error; err != nil {
+ return fmt.Errorf("failed to seed api key permission: %w", err)
+ }
+ }
+ slog.InfoContext(ctx, "Backfilled missing permissions for bootstrap api key", "api_key_id", key.ID, "perm_count", len(perms), "env_id", key.EnvironmentID)
+ }
+ return nil
+ })
+}
+
+func (s *RoleService) backfillPermsForKeyInternal(ctx context.Context, tx *gorm.DB, key models.ApiKey) ([]string, error) {
+ // Static admin bootstrap keys (no owner, no env scope) get full access.
+ if key.UserID == nil && key.EnvironmentID == nil {
+ return authz.AllPermissions(), nil
+ }
+ // Environment bootstrap keys (key bound to a specific env, no owner) get
+ // full access scoped to that environment via the auth bridge — replicate
+ // that by granting all permissions scoped to that environment. Org-level
+ // permissions land in PerEnv[envID] and are unreachable via org-level
+ // checks (which always pass envID=""), so over-granting is harmless here.
+ if key.UserID == nil && key.EnvironmentID != nil {
+ return authz.AllPermissions(), nil
+ }
+ // Otherwise inherit the owner's current effective permissions.
+ var owner models.User
+ if err := tx.WithContext(ctx).Where("id = ?", *key.UserID).First(&owner).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("failed to load api key owner: %w", err)
+ }
+ ps, err := s.resolveUserPermissionsInternal(ctx, tx, owner.ID)
+ if err != nil {
+ return nil, err
+ }
+ // Flatten ps into a deduplicated list of permissions for this key's scope.
+ seen := make(map[string]struct{}, len(ps.Global))
+ for p := range ps.Global {
+ seen[p] = struct{}{}
+ }
+ if key.EnvironmentID != nil {
+ if env, ok := ps.PerEnv[*key.EnvironmentID]; ok {
+ for p := range env {
+ seen[p] = struct{}{}
+ }
+ }
+ }
+ out := make([]string, 0, len(seen))
+ for p := range seen {
+ out = append(out, p)
+ }
+ return out, nil
+}
+
+// ---------- Role CRUD ----------
+
+func (s *RoleService) ListRoles(ctx context.Context, params pagination.QueryParams) ([]models.Role, pagination.Response, error) {
+ var roles []models.Role
+ query := s.db.WithContext(ctx).Model(&models.Role{})
+
+ if term := strings.TrimSpace(params.Search); term != "" {
+ pattern := "%" + term + "%"
+ query = query.Where("name LIKE ? OR COALESCE(description, '') LIKE ?", pattern, pattern)
+ }
+
+ resp, err := pagination.PaginateAndSortDB(params, query, &roles)
+ if err != nil {
+ return nil, pagination.Response{}, fmt.Errorf("failed to paginate roles: %w", err)
+ }
+ return roles, resp, nil
+}
+
+func (s *RoleService) ListAllRoles(ctx context.Context) ([]models.Role, error) {
+ var roles []models.Role
+ if err := s.db.WithContext(ctx).Order("name").Find(&roles).Error; err != nil {
+ return nil, fmt.Errorf("failed to list roles: %w", err)
+ }
+ return roles, nil
+}
+
+func (s *RoleService) GetRole(ctx context.Context, id string) (*models.Role, error) {
+ return dbutil.FirstWhere[models.Role](ctx, s.db.DB, &common.RoleNotFoundError{}, "id = ?", id)
+}
+
+func (s *RoleService) CreateRole(ctx context.Context, name string, description *string, permissions []string) (*models.Role, error) {
+ if strings.TrimSpace(name) == "" {
+ return nil, fmt.Errorf("role name is required")
+ }
+ if err := validatePermissionsInternal(permissions); err != nil {
+ return nil, err
+ }
+ role := &models.Role{
+ Name: name,
+ Description: description,
+ Permissions: models.StringSlice(permissions),
+ BuiltIn: false,
+ }
+ err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ var conflict int64
+ if err := tx.Model(&models.Role{}).Where("name = ?", name).Count(&conflict).Error; err != nil {
+ return fmt.Errorf("failed to check role name uniqueness: %w", err)
+ }
+ if conflict > 0 {
+ return &common.RoleNameTakenError{}
+ }
+ return tx.Create(role).Error
+ })
+ if err != nil {
+ return nil, err
+ }
+ return role, nil
+}
+
+func (s *RoleService) UpdateRole(ctx context.Context, id, name string, description *string, permissions []string) (*models.Role, error) {
+ if err := validatePermissionsInternal(permissions); err != nil {
+ return nil, err
+ }
+ var out models.Role
+ err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ var existing models.Role
+ if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return &common.RoleNotFoundError{}
+ }
+ return fmt.Errorf("failed to load role: %w", err)
+ }
+ if existing.BuiltIn {
+ return &common.RoleBuiltInError{}
+ }
+ if name != existing.Name {
+ var conflict int64
+ if err := tx.Model(&models.Role{}).Where("name = ? AND id <> ?", name, id).Count(&conflict).Error; err != nil {
+ return fmt.Errorf("failed to check role name uniqueness: %w", err)
+ }
+ if conflict > 0 {
+ return &common.RoleNameTakenError{}
+ }
+ }
+ existing.Name = name
+ existing.Description = description
+ existing.Permissions = models.StringSlice(permissions)
+ if err := tx.Save(&existing).Error; err != nil {
+ return fmt.Errorf("failed to update role: %w", err)
+ }
+ out = existing
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ s.invalidateUsersAssignedToInternal(ctx, id)
+ return &out, nil
+}
+
+func (s *RoleService) DeleteRole(ctx context.Context, id string) error {
+ var affected []string
+ err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ var existing models.Role
+ if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return &common.RoleNotFoundError{}
+ }
+ return fmt.Errorf("failed to load role: %w", err)
+ }
+ if existing.BuiltIn {
+ return &common.RoleBuiltInError{}
+ }
+ // Collect users affected before the delete so we can invalidate their caches.
+ if err := tx.Model(&models.UserRoleAssignment{}).
+ Where("role_id = ?", id).
+ Distinct("user_id").
+ Pluck("user_id", &affected).Error; err != nil {
+ return fmt.Errorf("failed to list affected users: %w", err)
+ }
+ if err := tx.Delete(&models.Role{}, "id = ?", id).Error; err != nil {
+ return fmt.Errorf("failed to delete role: %w", err)
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ // Invalidate caches AFTER the transaction commits so a concurrent
+ // cache-miss cannot re-populate with stale data from the not-yet-visible
+ // delete. Consistent with UpdateRole / SetUserAssignments.
+ for _, uid := range affected {
+ s.userCache.Delete(uid)
+ }
+ return nil
+}
+
+// CountUsersAssignedToRole returns how many distinct users hold an assignment
+// to the given role (any source, any environment scope).
+func (s *RoleService) CountUsersAssignedToRole(ctx context.Context, roleID string) (int, error) {
+ var count int64
+ if err := s.db.WithContext(ctx).
+ Model(&models.UserRoleAssignment{}).
+ Distinct("user_id").
+ Where("role_id = ?", roleID).
+ Count(&count).Error; err != nil {
+ return 0, fmt.Errorf("failed to count users assigned to role: %w", err)
+ }
+ return int(count), nil
+}
+
+// ---------- User role assignments ----------
+
+func (s *RoleService) ListUserAssignments(ctx context.Context, userID string) ([]models.UserRoleAssignment, error) {
+ var out []models.UserRoleAssignment
+ if err := s.db.WithContext(ctx).
+ Where("user_id = ?", userID).
+ Order("source ASC, role_id ASC").
+ Find(&out).Error; err != nil {
+ return nil, fmt.Errorf("failed to list user assignments: %w", err)
+ }
+ return out, nil
+}
+
+// SetUserAssignments replaces the user's source='manual' assignments with the
+// given desired set. Source='oidc' rows are preserved (use
+// ReplaceOidcAssignments for those). Enforces the global-admin guard.
+func (s *RoleService) SetUserAssignments(ctx context.Context, userID string, desired []models.UserRoleAssignment) error {
+ for i := range desired {
+ desired[i].UserID = userID
+ desired[i].Source = models.RoleAssignmentSourceManual
+ }
+ err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ // Validate inside the tx so a concurrent role/env delete can't race past
+ // this check. Yields a typed error → 400 at the handler, rather than an
+ // opaque FK violation surfacing as 500.
+ if err := validateAssignmentsExistInternal(tx, desired); err != nil {
+ return err
+ }
+ if err := tx.Where("user_id = ? AND source = ?", userID, models.RoleAssignmentSourceManual).
+ Delete(&models.UserRoleAssignment{}).Error; err != nil {
+ return fmt.Errorf("failed to clear manual assignments: %w", err)
+ }
+ if len(desired) > 0 {
+ if err := tx.Create(&desired).Error; err != nil {
+ return fmt.Errorf("failed to insert assignments: %w", err)
+ }
+ }
+ count, err := s.countGlobalAdminsInternal(ctx, tx)
+ if err != nil {
+ return err
+ }
+ if count == 0 {
+ return &common.NoGlobalAdminRemainsError{}
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ s.userCache.Delete(userID)
+ return nil
+}
+
+// validateAssignmentsExistInternal verifies every distinct RoleID and
+// EnvironmentID referenced by `desired` exists in the database. Returns the
+// first missing reference wrapped in an InvalidRoleAssignmentError so the
+// handler can map it to a 400 with a descriptive message.
+func validateAssignmentsExistInternal(tx *gorm.DB, desired []models.UserRoleAssignment) error {
+ roleIDSet := make(map[string]struct{}, len(desired))
+ envIDSet := make(map[string]struct{}, len(desired))
+ for _, a := range desired {
+ roleIDSet[a.RoleID] = struct{}{}
+ if a.EnvironmentID != nil {
+ envIDSet[*a.EnvironmentID] = struct{}{}
+ }
+ }
+
+ if len(roleIDSet) > 0 {
+ roleIDs := make([]string, 0, len(roleIDSet))
+ for id := range roleIDSet {
+ roleIDs = append(roleIDs, id)
+ }
+ var found []string
+ if err := tx.Model(&models.Role{}).Where("id IN ?", roleIDs).Pluck("id", &found).Error; err != nil {
+ return fmt.Errorf("failed to verify role ids: %w", err)
+ }
+ foundSet := make(map[string]struct{}, len(found))
+ for _, id := range found {
+ foundSet[id] = struct{}{}
+ }
+ for id := range roleIDSet {
+ if _, ok := foundSet[id]; !ok {
+ return &common.InvalidRoleAssignmentError{RoleID: id}
+ }
+ }
+ }
+
+ if len(envIDSet) > 0 {
+ envIDs := make([]string, 0, len(envIDSet))
+ for id := range envIDSet {
+ envIDs = append(envIDs, id)
+ }
+ var found []string
+ if err := tx.Model(&models.Environment{}).Where("id IN ?", envIDs).Pluck("id", &found).Error; err != nil {
+ return fmt.Errorf("failed to verify environment ids: %w", err)
+ }
+ foundSet := make(map[string]struct{}, len(found))
+ for _, id := range found {
+ foundSet[id] = struct{}{}
+ }
+ for id := range envIDSet {
+ if _, ok := foundSet[id]; !ok {
+ return &common.InvalidRoleAssignmentError{EnvironmentID: id}
+ }
+ }
+ }
+ return nil
+}
+
+// ReplaceOidcAssignments replaces the user's source='oidc' assignments. Manual
+// assignments are untouched. Enforces the global-admin guard after the swap.
+func (s *RoleService) ReplaceOidcAssignments(ctx context.Context, userID string, desired []models.UserRoleAssignment) error {
+ for i := range desired {
+ desired[i].UserID = userID
+ desired[i].Source = models.RoleAssignmentSourceOidc
+ }
+ err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ if err := tx.Where("user_id = ? AND source = ?", userID, models.RoleAssignmentSourceOidc).
+ Delete(&models.UserRoleAssignment{}).Error; err != nil {
+ return fmt.Errorf("failed to clear oidc assignments: %w", err)
+ }
+ if len(desired) > 0 {
+ if err := tx.Create(&desired).Error; err != nil {
+ return fmt.Errorf("failed to insert oidc assignments: %w", err)
+ }
+ }
+ count, err := s.countGlobalAdminsInternal(ctx, tx)
+ if err != nil {
+ return err
+ }
+ if count == 0 {
+ return &common.NoGlobalAdminRemainsError{}
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ s.userCache.Delete(userID)
+ return nil
+}
+
+// CountGlobalAdminsExcludingUser returns the number of distinct users (other
+// than excludedUserID) that hold a global Admin assignment. Used as the
+// authoritative check for "removing this user / demoting this assignment
+// would leave the system with no admin."
+func (s *RoleService) CountGlobalAdminsExcludingUser(ctx context.Context, excludedUserID string) (int, error) {
+ var count int64
+ if err := s.db.WithContext(ctx).
+ Model(&models.UserRoleAssignment{}).
+ Distinct("user_id").
+ Where("role_id = ? AND environment_id IS NULL AND user_id <> ?", authz.BuiltInRoleAdmin, excludedUserID).
+ Count(&count).Error; err != nil {
+ return 0, fmt.Errorf("failed to count global admins: %w", err)
+ }
+ return int(count), nil
+}
+
+func (s *RoleService) countGlobalAdminsInternal(_ context.Context, tx *gorm.DB) (int, error) {
+ var count int64
+ if err := tx.Model(&models.UserRoleAssignment{}).
+ Distinct("user_id").
+ Where("role_id = ? AND environment_id IS NULL", authz.BuiltInRoleAdmin).
+ Count(&count).Error; err != nil {
+ return 0, fmt.Errorf("failed to count global admins: %w", err)
+ }
+ return int(count), nil
+}
+
+// ---------- Permission resolution ----------
+
+// ResolvePermissions returns the effective PermissionSet for a user, caching
+// the result per-user for permissionCacheTTL.
+func (s *RoleService) ResolvePermissions(ctx context.Context, user *models.User) (*authz.PermissionSet, error) {
+ if user == nil {
+ return authz.NewPermissionSet(), nil
+ }
+ if ps, ok := s.userCache.Get(user.ID); ok {
+ return ps, nil
+ }
+ ps, err := s.resolveUserPermissionsInternal(ctx, s.db.WithContext(ctx), user.ID)
+ if err != nil {
+ return nil, err
+ }
+ s.userCache.Put(user.ID, ps)
+ return ps, nil
+}
+
+func (s *RoleService) resolveUserPermissionsInternal(_ context.Context, tx *gorm.DB, userID string) (*authz.PermissionSet, error) {
+ // Scan into raw string for the permissions JSON column to avoid GORM's
+ // schema-introspection on anonymous local structs (which can't see the
+ // type tags needed to wire models.StringSlice's Scanner).
+ type row struct {
+ Permissions string `gorm:"column:permissions"`
+ EnvironmentID *string `gorm:"column:environment_id"`
+ }
+ var rows []row
+ if err := tx.Table("user_role_assignments AS ura").
+ Select("r.permissions AS permissions, ura.environment_id AS environment_id").
+ Joins("INNER JOIN roles r ON r.id = ura.role_id").
+ Where("ura.user_id = ?", userID).
+ Scan(&rows).Error; err != nil {
+ return nil, fmt.Errorf("failed to resolve user permissions: %w", err)
+ }
+ ps := authz.NewPermissionSet()
+ for _, r := range rows {
+ perms, err := decodePermissionsJSONInternal(r.Permissions)
+ if err != nil {
+ return nil, fmt.Errorf("failed to decode role permissions: %w", err)
+ }
+ if r.EnvironmentID == nil {
+ ps.AddGlobal(perms...)
+ } else {
+ ps.AddEnv(*r.EnvironmentID, perms...)
+ }
+ }
+ return ps, nil
+}
+
+// decodePermissionsJSONInternal parses the JSON-encoded `roles.permissions` column
+// into a string slice. The column is `[]` for an empty role.
+func decodePermissionsJSONInternal(raw string) ([]string, error) {
+ if raw == "" || raw == "[]" {
+ return nil, nil
+ }
+ var out []string
+ if err := json.Unmarshal([]byte(raw), &out); err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// ResolveApiKeyPermissions returns the PermissionSet for an API key. Caches
+// per-key. Falls back to an empty set (deny-all) if the key has no perms.
+func (s *RoleService) ResolveApiKeyPermissions(ctx context.Context, apiKeyID string) (*authz.PermissionSet, error) {
+ if ps, ok := s.apiKeyCache.Get(apiKeyID); ok {
+ return ps, nil
+ }
+ var perms []models.ApiKeyPermission
+ if err := s.db.WithContext(ctx).Where("api_key_id = ?", apiKeyID).Find(&perms).Error; err != nil {
+ return nil, fmt.Errorf("failed to resolve api key permissions: %w", err)
+ }
+ ps := authz.NewPermissionSet()
+ for _, p := range perms {
+ if p.EnvironmentID == nil {
+ ps.AddGlobal(p.Permission)
+ } else {
+ ps.AddEnv(*p.EnvironmentID, p.Permission)
+ }
+ }
+ s.apiKeyCache.Put(apiKeyID, ps)
+ return ps, nil
+}
+
+// SetApiKeyPermissions replaces every permission row on the given API key
+// atomically. Validation that the granted permissions don't exceed the
+// creator's capabilities happens in the handler layer.
+func (s *RoleService) SetApiKeyPermissions(ctx context.Context, apiKeyID string, grants []models.ApiKeyPermission) error {
+ err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ return s.setApiKeyPermissionsInternal(ctx, tx, apiKeyID, grants)
+ })
+ if err != nil {
+ return err
+ }
+ s.apiKeyCache.Delete(apiKeyID)
+ return nil
+}
+
+func (s *RoleService) setApiKeyPermissionsInternal(ctx context.Context, tx *gorm.DB, apiKeyID string, grants []models.ApiKeyPermission) error {
+ for i := range grants {
+ grants[i].ApiKeyID = apiKeyID
+ }
+ if err := tx.WithContext(ctx).Where("api_key_id = ?", apiKeyID).Delete(&models.ApiKeyPermission{}).Error; err != nil {
+ return fmt.Errorf("failed to clear api key permissions: %w", err)
+ }
+ if len(grants) > 0 {
+ if err := tx.WithContext(ctx).Create(&grants).Error; err != nil {
+ return fmt.Errorf("failed to insert api key permissions: %w", err)
+ }
+ }
+ return nil
+}
+
+// ---------- OIDC role mappings ----------
+
+func (s *RoleService) ListOidcMappings(ctx context.Context) ([]models.OidcRoleMapping, error) {
+ var out []models.OidcRoleMapping
+ if err := s.db.WithContext(ctx).Order("claim_value, role_id").Find(&out).Error; err != nil {
+ return nil, fmt.Errorf("failed to list oidc mappings: %w", err)
+ }
+ return out, nil
+}
+
+func (s *RoleService) GetOidcMapping(ctx context.Context, id string) (*models.OidcRoleMapping, error) {
+ return dbutil.FirstWhere[models.OidcRoleMapping](ctx, s.db.DB, &common.OidcMappingNotFoundError{}, "id = ?", id)
+}
+
+func (s *RoleService) CreateOidcMapping(ctx context.Context, claimValue, roleID string, environmentID *string) (*models.OidcRoleMapping, error) {
+ if strings.TrimSpace(claimValue) == "" {
+ return nil, fmt.Errorf("claim value is required")
+ }
+ if strings.TrimSpace(roleID) == "" {
+ return nil, fmt.Errorf("role id is required")
+ }
+ mapping := &models.OidcRoleMapping{
+ ClaimValue: claimValue,
+ RoleID: roleID,
+ EnvironmentID: environmentID,
+ Source: models.OidcMappingSourceManual,
+ }
+ if err := s.db.WithContext(ctx).Create(mapping).Error; err != nil {
+ return nil, fmt.Errorf("failed to create oidc mapping: %w", err)
+ }
+ return mapping, nil
+}
+
+func (s *RoleService) UpdateOidcMapping(ctx context.Context, id, claimValue, roleID string, environmentID *string) (*models.OidcRoleMapping, error) {
+ var out models.OidcRoleMapping
+ err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ var existing models.OidcRoleMapping
+ if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return &common.OidcMappingNotFoundError{}
+ }
+ return fmt.Errorf("failed to load mapping: %w", err)
+ }
+ if existing.Source == models.OidcMappingSourceEnv {
+ return &common.OidcMappingEnvManagedError{}
+ }
+ existing.ClaimValue = claimValue
+ existing.RoleID = roleID
+ existing.EnvironmentID = environmentID
+ if err := tx.Save(&existing).Error; err != nil {
+ return fmt.Errorf("failed to update mapping: %w", err)
+ }
+ out = existing
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ return &out, nil
+}
+
+func (s *RoleService) DeleteOidcMapping(ctx context.Context, id string) error {
+ return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ var existing models.OidcRoleMapping
+ if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return &common.OidcMappingNotFoundError{}
+ }
+ return fmt.Errorf("failed to load mapping: %w", err)
+ }
+ if existing.Source == models.OidcMappingSourceEnv {
+ return &common.OidcMappingEnvManagedError{}
+ }
+ if err := tx.Delete(&models.OidcRoleMapping{}, "id = ?", id).Error; err != nil {
+ return fmt.Errorf("failed to delete mapping: %w", err)
+ }
+ return nil
+ })
+}
+
+// ReconcileEnvOidcMappings replaces every source='env' row in oidc_role_mappings
+// with the set declared by `rawSpec` (a JSON array of role.OidcRoleMappingSpec).
+// Called once at boot. Behavior is declarative:
+//
+// - rawSpec empty / unset → leaves DB rows alone (purely UI-managed mode).
+// - rawSpec is `[]` → wipes any previously-env-managed rows.
+// - rawSpec is a valid JSON array → upserts each spec, deletes stale env rows.
+//
+// Manual rows (source='manual') are never touched. Bad JSON or an unknown role
+// ID returns an error so a misconfigured deployment fails loudly rather than
+// silently dropping mappings.
+func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec string) error {
+ rawSpec = strings.TrimSpace(rawSpec)
+ if rawSpec == "" {
+ return nil
+ }
+ var specs []roletypes.OidcRoleMappingSpec
+ if err := json.Unmarshal([]byte(rawSpec), &specs); err != nil {
+ return fmt.Errorf("invalid OIDC_ROLE_MAPPINGS JSON: %w", err)
+ }
+ for i, sp := range specs {
+ if strings.TrimSpace(sp.ClaimValue) == "" {
+ return fmt.Errorf("OIDC_ROLE_MAPPINGS[%d]: claimValue is required", i)
+ }
+ if strings.TrimSpace(sp.RoleID) == "" {
+ return fmt.Errorf("OIDC_ROLE_MAPPINGS[%d]: roleId is required", i)
+ }
+ }
+
+ return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ // Verify every referenced role exists. Done inside the tx so a concurrent
+ // role delete can't race past this check.
+ for i, sp := range specs {
+ var count int64
+ if err := tx.Model(&models.Role{}).Where("id = ?", sp.RoleID).Count(&count).Error; err != nil {
+ return fmt.Errorf("OIDC_ROLE_MAPPINGS[%d]: failed to verify role: %w", i, err)
+ }
+ if count == 0 {
+ return fmt.Errorf("OIDC_ROLE_MAPPINGS[%d]: role %q does not exist", i, sp.RoleID)
+ }
+ }
+
+ // Declarative replace: drop every env-managed row, then insert the new
+ // set. Manual rows are untouched.
+ if err := tx.Where("source = ?", models.OidcMappingSourceEnv).Delete(&models.OidcRoleMapping{}).Error; err != nil {
+ return fmt.Errorf("failed to clear env-managed mappings: %w", err)
+ }
+ if len(specs) == 0 {
+ slog.InfoContext(ctx, "OIDC_ROLE_MAPPINGS reconciled (empty)", "envManagedCount", 0)
+ return nil
+ }
+ rows := make([]models.OidcRoleMapping, len(specs))
+ for i, sp := range specs {
+ rows[i] = models.OidcRoleMapping{
+ ClaimValue: sp.ClaimValue,
+ RoleID: sp.RoleID,
+ EnvironmentID: sp.EnvironmentID,
+ Source: models.OidcMappingSourceEnv,
+ }
+ }
+ if err := tx.Create(&rows).Error; err != nil {
+ return fmt.Errorf("failed to insert env-managed mappings: %w", err)
+ }
+ slog.InfoContext(ctx, "OIDC_ROLE_MAPPINGS reconciled", "envManagedCount", len(rows))
+ return nil
+ })
+}
+
+// ---------- Cache helpers ----------
+
+// InvalidateUser drops the cached PermissionSet for one user. Called from
+// auth_service after a login that mutates assignments, and from any mutation
+// path that doesn't already invalidate explicitly.
+func (s *RoleService) InvalidateUser(userID string) {
+ s.userCache.Delete(userID)
+}
+
+// InvalidateApiKey drops the cached PermissionSet for one API key.
+func (s *RoleService) InvalidateApiKey(apiKeyID string) {
+ s.apiKeyCache.Delete(apiKeyID)
+}
+
+// invalidateUsersAssignedToInternal invalidates every user holding an assignment to
+// the given role. Called after a role's permissions change.
+func (s *RoleService) invalidateUsersAssignedToInternal(ctx context.Context, roleID string) {
+ var userIDs []string
+ if err := s.db.WithContext(ctx).
+ Model(&models.UserRoleAssignment{}).
+ Distinct("user_id").
+ Where("role_id = ?", roleID).
+ Pluck("user_id", &userIDs).Error; err != nil {
+ slog.WarnContext(ctx, "failed to collect users for cache invalidation", "error", err, "role_id", roleID)
+ return
+ }
+ for _, id := range userIDs {
+ s.userCache.Delete(id)
+ }
+}
+
+// ---------- helpers ----------
+
+func validatePermissionsInternal(perms []string) error {
+ for _, p := range perms {
+ if !authz.IsKnownPermission(p) {
+ return &common.UnknownPermissionError{Perm: p}
+ }
+ }
+ return nil
+}
+
+// ValidatePermissionsAgainstCaller rejects any permission in `desired` that the
+// caller does not hold at global scope. Sudo callers (agent / env access
+// tokens, bootstrap paths) bypass entirely. Holding a permission only inside a
+// specific environment is intentionally insufficient: roles are reusable
+// templates that can later be assigned globally, so an env-scoped grant must
+// not let the caller mint a global-capable role.
+//
+// Unknown permission strings are rejected first with an UnknownPermissionError
+// so a caller typo-ing a permission gets a descriptive 400 instead of a
+// misleading 403 from the escalation guard below (which would always fire on
+// an unknown perm because no PermissionSet contains it). This also gives the
+// escalation loop a clean invariant: every perm reaching it is real.
+//
+// Callers should run this before persisting role permissions to defend against
+// privilege escalation if the role mutation endpoints are ever exposed beyond
+// global admins.
+func (s *RoleService) ValidatePermissionsAgainstCaller(caller *authz.PermissionSet, desired []string) error {
+ if err := validatePermissionsInternal(desired); err != nil {
+ return err
+ }
+ if caller == nil {
+ if len(desired) == 0 {
+ return nil
+ }
+ return &common.RolePermissionEscalationError{Perm: desired[0]}
+ }
+ if caller.Sudo {
+ return nil
+ }
+ for _, p := range desired {
+ if !caller.Allows(p, "") {
+ return &common.RolePermissionEscalationError{Perm: p}
+ }
+ }
+ return nil
+}
diff --git a/backend/internal/services/role_service_test.go b/backend/internal/services/role_service_test.go
new file mode 100644
index 000000000..8b60f70aa
--- /dev/null
+++ b/backend/internal/services/role_service_test.go
@@ -0,0 +1,104 @@
+package services
+
+import (
+ "context"
+ "slices"
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
+ "github.com/stretchr/testify/require"
+)
+
+func TestBackfillPermsForKeyDeduplicatesGlobalAndEnvironmentPermissions(t *testing.T) {
+ ctx := context.Background()
+ userSvc, roleSvc := setupUserAndRoleServices(t)
+ admin := createTestUser(t, userSvc, "admin", "admin")
+ grantGlobalAdmin(t, roleSvc, admin.ID)
+ user := createTestUser(t, userSvc, "api-key-owner", "api-key-owner")
+ envID := "env-1"
+ createTestEnvironment(t, roleSvc.db, envID, "http://localhost:3552", nil)
+
+ require.NoError(t, roleSvc.SetUserAssignments(ctx, user.ID, []models.UserRoleAssignment{
+ {RoleID: authz.BuiltInRoleViewer, EnvironmentID: nil},
+ {RoleID: authz.BuiltInRoleEditor, EnvironmentID: &envID},
+ }))
+
+ perms, err := roleSvc.backfillPermsForKeyInternal(ctx, roleSvc.db.WithContext(ctx), models.ApiKey{
+ UserID: &user.ID,
+ EnvironmentID: &envID,
+ })
+ require.NoError(t, err)
+ require.Contains(t, perms, authz.PermContainersList)
+ require.Equal(t, 1, countPermissionInternal(perms, authz.PermContainersList))
+}
+
+func countPermissionInternal(perms []string, permission string) int {
+ return len(slices.DeleteFunc(slices.Clone(perms), func(p string) bool {
+ return p != permission
+ }))
+}
+
+func TestValidatePermissionsAgainstCallerRejectsEscalation(t *testing.T) {
+ _, roleSvc := setupUserAndRoleServices(t)
+
+ caller := authz.NewPermissionSet()
+ caller.AddGlobal(authz.PermRolesRead, authz.PermRolesList)
+
+ err := roleSvc.ValidatePermissionsAgainstCaller(caller, []string{
+ authz.PermRolesRead,
+ authz.PermUsersDelete,
+ })
+ require.Error(t, err)
+ require.True(t, common.IsRolePermissionEscalationError(err))
+
+ require.NoError(t, roleSvc.ValidatePermissionsAgainstCaller(caller, []string{authz.PermRolesRead}))
+ require.NoError(t, roleSvc.ValidatePermissionsAgainstCaller(authz.SudoPermissionSet(), []string{authz.PermUsersDelete}))
+}
+
+func TestValidatePermissionsAgainstCallerRejectsEnvOnlyGrantForGlobalRole(t *testing.T) {
+ _, roleSvc := setupUserAndRoleServices(t)
+
+ caller := authz.NewPermissionSet()
+ caller.AddEnv("env-1", authz.PermContainersStart)
+
+ err := roleSvc.ValidatePermissionsAgainstCaller(caller, []string{authz.PermContainersStart})
+ require.Error(t, err)
+ require.True(t, common.IsRolePermissionEscalationError(err))
+}
+
+func TestValidatePermissionsAgainstCallerRejectsUnknownPermissionBeforeEscalation(t *testing.T) {
+ _, roleSvc := setupUserAndRoleServices(t)
+
+ // A sudo caller would otherwise short-circuit past the escalation loop;
+ // unknown perms must still surface as UnknownPermissionError (→ 400),
+ // not as an opaque escalation 403 or a silent pass.
+ err := roleSvc.ValidatePermissionsAgainstCaller(authz.SudoPermissionSet(), []string{"containrs:start"})
+ require.Error(t, err)
+ require.True(t, common.IsUnknownPermissionError(err))
+ require.False(t, common.IsRolePermissionEscalationError(err))
+}
+
+func TestBackfillLegacyRoleAssignmentsIsNoOpWhenColumnAbsent(t *testing.T) {
+ ctx := context.Background()
+ _, roleSvc := setupUserAndRoleServices(t)
+ // setupUserAndRoleServices runs migrations through to current, so
+ // users.roles never exists in the fresh test schema.
+ require.False(t, roleSvc.db.Migrator().HasColumn("users", "roles"))
+ require.NoError(t, roleSvc.BackfillLegacyRoleAssignments(ctx))
+ // Idempotent — second call is also fine.
+ require.NoError(t, roleSvc.BackfillLegacyRoleAssignments(ctx))
+}
+
+func TestSetUserAssignmentsRejectsUnknownRole(t *testing.T) {
+ ctx := context.Background()
+ userSvc, roleSvc := setupUserAndRoleServices(t)
+ user := createTestUser(t, userSvc, "victim", "victim")
+
+ err := roleSvc.SetUserAssignments(ctx, user.ID, []models.UserRoleAssignment{
+ {RoleID: "role_does_not_exist"},
+ })
+ require.Error(t, err)
+ require.True(t, common.IsInvalidRoleAssignmentError(err))
+}
diff --git a/backend/internal/services/session_service_test.go b/backend/internal/services/session_service_test.go
index 31fca49fe..c4e5e9a5f 100644
--- a/backend/internal/services/session_service_test.go
+++ b/backend/internal/services/session_service_test.go
@@ -17,7 +17,6 @@ func TestSessionService_RotateRefreshTokenRequiresCurrentHash(t *testing.T) {
require.NoError(t, userSvc.db.Create(&models.User{
BaseModel: models.BaseModel{ID: "u-session"},
Username: "session-user",
- Roles: models.StringSlice{"user"},
}).Error)
sessionSvc := NewSessionService(db)
@@ -41,7 +40,6 @@ func TestSessionService_DeleteExpiredSessions(t *testing.T) {
require.NoError(t, userSvc.db.Create(&models.User{
BaseModel: models.BaseModel{ID: "u-cleanup"},
Username: "cleanup-user",
- Roles: models.StringSlice{"user"},
}).Error)
sessionSvc := NewSessionService(db)
diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.go
index 0abf07f03..c085928f0 100644
--- a/backend/internal/services/settings_service.go
+++ b/backend/internal/services/settings_service.go
@@ -168,8 +168,7 @@ func DefaultSettingsConfig() *models.Settings {
OidcUserinfoEndpoint: models.SettingVariable{Value: ""},
OidcJwksEndpoint: models.SettingVariable{Value: ""},
OidcScopes: models.SettingVariable{Value: "openid email profile"},
- OidcAdminClaim: models.SettingVariable{Value: ""},
- OidcAdminValue: models.SettingVariable{Value: ""},
+ OidcGroupsClaim: models.SettingVariable{Value: "groups"},
OidcSkipTlsVerify: models.SettingVariable{Value: "false"},
OidcAutoRedirectToProvider: models.SettingVariable{Value: "false"},
OidcMergeAccounts: models.SettingVariable{Value: "false"},
diff --git a/backend/internal/services/user_service.go b/backend/internal/services/user_service.go
index 7a34d7389..93149354e 100644
--- a/backend/internal/services/user_service.go
+++ b/backend/internal/services/user_service.go
@@ -17,6 +17,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/getarcaneapp/arcane/backend/pkg/utils/dbutil"
"github.com/getarcaneapp/arcane/types/user"
@@ -42,6 +43,7 @@ func DefaultArgon2Params() *Argon2Params {
type UserService struct {
db *database.DB
+ roleService *RoleService
argon2Params *Argon2Params
}
@@ -54,6 +56,14 @@ func NewUserService(db *database.DB) *UserService {
}
}
+// WithRoleService wires the RoleService dependency. Separated from the
+// constructor so the bootstrap can construct UserService first (RoleService
+// itself has no UserService dependency).
+func (s *UserService) WithRoleService(roleService *RoleService) *UserService {
+ s.roleService = roleService
+ return s
+}
+
func (s *UserService) hashPassword(password string) (string, error) {
salt := make([]byte, s.argon2Params.saltLength)
_, err := rand.Read(salt)
@@ -163,27 +173,15 @@ func (s *UserService) GetUserByEmail(ctx context.Context, email string) (*models
func (s *UserService) UpdateUser(ctx context.Context, user *models.User) (*models.User, error) {
err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
- var existing models.User
if err := tx.
Clauses(clause.Locking{Strength: "UPDATE"}).
Where("id = ?", user.ID).
- First(&existing).Error; err != nil {
+ First(&models.User{}).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrUserNotFound
}
return fmt.Errorf("failed to load user: %w", err)
}
-
- if userHasRoleInternal(existing.Roles, "admin") && !userHasRoleInternal(user.Roles, "admin") {
- remainingAdmins, err := s.remainingAdminCountExcludingUserInternal(tx, user.ID)
- if err != nil {
- return err
- }
- if remainingAdmins == 0 {
- return ErrCannotRemoveLastAdmin
- }
- }
-
if err := tx.Save(user).Error; err != nil {
return fmt.Errorf("failed to update user: %w", err)
}
@@ -251,64 +249,127 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {
return fmt.Errorf("failed to hash default admin password: %w", err)
}
- return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ // Step 1: ensure the default admin user row exists. If the users table is
+ // empty we create it; otherwise we find the existing `arcane` user (if any).
+ // Either way the role assignment is reconciled below — idempotently — so
+ // upgrades from older builds that didn't grant the role get patched up.
+ var adminUserID string
+ err = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
var count int64
if err := tx.Model(&models.User{}).Count(&count).Error; err != nil {
return fmt.Errorf("failed to count users: %w", err)
}
- if count > 0 {
- slog.WarnContext(ctx, "Users already exist, skipping default admin creation")
+ if count == 0 {
+ email := "admin@localhost"
+ displayName := "Arcane Admin"
+ userModel := &models.User{
+ Username: "arcane",
+ Email: new(email),
+ DisplayName: new(displayName),
+ PasswordHash: hashedPassword,
+ RequiresPasswordChange: true,
+ }
+ if err := tx.Create(userModel).Error; err != nil {
+ return fmt.Errorf("failed to create default admin user: %w", err)
+ }
+ adminUserID = userModel.ID
+ slog.InfoContext(ctx, "👑 Default admin user created!")
+ slog.InfoContext(ctx, "🔑 Username: arcane")
+ slog.InfoContext(ctx, "🔑 Password: arcane-admin")
+ slog.InfoContext(ctx, "⚠️ User will be prompted to change password on first login")
return nil
}
- email := "admin@localhost"
- displayName := "Arcane Admin"
- userModel := &models.User{
- Username: "arcane",
- Email: new(email),
- DisplayName: new(displayName),
- PasswordHash: hashedPassword,
- Roles: models.StringSlice{"admin"},
- RequiresPasswordChange: true,
- }
-
- if err := tx.Create(userModel).Error; err != nil {
- return fmt.Errorf("failed to create default admin user: %w", err)
+ // Users already exist — see if `arcane` is one of them. If not,
+ // someone removed the default admin on purpose and we leave it alone.
+ var existing models.User
+ err := tx.Where("username = ?", "arcane").First(&existing).Error
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil
+ }
+ return fmt.Errorf("failed to look up default admin user: %w", err)
}
+ adminUserID = existing.ID
+ return nil
+ })
+ if err != nil {
+ return err
+ }
- slog.InfoContext(ctx, "👑 Default admin user created!")
- slog.InfoContext(ctx, "🔑 Username: arcane")
- slog.InfoContext(ctx, "🔑 Password: arcane-admin")
- slog.InfoContext(ctx, "⚠️ User will be prompted to change password on first login")
-
+ if adminUserID == "" || s.roleService == nil {
return nil
+ }
+
+ // Step 2: ensure the default admin holds the global Admin role assignment.
+ // Idempotent — if the assignment already exists, SetUserAssignments is a
+ // no-op write (it dedupes via the unique index). This recovers users that
+ // were created by older builds before the role-grant on bootstrap was
+ // wired up.
+ assignments, err := s.roleService.ListUserAssignments(ctx, adminUserID)
+ if err != nil {
+ return fmt.Errorf("failed to list default admin assignments: %w", err)
+ }
+ for _, a := range assignments {
+ if a.RoleID == authz.BuiltInRoleAdmin && a.EnvironmentID == nil {
+ return nil // already has it
+ }
+ }
+ desired := append([]models.UserRoleAssignment{}, assignments...)
+ desired = append(desired, models.UserRoleAssignment{
+ RoleID: authz.BuiltInRoleAdmin,
+ EnvironmentID: nil,
})
+ // Strip the source field so SetUserAssignments classifies everything as manual.
+ manual := make([]models.UserRoleAssignment, 0, len(desired))
+ for _, a := range desired {
+ manual = append(manual, models.UserRoleAssignment{RoleID: a.RoleID, EnvironmentID: a.EnvironmentID})
+ }
+ if err := s.roleService.SetUserAssignments(ctx, adminUserID, manual); err != nil {
+ return fmt.Errorf("failed to grant default admin global role: %w", err)
+ }
+ slog.InfoContext(ctx, "Default admin granted global Admin role assignment", "user_id", adminUserID)
+ return nil
}
func (s *UserService) DeleteUser(ctx context.Context, id string) error {
+ // Last-admin guard: if this user holds the only global Admin assignment,
+ // refuse the delete. Checked OUTSIDE the transaction because RoleService
+ // uses its own session — and the guard is informational only (the unique
+ // index in user_role_assignments wouldn't catch this cross-row condition).
+ if s.roleService != nil {
+ var holdsGlobalAdmin bool
+ assignments, err := s.roleService.ListUserAssignments(ctx, id)
+ if err == nil {
+ for _, a := range assignments {
+ if a.RoleID == authz.BuiltInRoleAdmin && a.EnvironmentID == nil {
+ holdsGlobalAdmin = true
+ break
+ }
+ }
+ }
+ if holdsGlobalAdmin {
+ remaining, err := s.roleService.CountGlobalAdminsExcludingUser(ctx, id)
+ if err != nil {
+ return err
+ }
+ if remaining == 0 {
+ return ErrCannotRemoveLastAdmin
+ }
+ }
+ }
return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
- var existing models.User
if err := tx.
Clauses(clause.Locking{Strength: "UPDATE"}).
Where("id = ?", id).
- First(&existing).Error; err != nil {
+ First(&models.User{}).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrUserNotFound
}
return fmt.Errorf("failed to load user: %w", err)
}
- if userHasRoleInternal(existing.Roles, "admin") {
- remainingAdmins, err := s.remainingAdminCountExcludingUserInternal(tx, id)
- if err != nil {
- return err
- }
- if remainingAdmins == 0 {
- return ErrCannotRemoveLastAdmin
- }
- }
-
if err := tx.Delete(&models.User{}, "id = ?", id).Error; err != nil {
return fmt.Errorf("failed to delete user: %w", err)
}
@@ -366,46 +427,90 @@ func (s *UserService) ListUsersPaginated(ctx context.Context, params pagination.
}
func (s *UserService) ToUserResponseDto(ctx context.Context, u models.User) (user.User, error) {
- if !userHasRoleInternal(u.Roles, "admin") {
- return toUserResponseDtoInternal(u, 0), nil
- }
-
- adminCount, err := s.adminUserCountInternal(ctx)
- if err != nil {
- return user.User{}, err
- }
-
- return toUserResponseDtoInternal(u, adminCount), nil
+ return s.toUserResponseDtoInternal(ctx, u), nil
}
func (s *UserService) toUserResponseDtosInternal(ctx context.Context, users []models.User) ([]user.User, error) {
- adminCount, err := s.adminUserCountInternal(ctx)
- if err != nil {
- return nil, err
- }
-
result := make([]user.User, len(users))
for i, u := range users {
- result[i] = toUserResponseDtoInternal(u, adminCount)
+ result[i] = s.toUserResponseDtoInternal(ctx, u)
}
-
return result, nil
}
-func toUserResponseDtoInternal(u models.User, adminCount int) user.User {
- return user.User{
+// toUserResponseDtoInternal builds the public User DTO. RoleAssignments and
+// PermissionsByEnv come from the RBAC service. CanDelete is false when this
+// user holds the only global Admin assignment (i.e. removing them would orphan
+// the instance).
+func (s *UserService) toUserResponseDtoInternal(ctx context.Context, u models.User) user.User {
+ dto := user.User{
ID: u.ID,
Username: u.Username,
DisplayName: u.DisplayName,
Email: u.Email,
- Roles: u.Roles,
- CanDelete: !userHasRoleInternal(u.Roles, "admin") || adminCount > 1,
+ CanDelete: true,
OidcSubjectId: u.OidcSubjectId,
Locale: u.Locale,
RequiresPasswordChange: u.RequiresPasswordChange,
CreatedAt: u.CreatedAt.Format("2006-01-02T15:04:05.999999Z"),
UpdatedAt: u.UpdatedAt.Format("2006-01-02T15:04:05.999999Z"),
+ RoleAssignments: []user.RoleAssignmentSummary{},
+ PermissionsByEnv: map[string][]string{},
+ }
+ if s.roleService == nil {
+ return dto
+ }
+ if rows, err := s.roleService.ListUserAssignments(ctx, u.ID); err == nil {
+ dto.RoleAssignments = make([]user.RoleAssignmentSummary, len(rows))
+ for i, r := range rows {
+ dto.RoleAssignments[i] = user.RoleAssignmentSummary{
+ RoleID: r.RoleID,
+ EnvironmentID: r.EnvironmentID,
+ Source: r.Source,
+ }
+ // Last-admin guard: this user is non-deletable if they hold the
+ // only global Admin assignment.
+ if r.RoleID == authz.BuiltInRoleAdmin && r.EnvironmentID == nil {
+ if remaining, cerr := s.roleService.CountGlobalAdminsExcludingUser(ctx, u.ID); cerr == nil && remaining == 0 {
+ dto.CanDelete = false
+ }
+ }
+ }
+ }
+ if ps, err := s.roleService.ResolvePermissions(ctx, &u); err == nil && ps != nil {
+ dto.PermissionsByEnv = permissionSetToMap(ps)
+ }
+ return dto
+}
+
+// permissionSetToMap flattens a PermissionSet into the wire format consumed
+// by the frontend: a map from environment ID (or "global") to a list of
+// permission strings. Sudo callers expose "*" under "global" as a sentinel
+// meaning "every permission".
+func permissionSetToMap(ps *authz.PermissionSet) map[string][]string {
+ out := map[string][]string{}
+ if ps == nil {
+ return out
}
+ if ps.Sudo {
+ out["global"] = []string{"*"}
+ return out
+ }
+ if len(ps.Global) > 0 {
+ globals := make([]string, 0, len(ps.Global))
+ for p := range ps.Global {
+ globals = append(globals, p)
+ }
+ out["global"] = globals
+ }
+ for envID, perms := range ps.PerEnv {
+ list := make([]string, 0, len(perms))
+ for p := range perms {
+ list = append(list, p)
+ }
+ out[envID] = list
+ }
+ return out
}
func (s *UserService) GetUser(ctx context.Context, userID string) (*models.User, error) {
@@ -422,49 +527,3 @@ func (s *UserService) getUserInternal(ctx context.Context, userID string, tx *go
Error
return &user, err
}
-
-func (s *UserService) remainingAdminCountExcludingUserInternal(tx *gorm.DB, excludedUserID string) (int, error) {
- var count int64
- if err := s.adminUsersScopeInternal(tx.Model(&models.User{}).Where("id <> ?", excludedUserID)).Count(&count).Error; err != nil {
- return 0, fmt.Errorf("failed to count remaining admin users: %w", err)
- }
-
- return int(count), nil
-}
-
-func userHasRoleInternal(roles models.StringSlice, role string) bool {
- for _, currentRole := range roles {
- if strings.EqualFold(currentRole, role) {
- return true
- }
- }
-
- return false
-}
-
-func (s *UserService) adminUserCountInternal(ctx context.Context) (int, error) {
- var count int64
- if err := s.adminUsersScopeInternal(s.db.WithContext(ctx).Model(&models.User{})).Count(&count).Error; err != nil {
- return 0, fmt.Errorf("failed to count admin users: %w", err)
- }
-
- return int(count), nil
-}
-
-func (s *UserService) adminUsersScopeInternal(query *gorm.DB) *gorm.DB {
- switch s.db.Name() {
- case "sqlite":
- return query.Where(
- "EXISTS (SELECT 1 FROM json_each(users.roles) WHERE lower(json_each.value) = ?)",
- "admin",
- )
- case "postgres":
- return query.Where(
- "EXISTS (SELECT 1 FROM jsonb_array_elements_text(users.roles::jsonb) AS role WHERE lower(role) = ?)",
- "admin",
- )
- default:
- slog.Warn("Using LIKE-based admin role query fallback for unsupported database dialect", "dialect", s.db.Name())
- return query.Where("LOWER(roles) LIKE ?", `%\"admin\"%`)
- }
-}
diff --git a/backend/internal/services/user_service_test.go b/backend/internal/services/user_service_test.go
index 7d0e1da1d..e82054f77 100644
--- a/backend/internal/services/user_service_test.go
+++ b/backend/internal/services/user_service_test.go
@@ -5,114 +5,95 @@ import (
"testing"
"github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/pkg/authz"
"github.com/getarcaneapp/arcane/backend/pkg/pagination"
"github.com/stretchr/testify/require"
)
-func createTestUser(t *testing.T, svc *UserService, id, username string, roles models.StringSlice) *models.User {
+// setupUserAndRoleServices wires both services together the way bootstrap
+// does, so the legacy-admin-guard tests exercise the real RBAC path.
+func setupUserAndRoleServices(t *testing.T) (*UserService, *RoleService) {
t.Helper()
+ db := setupAuthServiceTestDB(t)
+ role := NewRoleService(db)
+ require.NoError(t, role.EnsureBuiltInRoles(context.Background()))
+ user := NewUserService(db).WithRoleService(role)
+ return user, role
+}
- user := &models.User{
+func createTestUser(t *testing.T, svc *UserService, id, username string) *models.User {
+ t.Helper()
+ created, err := svc.CreateUser(context.Background(), &models.User{
BaseModel: models.BaseModel{ID: id},
Username: username,
- Roles: roles,
- }
-
- created, err := svc.CreateUser(context.Background(), user)
+ })
require.NoError(t, err)
-
return created
}
+// grantGlobalAdmin assigns the built-in Admin role globally to the user.
+func grantGlobalAdmin(t *testing.T, role *RoleService, userID string) {
+ t.Helper()
+ require.NoError(t, role.SetUserAssignments(context.Background(), userID, []models.UserRoleAssignment{
+ {RoleID: authz.BuiltInRoleAdmin, EnvironmentID: nil},
+ }))
+}
+
func TestDeleteUserRejectsDeletingOnlyAdmin(t *testing.T) {
- db := setupAuthServiceTestDB(t)
- svc := NewUserService(db)
+ userSvc, roleSvc := setupUserAndRoleServices(t)
ctx := context.Background()
- admin := createTestUser(t, svc, "admin-1", "arcane", models.StringSlice{"Admin"})
+ admin := createTestUser(t, userSvc, "admin-1", "arcane")
+ grantGlobalAdmin(t, roleSvc, admin.ID)
- err := svc.DeleteUser(ctx, admin.ID)
+ err := userSvc.DeleteUser(ctx, admin.ID)
require.ErrorIs(t, err, ErrCannotRemoveLastAdmin)
- stillThere, err := svc.GetUserByID(ctx, admin.ID)
+ stillThere, err := userSvc.GetUserByID(ctx, admin.ID)
require.NoError(t, err)
require.Equal(t, admin.ID, stillThere.ID)
}
func TestDeleteUserAllowsDeletingNonAdmin(t *testing.T) {
- db := setupAuthServiceTestDB(t)
- svc := NewUserService(db)
+ userSvc, roleSvc := setupUserAndRoleServices(t)
ctx := context.Background()
- createTestUser(t, svc, "admin-1", "arcane", models.StringSlice{"admin"})
- nonAdmin := createTestUser(t, svc, "user-1", "user", models.StringSlice{"user"})
+ admin := createTestUser(t, userSvc, "admin-1", "arcane")
+ grantGlobalAdmin(t, roleSvc, admin.ID)
+ nonAdmin := createTestUser(t, userSvc, "user-1", "user")
- err := svc.DeleteUser(ctx, nonAdmin.ID)
+ err := userSvc.DeleteUser(ctx, nonAdmin.ID)
require.NoError(t, err)
- _, err = svc.GetUserByID(ctx, nonAdmin.ID)
+ _, err = userSvc.GetUserByID(ctx, nonAdmin.ID)
require.ErrorIs(t, err, ErrUserNotFound)
}
func TestDeleteUserAllowsDeletingAdminWhenAnotherAdminExists(t *testing.T) {
- db := setupAuthServiceTestDB(t)
- svc := NewUserService(db)
+ userSvc, roleSvc := setupUserAndRoleServices(t)
ctx := context.Background()
- adminToDelete := createTestUser(t, svc, "admin-1", "arcane", models.StringSlice{"Admin"})
- createTestUser(t, svc, "admin-2", "backup", models.StringSlice{"admin"})
+ adminToDelete := createTestUser(t, userSvc, "admin-1", "arcane")
+ grantGlobalAdmin(t, roleSvc, adminToDelete.ID)
+ backup := createTestUser(t, userSvc, "admin-2", "backup")
+ grantGlobalAdmin(t, roleSvc, backup.ID)
- err := svc.DeleteUser(ctx, adminToDelete.ID)
+ err := userSvc.DeleteUser(ctx, adminToDelete.ID)
require.NoError(t, err)
- _, err = svc.GetUserByID(ctx, adminToDelete.ID)
+ _, err = userSvc.GetUserByID(ctx, adminToDelete.ID)
require.ErrorIs(t, err, ErrUserNotFound)
}
-func TestUpdateUserRejectsRemovingAdminFromOnlyAdmin(t *testing.T) {
- db := setupAuthServiceTestDB(t)
- svc := NewUserService(db)
- ctx := context.Background()
-
- admin := createTestUser(t, svc, "admin-1", "arcane", models.StringSlice{"ADMIN"})
- admin.Roles = models.StringSlice{"user"}
-
- _, err := svc.UpdateUser(ctx, admin)
- require.ErrorIs(t, err, ErrCannotRemoveLastAdmin)
-
- persisted, err := svc.GetUserByID(ctx, admin.ID)
- require.NoError(t, err)
- require.Equal(t, models.StringSlice{"ADMIN"}, persisted.Roles)
-}
-
-func TestUpdateUserAllowsRemovingAdminWhenAnotherAdminExists(t *testing.T) {
- db := setupAuthServiceTestDB(t)
- svc := NewUserService(db)
- ctx := context.Background()
-
- admin := createTestUser(t, svc, "admin-1", "arcane", models.StringSlice{"admin"})
- createTestUser(t, svc, "admin-2", "backup", models.StringSlice{"ADMIN"})
-
- admin.Roles = models.StringSlice{"user"}
-
- updated, err := svc.UpdateUser(ctx, admin)
- require.NoError(t, err)
- require.Equal(t, models.StringSlice{"user"}, updated.Roles)
-
- persisted, err := svc.GetUserByID(ctx, admin.ID)
- require.NoError(t, err)
- require.Equal(t, models.StringSlice{"user"}, persisted.Roles)
-}
-
func TestListUsersPaginatedSetsCanDeleteFromGlobalAdminCount(t *testing.T) {
- db := setupAuthServiceTestDB(t)
- svc := NewUserService(db)
+ userSvc, roleSvc := setupUserAndRoleServices(t)
ctx := context.Background()
- lastAdmin := createTestUser(t, svc, "admin-1", "arcane", models.StringSlice{"admin"})
- nonAdmin := createTestUser(t, svc, "user-1", "user", models.StringSlice{"user"})
+ lastAdmin := createTestUser(t, userSvc, "admin-1", "arcane")
+ grantGlobalAdmin(t, roleSvc, lastAdmin.ID)
+ nonAdmin := createTestUser(t, userSvc, "user-1", "user")
- users, _, err := svc.ListUsersPaginated(ctx, pagination.QueryParams{
+ users, _, err := userSvc.ListUsersPaginated(ctx, pagination.QueryParams{
PaginationParams: pagination.PaginationParams{Start: 0, Limit: 20},
SortParams: pagination.SortParams{Sort: "Username", Order: pagination.SortOrder("asc")},
Filters: map[string]string{},
diff --git a/backend/pkg/authz/catalog.go b/backend/pkg/authz/catalog.go
new file mode 100644
index 000000000..54205d6ea
--- /dev/null
+++ b/backend/pkg/authz/catalog.go
@@ -0,0 +1,204 @@
+package authz
+
+const (
+ PermissionScopeGlobal = "global"
+ PermissionScopeEnv = "env"
+)
+
+// PermissionCatalogResource describes a resource group in the permission
+// catalog. It is the authz-owned source for permission ordering, scope, and
+// display metadata used by API manifests and validation helpers.
+type PermissionCatalogResource struct {
+ Key string
+ Label string
+ Scope string
+ Actions []PermissionCatalogAction
+}
+
+// PermissionCatalogAction describes one recognized permission.
+type PermissionCatalogAction struct {
+ Key string
+ Permission string
+ Label string
+ Description string
+}
+
+var permissionCatalog = []PermissionCatalogResource{
+ {"users", "Users", PermissionScopeGlobal, []PermissionCatalogAction{
+ {"list", PermUsersList, "List", ""},
+ {"read", PermUsersRead, "Read", ""},
+ {"create", PermUsersCreate, "Create", ""},
+ {"update", PermUsersUpdate, "Update", ""},
+ {"delete", PermUsersDelete, "Delete", ""},
+ }},
+ {"roles", "Roles", PermissionScopeGlobal, []PermissionCatalogAction{
+ {"list", PermRolesList, "List", ""},
+ {"read", PermRolesRead, "Read", ""},
+ }},
+ {"apikeys", "API Keys", PermissionScopeGlobal, []PermissionCatalogAction{
+ {"list", PermApiKeysList, "List", ""},
+ {"read", PermApiKeysRead, "Read", ""},
+ {"create", PermApiKeysCreate, "Create", ""},
+ {"update", PermApiKeysUpdate, "Update", ""},
+ {"delete", PermApiKeysDelete, "Delete", ""},
+ }},
+ {"settings", "Settings", PermissionScopeGlobal, []PermissionCatalogAction{
+ {"read", PermSettingsRead, "Read", ""},
+ {"write", PermSettingsWrite, "Write", ""},
+ }},
+ {"environments", "Environments", PermissionScopeGlobal, []PermissionCatalogAction{
+ {"list", PermEnvironmentsList, "List", ""},
+ {"read", PermEnvironmentsRead, "Read", ""},
+ {"create", PermEnvironmentsCreate, "Create", ""},
+ {"update", PermEnvironmentsUpdate, "Update", ""},
+ {"delete", PermEnvironmentsDelete, "Delete", ""},
+ {"pair", PermEnvironmentsPair, "Pair agent", ""},
+ {"sync", PermEnvironmentsSync, "Sync heartbeat", ""},
+ }},
+ {"registries", "Container Registries", PermissionScopeGlobal, []PermissionCatalogAction{
+ {"list", PermRegistriesList, "List", ""},
+ {"read", PermRegistriesRead, "Read", ""},
+ {"create", PermRegistriesCreate, "Create", ""},
+ {"update", PermRegistriesUpdate, "Update", ""},
+ {"delete", PermRegistriesDelete, "Delete", ""},
+ {"test", PermRegistriesTest, "Test", ""},
+ }},
+ {"templates", "Templates", PermissionScopeGlobal, []PermissionCatalogAction{
+ {"list", PermTemplatesList, "List", ""},
+ {"read", PermTemplatesRead, "Read", ""},
+ {"create", PermTemplatesCreate, "Create", ""},
+ {"update", PermTemplatesUpdate, "Update", ""},
+ {"delete", PermTemplatesDelete, "Delete", ""},
+ }},
+ {"git-repositories", "Git Repositories", PermissionScopeGlobal, []PermissionCatalogAction{
+ {"list", PermGitReposList, "List", ""},
+ {"read", PermGitReposRead, "Read", ""},
+ {"create", PermGitReposCreate, "Create", ""},
+ {"update", PermGitReposUpdate, "Update", ""},
+ {"delete", PermGitReposDelete, "Delete", ""},
+ {"test", PermGitReposTest, "Test", ""},
+ {"sync", PermGitReposSync, "Sync", ""},
+ }},
+ {"events", "Events", PermissionScopeGlobal, []PermissionCatalogAction{
+ {"read", PermEventsRead, "Read", ""},
+ }},
+ {"customize", "Customize", PermissionScopeGlobal, []PermissionCatalogAction{
+ {"manage", PermCustomizeManage, "Manage", ""},
+ }},
+ {"containers", "Containers", PermissionScopeEnv, []PermissionCatalogAction{
+ {"list", PermContainersList, "List", ""},
+ {"read", PermContainersRead, "Read", ""},
+ {"logs", PermContainersLogs, "View logs", ""},
+ {"create", PermContainersCreate, "Create", ""},
+ {"start", PermContainersStart, "Start", ""},
+ {"stop", PermContainersStop, "Stop", ""},
+ {"restart", PermContainersRestart, "Restart", ""},
+ {"redeploy", PermContainersRedeploy, "Redeploy", ""},
+ {"delete", PermContainersDelete, "Delete", ""},
+ {"exec", PermContainersExec, "Exec / terminal", ""},
+ {"autoupdate", PermContainersAutoUpdate, "Auto-update", ""},
+ }},
+ {"projects", "Projects", PermissionScopeEnv, []PermissionCatalogAction{
+ {"list", PermProjectsList, "List", ""},
+ {"read", PermProjectsRead, "Read", ""},
+ {"logs", PermProjectsLogs, "View logs", ""},
+ {"create", PermProjectsCreate, "Create", ""},
+ {"update", PermProjectsUpdate, "Update", ""},
+ {"deploy", PermProjectsDeploy, "Deploy", ""},
+ {"down", PermProjectsDown, "Bring down", ""},
+ {"restart", PermProjectsRestart, "Restart", ""},
+ {"delete", PermProjectsDelete, "Delete", ""},
+ {"archive", PermProjectsArchive, "Archive / unarchive", ""},
+ }},
+ {"images", "Images", PermissionScopeEnv, []PermissionCatalogAction{
+ {"list", PermImagesList, "List", ""},
+ {"read", PermImagesRead, "Read", ""},
+ {"pull", PermImagesPull, "Pull", ""},
+ {"push", PermImagesPush, "Push", ""},
+ {"build", PermImagesBuild, "Build", ""},
+ {"prune", PermImagesPrune, "Prune", ""},
+ {"delete", PermImagesDelete, "Delete", ""},
+ {"upload", PermImagesUpload, "Upload", ""},
+ }},
+ {"volumes", "Volumes", PermissionScopeEnv, []PermissionCatalogAction{
+ {"list", PermVolumesList, "List", ""},
+ {"read", PermVolumesRead, "Read", ""},
+ {"create", PermVolumesCreate, "Create", ""},
+ {"delete", PermVolumesDelete, "Delete", ""},
+ {"prune", PermVolumesPrune, "Prune", ""},
+ {"browse", PermVolumesBrowse, "Browse", ""},
+ {"upload", PermVolumesUpload, "Upload", ""},
+ {"backup", PermVolumesBackup, "Backup / restore", ""},
+ }},
+ {"networks", "Networks", PermissionScopeEnv, []PermissionCatalogAction{
+ {"list", PermNetworksList, "List", ""},
+ {"read", PermNetworksRead, "Read", ""},
+ {"create", PermNetworksCreate, "Create", ""},
+ {"delete", PermNetworksDelete, "Delete", ""},
+ {"prune", PermNetworksPrune, "Prune", ""},
+ }},
+ {"swarm", "Swarm", PermissionScopeEnv, []PermissionCatalogAction{
+ {"read", PermSwarmRead, "Read", ""},
+ {"init", PermSwarmInit, "Initialize", ""},
+ {"join", PermSwarmJoin, "Join", ""},
+ {"leave", PermSwarmLeave, "Leave", ""},
+ {"spec", PermSwarmSpec, "Update spec", ""},
+ {"nodes", PermSwarmNodes, "Manage nodes", ""},
+ {"services", PermSwarmServices, "Manage services", ""},
+ {"services:logs", PermSwarmServicesLogs, "View service logs", ""},
+ {"stacks", PermSwarmStacks, "Manage stacks", ""},
+ {"configs", PermSwarmConfigs, "Manage configs", ""},
+ {"secrets", PermSwarmSecrets, "Manage secrets", ""},
+ {"unlock", PermSwarmUnlock, "Unlock / join tokens", ""},
+ }},
+ {"gitops", "GitOps Syncs", PermissionScopeEnv, []PermissionCatalogAction{
+ {"list", PermGitOpsList, "List", ""},
+ {"read", PermGitOpsRead, "Read", ""},
+ {"create", PermGitOpsCreate, "Create", ""},
+ {"update", PermGitOpsUpdate, "Update", ""},
+ {"delete", PermGitOpsDelete, "Delete", ""},
+ {"sync", PermGitOpsSync, "Trigger sync", ""},
+ }},
+ {"webhooks", "Webhooks", PermissionScopeEnv, []PermissionCatalogAction{
+ {"list", PermWebhooksList, "List", ""},
+ {"create", PermWebhooksCreate, "Create", ""},
+ {"update", PermWebhooksUpdate, "Update", ""},
+ {"delete", PermWebhooksDelete, "Delete", ""},
+ }},
+ {"jobs", "Background Jobs", PermissionScopeEnv, []PermissionCatalogAction{
+ {"manage", PermJobsManage, "Manage", ""},
+ }},
+ {"notifications", "Notifications", PermissionScopeEnv, []PermissionCatalogAction{
+ {"manage", PermNotificationsManage, "Manage", ""},
+ }},
+ {"dashboard", "Dashboard", PermissionScopeEnv, []PermissionCatalogAction{
+ {"read", PermDashboardRead, "Read", ""},
+ }},
+ {"system", "System", PermissionScopeEnv, []PermissionCatalogAction{
+ {"read", PermSystemRead, "Read", ""},
+ {"prune", PermSystemPrune, "Prune", ""},
+ {"upgrade", PermSystemUpgrade, "Trigger upgrade", ""},
+ }},
+ {"image-updates", "Image Updates", PermissionScopeEnv, []PermissionCatalogAction{
+ {"read", PermImageUpdatesRead, "Read", ""},
+ {"check", PermImageUpdatesCheck, "Check", ""},
+ }},
+ {"vulnerabilities", "Vulnerabilities", PermissionScopeEnv, []PermissionCatalogAction{
+ {"read", PermVulnsRead, "Read", ""},
+ {"scan", PermVulnsScan, "Scan", ""},
+ {"manage", PermVulnsManage, "Manage ignores", ""},
+ }},
+ {"build-workspaces", "Build Workspaces", PermissionScopeEnv, []PermissionCatalogAction{
+ {"manage", PermBuildWorkspacesManage, "Manage", ""},
+ }},
+}
+
+// PermissionCatalog returns a defensive copy of the full permission catalog.
+func PermissionCatalog() []PermissionCatalogResource {
+ out := make([]PermissionCatalogResource, len(permissionCatalog))
+ for i, resource := range permissionCatalog {
+ out[i] = resource
+ out[i].Actions = append([]PermissionCatalogAction(nil), resource.Actions...)
+ }
+ return out
+}
diff --git a/backend/pkg/authz/permission_set.go b/backend/pkg/authz/permission_set.go
new file mode 100644
index 000000000..dc7664461
--- /dev/null
+++ b/backend/pkg/authz/permission_set.go
@@ -0,0 +1,128 @@
+package authz
+
+import "strings"
+
+// PermissionSet is the effective permission set for one caller in one request.
+// Built once by the auth bridge and stashed in the request context.
+//
+// Global permissions apply to every environment and to org-level endpoints.
+// PerEnv permissions apply only when the caller is acting on that specific
+// environment. Sudo bypasses all checks (used for the agent token and the
+// per-environment access token paths).
+type PermissionSet struct {
+ Global map[string]struct{}
+ PerEnv map[string]map[string]struct{}
+ Sudo bool
+}
+
+// Allows reports whether the caller may perform `perm`. For env-scoped
+// permissions, envID is the target environment's ID. For org-level
+// permissions, pass envID = "" — only Global permissions count.
+func (ps *PermissionSet) Allows(perm, envID string) bool {
+ if ps == nil {
+ return false
+ }
+ if ps.Sudo {
+ return true
+ }
+ if _, ok := ps.Global[perm]; ok {
+ return true
+ }
+ if envID == "" {
+ return false
+ }
+ if env, ok := ps.PerEnv[envID]; ok {
+ if _, ok := env[perm]; ok {
+ return true
+ }
+ }
+ return false
+}
+
+// IsGlobalAdmin reports whether the caller holds enough global permissions to
+// be considered an administrator. True for sudo callers and for callers whose
+// Global set contains every defined permission. Used by the backward-compat
+// IsAdminFromContext helper and by last-admin guards.
+//
+// Implementation: every insertion path runs through
+// services.validatePermissionsInternal → authz.IsKnownPermission, which does
+// an exact-set check against AllPermissions(). ps.Global is therefore a true
+// subset of AllPermissions, and equal cardinality implies equality — no
+// per-call slice allocation or O(N) walk on the auth hot path.
+func (ps *PermissionSet) IsGlobalAdmin() bool {
+ if ps == nil {
+ return false
+ }
+ if ps.Sudo {
+ return true
+ }
+ return len(ps.Global) >= TotalPermissionsCount()
+}
+
+// SudoPermissionSet returns a PermissionSet that allows every action. Used for
+// the agent token and environment access token paths, which bypass per-user
+// permission resolution entirely.
+func SudoPermissionSet() *PermissionSet {
+ return &PermissionSet{Sudo: true}
+}
+
+// NewPermissionSet builds an empty PermissionSet ready for population.
+func NewPermissionSet() *PermissionSet {
+ return &PermissionSet{
+ Global: make(map[string]struct{}),
+ PerEnv: make(map[string]map[string]struct{}),
+ }
+}
+
+// AddGlobal grants `perms` at global scope.
+func (ps *PermissionSet) AddGlobal(perms ...string) {
+ if ps.Global == nil {
+ ps.Global = make(map[string]struct{})
+ }
+ for _, p := range perms {
+ ps.Global[p] = struct{}{}
+ }
+}
+
+// AddEnv grants `perms` scoped to envID.
+func (ps *PermissionSet) AddEnv(envID string, perms ...string) {
+ if envID == "" {
+ ps.AddGlobal(perms...)
+ return
+ }
+ if ps.PerEnv == nil {
+ ps.PerEnv = make(map[string]map[string]struct{})
+ }
+ env, ok := ps.PerEnv[envID]
+ if !ok {
+ env = make(map[string]struct{})
+ ps.PerEnv[envID] = env
+ }
+ for _, p := range perms {
+ env[p] = struct{}{}
+ }
+}
+
+// EnvIDFromPath extracts the environment ID from a Huma operation path of the
+// form /environments/{id}/... Returns "" for paths without an env segment.
+// Tolerates a leading /api prefix for safety, though the Huma group already
+// strips it.
+func EnvIDFromPath(path string) string {
+ path = strings.TrimPrefix(path, "/api")
+ if !strings.HasPrefix(path, "/environments/") {
+ return ""
+ }
+ rest := path[len("/environments/"):]
+ slash := strings.Index(rest, "/")
+ if slash == -1 {
+ // Path is just /environments/<id> (no trailing segment) — this is
+ // not an env-scoped operation, it's the env detail endpoint itself,
+ // which is org-level.
+ return ""
+ }
+ id := rest[:slash]
+ if id == "" {
+ return ""
+ }
+ return id
+}
diff --git a/backend/pkg/authz/permission_set_test.go b/backend/pkg/authz/permission_set_test.go
new file mode 100644
index 000000000..531daab25
--- /dev/null
+++ b/backend/pkg/authz/permission_set_test.go
@@ -0,0 +1,157 @@
+package authz
+
+import "testing"
+
+func TestPermissionSetAllowsGlobal(t *testing.T) {
+ ps := NewPermissionSet()
+ ps.AddGlobal(PermContainersList)
+
+ if !ps.Allows(PermContainersList, "env-1") {
+ t.Fatal("global perm should apply to any env")
+ }
+ if !ps.Allows(PermContainersList, "") {
+ t.Fatal("global perm should apply org-level too")
+ }
+ if ps.Allows(PermContainersStart, "env-1") {
+ t.Fatal("unrelated perm should be denied")
+ }
+}
+
+func TestPermissionSetEnvScopedDoesNotLeak(t *testing.T) {
+ ps := NewPermissionSet()
+ ps.AddEnv("env-1", PermContainersStart)
+
+ if !ps.Allows(PermContainersStart, "env-1") {
+ t.Fatal("env perm should apply to its own env")
+ }
+ if ps.Allows(PermContainersStart, "env-2") {
+ t.Fatal("env perm must not leak to another env")
+ }
+ if ps.Allows(PermContainersStart, "") {
+ t.Fatal("env perm must not satisfy an org-level check")
+ }
+}
+
+func TestSudoAllowsEverything(t *testing.T) {
+ ps := SudoPermissionSet()
+ if !ps.Allows(PermContainersDelete, "any-env") {
+ t.Fatal("sudo should allow any perm on any env")
+ }
+ if !ps.Allows(PermUsersDelete, "") {
+ t.Fatal("sudo should allow org-level perms")
+ }
+ if !ps.IsGlobalAdmin() {
+ t.Fatal("sudo should report as global admin")
+ }
+}
+
+func TestEnvIDFromPath(t *testing.T) {
+ cases := map[string]string{
+ "/environments/abc-123/containers": "abc-123",
+ "/environments/abc-123/containers/foo": "abc-123",
+ "/api/environments/abc-123/projects": "abc-123",
+ "/environments/abc-123": "", // org-level env detail
+ "/users": "",
+ "": "",
+ }
+ for input, want := range cases {
+ if got := EnvIDFromPath(input); got != want {
+ t.Errorf("EnvIDFromPath(%q) = %q, want %q", input, got, want)
+ }
+ }
+}
+
+func TestIsOrgLevelAndEnvScoped(t *testing.T) {
+ if !IsOrgLevel(PermUsersList) {
+ t.Fatal("users:list should be org-level")
+ }
+ if IsEnvScoped(PermUsersList) {
+ t.Fatal("users:list should not be env-scoped")
+ }
+ if IsOrgLevel(PermContainersStart) {
+ t.Fatal("containers:start should not be org-level")
+ }
+ if !IsEnvScoped(PermContainersStart) {
+ t.Fatal("containers:start should be env-scoped")
+ }
+}
+
+func TestIsKnownPermissionRejectsSyntheticPrefixMatches(t *testing.T) {
+ // Synthetic permissions whose prefix matches a known env-scoped family
+ // must not be accepted — otherwise an admin could inflate ps.Global past
+ // TotalPermissionsCount() with bogus entries and trip IsGlobalAdmin().
+ for _, p := range []string{"containers:fake1", "projects:bogus", "images:made-up"} {
+ if IsKnownPermission(p) {
+ t.Errorf("IsKnownPermission(%q) = true, want false", p)
+ }
+ if IsEnvScoped(p) {
+ t.Errorf("IsEnvScoped(%q) = true, want false", p)
+ }
+ }
+}
+
+func TestBuiltInRolesOnlyReferenceKnownPermissions(t *testing.T) {
+ for _, p := range BuiltInEditorPermissions() {
+ if !IsKnownPermission(p) {
+ t.Errorf("editor references unknown perm %q", p)
+ }
+ }
+ for _, p := range BuiltInDeployerPermissions() {
+ if !IsKnownPermission(p) {
+ t.Errorf("deployer references unknown perm %q", p)
+ }
+ }
+ for _, p := range BuiltInViewerPermissions() {
+ if !IsKnownPermission(p) {
+ t.Errorf("viewer references unknown perm %q", p)
+ }
+ }
+}
+
+func TestPermissionCatalogDerivesKnownPermissionsAndScopes(t *testing.T) {
+ catalog := PermissionCatalog()
+ if len(catalog) == 0 {
+ t.Fatal("permission catalog must not be empty")
+ }
+
+ all := AllPermissions()
+ if len(all) != TotalPermissionsCount() {
+ t.Fatalf("AllPermissions length = %d, TotalPermissionsCount = %d", len(all), TotalPermissionsCount())
+ }
+
+ seen := make(map[string]struct{}, len(all))
+ var catalogCount int
+ for _, resource := range catalog {
+ if resource.Scope != PermissionScopeGlobal && resource.Scope != PermissionScopeEnv {
+ t.Fatalf("resource %q has invalid scope %q", resource.Key, resource.Scope)
+ }
+ for _, action := range resource.Actions {
+ catalogCount++
+ if action.Permission == "" {
+ t.Fatalf("resource %q action %q has empty permission", resource.Key, action.Key)
+ }
+ if _, exists := seen[action.Permission]; exists {
+ t.Fatalf("duplicate permission %q in catalog", action.Permission)
+ }
+ seen[action.Permission] = struct{}{}
+ if !IsKnownPermission(action.Permission) {
+ t.Fatalf("catalog permission %q is not known", action.Permission)
+ }
+ if resource.Scope == PermissionScopeGlobal && !IsOrgLevel(action.Permission) {
+ t.Fatalf("catalog permission %q should be org-level", action.Permission)
+ }
+ if resource.Scope == PermissionScopeEnv && !IsEnvScoped(action.Permission) {
+ t.Fatalf("catalog permission %q should be env-scoped", action.Permission)
+ }
+ }
+ }
+
+ if catalogCount != len(all) {
+ t.Fatalf("catalog permission count = %d, AllPermissions count = %d", catalogCount, len(all))
+ }
+ for _, permission := range all {
+ if _, exists := seen[permission]; !exists {
+ t.Fatalf("AllPermissions includes %q outside catalog", permission)
+ }
+ }
+}
diff --git a/backend/pkg/authz/permissions.go b/backend/pkg/authz/permissions.go
new file mode 100644
index 000000000..5cd372a04
--- /dev/null
+++ b/backend/pkg/authz/permissions.go
@@ -0,0 +1,362 @@
+// Package authz defines the permission taxonomy and authorization primitives
+// used across Arcane handlers. Permissions are strings of the form
+// "<resource>:<action>" and are classified as either org-level (require a
+// globally-scoped role) or env-scoped (resolved against the environment ID
+// from the request path).
+package authz
+
+// Built-in role IDs. Stable across migrations so other code may reference them
+// safely. All six built-in roles are seeded by migration 054_add_rbac.
+const (
+ BuiltInRoleAdmin = "role_admin"
+ BuiltInRoleEditor = "role_editor"
+ BuiltInRoleNoShellEditor = "role_no_shell_editor"
+ BuiltInRoleDeployer = "role_deployer"
+ BuiltInRoleMonitor = "role_monitor"
+ BuiltInRoleViewer = "role_viewer"
+)
+
+// Org-level permissions (require a global-scope role assignment).
+const (
+ PermUsersList = "users:list"
+ PermUsersRead = "users:read"
+ PermUsersCreate = "users:create"
+ PermUsersUpdate = "users:update"
+ PermUsersDelete = "users:delete"
+
+ // Role management (Create / Update / Delete) and role assignment to users
+ // are reserved for global admins and intentionally not exposed as delegated
+ // permissions — see backend/api/middleware/role.go::RequireGlobalAdmin.
+ // Likewise, managing OIDC group → role mappings is admin-only because it
+ // is effectively another path for granting role assignments.
+ PermRolesList = "roles:list"
+ PermRolesRead = "roles:read"
+
+ PermApiKeysList = "apikeys:list"
+ PermApiKeysRead = "apikeys:read"
+ PermApiKeysCreate = "apikeys:create"
+ PermApiKeysUpdate = "apikeys:update"
+ PermApiKeysDelete = "apikeys:delete"
+
+ PermSettingsRead = "settings:read"
+ PermSettingsWrite = "settings:write"
+
+ PermEnvironmentsList = "environments:list"
+ PermEnvironmentsRead = "environments:read"
+ PermEnvironmentsCreate = "environments:create"
+ PermEnvironmentsUpdate = "environments:update"
+ PermEnvironmentsDelete = "environments:delete"
+ PermEnvironmentsPair = "environments:pair"
+ PermEnvironmentsSync = "environments:sync"
+
+ PermRegistriesList = "registries:list"
+ PermRegistriesRead = "registries:read"
+ PermRegistriesCreate = "registries:create"
+ PermRegistriesUpdate = "registries:update"
+ PermRegistriesDelete = "registries:delete"
+ PermRegistriesTest = "registries:test"
+
+ PermTemplatesList = "templates:list"
+ PermTemplatesRead = "templates:read"
+ PermTemplatesCreate = "templates:create"
+ PermTemplatesUpdate = "templates:update"
+ PermTemplatesDelete = "templates:delete"
+
+ PermGitReposList = "git-repositories:list"
+ PermGitReposRead = "git-repositories:read"
+ PermGitReposCreate = "git-repositories:create"
+ PermGitReposUpdate = "git-repositories:update"
+ PermGitReposDelete = "git-repositories:delete"
+ PermGitReposTest = "git-repositories:test"
+ PermGitReposSync = "git-repositories:sync"
+
+ PermEventsRead = "events:read"
+ PermCustomizeManage = "customize:manage"
+)
+
+// Env-scoped permissions (resolved against the {id} env ID in the path).
+const (
+ PermContainersList = "containers:list"
+ PermContainersRead = "containers:read"
+ PermContainersLogs = "containers:logs"
+ PermContainersCreate = "containers:create"
+ PermContainersStart = "containers:start"
+ PermContainersStop = "containers:stop"
+ PermContainersRestart = "containers:restart"
+ PermContainersRedeploy = "containers:redeploy"
+ PermContainersDelete = "containers:delete"
+ PermContainersExec = "containers:exec"
+ PermContainersAutoUpdate = "containers:autoupdate"
+
+ PermProjectsList = "projects:list"
+ PermProjectsRead = "projects:read"
+ PermProjectsLogs = "projects:logs"
+ PermProjectsCreate = "projects:create"
+ PermProjectsUpdate = "projects:update"
+ PermProjectsDeploy = "projects:deploy"
+ PermProjectsDown = "projects:down"
+ PermProjectsRestart = "projects:restart"
+ PermProjectsDelete = "projects:delete"
+ PermProjectsArchive = "projects:archive"
+
+ PermImagesList = "images:list"
+ PermImagesRead = "images:read"
+ PermImagesPull = "images:pull"
+ PermImagesPush = "images:push"
+ PermImagesBuild = "images:build"
+ PermImagesPrune = "images:prune"
+ PermImagesDelete = "images:delete"
+ PermImagesUpload = "images:upload"
+
+ PermVolumesList = "volumes:list"
+ PermVolumesRead = "volumes:read"
+ PermVolumesCreate = "volumes:create"
+ PermVolumesDelete = "volumes:delete"
+ PermVolumesPrune = "volumes:prune"
+ PermVolumesBrowse = "volumes:browse"
+ PermVolumesUpload = "volumes:upload"
+ PermVolumesBackup = "volumes:backup"
+
+ PermNetworksList = "networks:list"
+ PermNetworksRead = "networks:read"
+ PermNetworksCreate = "networks:create"
+ PermNetworksDelete = "networks:delete"
+ PermNetworksPrune = "networks:prune"
+
+ PermSwarmRead = "swarm:read"
+ PermSwarmInit = "swarm:init"
+ PermSwarmJoin = "swarm:join"
+ PermSwarmLeave = "swarm:leave"
+ PermSwarmSpec = "swarm:spec"
+ PermSwarmNodes = "swarm:nodes"
+ PermSwarmServices = "swarm:services"
+ PermSwarmServicesLogs = "swarm:services:logs"
+ PermSwarmStacks = "swarm:stacks"
+ PermSwarmConfigs = "swarm:configs"
+ PermSwarmSecrets = "swarm:secrets"
+ PermSwarmUnlock = "swarm:unlock"
+
+ PermGitOpsList = "gitops:list"
+ PermGitOpsRead = "gitops:read"
+ PermGitOpsCreate = "gitops:create"
+ PermGitOpsUpdate = "gitops:update"
+ PermGitOpsDelete = "gitops:delete"
+ PermGitOpsSync = "gitops:sync"
+
+ PermWebhooksList = "webhooks:list"
+ PermWebhooksCreate = "webhooks:create"
+ PermWebhooksUpdate = "webhooks:update"
+ PermWebhooksDelete = "webhooks:delete"
+
+ PermJobsManage = "jobs:manage"
+ PermNotificationsManage = "notifications:manage"
+ PermDashboardRead = "dashboard:read"
+
+ PermSystemRead = "system:read"
+ PermSystemPrune = "system:prune"
+ PermSystemUpgrade = "system:upgrade"
+
+ PermImageUpdatesRead = "image-updates:read"
+ PermImageUpdatesCheck = "image-updates:check"
+
+ PermVulnsRead = "vulnerabilities:read"
+ PermVulnsScan = "vulnerabilities:scan"
+ PermVulnsManage = "vulnerabilities:manage"
+
+ PermBuildWorkspacesManage = "build-workspaces:manage"
+)
+
+// orgLevelPermissions is derived from the authz permission catalog. Env-scoped
+// permissions are everything in the catalog that is not in this set.
+var orgLevelPermissions = buildOrgLevelPermissionsInternal()
+
+func buildOrgLevelPermissionsInternal() map[string]struct{} {
+ out := make(map[string]struct{})
+ for _, resource := range permissionCatalog {
+ if resource.Scope != PermissionScopeGlobal {
+ continue
+ }
+ for _, action := range resource.Actions {
+ out[action.Permission] = struct{}{}
+ }
+ }
+ return out
+}
+
+// IsOrgLevel reports whether the given permission requires a globally-scoped
+// role assignment (and applies only to org-level endpoints).
+func IsOrgLevel(perm string) bool {
+ _, ok := orgLevelPermissions[perm]
+ return ok
+}
+
+// IsEnvScoped reports whether the given permission is resolved against an
+// environment ID. Returns false for permissions not in AllPermissions().
+func IsEnvScoped(perm string) bool {
+ if _, ok := allPermissionsSet[perm]; !ok {
+ return false
+ }
+ return !IsOrgLevel(perm)
+}
+
+// allPermissionsSet is the canonical exact-set lookup of every defined
+// permission, built once from AllPermissions(). Anchors IsKnownPermission and
+// IsEnvScoped to exact membership so PermissionSet.IsGlobalAdmin can rely on
+// "ps.Global ⊆ allPermissionsSet" as a true invariant.
+var allPermissionsSet = func() map[string]struct{} {
+ all := AllPermissions()
+ m := make(map[string]struct{}, len(all))
+ for _, p := range all {
+ m[p] = struct{}{}
+ }
+ return m
+}()
+
+// totalPermissionsCount caches len(allPermissionsSet) so callers on the auth
+// hot path (notably PermissionSet.IsGlobalAdmin) don't re-allocate and walk a
+// ~100-element slice on every authenticated request.
+var totalPermissionsCount = len(allPermissionsSet)
+
+// TotalPermissionsCount returns the number of distinct permission constants
+// the package defines. Computed once at init; cheap to call repeatedly.
+func TotalPermissionsCount() int { return totalPermissionsCount }
+
+// AllPermissions returns every recognized permission constant. Used to seed
+// the Admin built-in role and to validate role definitions.
+func AllPermissions() []string {
+ var count int
+ for _, resource := range permissionCatalog {
+ count += len(resource.Actions)
+ }
+ out := make([]string, 0, count)
+ for _, resource := range permissionCatalog {
+ for _, action := range resource.Actions {
+ out = append(out, action.Permission)
+ }
+ }
+ return out
+}
+
+// IsKnownPermission reports whether perm matches any defined permission
+// constant. Used to reject role definitions referencing unknown permissions.
+func IsKnownPermission(perm string) bool {
+ _, ok := allPermissionsSet[perm]
+ return ok
+}
+
+// BuiltInEditorPermissions returns the permission set for the Editor built-in
+// role: read+write on Docker resources and read on most org-level resources.
+// Excludes user/role/key management and settings writes.
+func BuiltInEditorPermissions() []string {
+ return []string{
+ // Read on org-level
+ PermUsersList, PermUsersRead,
+ PermRolesList, PermRolesRead,
+ PermApiKeysList, PermApiKeysRead,
+ PermSettingsRead,
+ PermEnvironmentsList, PermEnvironmentsRead, PermEnvironmentsSync,
+ PermRegistriesList, PermRegistriesRead,
+ PermTemplatesList, PermTemplatesRead, PermTemplatesCreate, PermTemplatesUpdate, PermTemplatesDelete,
+ PermGitReposList, PermGitReposRead,
+ PermEventsRead,
+ // Full env-scoped Docker management
+ PermContainersList, PermContainersRead, PermContainersLogs, PermContainersCreate, PermContainersStart, PermContainersStop, PermContainersRestart, PermContainersRedeploy, PermContainersDelete, PermContainersExec, PermContainersAutoUpdate,
+ PermProjectsList, PermProjectsRead, PermProjectsLogs, PermProjectsCreate, PermProjectsUpdate, PermProjectsDeploy, PermProjectsDown, PermProjectsRestart, PermProjectsDelete, PermProjectsArchive,
+ PermImagesList, PermImagesRead, PermImagesPull, PermImagesPush, PermImagesBuild, PermImagesPrune, PermImagesDelete, PermImagesUpload,
+ PermVolumesList, PermVolumesRead, PermVolumesCreate, PermVolumesDelete, PermVolumesPrune, PermVolumesBrowse, PermVolumesUpload, PermVolumesBackup,
+ PermNetworksList, PermNetworksRead, PermNetworksCreate, PermNetworksDelete, PermNetworksPrune,
+ PermSwarmRead, PermSwarmSpec, PermSwarmNodes, PermSwarmServices, PermSwarmServicesLogs, PermSwarmStacks, PermSwarmConfigs, PermSwarmSecrets,
+ PermGitOpsList, PermGitOpsRead, PermGitOpsCreate, PermGitOpsUpdate, PermGitOpsDelete, PermGitOpsSync,
+ PermWebhooksList, PermWebhooksCreate, PermWebhooksUpdate, PermWebhooksDelete,
+ PermJobsManage, PermNotificationsManage, PermDashboardRead,
+ PermSystemRead, PermSystemPrune,
+ PermImageUpdatesRead, PermImageUpdatesCheck,
+ PermVulnsRead, PermVulnsScan, PermVulnsManage,
+ PermBuildWorkspacesManage,
+ }
+}
+
+// BuiltInDeployerPermissions returns the permission set for the Deployer
+// built-in role: container/project lifecycle and read-only on everything else.
+// Cannot create or delete resources; cannot manage settings/users/roles/keys.
+func BuiltInDeployerPermissions() []string {
+ return []string{
+ PermEnvironmentsList, PermEnvironmentsRead,
+ PermRegistriesList, PermRegistriesRead,
+ PermTemplatesList, PermTemplatesRead,
+ PermEventsRead,
+ PermContainersList, PermContainersRead, PermContainersLogs, PermContainersStart, PermContainersStop, PermContainersRestart, PermContainersRedeploy,
+ PermProjectsList, PermProjectsRead, PermProjectsLogs, PermProjectsDeploy, PermProjectsDown, PermProjectsRestart,
+ PermImagesList, PermImagesRead, PermImagesPull,
+ PermVolumesList, PermVolumesRead, PermVolumesBrowse,
+ PermNetworksList, PermNetworksRead,
+ PermSwarmRead, PermSwarmServicesLogs,
+ PermGitOpsList, PermGitOpsRead, PermGitOpsSync,
+ PermDashboardRead,
+ PermSystemRead,
+ PermImageUpdatesRead, PermImageUpdatesCheck,
+ PermVulnsRead,
+ }
+}
+
+// BuiltInViewerPermissions returns the permission set for the Viewer built-in
+// role: read-only access across every resource.
+func BuiltInViewerPermissions() []string {
+ return []string{
+ PermUsersList, PermUsersRead,
+ PermRolesList, PermRolesRead,
+ PermApiKeysList, PermApiKeysRead,
+ PermSettingsRead,
+ PermEnvironmentsList, PermEnvironmentsRead,
+ PermRegistriesList, PermRegistriesRead,
+ PermTemplatesList, PermTemplatesRead,
+ PermGitReposList, PermGitReposRead,
+ PermEventsRead,
+ PermContainersList, PermContainersRead, PermContainersLogs,
+ PermProjectsList, PermProjectsRead, PermProjectsLogs,
+ PermImagesList, PermImagesRead,
+ PermVolumesList, PermVolumesRead, PermVolumesBrowse,
+ PermNetworksList, PermNetworksRead,
+ PermSwarmRead, PermSwarmServicesLogs,
+ PermGitOpsList, PermGitOpsRead,
+ PermWebhooksList,
+ PermDashboardRead,
+ PermSystemRead,
+ PermImageUpdatesRead,
+ PermVulnsRead,
+ }
+}
+
+// BuiltInMonitorPermissions returns the permission set for the Monitor
+// built-in role: observability-only access — read Docker resources, view logs,
+// dashboards, and events. No mutations, no exec, no user/role/settings access.
+func BuiltInMonitorPermissions() []string {
+ return []string{
+ PermEnvironmentsList, PermEnvironmentsRead,
+ PermEventsRead,
+ PermContainersList, PermContainersRead, PermContainersLogs,
+ PermProjectsList, PermProjectsRead, PermProjectsLogs,
+ PermImagesList, PermImagesRead,
+ PermVolumesList, PermVolumesRead,
+ PermNetworksList, PermNetworksRead,
+ PermSwarmRead, PermSwarmServicesLogs,
+ PermDashboardRead,
+ PermSystemRead,
+ PermImageUpdatesRead,
+ PermVulnsRead,
+ }
+}
+
+// BuiltInNoShellEditorPermissions returns the Editor permission set minus
+// PermContainersExec. For teams that want full Docker management but no
+// interactive shell access into running containers.
+func BuiltInNoShellEditorPermissions() []string {
+ src := BuiltInEditorPermissions()
+ out := make([]string, 0, len(src))
+ for _, p := range src {
+ if p != PermContainersExec {
+ out = append(out, p)
+ }
+ }
+ return out
+}
diff --git a/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel_grpc.pb.go b/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel_grpc.pb.go
index 4f7424980..eba05fd77 100644
--- a/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel_grpc.pb.go
+++ b/backend/pkg/libarcane/edge/proto/tunnel/v1/tunnel_grpc.pb.go
@@ -1,6 +1,6 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
-// - protoc-gen-go-grpc v1.6.1
+// - protoc-gen-go-grpc v1.6.2
// - protoc (unknown)
// source: tunnel/v1/tunnel.proto
diff --git a/backend/pkg/libarcane/startup/startup.go b/backend/pkg/libarcane/startup/startup.go
index 3c246812d..f909e330f 100644
--- a/backend/pkg/libarcane/startup/startup.go
+++ b/backend/pkg/libarcane/startup/startup.go
@@ -77,6 +77,7 @@ func TestDockerConnection(ctx context.Context, testFunc func(context.Context) er
func InitializeNonAgentFeatures(
ctx context.Context,
cfg *RuntimeConfig,
+ ensureBuiltInRolesFunc func(context.Context) error,
createAdminFunc func(context.Context) error,
reconcileDefaultAdminAPIKeyFunc func(context.Context) error,
autoLoginInitFunc func(context.Context) error,
@@ -85,6 +86,12 @@ func InitializeNonAgentFeatures(
return
}
+ if ensureBuiltInRolesFunc != nil {
+ if err := ensureBuiltInRolesFunc(ctx); err != nil {
+ slog.ErrorContext(ctx, "Failed to seed built-in roles before admin bootstrap", "error", err.Error())
+ }
+ }
+
if err := createAdminFunc(ctx); err != nil {
slog.WarnContext(ctx, "Failed to create default admin user", "error", err.Error())
}
diff --git a/backend/pkg/libarcane/startup/startup_test.go b/backend/pkg/libarcane/startup/startup_test.go
index 4be6e8aaf..96460c465 100644
--- a/backend/pkg/libarcane/startup/startup_test.go
+++ b/backend/pkg/libarcane/startup/startup_test.go
@@ -259,7 +259,7 @@ func TestInitializeNonAgentFeatures(t *testing.T) {
return nil
}
- InitializeNonAgentFeatures(ctx, cfg, createAdminFunc, reconcileDefaultAdminAPIKeyFunc, nil)
+ InitializeNonAgentFeatures(ctx, cfg, nil, createAdminFunc, reconcileDefaultAdminAPIKeyFunc, nil)
assert.False(t, createAdminCalled)
assert.False(t, reconcileDefaultAdminAPIKeyCalled)
@@ -284,7 +284,7 @@ func TestInitializeNonAgentFeatures(t *testing.T) {
return nil
}
- InitializeNonAgentFeatures(ctx, cfg, createAdminFunc, reconcileDefaultAdminAPIKeyFunc, autoLoginInitFunc)
+ InitializeNonAgentFeatures(ctx, cfg, nil, createAdminFunc, reconcileDefaultAdminAPIKeyFunc, autoLoginInitFunc)
assert.True(t, createAdminCalled)
assert.True(t, reconcileDefaultAdminAPIKeyCalled)
@@ -303,6 +303,6 @@ func TestInitializeNonAgentFeatures(t *testing.T) {
return errors.New("admin creation failed")
}
- InitializeNonAgentFeatures(ctx, cfg, createAdminFunc, reconcileDefaultAdminAPIKeyFunc, autoLoginInitFunc)
+ InitializeNonAgentFeatures(ctx, cfg, nil, createAdminFunc, reconcileDefaultAdminAPIKeyFunc, autoLoginInitFunc)
})
}
diff --git a/backend/pkg/utils/auth.go b/backend/pkg/utils/auth.go
index 7a60a6a6b..afed77846 100644
--- a/backend/pkg/utils/auth.go
+++ b/backend/pkg/utils/auth.go
@@ -1,7 +1,5 @@
package utils
-import "slices"
-
// Auth header names and path prefixes shared between the Echo middleware
// (WebSocket/diagnostics) and the Huma auth bridge (REST). Keep these in one
// place so a change to a header name applies to every route type at once.
@@ -11,8 +9,3 @@ const (
HeaderApiKey = "X-API-Key" // #nosec G101: header name, not a credential
AgentPairingPrefix = "/api/environments/0/agent/pair"
)
-
-// UserHasRole reports whether the user's roles contains the given role.
-func UserHasRole(roles []string, role string) bool {
- return slices.Contains(roles, role)
-}
diff --git a/backend/pkg/utils/cache/ttl.go b/backend/pkg/utils/cache/ttl.go
index 1b5011422..0dd8b4338 100644
--- a/backend/pkg/utils/cache/ttl.go
+++ b/backend/pkg/utils/cache/ttl.go
@@ -64,3 +64,10 @@ func (c *TTL[V]) DeleteFunc(fn func(key string, value V) bool) {
}
}
}
+
+// Delete removes the entry for key, if present.
+func (c *TTL[V]) Delete(key string) {
+ c.mu.Lock()
+ delete(c.entries, key)
+ c.mu.Unlock()
+}
diff --git a/backend/pkg/utils/jwtclaims/jwt.go b/backend/pkg/utils/jwtclaims/jwt.go
index d947dcb64..403017738 100644
--- a/backend/pkg/utils/jwtclaims/jwt.go
+++ b/backend/pkg/utils/jwtclaims/jwt.go
@@ -161,36 +161,3 @@ func GetByPath(m map[string]any, path string) (any, bool) {
}
return cur, true
}
-
-// EvalMatch checks if a claim matches any of the desired values
-func EvalMatch(v any, want []string) bool {
- if len(want) == 0 {
- if b, ok := v.(bool); ok {
- return b
- }
- return false
- }
- wantSet := map[string]struct{}{}
- for _, s := range want {
- wantSet[strings.ToLower(s)] = struct{}{}
- }
- switch x := v.(type) {
- case string:
- _, ok := wantSet[strings.ToLower(x)]
- return ok
- case []any:
- for _, it := range x {
- if s, ok := it.(string); ok {
- if _, ok2 := wantSet[strings.ToLower(s)]; ok2 {
- return true
- }
- }
- }
- return false
- case bool:
- _, ok := wantSet[strings.ToLower(fmt.Sprintf("%v", x))]
- return ok
- default:
- return false
- }
-}
diff --git a/backend/resources/migrations/postgres/054_add_rbac.down.sql b/backend/resources/migrations/postgres/054_add_rbac.down.sql
new file mode 100644
index 000000000..0bc7893ed
--- /dev/null
+++ b/backend/resources/migrations/postgres/054_add_rbac.down.sql
@@ -0,0 +1,17 @@
+
+DELETE FROM settings WHERE key = 'oidcGroupsClaim';
+
+DROP INDEX IF EXISTS idx_orm_claim;
+DROP TABLE IF EXISTS oidc_role_mappings;
+
+DROP INDEX IF EXISTS idx_akp_uniq;
+DROP INDEX IF EXISTS idx_akp_key;
+DROP TABLE IF EXISTS api_key_permissions;
+
+DROP INDEX IF EXISTS idx_ura_uniq;
+DROP INDEX IF EXISTS idx_ura_env;
+DROP INDEX IF EXISTS idx_ura_role;
+DROP INDEX IF EXISTS idx_ura_user;
+DROP TABLE IF EXISTS user_role_assignments;
+
+DROP TABLE IF EXISTS roles;
diff --git a/backend/resources/migrations/postgres/054_add_rbac.up.sql b/backend/resources/migrations/postgres/054_add_rbac.up.sql
new file mode 100644
index 000000000..811d56bfb
--- /dev/null
+++ b/backend/resources/migrations/postgres/054_add_rbac.up.sql
@@ -0,0 +1,53 @@
+
+CREATE TABLE IF NOT EXISTS roles (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL UNIQUE,
+ description TEXT,
+ permissions JSONB NOT NULL DEFAULT '[]',
+ built_in BOOLEAN NOT NULL DEFAULT false,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ
+);
+
+CREATE TABLE IF NOT EXISTS user_role_assignments (
+ id TEXT PRIMARY KEY,
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ role_id TEXT NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
+ environment_id TEXT REFERENCES environments(id) ON DELETE CASCADE,
+ source TEXT NOT NULL DEFAULT 'manual',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ
+);
+
+CREATE INDEX IF NOT EXISTS idx_ura_user ON user_role_assignments(user_id);
+CREATE INDEX IF NOT EXISTS idx_ura_role ON user_role_assignments(role_id);
+CREATE INDEX IF NOT EXISTS idx_ura_env ON user_role_assignments(environment_id);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_ura_uniq
+ ON user_role_assignments(user_id, role_id, COALESCE(environment_id, ''));
+
+CREATE TABLE IF NOT EXISTS api_key_permissions (
+ id TEXT PRIMARY KEY,
+ api_key_id TEXT NOT NULL REFERENCES api_keys(id) ON DELETE CASCADE,
+ permission TEXT NOT NULL,
+ environment_id TEXT REFERENCES environments(id) ON DELETE CASCADE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ
+);
+
+CREATE INDEX IF NOT EXISTS idx_akp_key ON api_key_permissions(api_key_id);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_akp_uniq
+ ON api_key_permissions(api_key_id, permission, COALESCE(environment_id, ''));
+
+CREATE TABLE IF NOT EXISTS oidc_role_mappings (
+ id TEXT PRIMARY KEY,
+ claim_value TEXT NOT NULL,
+ role_id TEXT NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
+ environment_id TEXT REFERENCES environments(id) ON DELETE CASCADE,
+ -- 'manual' = created via UI/API; 'env' = declared via OIDC_ROLE_MAPPINGS
+ -- env var and reconciled at boot. The API refuses mutations on 'env' rows.
+ source TEXT NOT NULL DEFAULT 'manual',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMPTZ
+);
+
+CREATE INDEX IF NOT EXISTS idx_orm_claim ON oidc_role_mappings(claim_value);
diff --git a/backend/resources/migrations/sqlite/054_add_rbac.down.sql b/backend/resources/migrations/sqlite/054_add_rbac.down.sql
new file mode 100644
index 000000000..0bc7893ed
--- /dev/null
+++ b/backend/resources/migrations/sqlite/054_add_rbac.down.sql
@@ -0,0 +1,17 @@
+
+DELETE FROM settings WHERE key = 'oidcGroupsClaim';
+
+DROP INDEX IF EXISTS idx_orm_claim;
+DROP TABLE IF EXISTS oidc_role_mappings;
+
+DROP INDEX IF EXISTS idx_akp_uniq;
+DROP INDEX IF EXISTS idx_akp_key;
+DROP TABLE IF EXISTS api_key_permissions;
+
+DROP INDEX IF EXISTS idx_ura_uniq;
+DROP INDEX IF EXISTS idx_ura_env;
+DROP INDEX IF EXISTS idx_ura_role;
+DROP INDEX IF EXISTS idx_ura_user;
+DROP TABLE IF EXISTS user_role_assignments;
+
+DROP TABLE IF EXISTS roles;
diff --git a/backend/resources/migrations/sqlite/054_add_rbac.up.sql b/backend/resources/migrations/sqlite/054_add_rbac.up.sql
new file mode 100644
index 000000000..0428fc398
--- /dev/null
+++ b/backend/resources/migrations/sqlite/054_add_rbac.up.sql
@@ -0,0 +1,60 @@
+
+CREATE TABLE IF NOT EXISTS roles (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL UNIQUE,
+ description TEXT,
+ permissions TEXT NOT NULL DEFAULT '[]',
+ built_in BOOLEAN NOT NULL DEFAULT 0,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME
+);
+
+CREATE TABLE IF NOT EXISTS user_role_assignments (
+ id TEXT PRIMARY KEY,
+ user_id TEXT NOT NULL,
+ role_id TEXT NOT NULL,
+ environment_id TEXT,
+ source TEXT NOT NULL DEFAULT 'manual',
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME,
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,
+ FOREIGN KEY (environment_id) REFERENCES environments(id) ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS idx_ura_user ON user_role_assignments(user_id);
+CREATE INDEX IF NOT EXISTS idx_ura_role ON user_role_assignments(role_id);
+CREATE INDEX IF NOT EXISTS idx_ura_env ON user_role_assignments(environment_id);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_ura_uniq
+ ON user_role_assignments(user_id, role_id, COALESCE(environment_id, ''));
+
+CREATE TABLE IF NOT EXISTS api_key_permissions (
+ id TEXT PRIMARY KEY,
+ api_key_id TEXT NOT NULL,
+ permission TEXT NOT NULL,
+ environment_id TEXT,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME,
+ FOREIGN KEY (api_key_id) REFERENCES api_keys(id) ON DELETE CASCADE,
+ FOREIGN KEY (environment_id) REFERENCES environments(id) ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS idx_akp_key ON api_key_permissions(api_key_id);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_akp_uniq
+ ON api_key_permissions(api_key_id, permission, COALESCE(environment_id, ''));
+
+CREATE TABLE IF NOT EXISTS oidc_role_mappings (
+ id TEXT PRIMARY KEY,
+ claim_value TEXT NOT NULL,
+ role_id TEXT NOT NULL,
+ environment_id TEXT,
+ -- 'manual' = created via UI/API; 'env' = declared via OIDC_ROLE_MAPPINGS
+ -- env var and reconciled at boot. The API refuses mutations on 'env' rows.
+ source TEXT NOT NULL DEFAULT 'manual',
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at DATETIME,
+ FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,
+ FOREIGN KEY (environment_id) REFERENCES environments(id) ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS idx_orm_claim ON oidc_role_mappings(claim_value);
diff --git a/cli/internal/types/endpoints.go b/cli/internal/types/endpoints.go
index a8b273084..3aa235b05 100644
--- a/cli/internal/types/endpoints.go
+++ b/cli/internal/types/endpoints.go
@@ -24,8 +24,18 @@ type ArcaneApiEndpoints struct {
ApiKeyEndpoint string
// Users
- UsersEndpoint string
- UserEndpoint string
+ UsersEndpoint string
+ UserEndpoint string
+ UserRoleAssignmentsEndpoint string
+
+ // Roles (RBAC)
+ RolesEndpoint string
+ RoleEndpoint string
+ RolesAvailablePermissionsEndpoint string
+
+ // OIDC role mappings
+ OidcRoleMappingsEndpoint string
+ OidcRoleMappingEndpoint string
// Environments
EnvironmentsEndpoint string
@@ -185,8 +195,18 @@ var Endpoints = ArcaneApiEndpoints{ //nolint:gosec // static endpoint paths; aut
ApiKeyEndpoint: "/api/api-keys/%s",
// Users
- UsersEndpoint: "/api/users",
- UserEndpoint: "/api/users/%s",
+ UsersEndpoint: "/api/users",
+ UserEndpoint: "/api/users/%s",
+ UserRoleAssignmentsEndpoint: "/api/users/%s/role-assignments",
+
+ // Roles (RBAC)
+ RolesEndpoint: "/api/roles",
+ RoleEndpoint: "/api/roles/%s",
+ RolesAvailablePermissionsEndpoint: "/api/roles/available-permissions",
+
+ // OIDC role mappings
+ OidcRoleMappingsEndpoint: "/api/oidc/role-mappings",
+ OidcRoleMappingEndpoint: "/api/oidc/role-mappings/%s",
// Environments
EnvironmentsEndpoint: "/api/environments",
@@ -343,6 +363,22 @@ func (e ArcaneApiEndpoints) ApiKey(id string) string { return fmt.Sprintf(e.ApiK
// User endpoints
func (e ArcaneApiEndpoints) Users() string { return e.UsersEndpoint }
func (e ArcaneApiEndpoints) User(id string) string { return fmt.Sprintf(e.UserEndpoint, id) }
+func (e ArcaneApiEndpoints) UserRoleAssignments(userID string) string {
+ return fmt.Sprintf(e.UserRoleAssignmentsEndpoint, userID)
+}
+
+// Role (RBAC) endpoints
+func (e ArcaneApiEndpoints) Roles() string { return e.RolesEndpoint }
+func (e ArcaneApiEndpoints) Role(id string) string { return fmt.Sprintf(e.RoleEndpoint, id) }
+func (e ArcaneApiEndpoints) RolesAvailablePermissions() string {
+ return e.RolesAvailablePermissionsEndpoint
+}
+
+// OIDC role mapping endpoints
+func (e ArcaneApiEndpoints) OidcRoleMappings() string { return e.OidcRoleMappingsEndpoint }
+func (e ArcaneApiEndpoints) OidcRoleMapping(id string) string {
+ return fmt.Sprintf(e.OidcRoleMappingEndpoint, id)
+}
// Environment endpoints
func (e ArcaneApiEndpoints) Environments() string { return e.EnvironmentsEndpoint }
diff --git a/cli/pkg/admin/apikeys/cmd.go b/cli/pkg/admin/apikeys/cmd.go
index dab8200e6..534041727 100644
--- a/cli/pkg/admin/apikeys/cmd.go
+++ b/cli/pkg/admin/apikeys/cmd.go
@@ -1,11 +1,10 @@
package apikeys
import (
- "encoding/json"
"fmt"
+ "strings"
"time"
- "github.com/getarcaneapp/arcane/cli/internal/client"
"github.com/getarcaneapp/arcane/cli/internal/cmdutil"
"github.com/getarcaneapp/arcane/cli/internal/output"
"github.com/getarcaneapp/arcane/cli/internal/types"
@@ -21,12 +20,48 @@ var (
jsonOutput bool
)
+var (
+ apikeyCreatePermissions []string
+)
+
var (
apikeyUpdateName string
apikeyUpdateDescription string
apikeyUpdateExpiresAt string
+ apikeyUpdatePermissions []string
)
+// parsePermissionGrantsInternal turns `--permission` tokens into the wire-format
+// grant list. Each token is either `resource:action` (global grant) or
+// `resource:action:envId` (env-scoped grant). Anything else is an error so the
+// user catches typos before the server rejects them.
+func parsePermissionGrantsInternal(tokens []string) ([]apikey.PermissionGrant, error) {
+ out := make([]apikey.PermissionGrant, 0, len(tokens))
+ for _, raw := range tokens {
+ token := strings.TrimSpace(raw)
+ if token == "" {
+ continue
+ }
+ parts := strings.Split(token, ":")
+ switch len(parts) {
+ case 2:
+ out = append(out, apikey.PermissionGrant{Permission: token})
+ case 3:
+ env := parts[2]
+ if parts[0] == "" || parts[1] == "" || env == "" {
+ return nil, fmt.Errorf("invalid --permission value %q (expected `resource:action[:envId]`)", raw)
+ }
+ out = append(out, apikey.PermissionGrant{
+ Permission: parts[0] + ":" + parts[1],
+ EnvironmentID: &env,
+ })
+ default:
+ return nil, fmt.Errorf("invalid --permission value %q (expected `resource:action[:envId]`)", raw)
+ }
+ }
+ return out, nil
+}
+
// ApiKeysCmd is the parent command for API key operations
var ApiKeysCmd = &cobra.Command{
Use: "api-keys",
@@ -40,7 +75,7 @@ var listCmd = &cobra.Command{
Short: "List API keys",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -58,20 +93,15 @@ var listCmd = &cobra.Command{
defer func() { _ = resp.Body.Close() }()
var result base.Paginated[apikey.ApiKey]
- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return fmt.Errorf("failed to list API keys: %w", err)
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result, "", " ")
- if err != nil {
- return fmt.Errorf("failed to marshal JSON: %w", err)
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result)
}
- headers := []string{"ID", "NAME", "DESCRIPTION", "CREATED", "LAST USED"}
+ headers := []string{"ID", "NAME", "DESCRIPTION", "PERMISSIONS", "CREATED", "LAST USED"}
rows := make([][]string, len(result.Data))
for i, key := range result.Data {
description := ""
@@ -86,6 +116,7 @@ var listCmd = &cobra.Command{
key.ID,
key.Name,
description,
+ fmt.Sprintf("%d", len(key.Permissions)),
key.CreatedAt.Format("2006-01-02 15:04"),
lastUsed,
}
@@ -105,51 +136,46 @@ var createCmd = &cobra.Command{
RunE: func(cmd *cobra.Command, args []string) error {
description, _ := cmd.Flags().GetString("description")
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
+ grants, err := parsePermissionGrantsInternal(apikeyCreatePermissions)
+ if err != nil {
+ return err
+ }
+ if len(grants) == 0 {
+ return fmt.Errorf("at least one --permission is required (e.g. --permission containers:list)")
+ }
createReq := apikey.CreateApiKey{
- Name: args[0],
+ Name: args[0],
+ Permissions: grants,
}
if description != "" {
createReq.Description = &description
}
- // TODO: Parse expiresAt string to time.Time if needed
- // if expiresAt != "" {
- // parsedTime, err := time.Parse(time.RFC3339, expiresAt)
- // if err == nil {
- // createReq.ExpiresAt = &parsedTime
- // }
- // }
-
- reqBody, err := json.Marshal(createReq)
- if err != nil {
- return fmt.Errorf("failed to marshal request: %w", err)
+ if expiresAtRaw, _ := cmd.Flags().GetString("expires-at"); expiresAtRaw != "" {
+ parsed, err := time.Parse(time.RFC3339, expiresAtRaw)
+ if err != nil {
+ return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", err)
+ }
+ createReq.ExpiresAt = &parsed
}
- resp, err := c.Post(cmd.Context(), types.Endpoints.ApiKeys(), reqBody)
+ resp, err := c.Post(cmd.Context(), types.Endpoints.ApiKeys(), createReq)
if err != nil {
return fmt.Errorf("failed to create API key: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to create API key: %w", err)
- }
var result base.ApiResponse[apikey.ApiKeyCreatedDto]
- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return fmt.Errorf("failed to create API key: %w", err)
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return fmt.Errorf("failed to marshal JSON: %w", err)
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("API key created successfully")
@@ -181,7 +207,7 @@ var deleteCmd = &cobra.Command{
}
}
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -197,15 +223,10 @@ var deleteCmd = &cobra.Command{
if jsonOutput {
var result base.ApiResponse[any]
- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return fmt.Errorf("failed to delete API key: %w", err)
}
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return fmt.Errorf("failed to marshal JSON: %w", err)
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("API key deleted successfully")
@@ -219,7 +240,7 @@ var getCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -231,17 +252,12 @@ var getCmd = &cobra.Command{
defer func() { _ = resp.Body.Close() }()
var result base.ApiResponse[apikey.ApiKey]
- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return fmt.Errorf("failed to get API key: %w", err)
}
if jsonOutput {
- resultBytes, err := json.MarshalIndent(result.Data, "", " ")
- if err != nil {
- return fmt.Errorf("failed to marshal JSON: %w", err)
- }
- fmt.Println(string(resultBytes))
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Header("API Key Details")
@@ -258,6 +274,18 @@ var getCmd = &cobra.Command{
if result.Data.ExpiresAt != nil {
output.KeyValue("Expires", result.Data.ExpiresAt.Format("2006-01-02 15:04"))
}
+ output.KeyValue("Permissions", fmt.Sprintf("%d", len(result.Data.Permissions)))
+ if len(result.Data.Permissions) > 0 {
+ rows := make([][]string, len(result.Data.Permissions))
+ for i, g := range result.Data.Permissions {
+ scope := "global"
+ if g.EnvironmentID != nil {
+ scope = *g.EnvironmentID
+ }
+ rows[i] = []string{g.Permission, scope}
+ }
+ output.Table([]string{"PERMISSION", "SCOPE"}, rows)
+ }
return nil
},
}
@@ -268,7 +296,7 @@ var updateCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
- c, err := client.NewFromConfig()
+ c, err := cmdutil.ClientFromCommand(cmd)
if err != nil {
return err
}
@@ -287,6 +315,15 @@ var updateCmd = &cobra.Command{
}
req.ExpiresAt = &parsedTime
}
+ if cmd.Flags().Changed("permission") {
+ grants, err := parsePermissionGrantsInternal(apikeyUpdatePermissions)
+ if err != nil {
+ return err
+ }
+ // Allow `--permission ""` once to clear all grants. Otherwise
+ // the parsed slice replaces the key's permission set entirely.
+ req.Permissions = grants
+ }
resp, err := c.Put(cmd.Context(), types.Endpoints.ApiKey(args[0]), req)
if err != nil {
@@ -299,12 +336,10 @@ var updateCmd = &cobra.Command{
if jsonOutput {
var result base.ApiResponse[any]
- if err := json.NewDecoder(resp.Body).Decode(&result); err == nil {
- if resultBytes, err := json.MarshalIndent(result.Data, "", " "); err == nil {
- fmt.Println(string(resultBytes))
- }
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return fmt.Errorf("failed to update API key: %w", err)
}
- return nil
+ return cmdutil.PrintJSON(result.Data)
}
output.Success("API key updated successfully")
@@ -326,8 +361,11 @@ func init() {
// Create command flags
createCmd.Flags().StringP("description", "d", "", "Description for the API key")
- createCmd.Flags().String("expires-at", "", "Expiration date (ISO 8601 format)")
+ createCmd.Flags().String("expires-at", "", "Expiration date (RFC3339 format)")
+ createCmd.Flags().StringArrayVarP(&apikeyCreatePermissions, "permission", "p", nil,
+ "Permission to grant as `resource:action[:envId]` (repeatable, required). Omit envId for a global grant. Cannot exceed your own permissions.")
createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = createCmd.MarkFlagRequired("permission")
// Get command flags
getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
@@ -336,6 +374,8 @@ func init() {
updateCmd.Flags().StringVar(&apikeyUpdateName, "name", "", "API key name")
updateCmd.Flags().StringVarP(&apikeyUpdateDescription, "description", "d", "", "API key description")
updateCmd.Flags().StringVar(&apikeyUpdateExpiresAt, "expires-at", "", "Expiration date (RFC3339 format)")
+ updateCmd.Flags().StringArrayVarP(&apikeyUpdatePermissions, "permission", "p", nil,
+ "Replace the key's permission grants. Use `resource:action[:envId]` (repeatable). Pass --permission \"\" once to clear all grants.")
updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
// Delete command flags
diff --git a/cli/pkg/admin/cmd.go b/cli/pkg/admin/cmd.go
index c671a0451..43339b73e 100644
--- a/cli/pkg/admin/cmd.go
+++ b/cli/pkg/admin/cmd.go
@@ -4,6 +4,8 @@ import (
"github.com/getarcaneapp/arcane/cli/pkg/admin/apikeys"
"github.com/getarcaneapp/arcane/cli/pkg/admin/events"
"github.com/getarcaneapp/arcane/cli/pkg/admin/notifications"
+ "github.com/getarcaneapp/arcane/cli/pkg/admin/oidcmappings"
+ "github.com/getarcaneapp/arcane/cli/pkg/admin/roles"
"github.com/getarcaneapp/arcane/cli/pkg/admin/users"
"github.com/spf13/cobra"
)
@@ -17,6 +19,8 @@ var AdminCmd = &cobra.Command{
func init() {
AdminCmd.AddCommand(users.UsersCmd)
+ AdminCmd.AddCommand(roles.RolesCmd)
+ AdminCmd.AddCommand(oidcmappings.OidcMappingsCmd)
AdminCmd.AddCommand(apikeys.ApiKeysCmd)
AdminCmd.AddCommand(events.EventsCmd)
AdminCmd.AddCommand(notifications.NotificationsCmd)
diff --git a/cli/pkg/admin/oidcmappings/cmd.go b/cli/pkg/admin/oidcmappings/cmd.go
new file mode 100644
index 000000000..14d789524
--- /dev/null
+++ b/cli/pkg/admin/oidcmappings/cmd.go
@@ -0,0 +1,257 @@
+// Package oidcmappings provides the `arcane admin oidc-mappings` command tree.
+// Mappings convert OIDC group/claim values into role assignments on every
+// login — they're the SSO-driven counterpart to manual role assignments.
+package oidcmappings
+
+import (
+ "fmt"
+
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
+ "github.com/getarcaneapp/arcane/cli/internal/output"
+ "github.com/getarcaneapp/arcane/cli/internal/types"
+ "github.com/getarcaneapp/arcane/types/base"
+ roletypes "github.com/getarcaneapp/arcane/types/role"
+ "github.com/spf13/cobra"
+)
+
+var (
+ forceFlag bool
+ jsonOutput bool
+)
+
+var (
+ createClaim string
+ createRoleID string
+ createEnvironment string
+)
+
+var (
+ updateClaim string
+ updateRoleID string
+ updateEnvironment string
+)
+
+// OidcMappingsCmd is the parent command for OIDC role mapping operations.
+var OidcMappingsCmd = &cobra.Command{
+ Use: "oidc-mappings",
+ Aliases: []string{"oidc-mapping", "oidc"},
+ Short: "Manage OIDC group → role mappings",
+ Long: "Manage OIDC group → role mappings. On every OIDC login, Arcane " +
+ "looks up the user's groups claim and applies the matching mappings " +
+ "as source='oidc' role assignments. The groups claim itself is " +
+ "configured via the oidcGroupsClaim setting (default `groups`).",
+}
+
+var listCmd = &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List OIDC role mappings",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resp, err := c.Get(cmd.Context(), types.Endpoints.OidcRoleMappings())
+ if err != nil {
+ return fmt.Errorf("failed to list OIDC mappings: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[[]roletypes.OidcRoleMapping]
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return fmt.Errorf("failed to list OIDC mappings: %w", err)
+ }
+
+ if jsonOutput {
+ return cmdutil.PrintJSON(result.Data)
+ }
+
+ if len(result.Data) == 0 {
+ output.Info("No OIDC role mappings configured")
+ return nil
+ }
+
+ headers := []string{"ID", "CLAIM VALUE", "ROLE", "SCOPE"}
+ rows := make([][]string, len(result.Data))
+ for i, m := range result.Data {
+ scope := "global"
+ if m.EnvironmentID != nil {
+ scope = *m.EnvironmentID
+ }
+ rows[i] = []string{m.ID, m.ClaimValue, m.RoleID, scope}
+ }
+ output.Table(headers, rows)
+ return nil
+ },
+}
+
+var createCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create an OIDC role mapping",
+ Example: ` arcane admin oidc-mappings create --claim docker-admins --role role_admin`,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ req := roletypes.CreateOidcRoleMapping{
+ ClaimValue: createClaim,
+ RoleID: createRoleID,
+ }
+ if cmd.Flags().Changed("environment") && createEnvironment != "" {
+ env := createEnvironment
+ req.EnvironmentID = &env
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.OidcRoleMappings(), req)
+ if err != nil {
+ return fmt.Errorf("failed to create OIDC mapping: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ var result base.ApiResponse[roletypes.OidcRoleMapping]
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return fmt.Errorf("failed to create OIDC mapping: %w", err)
+ }
+
+ if jsonOutput {
+ return cmdutil.PrintJSON(result.Data)
+ }
+ output.Success("OIDC mapping created")
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Claim value", result.Data.ClaimValue)
+ output.KeyValue("Role", result.Data.RoleID)
+ scope := "global"
+ if result.Data.EnvironmentID != nil {
+ scope = *result.Data.EnvironmentID
+ }
+ output.KeyValue("Scope", scope)
+ return nil
+ },
+}
+
+var updateCmd = &cobra.Command{
+ Use: "update <mapping-id>",
+ Short: "Update an OIDC role mapping",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ // The PUT contract requires every field — fetch current and overlay.
+ current, err := fetchMappingInternal(cmd, args[0])
+ if err != nil {
+ return err
+ }
+
+ req := roletypes.UpdateOidcRoleMapping{
+ ClaimValue: current.ClaimValue,
+ RoleID: current.RoleID,
+ EnvironmentID: current.EnvironmentID,
+ }
+ if cmd.Flags().Changed("claim") {
+ req.ClaimValue = updateClaim
+ }
+ if cmd.Flags().Changed("role") {
+ req.RoleID = updateRoleID
+ }
+ if cmd.Flags().Changed("environment") {
+ if updateEnvironment == "" {
+ // Empty value flips an env-scoped mapping back to global.
+ req.EnvironmentID = nil
+ } else {
+ env := updateEnvironment
+ req.EnvironmentID = &env
+ }
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.OidcRoleMapping(args[0]), req)
+ if err != nil {
+ return fmt.Errorf("failed to update OIDC mapping: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to update OIDC mapping: %w", err)
+ }
+ output.Success("OIDC mapping updated")
+ return nil
+ },
+}
+
+var deleteCmd = &cobra.Command{
+ Use: "delete <mapping-id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete an OIDC role mapping",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if !forceFlag {
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Delete OIDC mapping %s?", args[0]))
+ if err != nil {
+ return err
+ }
+ if !confirmed {
+ fmt.Println("Cancelled")
+ return nil
+ }
+ }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resp, err := c.Delete(cmd.Context(), types.Endpoints.OidcRoleMapping(args[0]))
+ if err != nil {
+ return fmt.Errorf("failed to delete OIDC mapping: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete OIDC mapping: %w", err)
+ }
+ output.Success("OIDC mapping deleted")
+ return nil
+ },
+}
+
+func fetchMappingInternal(cmd *cobra.Command, id string) (*roletypes.OidcRoleMapping, error) {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return nil, err
+ }
+ resp, err := c.Get(cmd.Context(), types.Endpoints.OidcRoleMapping(id))
+ if err != nil {
+ return nil, fmt.Errorf("failed to load current mapping: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ var result base.ApiResponse[roletypes.OidcRoleMapping]
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return nil, fmt.Errorf("failed to load current mapping: %w", err)
+ }
+ return &result.Data, nil
+}
+
+func init() {
+ OidcMappingsCmd.AddCommand(listCmd)
+ OidcMappingsCmd.AddCommand(createCmd)
+ OidcMappingsCmd.AddCommand(updateCmd)
+ OidcMappingsCmd.AddCommand(deleteCmd)
+
+ listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ createCmd.Flags().StringVar(&createClaim, "claim", "", "OIDC claim value (required)")
+ createCmd.Flags().StringVar(&createRoleID, "role", "", "Role ID to grant when the claim matches (required)")
+ createCmd.Flags().StringVar(&createEnvironment, "environment", "", "Scope the grant to one environment (omit for global)")
+ createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = createCmd.MarkFlagRequired("claim")
+ _ = createCmd.MarkFlagRequired("role")
+
+ updateCmd.Flags().StringVar(&updateClaim, "claim", "", "New claim value")
+ updateCmd.Flags().StringVar(&updateRoleID, "role", "", "New role ID")
+ updateCmd.Flags().StringVar(&updateEnvironment, "environment", "", "New environment scope (pass empty to make global)")
+ updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
+}
diff --git a/cli/pkg/admin/roles/cmd.go b/cli/pkg/admin/roles/cmd.go
new file mode 100644
index 000000000..cb2b6662e
--- /dev/null
+++ b/cli/pkg/admin/roles/cmd.go
@@ -0,0 +1,479 @@
+// Package roles provides the `arcane admin roles` command tree for RBAC.
+// Roles are named permission sets that can be granted to users (globally or
+// per-environment) and to API keys. Four built-in roles (Admin, Editor,
+// Deployer, Viewer) ship with Arcane and cannot be modified; everything else
+// is a custom role created via this command.
+package roles
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/getarcaneapp/arcane/cli/internal/cmdutil"
+ "github.com/getarcaneapp/arcane/cli/internal/output"
+ "github.com/getarcaneapp/arcane/cli/internal/types"
+ "github.com/getarcaneapp/arcane/types/base"
+ roletypes "github.com/getarcaneapp/arcane/types/role"
+ "github.com/spf13/cobra"
+)
+
+var (
+ limitFlag int
+ startFlag int
+ forceFlag bool
+ jsonOutput bool
+)
+
+var (
+ roleCreateName string
+ roleCreateDescription string
+ roleCreatePermissions []string
+)
+
+var (
+ roleUpdateName string
+ roleUpdateDescription string
+ roleUpdatePermissions []string
+)
+
+// `assign` flags. Each --role argument is parsed as `<roleId>[:<envId>]`.
+// Omitting the env id gives a global assignment.
+var (
+ assignRoles []string
+)
+
+// RolesCmd is the parent command for role operations.
+var RolesCmd = &cobra.Command{
+ Use: "roles",
+ Aliases: []string{"role"},
+ Short: "Manage roles and per-user role assignments",
+}
+
+// ---------- Role CRUD ----------
+
+var listCmd = &cobra.Command{
+ Use: "list",
+ Aliases: []string{"ls"},
+ Short: "List roles",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ path := types.Endpoints.Roles()
+ path, err = cmdutil.ApplyPaginationParams(cmd, path, "roles", "limit", limitFlag, 20, "start", startFlag)
+ if err != nil {
+ return fmt.Errorf("failed to build pagination query: %w", err)
+ }
+
+ resp, err := c.Get(cmd.Context(), path)
+ if err != nil {
+ return fmt.Errorf("failed to list roles: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.Paginated[roletypes.Role]
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return fmt.Errorf("failed to list roles: %w", err)
+ }
+
+ if jsonOutput {
+ return cmdutil.PrintJSON(result)
+ }
+
+ headers := []string{"ID", "NAME", "TYPE", "USERS", "PERMISSIONS"}
+ rows := make([][]string, len(result.Data))
+ for i, r := range result.Data {
+ roleType := "custom"
+ if r.BuiltIn {
+ roleType = "built-in"
+ }
+ rows[i] = []string{
+ r.ID,
+ r.Name,
+ roleType,
+ fmt.Sprintf("%d", r.AssignedUserCount),
+ fmt.Sprintf("%d", len(r.Permissions)),
+ }
+ }
+ output.Table(headers, rows)
+ output.Showing(len(result.Data), result.Pagination.TotalItems, "roles")
+ return nil
+ },
+}
+
+var getCmd = &cobra.Command{
+ Use: "get <role-id>",
+ Short: "Get role details",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resp, err := c.Get(cmd.Context(), types.Endpoints.Role(args[0]))
+ if err != nil {
+ return fmt.Errorf("failed to get role: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[roletypes.Role]
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return fmt.Errorf("failed to get role: %w", err)
+ }
+
+ if jsonOutput {
+ return cmdutil.PrintJSON(result.Data)
+ }
+
+ output.Header("Role Details")
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Name", result.Data.Name)
+ if result.Data.Description != nil {
+ output.KeyValue("Description", *result.Data.Description)
+ }
+ output.KeyValue("Built-in", fmt.Sprintf("%t", result.Data.BuiltIn))
+ output.KeyValue("Assigned users", fmt.Sprintf("%d", result.Data.AssignedUserCount))
+ output.KeyValue("Permissions", fmt.Sprintf("%d", len(result.Data.Permissions)))
+ if len(result.Data.Permissions) > 0 {
+ rows := make([][]string, len(result.Data.Permissions))
+ for i, p := range result.Data.Permissions {
+ rows[i] = []string{p}
+ }
+ output.Table([]string{"PERMISSION"}, rows)
+ }
+ return nil
+ },
+}
+
+var createCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create a custom role",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if roleCreateName == "" {
+ return fmt.Errorf("--name is required")
+ }
+ if len(roleCreatePermissions) == 0 {
+ return fmt.Errorf("at least one --permission is required")
+ }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ req := roletypes.CreateRole{
+ Name: roleCreateName,
+ Permissions: roleCreatePermissions,
+ }
+ if cmd.Flags().Changed("description") {
+ req.Description = &roleCreateDescription
+ }
+
+ resp, err := c.Post(cmd.Context(), types.Endpoints.Roles(), req)
+ if err != nil {
+ return fmt.Errorf("failed to create role: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ var result base.ApiResponse[roletypes.Role]
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return fmt.Errorf("failed to create role: %w", err)
+ }
+
+ if jsonOutput {
+ return cmdutil.PrintJSON(result.Data)
+ }
+ output.Success("Role %s created", result.Data.Name)
+ output.KeyValue("ID", result.Data.ID)
+ output.KeyValue("Permissions", fmt.Sprintf("%d", len(result.Data.Permissions)))
+ return nil
+ },
+}
+
+var updateCmd = &cobra.Command{
+ Use: "update <role-id>",
+ Short: "Update a custom role (built-in roles are immutable)",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+
+ // The PUT contract requires every field — fetch the current state
+ // and overlay only the flags the caller set, so partial updates work
+ // from the CLI without forcing the user to retype everything.
+ current, err := fetchRoleInternal(cmd, args[0])
+ if err != nil {
+ return err
+ }
+
+ req := roletypes.UpdateRole{
+ Name: current.Name,
+ Description: current.Description,
+ Permissions: current.Permissions,
+ }
+ if cmd.Flags().Changed("name") {
+ req.Name = roleUpdateName
+ }
+ if cmd.Flags().Changed("description") {
+ req.Description = &roleUpdateDescription
+ }
+ if cmd.Flags().Changed("permission") {
+ req.Permissions = roleUpdatePermissions
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.Role(args[0]), req)
+ if err != nil {
+ return fmt.Errorf("failed to update role: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to update role: %w", err)
+ }
+
+ output.Success("Role updated")
+ return nil
+ },
+}
+
+var deleteCmd = &cobra.Command{
+ Use: "delete <role-id>",
+ Aliases: []string{"rm", "remove"},
+ Short: "Delete a custom role (built-in roles cannot be deleted)",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if !forceFlag {
+ confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Delete role %s? This removes every assignment of it.", args[0]))
+ if err != nil {
+ return err
+ }
+ if !confirmed {
+ fmt.Println("Cancelled")
+ return nil
+ }
+ }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resp, err := c.Delete(cmd.Context(), types.Endpoints.Role(args[0]))
+ if err != nil {
+ return fmt.Errorf("failed to delete role: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
+ return fmt.Errorf("failed to delete role: %w", err)
+ }
+ output.Success("Role deleted")
+ return nil
+ },
+}
+
+// ---------- Permission manifest ----------
+
+var permissionsCmd = &cobra.Command{
+ Use: "permissions",
+ Aliases: []string{"perms"},
+ Short: "List every permission the server recognizes (the manifest)",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resp, err := c.Get(cmd.Context(), types.Endpoints.RolesAvailablePermissions())
+ if err != nil {
+ return fmt.Errorf("failed to load permission manifest: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[roletypes.PermissionsManifest]
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return fmt.Errorf("failed to load permission manifest: %w", err)
+ }
+
+ if jsonOutput {
+ return cmdutil.PrintJSON(result.Data)
+ }
+
+ for _, group := range result.Data.Resources {
+ output.Header("%s (%s)", group.Label, group.Scope)
+ rows := make([][]string, len(group.Actions))
+ for i, a := range group.Actions {
+ rows[i] = []string{a.Permission, a.Label, a.Description}
+ }
+ output.Table([]string{"PERMISSION", "LABEL", "DESCRIPTION"}, rows)
+ }
+ return nil
+ },
+}
+
+// ---------- User assignments ----------
+
+var assignmentsCmd = &cobra.Command{
+ Use: "assignments <user-id>",
+ Short: "List a user's role assignments",
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resp, err := c.Get(cmd.Context(), types.Endpoints.UserRoleAssignments(args[0]))
+ if err != nil {
+ return fmt.Errorf("failed to list assignments: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[[]roletypes.RoleAssignment]
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return fmt.Errorf("failed to list assignments: %w", err)
+ }
+
+ if jsonOutput {
+ return cmdutil.PrintJSON(result.Data)
+ }
+
+ if len(result.Data) == 0 {
+ output.Info("No role assignments for user %s", args[0])
+ return nil
+ }
+ rows := make([][]string, len(result.Data))
+ for i, a := range result.Data {
+ scope := "global"
+ if a.EnvironmentID != nil {
+ scope = *a.EnvironmentID
+ }
+ rows[i] = []string{a.RoleID, scope, a.Source, a.CreatedAt.Format("2006-01-02 15:04")}
+ }
+ output.Table([]string{"ROLE", "SCOPE", "SOURCE", "CREATED"}, rows)
+ return nil
+ },
+}
+
+var assignCmd = &cobra.Command{
+ Use: "assign <user-id>",
+ Short: "Replace a user's manual role assignments",
+ Long: "Replace every MANUAL role assignment on the user with the set " +
+ "passed via --role. OIDC-sourced assignments are left untouched — " +
+ "manage those via OIDC role mappings.\n\n" +
+ "Each --role flag accepts `<roleId>[:<envId>]`. Omit the env id for " +
+ "a global assignment. Pass --role multiple times to assign more than " +
+ "one role. Pass --role \"\" (empty) once to clear every manual " +
+ "assignment.",
+ Example: ` arcane admin roles assign u_123 --role role_editor:env_prod --role role_viewer
+ arcane admin roles assign u_123 --role role_admin
+ arcane admin roles assign u_123 --role "" # clear all manual assignments`,
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ req := roletypes.SetUserAssignments{
+ Assignments: parseAssignmentsInternal(assignRoles),
+ }
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return err
+ }
+ resp, err := c.Put(cmd.Context(), types.Endpoints.UserRoleAssignments(args[0]), req)
+ if err != nil {
+ return fmt.Errorf("failed to set assignments: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ var result base.ApiResponse[[]roletypes.RoleAssignment]
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return fmt.Errorf("failed to set assignments: %w", err)
+ }
+ if jsonOutput {
+ return cmdutil.PrintJSON(result.Data)
+ }
+ output.Success("User %s now has %d role assignment(s)", args[0], len(result.Data))
+ return nil
+ },
+}
+
+// ---------- helpers ----------
+
+// parseAssignmentsInternal converts CLI --role tokens into the request payload.
+// Format: "<roleId>" (global) or "<roleId>:<envId>" (env-scoped). A single
+// empty token means "clear all assignments".
+func parseAssignmentsInternal(tokens []string) []roletypes.UserAssignmentInput {
+ if len(tokens) == 1 && strings.TrimSpace(tokens[0]) == "" {
+ return []roletypes.UserAssignmentInput{}
+ }
+ out := make([]roletypes.UserAssignmentInput, 0, len(tokens))
+ for _, raw := range tokens {
+ token := strings.TrimSpace(raw)
+ if token == "" {
+ continue
+ }
+ roleID, envID, hasEnv := strings.Cut(token, ":")
+ entry := roletypes.UserAssignmentInput{RoleID: roleID}
+ if hasEnv && envID != "" {
+ env := envID
+ entry.EnvironmentID = &env
+ }
+ out = append(out, entry)
+ }
+ return out
+}
+
+func fetchRoleInternal(cmd *cobra.Command, id string) (*roletypes.Role, error) {
+ c, err := cmdutil.ClientFromCommand(cmd)
+ if err != nil {
+ return nil, err
+ }
+ resp, err := c.Get(cmd.Context(), types.Endpoints.Role(id))
+ if err != nil {
+ return nil, fmt.Errorf("failed to load current role: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ var result base.ApiResponse[roletypes.Role]
+ if err := cmdutil.DecodeJSON(resp, &result); err != nil {
+ return nil, fmt.Errorf("failed to load current role: %w", err)
+ }
+ return &result.Data, nil
+}
+
+func init() {
+ RolesCmd.AddCommand(listCmd)
+ RolesCmd.AddCommand(getCmd)
+ RolesCmd.AddCommand(createCmd)
+ RolesCmd.AddCommand(updateCmd)
+ RolesCmd.AddCommand(deleteCmd)
+ RolesCmd.AddCommand(permissionsCmd)
+ RolesCmd.AddCommand(assignmentsCmd)
+ RolesCmd.AddCommand(assignCmd)
+
+ listCmd.Flags().IntVarP(&limitFlag, "limit", "n", 20, "Number of roles to show")
+ listCmd.Flags().IntVar(&startFlag, "start", 0, "Offset for pagination")
+ listCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ createCmd.Flags().StringVar(&roleCreateName, "name", "", "Role name (required)")
+ createCmd.Flags().StringVarP(&roleCreateDescription, "description", "d", "", "Role description")
+ createCmd.Flags().StringArrayVarP(&roleCreatePermissions, "permission", "p", nil, "Permission to grant (repeatable, e.g. containers:start)")
+ createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ updateCmd.Flags().StringVar(&roleUpdateName, "name", "", "New role name")
+ updateCmd.Flags().StringVarP(&roleUpdateDescription, "description", "d", "", "New role description")
+ updateCmd.Flags().StringArrayVarP(&roleUpdatePermissions, "permission", "p", nil, "Replace the permission set (repeatable)")
+ updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
+
+ permissionsCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ assignmentsCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ assignCmd.Flags().StringArrayVar(&assignRoles, "role", nil, "Role to grant as `<roleId>[:<envId>]` (repeatable). Pass --role \"\" to clear all manual assignments.")
+ assignCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ _ = assignCmd.MarkFlagRequired("role")
+}
diff --git a/cli/pkg/admin/users/cmd.go b/cli/pkg/admin/users/cmd.go
index b88709d4b..5c844de60 100644
--- a/cli/pkg/admin/users/cmd.go
+++ b/cli/pkg/admin/users/cmd.go
@@ -28,14 +28,12 @@ var (
userCreatePassword string
userCreateDisplayName string
userCreateEmail string
- userCreateRoles []string
)
var (
userUpdateUsername string
userUpdateDisplayName string
userUpdateEmail string
- userUpdateRoles []string
)
// UsersCmd is the parent command for user operations
@@ -43,6 +41,52 @@ var UsersCmd = &cobra.Command{
Use: "users",
Aliases: []string{"user", "usr"},
Short: "Manage users",
+ Long: "Manage users. Role assignments are managed separately via " +
+ "`arcane admin roles assign` — the legacy `--role` flag has been " +
+ "removed alongside the binary admin/user model.",
+}
+
+// summarizeRoleAssignments turns a user's role-assignment list into a short
+// human label for the list table — e.g. "Admin (global)", "Editor on 2 envs",
+// or "Admin (global) + 1 more". Returns "—" when the user holds none.
+func summarizeRoleAssignments(assignments []user.RoleAssignmentSummary) string {
+ if len(assignments) == 0 {
+ return "—"
+ }
+ type bucket struct {
+ envScoped int
+ hasGlobal bool
+ }
+ buckets := map[string]*bucket{}
+ order := []string{}
+ for _, a := range assignments {
+ b, ok := buckets[a.RoleID]
+ if !ok {
+ b = &bucket{}
+ buckets[a.RoleID] = b
+ order = append(order, a.RoleID)
+ }
+ if a.EnvironmentID == nil {
+ b.hasGlobal = true
+ } else {
+ b.envScoped++
+ }
+ }
+ parts := make([]string, 0, len(order))
+ for _, roleID := range order {
+ b := buckets[roleID]
+ switch {
+ case b.hasGlobal && b.envScoped == 0:
+ parts = append(parts, fmt.Sprintf("%s (global)", roleID))
+ case b.hasGlobal && b.envScoped > 0:
+ parts = append(parts, fmt.Sprintf("%s (global +%d envs)", roleID, b.envScoped))
+ case b.envScoped == 1:
+ parts = append(parts, fmt.Sprintf("%s on 1 env", roleID))
+ default:
+ parts = append(parts, fmt.Sprintf("%s on %d envs", roleID, b.envScoped))
+ }
+ }
+ return strings.Join(parts, ", ")
}
var listCmd = &cobra.Command{
@@ -82,7 +126,7 @@ var listCmd = &cobra.Command{
return nil
}
- headers := []string{"ID", "USERNAME", "DISPLAY NAME", "EMAIL", "ROLES"}
+ headers := []string{"ID", "USERNAME", "DISPLAY NAME", "EMAIL", "ROLE ASSIGNMENTS"}
rows := make([][]string, len(result.Data))
for i, usr := range result.Data {
displayName := ""
@@ -93,13 +137,12 @@ var listCmd = &cobra.Command{
if usr.Email != nil {
email = *usr.Email
}
- roles := strings.Join(usr.Roles, ", ")
rows[i] = []string{
usr.ID,
usr.Username,
displayName,
email,
- roles,
+ summarizeRoleAssignments(usr.RoleAssignments),
}
}
@@ -110,8 +153,11 @@ var listCmd = &cobra.Command{
}
var createCmd = &cobra.Command{
- Use: "create",
- Short: "Create a new user",
+ Use: "create",
+ Short: "Create a new user",
+ Long: "Create a new user. The user is created without any role " +
+ "assignments — grant them via `arcane admin roles assign <userId>` " +
+ "after creation.",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
c, err := client.NewFromConfig()
@@ -139,9 +185,6 @@ var createCmd = &cobra.Command{
if cmd.Flags().Changed("email") {
req.Email = &userCreateEmail
}
- if cmd.Flags().Changed("role") {
- req.Roles = userCreateRoles
- }
resp, err := c.Post(cmd.Context(), types.Endpoints.Users(), req)
if err != nil {
@@ -169,7 +212,7 @@ var createCmd = &cobra.Command{
output.Success("User %s created successfully", result.Data.Username)
output.KeyValue("ID", result.Data.ID)
output.KeyValue("Username", result.Data.Username)
- output.KeyValue("Roles", strings.Join(result.Data.Roles, ", "))
+ output.Info("No roles assigned. Use `arcane admin roles assign %s --role <roleId>` to grant access.", result.Data.ID)
return nil
},
}
@@ -214,15 +257,26 @@ var getCmd = &cobra.Command{
if result.Data.Email != nil {
output.KeyValue("Email", *result.Data.Email)
}
- output.KeyValue("Roles", strings.Join(result.Data.Roles, ", "))
output.KeyValue("Created", result.Data.CreatedAt)
+ output.KeyValue("Role Assignments", summarizeRoleAssignments(result.Data.RoleAssignments))
+ if len(result.Data.RoleAssignments) > 0 {
+ rows := make([][]string, len(result.Data.RoleAssignments))
+ for i, a := range result.Data.RoleAssignments {
+ env := "global"
+ if a.EnvironmentID != nil {
+ env = *a.EnvironmentID
+ }
+ rows[i] = []string{a.RoleID, env, a.Source}
+ }
+ output.Table([]string{"ROLE", "SCOPE", "SOURCE"}, rows)
+ }
return nil
},
}
var updateCmd = &cobra.Command{
Use: "update <user-id>",
- Short: "Update user",
+ Short: "Update user profile (role assignments managed separately)",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
@@ -241,9 +295,6 @@ var updateCmd = &cobra.Command{
if cmd.Flags().Changed("email") {
req.Email = &userUpdateEmail
}
- if cmd.Flags().Changed("role") {
- req.Roles = userUpdateRoles
- }
resp, err := c.Put(cmd.Context(), types.Endpoints.User(args[0]), req)
if err != nil {
@@ -321,7 +372,6 @@ func init() {
createCmd.Flags().StringVar(&userCreatePassword, "password", "", "Password (if omitted, will prompt securely)")
createCmd.Flags().StringVar(&userCreateDisplayName, "display-name", "", "Display name")
createCmd.Flags().StringVar(&userCreateEmail, "email", "", "Email address")
- createCmd.Flags().StringArrayVar(&userCreateRoles, "role", nil, "User role")
createCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
_ = createCmd.MarkFlagRequired("username")
@@ -330,7 +380,6 @@ func init() {
updateCmd.Flags().StringVar(&userUpdateUsername, "username", "", "New username")
updateCmd.Flags().StringVar(&userUpdateDisplayName, "display-name", "", "Display name")
updateCmd.Flags().StringVar(&userUpdateEmail, "email", "", "Email address")
- updateCmd.Flags().StringArrayVar(&userUpdateRoles, "role", nil, "User role")
updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
deleteCmd.Flags().BoolVarP(&forceFlag, "force", "f", false, "Force deletion without confirmation")
diff --git a/docs/rbac.md b/docs/rbac.md
new file mode 100644
index 000000000..17711c862
--- /dev/null
+++ b/docs/rbac.md
@@ -0,0 +1,180 @@
+# Role-Based Access Control
+
+Arcane uses a role-based access control (RBAC) system to govern what users and API keys can do. Every action — starting a container, deploying a project, editing settings — is gated by a specific permission. Permissions are bundled into roles, and roles are assigned to users (optionally scoped to a specific environment).
+
+If you're upgrading from an earlier version of Arcane, see the [Upgrade & Migration](#upgrade--migration) section below.
+
+## The mental model
+
+There are four moving parts:
+
+- **Permissions** are fine-grained strings of the form `<resource>:<action>` — for example `containers:start`, `projects:deploy`, `users:create`. You don't pick these one-by-one; you bundle them into roles.
+- **Roles** are named permission sets. Arcane ships with four built-in roles (Admin, Editor, Deployer, Viewer) and lets admins create custom ones.
+- **Role assignments** bind a user to a role, optionally scoped to a single environment. A user can hold many assignments — for example *Admin globally*, or *Editor on production + Viewer on staging*.
+- **OIDC mappings** translate SSO group claims into role assignments automatically on every login.
+
+Permissions split into two scopes:
+
+- **Org-level permissions** apply across the whole instance. Settings, users, registries, templates, environments management — these are all org-level. To get an org-level permission you need a **globally-scoped** role assignment.
+- **Env-scoped permissions** apply to one environment at a time. Containers, projects, images, volumes, networks, swarm, GitOps — these are all env-scoped. You can hold a different role on each environment.
+
+A user with `Editor on production` can manage Docker resources on that environment, but cannot change settings (org-level), and has no access at all on other environments.
+
+## Built-in roles
+
+The six built-in roles cover the common access patterns. They are immutable — you can't edit or delete them, but you can clone one as a starting point for a custom role.
+
+| Role | Intended use | What it can do |
+| -------------------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **Admin** | Full instance operators | Everything. Manages users, roles, settings, registries, and every Docker resource on every environment. |
+| **Editor** | Day-to-day Docker management | Read+write on containers, projects, images, volumes, networks, swarm resources, GitOps syncs, webhooks, jobs, notifications, vulnerabilities. Read-only on settings/users. |
+| **No-Shell Editor** | Editor without `exec` access | Same as Editor, but cannot open an interactive shell inside a running container. |
+| **Deployer** | CI/CD service accounts and on-call responders | Deploy projects, restart/start/stop/redeploy containers, sync GitOps, pull images. Cannot create or delete resources, cannot manage settings or users. |
+| **Monitor** | Observability and on-call read access | Read Docker resources, view container/project/service logs, dashboards, events. No mutations, no exec, no settings access. |
+| **Viewer** | Auditors and read-only stakeholders | Read-only access to every Docker resource and to most org-level pages. Cannot view logs, start, stop, change, or delete anything. |
+
+You must have at least one user holding **Admin** globally at all times. Arcane will refuse role-assignment edits, OIDC mapping changes, and user deletions that would leave the system with zero global admins.
+
+## Custom roles
+
+> **Admin-only:** creating, editing, and deleting roles — and assigning roles to users — is reserved for global admins. The same applies to OIDC group mappings. These actions are intentionally not delegatable as fine-grained permissions; the matching API routes return 403 to non-admins.
+
+Admins can create custom roles to fit narrower job functions — for example, "Database Operator" that can manage only volumes and backups, or "Security Reviewer" that can read vulnerability scans but trigger nothing.
+
+To create a custom role:
+
+1. Open **Settings → Roles**.
+2. Click **Create role**.
+3. Name the role, optionally add a description.
+4. In the permission picker on the right, expand each resource group and check the actions this role should grant. A "select all" checkbox at the top of each group is handy for full-read or full-write roles.
+5. Save.
+
+Custom roles can be edited and deleted at any time. Built-in roles show a badge and the editor is read-only — use the **Clone as custom role** button to start a new role pre-populated with a built-in's permissions.
+
+When you delete a custom role, every assignment of it is also removed. The global-admin guard still applies — if removing the role would orphan the last global Admin, the deletion is refused.
+
+## Assigning roles to users
+
+From **Settings → Users**, open a user. The **Role assignments** section shows every role they hold, with a scope label (Global or a specific environment name). You can:
+
+- Add a row to grant a new role on an environment (or globally).
+- Remove a row to revoke that grant.
+- Use the **Global** scope to grant org-level permissions.
+
+A user with no assignments at all can authenticate but cannot read or do anything — they'll land on a "no access" screen until an admin grants them a role.
+
+### OIDC users
+
+If a user authenticated via OIDC matches an OIDC role mapping, their assignments come from the mapping table and are managed there. The user editor will be read-only for those assignments and link to **Settings → OIDC Mappings**. Manual assignments on OIDC users (for groups that have no mapping) still work and are preserved across logins.
+
+## OIDC group mappings
+
+For SSO-only deployments, role assignment can be driven entirely from your IdP. Map an OIDC group claim value to a role and an optional environment scope; on every login Arcane reads the user's group claim and re-syncs their `source=oidc` assignments to match.
+
+### Setup
+
+1. Confirm your IdP issues a groups claim. By default Arcane reads it from the `groups` claim — you can change this in **Settings → Settings** under **OIDC Groups Claim**. Common alternatives are `realm_access.roles` (Keycloak), `memberOf` (Azure AD), or a custom claim path.
+2. Open **Settings → OIDC Mappings**.
+3. Click **Add mapping** and fill in:
+ - **Claim value**: the exact string that appears in the user's groups claim (e.g. `docker-admins`)
+ - **Role**: the role to grant when this claim is present
+ - **Environment scope**: `Global` for org-level role, or a specific environment
+4. Save.
+
+A user who is a member of multiple mapped groups receives the **union** of the matching assignments. A user demoted in the IdP loses their OIDC-sourced assignments on next login; their manual assignments (if any) remain.
+
+The legacy `OidcAdminClaim` / `OidcAdminValue` settings continue to work as an implicit "matching claim grants Admin globally" mapping. New deployments should configure mappings explicitly and leave those settings empty.
+
+### Declaring mappings via env (GitOps / IaC)
+
+For deployments that prefer to keep everything in source control, mappings can be declared via the `OIDC_ROLE_MAPPINGS` env var. The value is a JSON array of `{claimValue, roleId, environmentId?}` entries; reconciliation runs at every boot and is fully declarative — adding an entry creates it, removing one deletes it, editing one updates it. Manual mappings created in the UI are never touched.
+
+```
+OIDC_ROLE_MAPPINGS='[
+ {"claimValue": "docker-admins", "roleId": "role_admin"},
+ {"claimValue": "devops", "roleId": "role_editor", "environmentId": "env-prod"}
+]'
+```
+
+Env-managed rows are flagged with a `ENV` badge in the UI and are read-only — the Edit/Delete actions are disabled, and the API returns 409 if you try to mutate them. To change one, edit the env var and restart. Set `OIDC_ROLE_MAPPINGS='[]'` to wipe every env-managed row. The matching `OIDC_ROLE_MAPPINGS_FILE` env var works for Docker secret files.
+
+## API keys
+
+Every API key now carries its own permission set, independent of the owning user. This means you can issue narrow-scoped keys for CI/CD ("can deploy projects on prod, nothing else") without granting the owning user the same scope.
+
+### Creating a scoped API key
+
+1. Open **Settings → API Keys** and click **Create API key**.
+2. Fill in name, description, optional expiration.
+3. In the **Permissions** section, check the permissions this key should hold. Use environment scope just like role assignments.
+4. Save and copy the key value — it is shown only once.
+
+You cannot grant a key permissions you don't have yourself. Server-side validation rejects creating a key whose permission set exceeds the creator's effective permission set.
+
+### What happens to existing keys on upgrade
+
+Existing API keys created before this release inherit a snapshot of their owner's current effective permissions at upgrade time, scoped per the key's environment binding. If an owner's permissions change later, their existing keys are *not* automatically re-scoped — admins should review and re-issue keys after large permission changes.
+
+## The permission catalog
+
+Permissions follow `<resource>:<action>`. You don't usually pick them individually — the role editor groups them by resource — but here's the catalog for reference.
+
+### Org-level (require global-scope role)
+
+- **users**: `list`, `read`, `create`, `update`, `delete`
+- **roles**: `list`, `read` *(creating, editing, deleting, and assigning roles are admin-only — not delegatable)*
+- **apikeys**: `list`, `read`, `create`, `update`, `delete`
+- **settings**: `read`, `write`
+- **environments**: `list`, `read`, `create`, `update`, `delete`, `pair`, `sync`
+- **registries** (container registries): `list`, `read`, `create`, `update`, `delete`, `test`
+- **templates**: `list`, `read`, `create`, `update`, `delete`
+- **git-repositories**: `list`, `read`, `create`, `update`, `delete`, `test`, `sync`
+- **events**: `read`
+- **customize**: `manage`
+
+### Env-scoped (per environment)
+
+- **containers**: `list`, `read`, `logs`, `create`, `start`, `stop`, `restart`, `redeploy`, `delete`, `exec`, `autoupdate`
+- **projects**: `list`, `read`, `logs`, `create`, `update`, `deploy`, `down`, `restart`, `delete`, `archive`
+- **images**: `list`, `read`, `pull`, `push`, `build`, `prune`, `delete`, `upload`
+- **volumes**: `list`, `read`, `create`, `delete`, `prune`, `browse`, `upload`, `backup`
+- **networks**: `list`, `read`, `create`, `delete`, `prune`
+- **swarm**: `read`, `init`, `join`, `leave`, `spec`, `nodes`, `services`, `services:logs`, `stacks`, `configs`, `secrets`, `unlock`
+- **gitops**: `list`, `read`, `create`, `update`, `delete`, `sync`
+- **webhooks**: `list`, `create`, `update`, `delete`
+- **jobs**: `manage`
+- **notifications**: `manage`
+- **dashboard**: `read`
+- **system**: `read`, `prune`, `upgrade`
+- **image-updates**: `read`, `check`
+- **vulnerabilities**: `read`, `scan`, `manage`
+- **build-workspaces**: `manage`
+
+## Upgrade & migration
+
+When you upgrade from a pre-RBAC release of Arcane, the migration runs automatically the first time the new server starts:
+
+- Every user that held the legacy `admin` role gets a **global Admin** assignment.
+- Every other user gets a single **global Viewer** assignment (read-only across everything, including the Settings area).
+- Existing API keys inherit a snapshot of their owner's effective permissions.
+
+If for some reason the migration would leave no global admins, Arcane refuses to start and logs an error — restore from backup and investigate before retrying.
+
+After the upgrade you should:
+
+1. **Review your admins.** `Settings → Users` shows every user and their assignments at a glance.
+2. **Right-size non-admins.** Defaulting everyone to global Viewer is safe but very restrictive (read-only, no logs). Promote individual users to Editor / No-Shell Editor / Deployer / Monitor on the environments they actually use.
+3. **Map OIDC groups, if you use SSO.** Set the `OIDC Groups Claim` and add mappings under `Settings → OIDC Mappings`. Existing legacy `OidcAdminClaim` / `OidcAdminValue` settings keep working, but mappings give you finer control.
+4. **Review API keys.** Each key now carries its own permissions; the upgrade gives them a snapshot of the owner's permissions, which is the most permissive safe default. Tighten down CI/CD keys to least privilege.
+
+## Troubleshooting
+
+**"permission denied: ..." errors after upgrade.** Find the permission string in the error, look it up in the catalog above, and check whether the caller's role grants it on the right environment. Admins can audit a user's effective permissions from `Settings → Users`.
+
+**A user has no access at all.** They probably have no role assignments. Open them in `Settings → Users` and add at least one assignment (typically `Viewer` on every environment they should see).
+
+**Last-admin guard tripped (`at least one user must retain a global Admin role assignment`).** You tried to remove, demote, or OIDC-resync away the last globally-scoped Admin. Add another global Admin first, then retry.
+
+**OIDC user lost their access on login.** Their group claim no longer matches any mapping. Check the IdP-side group membership and the mapping table; OIDC-sourced assignments are re-evaluated on every login.
+
+**API key fails with permission denied.** Keys carry their own permissions, not the owner's current permissions. If you changed the owner's role, the key still has whatever it was provisioned with. Re-issue the key with the desired scope.
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index cbb073dc0..7368f8b6e 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -2050,13 +2050,11 @@
"oidc_issuer_url_description": "The issuer URL will be used to auto-discover OIDC endpoints.",
"oidc_scopes_label": "Scopes",
"oidc_scopes_placeholder": "openid email profile",
- "oidc_admin_claim_label": "Admin Claim",
- "oidc_admin_value_label": "Required Value(s)",
- "oidc_admin_role_mapping_title": "Admin Role Mapping",
- "oidc_admin_role_mapping_description": "Map an OIDC claim to grant the admin role. Examples: roles=admin, groups=admin, or admin=true.",
- "oidc_admin_claim_placeholder": "e.g., roles, groups, realm_access.roles, admin",
- "oidc_admin_value_placeholder": "e.g., admin (comma-separated)",
- "oidc_admin_value_help": "Leave empty for boolean claims (admin=true).",
+ "oidc_groups_claim_label": "Groups Claim",
+ "oidc_groups_claim_placeholder": "groups",
+ "oidc_groups_claim_help": "JSON path to the claim that contains the user's groups. Default: groups. Examples: groups, realm_access.roles, memberOf.",
+ "oidc_role_mappings_title": "Role Mappings",
+ "oidc_role_mappings_description": "Map claim values to roles assigned on login. Manual role assignments are preserved across logins.",
"oidc_skip_tls_verify_label": "Skip TLS Verification",
"oidc_skip_tls_verify_description": "Disable TLS certificate verification for OIDC endpoints. Proceed with CAUTION.",
"oidc_auto_redirect_label": "Auto Redirect to Provider",
@@ -2501,6 +2499,9 @@
"api_key_delete_success": "API key \"{name}\" deleted successfully",
"api_key_static_title": "Static Admin API Key",
"api_key_static_description": "This API key is managed by ADMIN_STATIC_API_KEY and cannot be edited or deleted from the UI.",
+ "api_key_bootstrap_title": "Environment Bootstrap API Key",
+ "api_key_bootstrap_description": "This API key is auto-generated for the agent pairing flow and cannot be edited or deleted from the UI.",
+ "api_key_bootstrap_locked_description": "This is an auto-generated key used by the agent pairing flow for an environment. It's locked from manual edits — modifying its permissions or deleting it would break the paired edge agent.",
"api_key_bulk_delete_success": "Successfully deleted {count} API key(s)",
"api_key_bulk_delete_failed": "Failed to delete {count} API key(s)",
"api_key_bulk_delete_static_skipped": "Skipped {count} static API key(s). Only deletable keys will be removed.",
@@ -2774,5 +2775,84 @@
"webhook_disable_failed": "Failed to disable webhook \"{name}\"",
"webhook_status_enabled": "Enabled",
"webhook_status_disabled": "Disabled",
- "webhook_col_status": "Status"
+ "webhook_col_status": "Status",
+ "resource_role": "role",
+ "resource_role_cap": "Role",
+ "resource_oidc_mapping": "mapping",
+ "resource_oidc_mapping_cap": "Mapping",
+ "_comment_roles": "=== ROLES & RBAC ===",
+ "roles_title": "Roles",
+ "roles_subtitle": "Define what users and API keys can do",
+ "roles_create_title": "Create role",
+ "roles_edit_title": "Edit role",
+ "roles_delete_message": "Delete role \"{name}\"? This removes every assignment of it.",
+ "roles_save_changes": "Save changes",
+ "roles_clone_button": "Clone as custom role",
+ "roles_clone_success": "Cloned to \"{name}\"",
+ "roles_clone_failed": "Failed to clone role",
+ "roles_built_in": "Built-in",
+ "roles_built_in_note": "Built-in roles cannot be edited or deleted. Use Clone to start from this set of permissions.",
+ "roles_custom": "Custom",
+ "roles_name_label": "Name",
+ "roles_name_placeholder": "e.g. Deploy Bot",
+ "roles_name_required": "Name is required",
+ "roles_description_label": "Description",
+ "roles_description_placeholder": "What is this role for?",
+ "roles_permissions_label": "Permissions",
+ "roles_permissions_required": "Pick at least one permission",
+ "roles_permissions_count": "{count} of {total} permissions",
+ "roles_col_type": "Type",
+ "roles_col_assigned_users": "Assigned users",
+ "roles_col_permissions": "Permissions",
+ "roles_assigned_users_count": "{count} users",
+ "_comment_permissions": "=== PERMISSION PICKER ===",
+ "permissions_group_label": "{resource} ({selected}/{total})",
+ "permissions_select_all": "Select all",
+ "permissions_search_placeholder": "Filter permissions…",
+ "permissions_no_matches": "No permissions match this search.",
+ "permissions_scope_global": "Global",
+ "permissions_scope_env": "Per-environment",
+ "_comment_oidc_mappings": "=== OIDC ROLE MAPPINGS ===",
+ "oidc_mappings_title": "OIDC Mappings",
+ "oidc_mappings_subtitle": "Map OIDC group claims to roles assigned on login",
+ "oidc_mappings_create_title": "Add OIDC mapping",
+ "oidc_mappings_edit_title": "Edit OIDC mapping",
+ "oidc_mappings_delete_message": "Delete mapping for claim \"{claim}\"? Users logged in through this claim will lose their assigned role on next login.",
+ "oidc_mappings_col_claim": "Claim value",
+ "oidc_mappings_col_scope": "Environment",
+ "oidc_mappings_claim_label": "Claim value",
+ "oidc_mappings_claim_placeholder": "e.g. docker-admins",
+ "oidc_mappings_claim_required": "Claim value is required",
+ "oidc_mappings_role_label": "Role",
+ "oidc_mappings_role_required": "Role is required",
+ "oidc_mappings_scope_label": "Environment scope",
+ "oidc_mappings_scope_global_option": "Global (org-wide)",
+ "oidc_mappings_empty_title": "No OIDC mappings yet",
+ "oidc_mappings_empty_body": "When OIDC users log in, Arcane checks their group claim against these mappings to assign roles. Configure the claim under Authentication settings.",
+ "_comment_user_role_assignments": "=== USER ROLE ASSIGNMENTS ===",
+ "users_role_assignments_label": "Role assignments",
+ "users_role_assignments_description": "Pick the role this user holds on each environment. Add a Global assignment for org-wide permissions.",
+ "users_role_assignments_required": "Pick at least one role assignment",
+ "users_role_assignments_add": "Add assignment",
+ "users_role_assignments_remove": "Remove",
+ "users_role_assignments_environment": "Environment",
+ "users_role_assignments_role": "Role",
+ "users_role_assignments_scope_global": "Global (org-wide)",
+ "users_role_assignments_oidc_managed": "Role assignments for this user are managed by OIDC group mappings. Manual changes will be overwritten on next login.",
+ "users_role_assignments_oidc_link": "Manage OIDC mappings",
+ "users_role_summary_none": "No access",
+ "users_role_summary_env_count": "Assigned on {count} environments",
+ "_comment_api_key_permissions": "=== API KEY PERMISSIONS ===",
+ "api_key_permissions_description": "Choose the permissions this key may use. You cannot grant a permission you do not hold yourself.",
+ "api_key_permissions_required": "Pick at least one permission",
+ "api_key_scope_all": "All permissions",
+ "api_key_scope_role": "Matches {role}",
+ "api_key_scope_count": "{count} {count, plural, one {permission} other {permissions}}",
+ "_comment_rbac_migration": "=== RBAC MIGRATION BANNER ===",
+ "rbac_migration_banner_title": "Welcome to RBAC",
+ "rbac_migration_banner_body": "Your access was migrated to Viewer on all environments. Admins can promote users from Settings → Users.",
+ "rbac_migration_banner_dismiss": "Dismiss",
+ "_comment_no_access": "=== NO ACCESS PAGE ===",
+ "no_access_page_title": "You don't have access to anything yet",
+ "no_access_page_body": "Your Arcane administrator hasn't assigned you any role permissions. Ask them to add a role to your account from Settings → Users."
}
diff --git a/frontend/src/lib/components/action-buttons.svelte b/frontend/src/lib/components/action-buttons.svelte
index c90836b8b..027ab873b 100644
--- a/frontend/src/lib/components/action-buttons.svelte
+++ b/frontend/src/lib/components/action-buttons.svelte
@@ -19,6 +19,8 @@
import { sanitizeLogText } from '$lib/utils/log-text';
import { EllipsisIcon, DownloadIcon, HammerIcon } from '$lib/icons';
import { createMutation } from '@tanstack/svelte-query';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
type TargetType = 'container' | 'project';
type LoadingStates = {
@@ -190,6 +192,29 @@
const isRunning = $derived(itemState === 'running' || (type === 'project' && itemState === 'partially running'));
const projectHasBuildDirective = $derived(type === 'project' && hasBuildDirective);
+
+ // Per-action RBAC gating. Each button hides if the caller lacks the
+ // corresponding permission on the currently-selected environment. Project
+ // pull / build / redeploy all share the `projects:deploy` permission since
+ // they're stages of the deploy flow.
+ const currentEnvId = $derived(environmentStore.selected?.id);
+ const canStart = $derived(
+ type === 'container' ? hasPermission('containers:start', currentEnvId) : hasPermission('projects:deploy', currentEnvId)
+ );
+ const canStop = $derived(
+ type === 'container' ? hasPermission('containers:stop', currentEnvId) : hasPermission('projects:down', currentEnvId)
+ );
+ const canRestart = $derived(
+ type === 'container' ? hasPermission('containers:restart', currentEnvId) : hasPermission('projects:restart', currentEnvId)
+ );
+ const canRedeploy = $derived(
+ type === 'container' ? hasPermission('containers:redeploy', currentEnvId) : hasPermission('projects:deploy', currentEnvId)
+ );
+ const canRemove = $derived(
+ type === 'container' ? hasPermission('containers:delete', currentEnvId) : hasPermission('projects:delete', currentEnvId)
+ );
+ const canPull = $derived(type === 'project' && hasPermission('projects:deploy', currentEnvId));
+ const canBuild = $derived(type === 'project' && hasPermission('projects:deploy', currentEnvId));
const deployButtonLabel = $derived(projectHasBuildDirective ? m.compose_build_and_deploy() : m.common_up());
const depotAvailable = $derived.by(() => {
const projectId = ($settingsStore?.depotProjectId ?? '').trim();
@@ -819,24 +844,28 @@
</script>
{#snippet RedeployActionButton(size: 'default' | 'icon' = 'default', showLabel = true)}
- {#if disableRedeploy}
- <span class="inline-flex" title={m.common_redeploy_disabled_arcane_self()}>
- <ArcaneButton action="redeploy" {size} {showLabel} disabled />
- </span>
- {:else}
- <ArcaneButton action="redeploy" {size} {showLabel} onclick={() => confirmAction('redeploy')} loading={uiLoading.redeploy} />
+ {#if canRedeploy}
+ {#if disableRedeploy}
+ <span class="inline-flex" title={m.common_redeploy_disabled_arcane_self()}>
+ <ArcaneButton action="redeploy" {size} {showLabel} disabled />
+ </span>
+ {:else}
+ <ArcaneButton action="redeploy" {size} {showLabel} onclick={() => confirmAction('redeploy')} loading={uiLoading.redeploy} />
+ {/if}
{/if}
{/snippet}
{#snippet RedeployMenuItem()}
- {#if disableRedeploy}
- <DropdownMenu.Item disabled title={m.common_redeploy_disabled_arcane_self()}>
- {m.common_redeploy()}
- </DropdownMenu.Item>
- {:else}
- <DropdownMenu.Item onclick={() => confirmAction('redeploy')} disabled={uiLoading.redeploy}>
- {m.common_redeploy()}
- </DropdownMenu.Item>
+ {#if canRedeploy}
+ {#if disableRedeploy}
+ <DropdownMenu.Item disabled title={m.common_redeploy_disabled_arcane_self()}>
+ {m.common_redeploy()}
+ </DropdownMenu.Item>
+ {:else}
+ <DropdownMenu.Item onclick={() => confirmAction('redeploy')} disabled={uiLoading.redeploy}>
+ {m.common_redeploy()}
+ </DropdownMenu.Item>
+ {/if}
{/if}
{/snippet}
@@ -845,7 +874,7 @@
<!-- On xl+ show labels; below xl use icon-only to avoid overflow in constrained headers (sidebar layouts) -->
{#if isLgUp}
<div class="flex items-center gap-2">
- {#if !isRunning}
+ {#if !isRunning && canStart}
{#if type === 'container'}
<ArcaneButton
action="start"
@@ -881,37 +910,43 @@
{/if}
{#if isRunning}
- <ArcaneButton
- action="stop"
- size={adaptiveIconOnly ? 'icon' : 'default'}
- showLabel={!adaptiveIconOnly}
- customLabel={type === 'project' ? m.common_down() : undefined}
- onclick={() => handleStop()}
- loading={uiLoading.stop}
- />
- <ArcaneButton
- action="restart"
- size={adaptiveIconOnly ? 'icon' : 'default'}
- showLabel={!adaptiveIconOnly}
- onclick={() => handleRestart()}
- loading={uiLoading.restart}
- />
+ {#if canStop}
+ <ArcaneButton
+ action="stop"
+ size={adaptiveIconOnly ? 'icon' : 'default'}
+ showLabel={!adaptiveIconOnly}
+ customLabel={type === 'project' ? m.common_down() : undefined}
+ onclick={() => handleStop()}
+ loading={uiLoading.stop}
+ />
+ {/if}
+ {#if canRestart}
+ <ArcaneButton
+ action="restart"
+ size={adaptiveIconOnly ? 'icon' : 'default'}
+ showLabel={!adaptiveIconOnly}
+ onclick={() => handleRestart()}
+ loading={uiLoading.restart}
+ />
+ {/if}
{/if}
{#if type === 'container'}
{@render RedeployActionButton(adaptiveIconOnly ? 'icon' : 'default', !adaptiveIconOnly)}
- <ArcaneButton
- action="remove"
- size={adaptiveIconOnly ? 'icon' : 'default'}
- showLabel={!adaptiveIconOnly}
- onclick={() => confirmAction('remove')}
- loading={uiLoading.remove}
- />
+ {#if canRemove}
+ <ArcaneButton
+ action="remove"
+ size={adaptiveIconOnly ? 'icon' : 'default'}
+ showLabel={!adaptiveIconOnly}
+ onclick={() => confirmAction('remove')}
+ loading={uiLoading.remove}
+ />
+ {/if}
{:else}
{@render RedeployActionButton(adaptiveIconOnly ? 'icon' : 'default', !adaptiveIconOnly)}
{#if type === 'project'}
- {#if projectHasBuildDirective}
+ {#if projectHasBuildDirective && canBuild}
<ProgressPopover
bind:open={buildPopoverOpen}
bind:progress={pullProgress}
@@ -936,24 +971,26 @@
</ProgressPopover>
{/if}
- <ProgressPopover
- bind:open={pullPopoverOpen}
- bind:progress={pullProgress}
- title={m.progress_pulling_images()}
- statusText={pullStatusText}
- error={pullError}
- loading={projectPulling}
- icon={DownloadIcon}
- layers={layerProgress}
- >
- <ArcaneButton
- action="pull"
- size={adaptiveIconOnly ? 'icon' : 'default'}
- showLabel={!adaptiveIconOnly}
- onclick={() => handleProjectPull()}
+ {#if canPull}
+ <ProgressPopover
+ bind:open={pullPopoverOpen}
+ bind:progress={pullProgress}
+ title={m.progress_pulling_images()}
+ statusText={pullStatusText}
+ error={pullError}
loading={projectPulling}
- />
- </ProgressPopover>
+ icon={DownloadIcon}
+ layers={layerProgress}
+ >
+ <ArcaneButton
+ action="pull"
+ size={adaptiveIconOnly ? 'icon' : 'default'}
+ showLabel={!adaptiveIconOnly}
+ onclick={() => handleProjectPull()}
+ loading={projectPulling}
+ />
+ </ProgressPopover>
+ {/if}
{/if}
{#if onRefresh}
@@ -966,14 +1003,16 @@
/>
{/if}
- <ArcaneButton
- customLabel={type === 'project' ? m.compose_destroy() : m.common_remove()}
- action="remove"
- size={adaptiveIconOnly ? 'icon' : 'default'}
- showLabel={!adaptiveIconOnly}
- onclick={() => confirmAction('remove')}
- loading={uiLoading.remove}
- />
+ {#if canRemove}
+ <ArcaneButton
+ customLabel={type === 'project' ? m.compose_destroy() : m.common_remove()}
+ action="remove"
+ size={adaptiveIconOnly ? 'icon' : 'default'}
+ showLabel={!adaptiveIconOnly}
+ onclick={() => confirmAction('remove')}
+ loading={uiLoading.remove}
+ />
+ {/if}
{/if}
</div>
{:else}
@@ -989,7 +1028,7 @@
class="bg-popover/20 z-50 min-w-[180px] rounded-xl border p-1 shadow-lg backdrop-blur-md"
>
<DropdownMenu.Group>
- {#if !isRunning}
+ {#if !isRunning && canStart}
{#if type === 'container'}
<DropdownMenu.Item onclick={handleStart} disabled={uiLoading.start}>
{m.common_start()}
@@ -1019,32 +1058,40 @@
</DropdownMenu.CheckboxItem>
{/if}
{/if}
- {:else}
- <DropdownMenu.Item onclick={handleStop} disabled={uiLoading.stop}>
- {type === 'project' ? m.common_down() : m.common_stop()}
- </DropdownMenu.Item>
- <DropdownMenu.Item onclick={handleRestart} disabled={uiLoading.restart}>
- {m.common_restart()}
- </DropdownMenu.Item>
+ {:else if isRunning}
+ {#if canStop}
+ <DropdownMenu.Item onclick={handleStop} disabled={uiLoading.stop}>
+ {type === 'project' ? m.common_down() : m.common_stop()}
+ </DropdownMenu.Item>
+ {/if}
+ {#if canRestart}
+ <DropdownMenu.Item onclick={handleRestart} disabled={uiLoading.restart}>
+ {m.common_restart()}
+ </DropdownMenu.Item>
+ {/if}
{/if}
{#if type === 'container'}
{@render RedeployMenuItem()}
- <DropdownMenu.Item onclick={() => confirmAction('remove')} disabled={uiLoading.remove}>
- {m.common_remove()}
- </DropdownMenu.Item>
+ {#if canRemove}
+ <DropdownMenu.Item onclick={() => confirmAction('remove')} disabled={uiLoading.remove}>
+ {m.common_remove()}
+ </DropdownMenu.Item>
+ {/if}
{:else}
{@render RedeployMenuItem()}
{#if type === 'project'}
- {#if projectHasBuildDirective}
+ {#if projectHasBuildDirective && canBuild}
<DropdownMenu.Item onclick={handleProjectBuild} disabled={projectBuilding || uiLoading.building}>
{m.build()}
</DropdownMenu.Item>
{/if}
- <DropdownMenu.Item onclick={handleProjectPull} disabled={projectPulling || uiLoading.pulling}>
- {m.images_pull()}
- </DropdownMenu.Item>
+ {#if canPull}
+ <DropdownMenu.Item onclick={handleProjectPull} disabled={projectPulling || uiLoading.pulling}>
+ {m.images_pull()}
+ </DropdownMenu.Item>
+ {/if}
{/if}
{#if onRefresh}
@@ -1053,9 +1100,11 @@
</DropdownMenu.Item>
{/if}
- <DropdownMenu.Item onclick={() => confirmAction('remove')} disabled={uiLoading.remove}>
- {type === 'project' ? m.compose_destroy() : m.common_remove()}
- </DropdownMenu.Item>
+ {#if canRemove}
+ <DropdownMenu.Item onclick={() => confirmAction('remove')} disabled={uiLoading.remove}>
+ {type === 'project' ? m.compose_destroy() : m.common_remove()}
+ </DropdownMenu.Item>
+ {/if}
{/if}
</DropdownMenu.Group>
</DropdownMenu.Content>
@@ -1118,7 +1167,7 @@
{:else}
<div>
<div class="hidden items-center gap-2 lg:flex">
- {#if !isRunning}
+ {#if !isRunning && canStart}
{#if type === 'container'}
<ArcaneButton action="start" onclick={() => handleStart()} loading={uiLoading.start} />
{:else}
@@ -1142,23 +1191,29 @@
{/if}
{#if isRunning}
- <ArcaneButton
- action="stop"
- customLabel={type === 'project' ? m.common_down() : undefined}
- onclick={() => handleStop()}
- loading={uiLoading.stop}
- />
- <ArcaneButton action="restart" onclick={() => handleRestart()} loading={uiLoading.restart} />
+ {#if canStop}
+ <ArcaneButton
+ action="stop"
+ customLabel={type === 'project' ? m.common_down() : undefined}
+ onclick={() => handleStop()}
+ loading={uiLoading.stop}
+ />
+ {/if}
+ {#if canRestart}
+ <ArcaneButton action="restart" onclick={() => handleRestart()} loading={uiLoading.restart} />
+ {/if}
{/if}
{#if type === 'container'}
{@render RedeployActionButton()}
- <ArcaneButton action="remove" onclick={() => confirmAction('remove')} loading={uiLoading.remove} />
+ {#if canRemove}
+ <ArcaneButton action="remove" onclick={() => confirmAction('remove')} loading={uiLoading.remove} />
+ {/if}
{:else}
{@render RedeployActionButton()}
{#if type === 'project'}
- {#if projectHasBuildDirective}
+ {#if projectHasBuildDirective && canBuild}
<ProgressPopover
bind:open={buildPopoverOpen}
bind:progress={pullProgress}
@@ -1177,30 +1232,34 @@
</ProgressPopover>
{/if}
- <ProgressPopover
- bind:open={pullPopoverOpen}
- bind:progress={pullProgress}
- title={m.progress_pulling_images()}
- statusText={pullStatusText}
- error={pullError}
- loading={projectPulling}
- icon={DownloadIcon}
- layers={layerProgress}
- >
- <ArcaneButton action="pull" onclick={() => handleProjectPull()} loading={projectPulling} />
- </ProgressPopover>
+ {#if canPull}
+ <ProgressPopover
+ bind:open={pullPopoverOpen}
+ bind:progress={pullProgress}
+ title={m.progress_pulling_images()}
+ statusText={pullStatusText}
+ error={pullError}
+ loading={projectPulling}
+ icon={DownloadIcon}
+ layers={layerProgress}
+ >
+ <ArcaneButton action="pull" onclick={() => handleProjectPull()} loading={projectPulling} />
+ </ProgressPopover>
+ {/if}
{/if}
{#if onRefresh}
<ArcaneButton action="refresh" onclick={() => handleRefresh()} loading={uiLoading.refresh} />
{/if}
- <ArcaneButton
- customLabel={type === 'project' ? m.compose_destroy() : m.common_remove()}
- action="remove"
- onclick={() => confirmAction('remove')}
- loading={uiLoading.remove}
- />
+ {#if canRemove}
+ <ArcaneButton
+ customLabel={type === 'project' ? m.compose_destroy() : m.common_remove()}
+ action="remove"
+ onclick={() => confirmAction('remove')}
+ loading={uiLoading.remove}
+ />
+ {/if}
{/if}
</div>
@@ -1216,7 +1275,7 @@
class="bg-popover/20 z-50 min-w-[180px] rounded-xl border p-1 shadow-lg backdrop-blur-md"
>
<DropdownMenu.Group>
- {#if !isRunning}
+ {#if !isRunning && canStart}
{#if type === 'container'}
<DropdownMenu.Item onclick={handleStart} disabled={uiLoading.start}>
{m.common_start()}
@@ -1246,32 +1305,40 @@
</DropdownMenu.CheckboxItem>
{/if}
{/if}
- {:else}
- <DropdownMenu.Item onclick={handleStop} disabled={uiLoading.stop}>
- {type === 'project' ? m.common_down() : m.common_stop()}
- </DropdownMenu.Item>
- <DropdownMenu.Item onclick={handleRestart} disabled={uiLoading.restart}>
- {m.common_restart()}
- </DropdownMenu.Item>
+ {:else if isRunning}
+ {#if canStop}
+ <DropdownMenu.Item onclick={handleStop} disabled={uiLoading.stop}>
+ {type === 'project' ? m.common_down() : m.common_stop()}
+ </DropdownMenu.Item>
+ {/if}
+ {#if canRestart}
+ <DropdownMenu.Item onclick={handleRestart} disabled={uiLoading.restart}>
+ {m.common_restart()}
+ </DropdownMenu.Item>
+ {/if}
{/if}
{#if type === 'container'}
{@render RedeployMenuItem()}
- <DropdownMenu.Item onclick={() => confirmAction('remove')} disabled={uiLoading.remove}>
- {m.common_remove()}
- </DropdownMenu.Item>
+ {#if canRemove}
+ <DropdownMenu.Item onclick={() => confirmAction('remove')} disabled={uiLoading.remove}>
+ {m.common_remove()}
+ </DropdownMenu.Item>
+ {/if}
{:else}
{@render RedeployMenuItem()}
{#if type === 'project'}
- {#if projectHasBuildDirective}
+ {#if projectHasBuildDirective && canBuild}
<DropdownMenu.Item onclick={handleProjectBuild} disabled={projectBuilding || uiLoading.building}>
{m.build()}
</DropdownMenu.Item>
{/if}
- <DropdownMenu.Item onclick={handleProjectPull} disabled={projectPulling || uiLoading.pulling}>
- {m.images_pull()}
- </DropdownMenu.Item>
+ {#if canPull}
+ <DropdownMenu.Item onclick={handleProjectPull} disabled={projectPulling || uiLoading.pulling}>
+ {m.images_pull()}
+ </DropdownMenu.Item>
+ {/if}
{/if}
{#if onRefresh}
@@ -1280,9 +1347,11 @@
</DropdownMenu.Item>
{/if}
- <DropdownMenu.Item onclick={() => confirmAction('remove')} disabled={uiLoading.remove}>
- {type === 'project' ? m.compose_destroy() : m.common_remove()}
- </DropdownMenu.Item>
+ {#if canRemove}
+ <DropdownMenu.Item onclick={() => confirmAction('remove')} disabled={uiLoading.remove}>
+ {type === 'project' ? m.compose_destroy() : m.common_remove()}
+ </DropdownMenu.Item>
+ {/if}
{/if}
</DropdownMenu.Group>
</DropdownMenu.Content>
diff --git a/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte b/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte
index cf672ff3e..cb8674819 100644
--- a/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/environment-switcher-dialog.svelte
@@ -17,13 +17,13 @@
import { tick } from 'svelte';
import { EnvironmentsIcon, RemoteEnvironmentIcon, AddIcon, SearchIcon, CloseIcon, SettingsIcon } from '$lib/icons';
import { useQueryClient } from '@tanstack/svelte-query';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
type Props = {
open: boolean;
- isAdmin?: boolean;
};
- let { open = $bindable(false), isAdmin = false }: Props = $props();
+ let { open = $bindable(false) }: Props = $props();
const queryClient = useQueryClient();
let searchQuery = $state('');
@@ -356,7 +356,7 @@
{#snippet footer()}
<div class="flex w-full items-center justify-between gap-2">
- {#if isAdmin}
+ <IfPermitted perm="environments:create">
<ArcaneButton
action="base"
tone="outline"
@@ -367,9 +367,10 @@
goto('/environments');
}}
/>
- {:else}
- <div></div>
- {/if}
+ {#snippet fallback()}
+ <div></div>
+ {/snippet}
+ </IfPermitted>
<ArcaneButton action="base" tone="outline" customLabel={m.common_close()} onclick={closeDialog} />
</div>
{/snippet}
diff --git a/frontend/src/lib/components/dialogs/rbac-migration-banner.svelte b/frontend/src/lib/components/dialogs/rbac-migration-banner.svelte
new file mode 100644
index 000000000..5e8ad4435
--- /dev/null
+++ b/frontend/src/lib/components/dialogs/rbac-migration-banner.svelte
@@ -0,0 +1,71 @@
+<script lang="ts">
+ import * as Alert from '$lib/components/ui/alert';
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import userStore from '$lib/stores/user-store';
+ import { BUILT_IN_ROLE_VIEWER } from '$lib/types/role.type';
+ import { CloseIcon } from '$lib/icons';
+ import { m } from '$lib/paraglide/messages';
+ import type { User } from '$lib/types/user.type';
+
+ const STORAGE_KEY = 'rbac-migration-banner-dismissed';
+
+ let dismissed = $state(false);
+
+ $effect(() => {
+ if (typeof window === 'undefined') return;
+ try {
+ if (window.localStorage.getItem(STORAGE_KEY) === 'true') {
+ dismissed = true;
+ }
+ } catch {
+ // Ignore storage access errors (e.g., private browsing).
+ }
+ });
+
+ function shouldShowFor(user: User | null): boolean {
+ if (!user) return false;
+ const assignments = user.roleAssignments ?? [];
+ if (assignments.length === 0) return false;
+
+ const manualAssignments = assignments.filter((a) => a.source === 'manual');
+ if (manualAssignments.length === 0) return false;
+
+ const hasViewerOnEnv = manualAssignments.some((a) => a.roleId === BUILT_IN_ROLE_VIEWER && !!a.environmentId);
+ if (!hasViewerOnEnv) return false;
+
+ const hasNonViewerManual = manualAssignments.some((a) => a.roleId !== BUILT_IN_ROLE_VIEWER);
+ return !hasNonViewerManual;
+ }
+
+ const visible = $derived(!dismissed && shouldShowFor($userStore));
+
+ function dismiss() {
+ try {
+ if (typeof window !== 'undefined') {
+ window.localStorage.setItem(STORAGE_KEY, 'true');
+ }
+ } catch {
+ // Ignore storage access errors.
+ }
+ dismissed = true;
+ }
+</script>
+
+{#if visible}
+ <Alert.Root variant="default" class="mb-4 flex items-start gap-3">
+ <div class="flex-1">
+ <Alert.Title>{m.rbac_migration_banner_title()}</Alert.Title>
+ <Alert.Description>{m.rbac_migration_banner_body()}</Alert.Description>
+ </div>
+ <ArcaneButton
+ action="base"
+ tone="ghost"
+ size="icon"
+ icon={CloseIcon}
+ showLabel={false}
+ onclick={dismiss}
+ customLabel={m.rbac_migration_banner_dismiss()}
+ class="text-muted-foreground hover:text-foreground"
+ />
+ </Alert.Root>
+{/if}
diff --git a/frontend/src/lib/components/file-browser/FileList.svelte b/frontend/src/lib/components/file-browser/FileList.svelte
index dc0983e42..6e780856f 100644
--- a/frontend/src/lib/components/file-browser/FileList.svelte
+++ b/frontend/src/lib/components/file-browser/FileList.svelte
@@ -40,7 +40,7 @@
persistKey?: string;
onNavigate: (path: string) => void;
onRefresh: () => void;
- onDelete: (file: FileEntry) => Promise<void>;
+ onDelete?: (file: FileEntry) => Promise<void>;
onDownload: (file: FileEntry) => Promise<void>;
onPreview: (file: FileEntry) => void;
onRestoreFromBackup?: (file: FileEntry) => void;
@@ -102,6 +102,7 @@
}
async function handleDelete(file: FileEntry) {
+ if (!onDelete) return;
openConfirmDialog({
title: m.common_remove_title({ resource: file.name }),
message: m.volumes_browser_delete_confirm({ name: file.name }),
@@ -225,10 +226,12 @@
{/if}
<DropdownMenu.Separator />
{/if}
- <DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)}>
- <TrashIcon class="size-4" />
- {m.common_delete()}
- </DropdownMenu.Item>
+ {#if onDelete}
+ <DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)}>
+ <TrashIcon class="size-4" />
+ {m.common_delete()}
+ </DropdownMenu.Item>
+ {/if}
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/lib/components/file-browser/GenericFileBrowser.svelte b/frontend/src/lib/components/file-browser/GenericFileBrowser.svelte
index 501178237..216cf9d96 100644
--- a/frontend/src/lib/components/file-browser/GenericFileBrowser.svelte
+++ b/frontend/src/lib/components/file-browser/GenericFileBrowser.svelte
@@ -32,9 +32,16 @@
import { toast } from 'svelte-sonner';
import bytes from '$lib/utils/bytes';
import { format } from 'date-fns';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
let { provider, rootLabel, persistKey }: { provider: FileProvider; rootLabel?: string; persistKey?: string } = $props();
+ const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const canDeleteVolume = $derived(hasPermission('volumes:delete', currentEnvId));
+ const canBackupVolume = $derived(hasPermission('volumes:backup', currentEnvId));
+
let currentPath = $state('/');
let files = $state<FileEntry[]>([]);
let loading = $state(true);
@@ -167,22 +174,24 @@
<div class="flex items-center justify-between">
<FileBreadcrumb path={currentPath} {rootLabel} onNavigate={handleNavigate} />
<div class="flex gap-2">
- <ArcaneButton
- action="base"
- tone="outline"
- size="sm"
- onclick={() => (showCreateFolder = true)}
- icon={MoveToFolderIcon}
- customLabel={m.volumes_browser_new_folder()}
- />
- <ArcaneButton
- action="base"
- tone="outline"
- size="sm"
- onclick={() => (showUpload = true)}
- icon={UploadIcon}
- customLabel={m.volumes_browser_upload_files()}
- />
+ <IfPermitted perm="volumes:upload">
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ size="sm"
+ onclick={() => (showCreateFolder = true)}
+ icon={MoveToFolderIcon}
+ customLabel={m.volumes_browser_new_folder()}
+ />
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ size="sm"
+ onclick={() => (showUpload = true)}
+ icon={UploadIcon}
+ customLabel={m.volumes_browser_upload_files()}
+ />
+ </IfPermitted>
</div>
</div>
@@ -201,10 +210,10 @@
{persistKey}
onNavigate={handleNavigate}
onRefresh={() => loadFiles(currentPath)}
- onDelete={(file) => provider.delete(file.path)}
+ onDelete={canDeleteVolume ? (file) => provider.delete(file.path) : undefined}
onDownload={(file) => provider.download(file.path)}
onPreview={(file) => (previewFile = file)}
- onRestoreFromBackup={canRestoreFromBackup ? openRestoreFileDialog : undefined}
+ onRestoreFromBackup={canRestoreFromBackup && canBackupVolume ? openRestoreFileDialog : undefined}
/>
{/if}
</div>
@@ -315,17 +324,19 @@
selectedBackupId = '';
}}
/>
- <ArcaneButton
- action="create"
- customLabel="Restore file"
- onclick={handleRestoreFile}
- loading={restoringFile}
- disabled={restoringFile ||
- loadingBackups ||
- checkingBackup ||
- !selectedBackupId ||
- !restoreTarget ||
- (requiresBackupCheck && backupHasFile !== true)}
- />
+ {#if canBackupVolume}
+ <ArcaneButton
+ action="create"
+ customLabel="Restore file"
+ onclick={handleRestoreFile}
+ loading={restoringFile}
+ disabled={restoringFile ||
+ loadingBackups ||
+ checkingBackup ||
+ !selectedBackupId ||
+ !restoreTarget ||
+ (requiresBackupCheck && backupHasFile !== true)}
+ />
+ {/if}
{/snippet}
</ResponsiveDialog>
diff --git a/frontend/src/lib/components/forms/role-assignments-editor.svelte b/frontend/src/lib/components/forms/role-assignments-editor.svelte
new file mode 100644
index 000000000..f2855c404
--- /dev/null
+++ b/frontend/src/lib/components/forms/role-assignments-editor.svelte
@@ -0,0 +1,172 @@
+<script lang="ts">
+ import * as Select from '$lib/components/ui/select';
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import {
+ type Role,
+ BUILT_IN_ROLE_ADMIN,
+ BUILT_IN_ROLE_EDITOR,
+ BUILT_IN_ROLE_DEPLOYER,
+ BUILT_IN_ROLE_VIEWER
+ } from '$lib/types/role.type';
+ import type { Environment } from '$lib/types/environment.type';
+ import { CloseIcon } from '$lib/icons';
+ import { m } from '$lib/paraglide/messages';
+
+ type Assignment = { roleId: string; environmentId?: string };
+
+ type Props = {
+ assignments: Assignment[];
+ roles: Role[];
+ environments: Environment[];
+ disabled?: boolean;
+ };
+
+ let { assignments = $bindable([]), roles, environments, disabled = false }: Props = $props();
+
+ const GLOBAL_OPTION_ID = 'global';
+
+ type EnvOption = { id: string; name: string };
+
+ const envOptions: EnvOption[] = $derived([
+ { id: GLOBAL_OPTION_ID, name: m.users_role_assignments_scope_global() },
+ ...environments.map((env) => ({ id: env.id, name: env.name }))
+ ]);
+
+ function getRoleVariant(roleId: string) {
+ switch (roleId) {
+ case BUILT_IN_ROLE_ADMIN:
+ return 'red';
+ case BUILT_IN_ROLE_EDITOR:
+ return 'blue';
+ case BUILT_IN_ROLE_DEPLOYER:
+ return 'purple';
+ case BUILT_IN_ROLE_VIEWER:
+ return 'gray';
+ default:
+ return 'green';
+ }
+ }
+
+ function envIdToSelectValue(envId: string | undefined): string {
+ return envId ?? GLOBAL_OPTION_ID;
+ }
+
+ function selectValueToEnvId(value: string): string | undefined {
+ return value === GLOBAL_OPTION_ID ? undefined : value;
+ }
+
+ function isEnvTaken(envValue: string, roleId: string, currentIndex: number): boolean {
+ return assignments.some((a, i) => {
+ if (i === currentIndex) return false;
+ if (a.roleId !== roleId) return false;
+ return envIdToSelectValue(a.environmentId) === envValue;
+ });
+ }
+
+ function updateAssignment(index: number, patch: Partial<Assignment>) {
+ if (disabled) return;
+ assignments = assignments.map((a, i) => (i === index ? { ...a, ...patch } : a));
+ }
+
+ function addAssignment() {
+ if (disabled) return;
+ const defaultRoleId = roles[0]?.id ?? '';
+ assignments = [...assignments, { roleId: defaultRoleId, environmentId: undefined }];
+ }
+
+ function removeAssignment(index: number) {
+ if (disabled) return;
+ assignments = assignments.filter((_, i) => i !== index);
+ }
+
+ function envSelectedLabel(value: string): string {
+ return envOptions.find((o) => o.id === value)?.name ?? m.common_select_option();
+ }
+
+ function roleSelectedLabel(value: string): string {
+ return roles.find((r) => r.id === value)?.name ?? m.common_select_option();
+ }
+</script>
+
+<div class="space-y-3">
+ {#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()}
+ </p>
+ {/if}
+
+ {#each assignments as assignment, index (`${assignment.roleId}-${assignment.environmentId ?? 'global'}`)}
+ {@const envValue = envIdToSelectValue(assignment.environmentId)}
+ <div class="bg-card/50 grid grid-cols-1 gap-2 rounded-md border p-3 sm:grid-cols-[1fr_1fr_auto] sm:items-center">
+ <Select.Root
+ type="single"
+ value={envValue}
+ {disabled}
+ onValueChange={(v) => updateAssignment(index, { environmentId: selectValueToEnvId(v) })}
+ >
+ <Select.Trigger class="w-full" aria-label={m.users_role_assignments_environment()}>
+ <span>{envSelectedLabel(envValue)}</span>
+ </Select.Trigger>
+ <Select.Content>
+ {#each envOptions as option (option.id)}
+ <Select.Item
+ value={option.id}
+ label={option.name}
+ disabled={option.id !== envValue && isEnvTaken(option.id, assignment.roleId, index)}
+ >
+ {option.name}
+ </Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+
+ <Select.Root
+ type="single"
+ value={assignment.roleId}
+ {disabled}
+ onValueChange={(v) => updateAssignment(index, { roleId: v })}
+ >
+ <Select.Trigger class="w-full" aria-label={m.users_role_assignments_role()}>
+ <span class="flex items-center gap-2">
+ <span>{roleSelectedLabel(assignment.roleId)}</span>
+ </span>
+ </Select.Trigger>
+ <Select.Content>
+ {#each roles as role (role.id)}
+ <Select.Item value={role.id} label={role.name}>
+ <span class="flex items-center gap-2">
+ <StatusBadge text={role.name} variant={getRoleVariant(role.id)} size="sm" minWidth="none" />
+ {#if role.description}
+ <span class="text-muted-foreground text-xs">{role.description}</span>
+ {/if}
+ </span>
+ </Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+
+ <ArcaneButton
+ action="remove"
+ tone="ghost"
+ size="icon"
+ icon={CloseIcon}
+ showLabel={false}
+ onclick={() => removeAssignment(index)}
+ {disabled}
+ class="text-muted-foreground hover:text-destructive justify-self-end"
+ customLabel={m.users_role_assignments_remove()}
+ />
+ </div>
+ {/each}
+
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ size="sm"
+ type="button"
+ onclick={addAssignment}
+ {disabled}
+ customLabel={m.users_role_assignments_add()}
+ />
+</div>
diff --git a/frontend/src/lib/components/if-permitted.svelte b/frontend/src/lib/components/if-permitted.svelte
new file mode 100644
index 000000000..5b1e7316c
--- /dev/null
+++ b/frontend/src/lib/components/if-permitted.svelte
@@ -0,0 +1,48 @@
+<!--
+ IfPermitted — conditionally renders its children based on the current
+ user's RBAC permissions in the active (or explicitly supplied) environment.
+
+ The check is wrapped in `$derived.by`, which reads
+ `environmentStore.selected?.id` as part of the computation. That makes the
+ guard reactive to environment switches: when the user picks a different env,
+ this component re-evaluates and shows/hides its children without a remount.
+
+ Permission logic lives in `$lib/utils/permissions.util` — this component is
+ a thin presentational wrapper around `hasPermission`, `hasAnyPermission`,
+ and `isGlobalAdmin`.
+-->
+<script lang="ts">
+ import { hasPermission, hasAnyPermission, isGlobalAdmin } from '$lib/utils/permissions.util';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import type { Snippet } from 'svelte';
+
+ let {
+ perm,
+ envId,
+ adminOnly = false,
+ children,
+ fallback
+ }: {
+ perm?: string | string[];
+ envId?: string;
+ adminOnly?: boolean;
+ children: Snippet;
+ fallback?: Snippet;
+ } = $props();
+
+ const allowed = $derived.by(() => {
+ // Touch the selected env id so the derived re-runs when it changes.
+ const activeEnvId = envId ?? environmentStore.selected?.id;
+
+ if (adminOnly) return isGlobalAdmin();
+ if (perm === undefined) return true;
+ if (typeof perm === 'string') return hasPermission(perm, activeEnvId);
+ return hasAnyPermission(perm, activeEnvId);
+ });
+</script>
+
+{#if allowed}
+ {@render children()}
+{:else if fallback}
+ {@render fallback()}
+{/if}
diff --git a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte
index 0220573f1..e796da417 100644
--- a/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte
+++ b/frontend/src/lib/components/mobile-nav/mobile-nav-sheet.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import { navigationItems, getManagementItems } from '$lib/config/navigation-config';
+ import { navigationItems, getManagementItems, filterByPermissions } from '$lib/config/navigation-config';
import type { NavigationItem } from '$lib/config/navigation-config';
import { cn } from '$lib/utils';
import { page } from '$app/state';
@@ -13,6 +13,7 @@
import UpdateCenterDialog from '$lib/components/dialogs/update-center-dialog.svelte';
import { toast } from 'svelte-sonner';
import { extractApiErrorMessage } from '$lib/utils/api.util';
+ import { hasPermission } from '$lib/utils/permissions.util';
import type { AppVersionInformation } from '$lib/types/application-configuration';
import { createMutation, createQuery } from '@tanstack/svelte-query';
@@ -40,13 +41,16 @@
const currentPath = $derived(page.url.pathname);
const memoizedUser = $derived.by(() => user ?? storeUser);
const currentEnvId = $derived(environmentStore.selected?.id || '0');
- const managementItems = $derived(getManagementItems(currentEnvId));
+ 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));
let upgrading = $state(false);
let showConfirmDialog = $state(false);
- const isAdmin = $derived(!!user?.roles?.includes('admin'));
+ const canInstallUpdates = $derived(hasPermission('environments:update'));
- const shouldCheckUpgrade = $derived(!!(versionInformation?.updateAvailable && isAdmin && !debug));
+ const shouldCheckUpgrade = $derived(!!(versionInformation?.updateAvailable && canInstallUpdates && !debug));
const upgradeAvailabilityQuery = createQuery(() => ({
queryKey: queryKeys.system.upgradeAvailable('mobile-nav'),
queryFn: () => systemUpgradeService.checkUpgradeAvailable(),
@@ -62,7 +66,7 @@
const checkingUpgrade = $derived(
!!(shouldCheckUpgrade && (upgradeAvailabilityQuery.isPending || upgradeAvailabilityQuery.isFetching))
);
- const shouldShowUpgrade = $derived((canUpgrade && isAdmin) || debug);
+ const shouldShowUpgrade = $derived((canUpgrade && canInstallUpdates) || debug);
const updateType = $derived.by(() => {
if (!versionInformation) return 'none';
@@ -192,7 +196,7 @@
{m.sidebar_resources()}
</h4>
<div class="space-y-2">
- {#each navigationItems.resourceItems as item (item.url)}
+ {#each resourceItems as item (item.url)}
{#if item.items}
{@const IconComponent = item.icon}
<div class="space-y-2">
@@ -282,53 +286,16 @@
</section>
{/if}
- {#if isAdmin}
- {#if navigationItems.settingsItems}
- <section>
- <h4 class="text-muted-foreground/70 mb-4 px-3 text-[11px] font-semibold tracking-widest uppercase">
- {m.sidebar_administration()}
- </h4>
- <div class="space-y-2">
- {#each navigationItems.settingsItems as item (item.url)}
- {#if item.items}
- {@const IconComponent = item.icon}
- <div class="space-y-2">
- <a
- href={item.url}
- onclick={handleItemClick}
- class={cn(
- 'flex items-center gap-3 rounded-2xl px-4 py-3 text-sm font-medium transition-all duration-200 ease-out',
- isActiveItem(item)
- ? 'bg-muted text-foreground hover:bg-muted/70 shadow-sm'
- : 'text-foreground hover:bg-muted/50'
- )}
- >
- <IconComponent size={20} />
- <span>{item.title}</span>
- </a>
- <div class="ml-6 space-y-1">
- {#each item.items as subItem (subItem.url)}
- {@const SubIconComponent = subItem.icon}
- <a
- href={subItem.url}
- onclick={handleItemClick}
- class={cn(
- 'flex items-center gap-3 rounded-xl px-4 py-2 text-sm transition-all duration-200 ease-out',
- 'focus-visible:ring-muted-foreground/50 hover:scale-[1.01] focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:ring-offset-transparent',
- isActiveItem(subItem)
- ? 'bg-muted/70 text-foreground shadow-sm'
- : 'text-muted-foreground hover:text-foreground hover:bg-muted/40'
- )}
- aria-current={isActiveItem(subItem) ? 'page' : undefined}
- >
- <SubIconComponent size={16} />
- <span>{subItem.title}</span>
- </a>
- {/each}
- </div>
- </div>
- {:else}
- {@const IconComponent = item.icon}
+ {#if settingsItems.length > 0}
+ <section>
+ <h4 class="text-muted-foreground/70 mb-4 px-3 text-[11px] font-semibold tracking-widest uppercase">
+ {m.sidebar_administration()}
+ </h4>
+ <div class="space-y-2">
+ {#each settingsItems as item (item.url)}
+ {#if item.items}
+ {@const IconComponent = item.icon}
+ <div class="space-y-2">
<a
href={item.url}
onclick={handleItemClick}
@@ -342,11 +309,46 @@
<IconComponent size={20} />
<span>{item.title}</span>
</a>
- {/if}
- {/each}
- </div>
- </section>
- {/if}
+ <div class="ml-6 space-y-1">
+ {#each item.items as subItem (subItem.url)}
+ {@const SubIconComponent = subItem.icon}
+ <a
+ href={subItem.url}
+ onclick={handleItemClick}
+ class={cn(
+ 'flex items-center gap-3 rounded-xl px-4 py-2 text-sm transition-all duration-200 ease-out',
+ 'focus-visible:ring-muted-foreground/50 hover:scale-[1.01] focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:ring-offset-transparent',
+ isActiveItem(subItem)
+ ? 'bg-muted/70 text-foreground shadow-sm'
+ : 'text-muted-foreground hover:text-foreground hover:bg-muted/40'
+ )}
+ aria-current={isActiveItem(subItem) ? 'page' : undefined}
+ >
+ <SubIconComponent size={16} />
+ <span>{subItem.title}</span>
+ </a>
+ {/each}
+ </div>
+ </div>
+ {:else}
+ {@const IconComponent = item.icon}
+ <a
+ href={item.url}
+ onclick={handleItemClick}
+ class={cn(
+ 'flex items-center gap-3 rounded-2xl px-4 py-3 text-sm font-medium transition-all duration-200 ease-out',
+ isActiveItem(item)
+ ? 'bg-muted text-foreground hover:bg-muted/70 shadow-sm'
+ : 'text-foreground hover:bg-muted/50'
+ )}
+ >
+ <IconComponent size={20} />
+ <span>{item.title}</span>
+ </a>
+ {/if}
+ {/each}
+ </div>
+ </section>
{/if}
</div>
</div>
diff --git a/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte b/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte
index 5e3bd2293..6af1473fe 100644
--- a/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte
+++ b/frontend/src/lib/components/mobile-nav/mobile-user-card.svelte
@@ -7,7 +7,9 @@
import LocalePicker from '$lib/components/locale-picker.svelte';
import EnvironmentSwitcherDialog from '$lib/components/dialogs/environment-switcher-dialog.svelte';
import settingsStore from '$lib/stores/config-store';
+ import userStore from '$lib/stores/user-store';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
import {
ArrowDownIcon,
MoonIcon,
@@ -38,7 +40,6 @@
const isDarkMode = $derived(mode.current === 'dark');
const effectiveUser = $derived(user);
- const isAdmin = $derived(!!effectiveUser.roles?.includes('admin'));
function getConnectionString(): string {
if (!environmentStore.selected) return '';
@@ -63,7 +64,7 @@
<div class="flex-1">
<h3 class="text-foreground text-lg font-semibold">{effectiveUser.displayName || effectiveUser.username}</h3>
<p class="text-muted-foreground/80 text-sm">
- {effectiveUser.roles?.join(', ')}
+ {userStore.isGlobalAdmin() ? m.common_admin() : m.common_user()}
</p>
</div>
<div class="flex items-center gap-2">
@@ -94,7 +95,7 @@
{#if userCardExpanded}
<div class="border-border/20 bg-muted/10 space-y-4 border-t p-4">
- {#if isAdmin}
+ <IfPermitted adminOnly>
<button
class="bg-background/50 border-border/20 hover:bg-muted/30 flex w-full items-center gap-3 rounded-2xl border p-4 text-left transition-colors"
onclick={() => (envDialogOpen = true)}
@@ -121,7 +122,7 @@
</div>
<ArrowRightIcon class="text-muted-foreground/60 size-5 shrink-0" />
</button>
- {/if}
+ </IfPermitted>
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
<div class="bg-background/50 border-border/20 rounded-2xl border p-4">
@@ -167,4 +168,4 @@
{/if}
</div>
-<EnvironmentSwitcherDialog bind:open={envDialogOpen} {isAdmin} />
+<EnvironmentSwitcherDialog bind:open={envDialogOpen} />
diff --git a/frontend/src/lib/components/quick-actions.svelte b/frontend/src/lib/components/quick-actions.svelte
index 42cea9386..befbc6a05 100644
--- a/frontend/src/lib/components/quick-actions.svelte
+++ b/frontend/src/lib/components/quick-actions.svelte
@@ -5,7 +5,8 @@
import { m } from '$lib/paraglide/messages';
import { StartIcon, StopIcon, TrashIcon } from '$lib/icons';
import { cn } from '$lib/utils';
- import type { User } from '$lib/types/user.type';
+ import { hasAnyPermission, hasPermission } from '$lib/utils/permissions.util';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
type IsLoadingFlags = {
starting: boolean;
@@ -14,7 +15,6 @@
};
let {
- user = null,
stoppedContainers,
runningContainers,
isLoading,
@@ -26,7 +26,6 @@
compact = false,
class: className
}: {
- user?: User | null;
stoppedContainers: number;
runningContainers: number;
isLoading: IsLoadingFlags;
@@ -42,36 +41,46 @@
const isTablet = new IsTablet();
const isAnyActionLoading = $derived(isLoading.starting || isLoading.stopping || isLoading.pruning);
- const currentUserIsAdmin = $derived(!!user?.roles?.includes('admin'));
+ const currentEnvId = $derived(environmentStore.selected?.id);
+ const canStartAll = $derived(hasPermission('containers:start', currentEnvId));
+ const canStopAll = $derived(hasPermission('containers:stop', currentEnvId));
+ const canPrune = $derived(hasAnyPermission(['images:prune', 'volumes:prune', 'networks:prune'], currentEnvId));
+ const hasAnyQuickAction = $derived(canStartAll || canStopAll || canPrune);
const actionButtons: ActionButton[] = $derived(
[
- {
- id: 'start-all',
- action: 'start_all' as const,
- label: m.quick_actions_start_all(),
- onclick: onStartAll,
- loading: isLoading.starting,
- disabled: stoppedContainers === 0 || isAnyActionLoading,
- badge: stoppedContainers
- },
- {
- id: 'stop-all',
- action: 'stop_all' as const,
- label: m.quick_actions_stop_all(),
- onclick: onStopAll,
- loading: isLoading.stopping,
- disabled: runningContainers === 0 || isAnyActionLoading,
- badge: runningContainers
- },
- {
- id: 'prune',
- action: 'prune' as const,
- label: m.quick_actions_prune_system(),
- onclick: onOpenPruneDialog,
- loading: isLoading.pruning,
- disabled: isAnyActionLoading
- },
+ canStartAll
+ ? {
+ id: 'start-all',
+ action: 'start_all' as const,
+ label: m.quick_actions_start_all(),
+ onclick: onStartAll,
+ loading: isLoading.starting,
+ disabled: stoppedContainers === 0 || isAnyActionLoading,
+ badge: stoppedContainers
+ }
+ : null,
+ canStopAll
+ ? {
+ id: 'stop-all',
+ action: 'stop_all' as const,
+ label: m.quick_actions_stop_all(),
+ onclick: onStopAll,
+ loading: isLoading.stopping,
+ disabled: runningContainers === 0 || isAnyActionLoading,
+ badge: runningContainers
+ }
+ : null,
+ canPrune
+ ? {
+ id: 'prune',
+ action: 'prune' as const,
+ label: m.quick_actions_prune_system(),
+ onclick: onOpenPruneDialog,
+ loading: isLoading.pruning,
+ disabled: isAnyActionLoading
+ }
+ : null,
{
id: 'refresh',
action: 'refresh' as const,
@@ -80,7 +89,7 @@
loading: refreshing,
disabled: isAnyActionLoading || refreshing
}
- ].filter((b) => currentUserIsAdmin || b.id === 'refresh')
+ ].filter((b) => b !== null) as ActionButton[]
);
</script>
@@ -106,94 +115,100 @@
{:else}
<ActionButtonGroup buttons={actionButtons} />
{/if}
- {:else if currentUserIsAdmin}
+ {:else if hasAnyQuickAction}
<h2 class="mb-3 text-lg font-semibold tracking-tight">{m.quick_actions_title()}</h2>
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
- <div class="group hover-lift rounded-2xl bg-gradient-to-br from-emerald-500/20 to-emerald-500/0 p-[1px]">
- <ArcaneButton
- action="start_all"
- size="card"
- tone="outline-success"
- class="bg-card/90 bubble bubble-shadow backdrop-blur-sm"
- onclick={onStartAll}
- loading={isLoading.starting}
- disabled={stoppedContainers === 0 || isAnyActionLoading}
- icon={null}
- showLabel={false}
- >
- <div class="relative">
- <div class="flex size-10 items-center justify-center rounded-lg bg-emerald-500/10 ring-1 ring-emerald-500/30">
- <StartIcon class="size-5 text-emerald-400" />
+ {#if canStartAll}
+ <div class="group hover-lift rounded-2xl bg-gradient-to-br from-emerald-500/20 to-emerald-500/0 p-[1px]">
+ <ArcaneButton
+ action="start_all"
+ size="card"
+ tone="outline-success"
+ class="bg-card/90 bubble bubble-shadow backdrop-blur-sm"
+ onclick={onStartAll}
+ loading={isLoading.starting}
+ disabled={stoppedContainers === 0 || isAnyActionLoading}
+ icon={null}
+ showLabel={false}
+ >
+ <div class="relative">
+ <div class="flex size-10 items-center justify-center rounded-lg bg-emerald-500/10 ring-1 ring-emerald-500/30">
+ <StartIcon class="size-5 text-emerald-400" />
+ </div>
+ <div
+ class="pointer-events-none absolute -inset-1 rounded-lg bg-emerald-500/20 opacity-0 blur-lg transition-opacity group-hover:opacity-40"
+ ></div>
</div>
- <div
- class="pointer-events-none absolute -inset-1 rounded-lg bg-emerald-500/20 opacity-0 blur-lg transition-opacity group-hover:opacity-40"
- ></div>
- </div>
- <div class="flex-1 text-left">
- <div class="text-sm font-medium">{m.quick_actions_start_all()}</div>
- <div class="text-muted-foreground text-xs">
- <span class="rounded-full border px-1.5 py-0.5">{m.quick_actions_containers({ count: stoppedContainers })}</span>
+ <div class="flex-1 text-left">
+ <div class="text-sm font-medium">{m.quick_actions_start_all()}</div>
+ <div class="text-muted-foreground text-xs">
+ <span class="rounded-full border px-1.5 py-0.5">{m.quick_actions_containers({ count: stoppedContainers })}</span>
+ </div>
</div>
- </div>
- </ArcaneButton>
- </div>
+ </ArcaneButton>
+ </div>
+ {/if}
- <div class="group hover-lift rounded-2xl bg-gradient-to-br from-sky-500/20 to-sky-500/0 p-[1px]">
- <ArcaneButton
- action="stop_all"
- size="card"
- tone="outline-info"
- class="bg-card/90 bubble bubble-shadow backdrop-blur-sm"
- onclick={onStopAll}
- loading={isLoading.stopping}
- disabled={runningContainers === 0 || isAnyActionLoading}
- icon={null}
- showLabel={false}
- >
- <div class="relative">
- <div class="flex size-10 items-center justify-center rounded-lg bg-sky-500/10 ring-1 ring-sky-500/30">
- <StopIcon class="size-5 text-sky-400" />
+ {#if canStopAll}
+ <div class="group hover-lift rounded-2xl bg-gradient-to-br from-sky-500/20 to-sky-500/0 p-[1px]">
+ <ArcaneButton
+ action="stop_all"
+ size="card"
+ tone="outline-info"
+ class="bg-card/90 bubble bubble-shadow backdrop-blur-sm"
+ onclick={onStopAll}
+ loading={isLoading.stopping}
+ disabled={runningContainers === 0 || isAnyActionLoading}
+ icon={null}
+ showLabel={false}
+ >
+ <div class="relative">
+ <div class="flex size-10 items-center justify-center rounded-lg bg-sky-500/10 ring-1 ring-sky-500/30">
+ <StopIcon class="size-5 text-sky-400" />
+ </div>
+ <div
+ class="pointer-events-none absolute -inset-1 rounded-lg bg-sky-500/20 opacity-0 blur-lg transition-opacity group-hover:opacity-40"
+ ></div>
</div>
- <div
- class="pointer-events-none absolute -inset-1 rounded-lg bg-sky-500/20 opacity-0 blur-lg transition-opacity group-hover:opacity-40"
- ></div>
- </div>
- <div class="flex-1 text-left">
- <div class="text-sm font-medium">{m.quick_actions_stop_all()}</div>
- <div class="text-muted-foreground text-xs">
- <span class="rounded-full border px-1.5 py-0.5">{m.quick_actions_containers({ count: runningContainers })}</span>
+ <div class="flex-1 text-left">
+ <div class="text-sm font-medium">{m.quick_actions_stop_all()}</div>
+ <div class="text-muted-foreground text-xs">
+ <span class="rounded-full border px-1.5 py-0.5">{m.quick_actions_containers({ count: runningContainers })}</span>
+ </div>
</div>
- </div>
- </ArcaneButton>
- </div>
+ </ArcaneButton>
+ </div>
+ {/if}
- <div class="group hover-lift rounded-2xl bg-gradient-to-br from-red-500/20 to-red-500/0 p-[1px]">
- <ArcaneButton
- action="prune"
- size="card"
- tone="outline-destructive"
- class="bg-card/90 bubble bubble-shadow backdrop-blur-sm"
- onclick={onOpenPruneDialog}
- loading={isLoading.pruning}
- disabled={isAnyActionLoading}
- icon={null}
- showLabel={false}
- >
- <div class="relative">
- <div class="flex size-10 items-center justify-center rounded-lg bg-red-500/10 ring-1 ring-red-500/30">
- <TrashIcon class="size-5 text-red-400" />
+ {#if canPrune}
+ <div class="group hover-lift rounded-2xl bg-gradient-to-br from-red-500/20 to-red-500/0 p-[1px]">
+ <ArcaneButton
+ action="prune"
+ size="card"
+ tone="outline-destructive"
+ class="bg-card/90 bubble bubble-shadow backdrop-blur-sm"
+ onclick={onOpenPruneDialog}
+ loading={isLoading.pruning}
+ disabled={isAnyActionLoading}
+ icon={null}
+ showLabel={false}
+ >
+ <div class="relative">
+ <div class="flex size-10 items-center justify-center rounded-lg bg-red-500/10 ring-1 ring-red-500/30">
+ <TrashIcon class="size-5 text-red-400" />
+ </div>
+ <div
+ class="pointer-events-none absolute -inset-1 rounded-lg bg-red-500/20 opacity-0 blur-lg transition-opacity group-hover:opacity-40"
+ ></div>
</div>
- <div
- class="pointer-events-none absolute -inset-1 rounded-lg bg-red-500/20 opacity-0 blur-lg transition-opacity group-hover:opacity-40"
- ></div>
- </div>
- <div class="flex-1 text-left">
- <div class="text-sm font-medium">{m.quick_actions_prune_system()}</div>
- <div class="text-muted-foreground text-xs">{m.quick_actions_prune_description()}</div>
- </div>
- </ArcaneButton>
- </div>
+ <div class="flex-1 text-left">
+ <div class="text-sm font-medium">{m.quick_actions_prune_system()}</div>
+ <div class="text-muted-foreground text-xs">{m.quick_actions_prune_description()}</div>
+ </div>
+ </ArcaneButton>
+ </div>
+ {/if}
</div>
{/if}
</section>
diff --git a/frontend/src/lib/components/role-editor/permission-picker.svelte b/frontend/src/lib/components/role-editor/permission-picker.svelte
new file mode 100644
index 000000000..39f221d09
--- /dev/null
+++ b/frontend/src/lib/components/role-editor/permission-picker.svelte
@@ -0,0 +1,155 @@
+<script lang="ts">
+ import * as Accordion from '$lib/components/ui/accordion';
+ 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/role.type';
+ import { m } from '$lib/paraglide/messages';
+
+ type Props = {
+ manifest: PermissionsManifest;
+ selected: string[];
+ disabled?: boolean;
+ showSearch?: boolean;
+ };
+
+ let { manifest, selected = $bindable([]), disabled = false, showSearch = true }: Props = $props();
+
+ let query = $state('');
+
+ const normalizedQuery = $derived(query.trim().toLowerCase());
+
+ type FilteredResource = {
+ resource: PermissionResource;
+ actions: PermissionAction[];
+ };
+
+ const filteredGroups: FilteredResource[] = $derived(
+ manifest.resources
+ .map((resource) => {
+ if (!normalizedQuery) {
+ return { resource, actions: resource.actions };
+ }
+ const actions = resource.actions.filter(
+ (action) =>
+ action.label.toLowerCase().includes(normalizedQuery) || action.permission.toLowerCase().includes(normalizedQuery)
+ );
+ return { resource, actions };
+ })
+ .filter((g) => g.actions.length > 0)
+ );
+
+ const selectedSet = $derived(new Set(selected));
+
+ const openValues: string[] = $derived(normalizedQuery ? filteredGroups.map((g) => g.resource.key) : []);
+
+ function countSelectedInGroup(resource: PermissionResource): number {
+ let count = 0;
+ for (const action of resource.actions) {
+ if (selectedSet.has(action.permission)) count++;
+ }
+ return count;
+ }
+
+ function groupCheckState(resource: PermissionResource): boolean | 'indeterminate' {
+ const count = countSelectedInGroup(resource);
+ if (count === 0) return false;
+ if (count === resource.actions.length) return true;
+ return 'indeterminate';
+ }
+
+ function toggleGroup(resource: PermissionResource, checked: boolean) {
+ if (disabled) return;
+ const groupPerms = resource.actions.map((a) => a.permission);
+ if (checked) {
+ const without = selected.filter((p) => !groupPerms.includes(p));
+ selected = [...without, ...groupPerms];
+ } else {
+ selected = selected.filter((p) => !groupPerms.includes(p));
+ }
+ }
+
+ function toggleAction(permission: string, checked: boolean) {
+ if (disabled) return;
+ if (checked) {
+ if (!selected.includes(permission)) {
+ selected = [...selected, permission];
+ }
+ } else {
+ selected = selected.filter((p) => p !== permission);
+ }
+ }
+</script>
+
+<div class="space-y-4">
+ {#if showSearch}
+ <Input type="text" placeholder={m.permissions_search_placeholder()} bind:value={query} {disabled} />
+ {/if}
+
+ {#if filteredGroups.length === 0}
+ <p class="text-muted-foreground py-6 text-center text-sm">{m.permissions_no_matches()}</p>
+ {:else}
+ <Accordion.Root type="multiple" value={openValues} class="w-full">
+ {#each filteredGroups as group (group.resource.key)}
+ {@const checkState = groupCheckState(group.resource)}
+ {@const isAllChecked = checkState === true}
+ {@const isIndeterminate = checkState === 'indeterminate'}
+ <Accordion.Item value={group.resource.key}>
+ <div class="flex w-full items-center gap-3 py-1">
+ <Checkbox
+ id={`group-${group.resource.key}`}
+ checked={isAllChecked}
+ indeterminate={isIndeterminate}
+ {disabled}
+ onCheckedChange={(checked) => toggleGroup(group.resource, checked === true)}
+ aria-label={m.permissions_select_all()}
+ />
+ <Accordion.Trigger class="flex-1 py-2 text-left text-sm font-medium">
+ <div class="flex flex-1 items-center justify-between gap-2 pr-2">
+ <span>
+ {m.permissions_group_label({
+ resource: group.resource.label,
+ selected: countSelectedInGroup(group.resource),
+ total: group.resource.actions.length
+ })}
+ </span>
+ <StatusBadge
+ text={group.resource.scope === 'global' ? m.permissions_scope_global() : m.permissions_scope_env()}
+ variant={group.resource.scope === 'global' ? 'amber' : 'blue'}
+ size="sm"
+ minWidth="none"
+ />
+ </div>
+ </Accordion.Trigger>
+ </div>
+ <Accordion.Content>
+ <div class="grid grid-cols-1 gap-3 pt-2 pl-7 sm:grid-cols-2">
+ {#each group.actions as action (action.permission)}
+ {@const checked = selectedSet.has(action.permission)}
+ <label
+ for={`perm-${action.permission}`}
+ class="flex cursor-pointer items-start gap-3 rounded-md p-2 hover:bg-accent/40"
+ >
+ <Checkbox
+ id={`perm-${action.permission}`}
+ {checked}
+ {disabled}
+ onCheckedChange={(c) => toggleAction(action.permission, c === true)}
+ class="mt-0.5"
+ />
+ <div class="flex flex-col gap-0.5">
+ <span class="text-sm leading-none font-medium">{action.label}</span>
+ <code class="text-muted-foreground text-xs">{action.permission}</code>
+ {#if action.description}
+ <span class="text-muted-foreground text-xs">{action.description}</span>
+ {/if}
+ </div>
+ </label>
+ {/each}
+ </div>
+ </Accordion.Content>
+ </Accordion.Item>
+ {/each}
+ </Accordion.Root>
+ {/if}
+</div>
diff --git a/frontend/src/lib/components/role-editor/role-editor.svelte b/frontend/src/lib/components/role-editor/role-editor.svelte
new file mode 100644
index 000000000..167dd6002
--- /dev/null
+++ b/frontend/src/lib/components/role-editor/role-editor.svelte
@@ -0,0 +1,132 @@
+<script lang="ts">
+ import * as Card from '$lib/components/ui/card';
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import FormInput from '$lib/components/form/form-input.svelte';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import PermissionPicker from './permission-picker.svelte';
+ import type { Role, PermissionsManifest } from '$lib/types/role.type';
+ import { CopyIcon } from '$lib/icons';
+ import { z } from 'zod/v4';
+ import { createForm, preventDefault } from '$lib/utils/form.utils';
+ import { m } from '$lib/paraglide/messages';
+
+ type Props = {
+ role: Role | null;
+ manifest: PermissionsManifest;
+ isLoading?: boolean;
+ onSubmit: (data: { name: string; description?: string; permissions: string[] }) => void | Promise<void>;
+ onClone?: () => void;
+ };
+
+ let { role, manifest, isLoading = false, onSubmit, onClone }: Props = $props();
+
+ const isBuiltIn = $derived(role?.builtIn ?? false);
+ const totalPermissions = $derived(manifest.resources.reduce((sum, r) => sum + r.actions.length, 0));
+
+ const formSchema = z.object({
+ name: z.string().min(1, m.roles_name_required()),
+ description: z.string().optional().default(''),
+ permissions: z.array(z.string()).min(1, m.roles_permissions_required())
+ });
+
+ const formData = $derived({
+ name: role?.name ?? '',
+ description: role?.description ?? '',
+ permissions: role?.permissions ?? []
+ });
+
+ const { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
+
+ const selectedCount = $derived($inputs.permissions?.value?.length ?? 0);
+
+ function handleSubmit() {
+ if (isBuiltIn) return;
+ const data = form.validate();
+ if (!data) return;
+ onSubmit({
+ name: data.name,
+ description: data.description ? data.description : undefined,
+ permissions: data.permissions
+ });
+ }
+</script>
+
+<form onsubmit={preventDefault(handleSubmit)} novalidate class="grid grid-cols-1 gap-6 lg:grid-cols-[320px_1fr]">
+ <div class="space-y-4">
+ <Card.Root>
+ <Card.Header>
+ <Card.Title class="text-base">
+ {role ? m.roles_edit_title() : m.roles_create_title()}
+ </Card.Title>
+ </Card.Header>
+ <Card.Content class="space-y-4 p-6 pt-2">
+ <div class="flex items-center gap-2">
+ <StatusBadge
+ text={isBuiltIn ? m.roles_built_in() : m.roles_custom()}
+ variant={isBuiltIn ? 'blue' : 'green'}
+ size="sm"
+ minWidth="none"
+ />
+ </div>
+
+ <FormInput
+ label={m.roles_name_label()}
+ type="text"
+ placeholder={m.roles_name_placeholder()}
+ disabled={isBuiltIn || isLoading}
+ bind:input={$inputs.name}
+ />
+
+ <FormInput
+ label={m.roles_description_label()}
+ type="text"
+ placeholder={m.roles_description_placeholder()}
+ disabled={isBuiltIn || isLoading}
+ bind:input={$inputs.description}
+ />
+
+ <div>
+ <div class="text-muted-foreground text-xs">
+ {m.roles_permissions_count({ count: selectedCount, total: totalPermissions })}
+ </div>
+ {#if $inputs.permissions?.error}
+ <p class="mt-1 text-sm text-red-500">{$inputs.permissions.error}</p>
+ {/if}
+ </div>
+
+ {#if isBuiltIn}
+ <p class="text-muted-foreground text-xs">{m.roles_built_in_note()}</p>
+ {/if}
+
+ {#if isBuiltIn && onClone}
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ type="button"
+ class="w-full"
+ icon={CopyIcon}
+ onclick={onClone}
+ customLabel={m.roles_clone_button()}
+ disabled={isLoading}
+ />
+ {/if}
+
+ {#if !isBuiltIn}
+ <ArcaneButton
+ action="save"
+ type="submit"
+ class="w-full"
+ disabled={isLoading}
+ loading={isLoading}
+ onclick={handleSubmit}
+ customLabel={role ? m.roles_save_changes() : m.common_create_button({ resource: m.roles_title() })}
+ />
+ {/if}
+ </Card.Content>
+ </Card.Root>
+ </div>
+
+ <div>
+ <PermissionPicker {manifest} bind:selected={$inputs.permissions.value} disabled={isBuiltIn || isLoading} />
+ </div>
+</form>
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 a2ffb9aa0..679930a64 100644
--- a/frontend/src/lib/components/sheets/api-key-form-sheet.svelte
+++ b/frontend/src/lib/components/sheets/api-key-form-sheet.svelte
@@ -2,7 +2,9 @@
import * as ResponsiveDialog from '$lib/components/ui/responsive-dialog/index.js';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import FormInput from '$lib/components/form/form-input.svelte';
+ import PermissionPicker from '$lib/components/role-editor/permission-picker.svelte';
import type { ApiKey } from '$lib/types/api-key.type';
+ import type { PermissionsManifest, ApiKeyPermissionGrant } from '$lib/types/role.type';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/form.utils';
import * as m from '$lib/paraglide/messages.js';
@@ -10,35 +12,53 @@
type ApiKeyFormProps = {
open: boolean;
apiKeyToEdit: ApiKey | null;
+ manifest: PermissionsManifest;
+ availablePermissions?: ApiKeyPermissionGrant[];
onSubmit: (data: {
- apiKey: { name: string; description?: string; expiresAt?: string };
+ apiKey: {
+ name: string;
+ description?: string;
+ expiresAt?: string;
+ permissions: ApiKeyPermissionGrant[];
+ };
isEditMode: boolean;
apiKeyId?: string;
}) => void;
isLoading: boolean;
};
- let { open = $bindable(false), apiKeyToEdit = $bindable(), onSubmit, isLoading }: ApiKeyFormProps = $props();
+ let {
+ open = $bindable(false),
+ apiKeyToEdit = $bindable(),
+ manifest,
+ availablePermissions = [],
+ onSubmit,
+ isLoading
+ }: ApiKeyFormProps = $props();
let isEditMode = $derived(!!apiKeyToEdit);
let isStaticApiKey = $derived(apiKeyToEdit?.isStatic ?? false);
+ let isBootstrapApiKey = $derived(apiKeyToEdit?.isBootstrap ?? false);
+ let isReadOnlyApiKey = $derived(isStaticApiKey || isBootstrapApiKey);
const formSchema = z.object({
name: z.string().min(1, m.common_field_required({ field: m.api_key_name() })),
description: z.string().optional(),
- expiresAt: z.date().optional()
+ expiresAt: z.date().optional(),
+ permissions: z.array(z.string()).min(1, m.api_key_permissions_required())
});
let formData = $derived({
name: apiKeyToEdit?.name || '',
description: apiKeyToEdit?.description || '',
- expiresAt: apiKeyToEdit?.expiresAt ? new Date(apiKeyToEdit.expiresAt) : undefined
+ expiresAt: apiKeyToEdit?.expiresAt ? new Date(apiKeyToEdit.expiresAt) : undefined,
+ permissions: availablePermissions.map((p) => p.permission)
});
let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
function handleSubmit() {
- if (isStaticApiKey) return;
+ if (isReadOnlyApiKey) return;
const data = form.validate();
if (!data) return;
@@ -46,7 +66,10 @@
const apiKeyData = {
name: data.name,
description: data.description || undefined,
- expiresAt: data.expiresAt ? data.expiresAt.toISOString() : undefined
+ expiresAt: data.expiresAt ? data.expiresAt.toISOString() : undefined,
+ // v1: persist all picks as global grants (environmentId undefined).
+ // env-scoped picking is a follow-up.
+ permissions: data.permissions.map((p) => ({ permission: p }))
};
onSubmit({ apiKey: apiKeyData, isEditMode, apiKeyId: apiKeyToEdit?.id });
@@ -66,25 +89,32 @@
variant="sheet"
title={isStaticApiKey
? (apiKeyToEdit?.name ?? m.api_key_static_title())
- : isEditMode
- ? m.api_key_edit_title()
- : m.api_key_create_title()}
+ : isBootstrapApiKey
+ ? (apiKeyToEdit?.name ?? m.api_key_bootstrap_title())
+ : isEditMode
+ ? m.api_key_edit_title()
+ : m.api_key_create_title()}
description={isEditMode
? isStaticApiKey
? m.api_key_static_description()
- : m.api_key_edit_description({ name: apiKeyToEdit?.name ?? m.common_unknown() })
+ : isBootstrapApiKey
+ ? m.api_key_bootstrap_description()
+ : m.api_key_edit_description({ name: apiKeyToEdit?.name ?? m.common_unknown() })
: m.api_key_create_description()}
contentClass="sm:max-w-[500px]"
>
{#snippet children()}
<form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-6">
+ {#if isBootstrapApiKey && !isStaticApiKey}
+ <p class="text-muted-foreground text-sm">{m.api_key_bootstrap_locked_description()}</p>
+ {/if}
<FormInput
label={m.api_key_name()}
type="text"
placeholder={m.api_key_name_placeholder()}
description={m.api_key_name_description()}
bind:input={$inputs.name}
- disabled={isStaticApiKey}
+ disabled={isReadOnlyApiKey}
/>
<FormInput
label={m.api_key_description_label()}
@@ -92,15 +122,25 @@
placeholder={m.api_key_description_placeholder()}
description={m.api_key_description_help()}
bind:input={$inputs.description}
- disabled={isStaticApiKey}
+ disabled={isReadOnlyApiKey}
/>
<FormInput
label={m.api_key_expires_at()}
type="date"
description={m.api_key_expires_at_description()}
bind:input={$inputs.expiresAt}
- disabled={isStaticApiKey}
+ disabled={isReadOnlyApiKey}
/>
+ {#if !isReadOnlyApiKey}
+ <div>
+ <label for="permissions" class="text-sm font-medium">{m.roles_permissions_label()}</label>
+ <p class="text-muted-foreground mb-3 text-xs">{m.api_key_permissions_description()}</p>
+ <PermissionPicker {manifest} bind:selected={$inputs.permissions.value} showSearch />
+ {#if $inputs.permissions.error}
+ <p class="text-destructive mt-1 text-xs">{$inputs.permissions.error}</p>
+ {/if}
+ </div>
+ {/if}
</form>
{/snippet}
@@ -114,7 +154,7 @@
onclick={() => (open = false)}
disabled={isLoading}
/>
- {#if !isStaticApiKey}
+ {#if !isReadOnlyApiKey}
<ArcaneButton
action={isEditMode ? 'save' : 'create'}
type="submit"
diff --git a/frontend/src/lib/components/sheets/oidc-mapping-form-sheet.svelte b/frontend/src/lib/components/sheets/oidc-mapping-form-sheet.svelte
new file mode 100644
index 000000000..69a80da10
--- /dev/null
+++ b/frontend/src/lib/components/sheets/oidc-mapping-form-sheet.svelte
@@ -0,0 +1,151 @@
+<script lang="ts">
+ import * as ResponsiveDialog from '$lib/components/ui/responsive-dialog/index.js';
+ import * as Select from '$lib/components/ui/select';
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import FormInput from '$lib/components/form/form-input.svelte';
+ import { Label } from '$lib/components/ui/label';
+ import type { OidcRoleMapping, Role } from '$lib/types/role.type';
+ import type { Environment } from '$lib/types/environment.type';
+ import { z } from 'zod/v4';
+ import { createForm, preventDefault } from '$lib/utils/form.utils';
+ import { m } from '$lib/paraglide/messages';
+
+ type Props = {
+ open: boolean;
+ mappingToEdit: OidcRoleMapping | null;
+ roles: Role[];
+ environments: Environment[];
+ isLoading: boolean;
+ onSubmit: (data: { claimValue: string; roleId: string; environmentId?: string }) => void;
+ };
+
+ let { open = $bindable(false), mappingToEdit, roles, environments, isLoading, onSubmit }: Props = $props();
+
+ const GLOBAL_OPTION_ID = 'global';
+
+ const isEditMode = $derived(!!mappingToEdit);
+
+ const envOptions = $derived([
+ { id: GLOBAL_OPTION_ID, name: m.oidc_mappings_scope_global_option() },
+ ...environments.map((env) => ({ id: env.id, name: env.name }))
+ ]);
+
+ const formSchema = z.object({
+ claimValue: z.string().min(1, m.oidc_mappings_claim_required()),
+ roleId: z.string().min(1, m.oidc_mappings_role_required()),
+ environmentId: z.string()
+ });
+
+ const formData = $derived({
+ claimValue: mappingToEdit?.claimValue ?? '',
+ roleId: mappingToEdit?.roleId ?? roles[0]?.id ?? '',
+ environmentId: mappingToEdit?.environmentId ?? GLOBAL_OPTION_ID
+ });
+
+ const { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
+
+ function envSelectedLabel(value: string): string {
+ return envOptions.find((o) => o.id === value)?.name ?? m.common_select_option();
+ }
+
+ function roleSelectedLabel(value: string): string {
+ return roles.find((r) => r.id === value)?.name ?? m.common_select_option();
+ }
+
+ function handleSubmit() {
+ const data = form.validate();
+ if (!data) return;
+ onSubmit({
+ claimValue: data.claimValue,
+ roleId: data.roleId,
+ environmentId: data.environmentId === GLOBAL_OPTION_ID ? undefined : data.environmentId
+ });
+ }
+
+ function handleOpenChange(newOpenState: boolean) {
+ open = newOpenState;
+ }
+</script>
+
+<ResponsiveDialog.Root
+ bind:open
+ onOpenChange={handleOpenChange}
+ variant="sheet"
+ title={isEditMode ? m.oidc_mappings_edit_title() : m.oidc_mappings_create_title()}
+ description={m.oidc_mappings_subtitle()}
+ contentClass="sm:max-w-[500px]"
+>
+ {#snippet children()}
+ <form onsubmit={preventDefault(handleSubmit)} novalidate class="grid gap-4 py-6">
+ <FormInput
+ label={m.oidc_mappings_claim_label()}
+ type="text"
+ placeholder={m.oidc_mappings_claim_placeholder()}
+ disabled={isLoading}
+ bind:input={$inputs.claimValue}
+ />
+
+ <div class="space-y-2">
+ <Label for="oidc-mapping-role" class="mb-0">{m.oidc_mappings_role_label()}</Label>
+ <Select.Root type="single" bind:value={$inputs.roleId.value} disabled={isLoading}>
+ <Select.Trigger id="oidc-mapping-role" class="w-full {$inputs.roleId.error ? 'border-destructive' : ''}">
+ <span>{roleSelectedLabel($inputs.roleId.value)}</span>
+ </Select.Trigger>
+ <Select.Content>
+ {#each roles as role (role.id)}
+ <Select.Item value={role.id} label={role.name}>
+ <div class="flex flex-col items-start gap-0.5">
+ <span class="font-medium">{role.name}</span>
+ {#if role.description}
+ <span class="text-muted-foreground text-xs">{role.description}</span>
+ {/if}
+ </div>
+ </Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ {#if $inputs.roleId.error}
+ <p class="text-destructive text-xs font-medium">{$inputs.roleId.error}</p>
+ {/if}
+ </div>
+
+ <div class="space-y-2">
+ <Label for="oidc-mapping-env" class="mb-0">{m.oidc_mappings_scope_label()}</Label>
+ <Select.Root type="single" bind:value={$inputs.environmentId.value} disabled={isLoading}>
+ <Select.Trigger id="oidc-mapping-env" class="w-full">
+ <span>{envSelectedLabel($inputs.environmentId.value)}</span>
+ </Select.Trigger>
+ <Select.Content>
+ {#each envOptions as option (option.id)}
+ <Select.Item value={option.id} label={option.name}>
+ {option.name}
+ </Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ </div>
+ </form>
+ {/snippet}
+
+ {#snippet footer()}
+ <div class="flex w-full flex-row gap-2">
+ <ArcaneButton
+ action="cancel"
+ tone="outline"
+ type="button"
+ class="flex-1"
+ onclick={() => (open = false)}
+ disabled={isLoading}
+ />
+ <ArcaneButton
+ action={isEditMode ? 'save' : 'create'}
+ type="submit"
+ class="flex-1"
+ disabled={isLoading}
+ loading={isLoading}
+ onclick={handleSubmit}
+ customLabel={isEditMode ? m.common_save() : m.common_create()}
+ />
+ </div>
+ {/snippet}
+</ResponsiveDialog.Root>
diff --git a/frontend/src/lib/components/sheets/user-form-sheet.svelte b/frontend/src/lib/components/sheets/user-form-sheet.svelte
index d4d3604fc..75047764d 100644
--- a/frontend/src/lib/components/sheets/user-form-sheet.svelte
+++ b/frontend/src/lib/components/sheets/user-form-sheet.svelte
@@ -1,18 +1,31 @@
<script lang="ts">
import * as ResponsiveDialog from '$lib/components/ui/responsive-dialog/index.js';
+ import * as Alert from '$lib/components/ui/alert/index.js';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import FormInput from '$lib/components/form/form-input.svelte';
- import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
+ import RoleAssignmentsEditor from '$lib/components/forms/role-assignments-editor.svelte';
import type { User } from '$lib/types/user.type';
+ import type { Role } from '$lib/types/role.type';
+ import type { Environment } from '$lib/types/environment.type';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/form.utils';
import { isValidUserEmail } from '$lib/utils/email.utils';
import { m } from '$lib/paraglide/messages';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
+
+ type RoleAssignmentInput = { roleId: string; environmentId?: string };
+ type UserSubmission = Omit<Partial<User>, 'roleAssignments'> & {
+ password?: string;
+ roleAssignments?: RoleAssignmentInput[];
+ };
type UserFormProps = {
open: boolean;
userToEdit: User | null;
- onSubmit: (data: { user: Partial<User> & { password?: string }; isEditMode: boolean; userId?: string }) => void;
+ roles: Role[];
+ environments: Environment[];
+ availableRoleAssignments?: RoleAssignmentInput[];
+ onSubmit: (data: { user: UserSubmission; isEditMode: boolean; userId?: string }) => void;
isLoading: boolean;
allowUsernameEdit?: boolean;
};
@@ -20,6 +33,9 @@
let {
open = $bindable(false),
userToEdit = $bindable(),
+ roles,
+ environments,
+ availableRoleAssignments = [],
onSubmit,
isLoading,
allowUsernameEdit = false
@@ -30,6 +46,8 @@
let canEditUsername = $derived(!isEditMode || allowUsernameEdit);
let isOidcUser = $derived(!!userToEdit?.oidcSubjectId);
+ let hasOidcAssignments = $derived(!!userToEdit?.roleAssignments?.some((a) => a.source === 'oidc'));
+ let assignmentsDisabled = $derived(isOidcUser && hasOidcAssignments);
const formSchema = z.object({
username: z.string().min(1, m.common_username_required()),
@@ -39,7 +57,14 @@
.string()
.trim()
.refine((value) => value === '' || isValidUserEmail(value), m.common_invalid_email()),
- isAdmin: z.boolean().default(false)
+ roleAssignments: z
+ .array(
+ z.object({
+ roleId: z.string().min(1),
+ environmentId: z.string().optional()
+ })
+ )
+ .min(1, m.users_role_assignments_required())
});
let formData = $derived({
@@ -47,7 +72,7 @@
password: '',
displayName: userToEdit?.displayName || '',
email: userToEdit?.email || '',
- isAdmin: Boolean(userToEdit?.roles?.includes('admin'))
+ roleAssignments: availableRoleAssignments
});
let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
@@ -56,19 +81,19 @@
const data = form.validate();
if (!data) return;
- // For OIDC users, only allow role changes
+ // For OIDC users, only allow role assignment changes
if (isOidcUser) {
onSubmit({
- user: { roles: [data.isAdmin ? 'admin' : 'user'] },
+ user: { roleAssignments: data.roleAssignments },
isEditMode,
userId: userToEdit?.id
});
return;
}
- const userData: Partial<User> & { password?: string } = {
+ const userData: UserSubmission = {
displayName: data.displayName,
- roles: [data.isAdmin ? 'admin' : 'user']
+ roleAssignments: data.roleAssignments
};
if (data.email) {
@@ -104,7 +129,7 @@
description={isEditMode
? m.users_edit_description({ username: userToEdit?.username ?? m.common_unknown() })
: m.users_create_description()}
- contentClass="sm:max-w-[500px]"
+ contentClass="sm:max-w-[640px]"
>
{#snippet children()}
<form onsubmit={preventDefault(handleSubmit)} novalidate class="grid gap-4 py-6">
@@ -148,12 +173,29 @@
disabled={isOidcUser}
bind:input={$inputs.email}
/>
- <SwitchWithLabel
- id="isAdminSwitch"
- label={m.common_admin()}
- description={m.users_administrator_description()}
- bind:checked={$inputs.isAdmin.value}
- />
+ <IfPermitted adminOnly>
+ <div>
+ <label for="roleAssignments" class="text-sm font-medium">{m.users_role_assignments_label()}</label>
+ <p class="text-muted-foreground mb-2 text-xs">{m.users_role_assignments_description()}</p>
+ {#if assignmentsDisabled}
+ <Alert.Root variant="default" class="mb-3">
+ <Alert.Description>
+ {m.users_role_assignments_oidc_managed()}
+ <a href="/settings/authentication" class="text-primary ml-2 underline">{m.users_role_assignments_oidc_link()}</a>
+ </Alert.Description>
+ </Alert.Root>
+ {/if}
+ <RoleAssignmentsEditor
+ bind:assignments={$inputs.roleAssignments.value}
+ {roles}
+ {environments}
+ disabled={assignmentsDisabled}
+ />
+ {#if $inputs.roleAssignments.error}
+ <p class="text-destructive mt-1 text-xs">{$inputs.roleAssignments.error}</p>
+ {/if}
+ </div>
+ </IfPermitted>
</form>
{/snippet}
diff --git a/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte b/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte
index 547e32d48..0df960c39 100644
--- a/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar-updatebanner.svelte
@@ -4,7 +4,6 @@
import * as Tooltip from '$lib/components/ui/tooltip/index.js';
import { useSidebar } from '$lib/components/ui/sidebar/index.js';
import type { AppVersionInformation } from '$lib/types/application-configuration';
- import type { User } from '$lib/types/user.type';
import { m } from '$lib/paraglide/messages';
import { queryKeys } from '$lib/query/query-keys';
import systemUpgradeService from '$lib/services/api/system-upgrade-service';
@@ -13,26 +12,25 @@
import { DownloadIcon } from '$lib/icons';
import { extractApiErrorMessage } from '$lib/utils/api.util';
import { createMutation, createQuery } from '@tanstack/svelte-query';
+ import { hasPermission } from '$lib/utils/permissions.util';
let {
isCollapsed,
versionInformation,
- debug = false,
- user
+ debug = false
}: {
isCollapsed: boolean;
versionInformation?: AppVersionInformation;
debug?: boolean;
- user?: User | null;
} = $props();
const sidebar = useSidebar();
let upgrading = $state(false);
let showConfirmDialog = $state(false);
- const isAdmin = $derived(!!user?.roles?.includes('admin'));
+ const canInstallUpdates = $derived(hasPermission('environments:update'));
- const shouldCheckUpgrade = $derived(!!(versionInformation?.updateAvailable && isAdmin && !debug));
+ const shouldCheckUpgrade = $derived(!!(versionInformation?.updateAvailable && canInstallUpdates && !debug));
const upgradeAvailabilityQuery = createQuery(() => ({
queryKey: queryKeys.system.upgradeAvailable('sidebar'),
queryFn: () => systemUpgradeService.checkUpgradeAvailable(),
@@ -48,7 +46,7 @@
const checkingUpgrade = $derived(
!!(shouldCheckUpgrade && (upgradeAvailabilityQuery.isPending || upgradeAvailabilityQuery.isFetching))
);
- const shouldShowUpgrade = $derived((canUpgrade && isAdmin) || debug);
+ const shouldShowUpgrade = $derived((canUpgrade && canInstallUpdates) || debug);
const updateType = $derived.by(() => {
if (!versionInformation) return 'none';
diff --git a/frontend/src/lib/components/sidebar/sidebar.svelte b/frontend/src/lib/components/sidebar/sidebar.svelte
index d148b7f94..683dbe2cb 100644
--- a/frontend/src/lib/components/sidebar/sidebar.svelte
+++ b/frontend/src/lib/components/sidebar/sidebar.svelte
@@ -1,5 +1,10 @@
<script lang="ts" module>
- import { navigationItems, getManagementItems, getSwarmNavigationItems } from '$lib/config/navigation-config';
+ import {
+ navigationItems,
+ getManagementItems,
+ getSwarmNavigationItems,
+ filterByPermissions
+ } from '$lib/config/navigation-config';
</script>
<script lang="ts">
@@ -51,12 +56,16 @@
const effectiveUser = $derived(user ?? storeUser.current);
const isCollapsed = $derived(sidebar.state === 'collapsed' && !(sidebar.hoverExpansionEnabled && sidebar.isHovered));
- const isAdmin = $derived(!!effectiveUser?.roles?.includes('admin'));
let envSwitcherOpen = $state(false);
const currentEnvId = $derived(environmentStore.selected?.id || '0');
- const managementItems = $derived(getManagementItems(currentEnvId));
- const swarmItems = $derived(getSwarmNavigationItems(swarmEnabled));
+ 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));
</script>
<VersionInfoDialog
@@ -66,7 +75,7 @@
debugMode={false}
/>
-<EnvironmentSwitcherDialog bind:open={envSwitcherOpen} {isAdmin} />
+<EnvironmentSwitcherDialog bind:open={envSwitcherOpen} />
<Sidebar.Root {collapsible} {variant} {...restProps}>
<Sidebar.Header class={isCollapsed ? 'gap-0 p-1 pb-2' : ''}>
@@ -92,17 +101,21 @@
{/if}
</Sidebar.Header>
<Sidebar.Content class={!isCollapsed ? '-mt-2' : ''}>
- <SidebarItemGroup label={m.sidebar_management()} items={managementItems} />
- <SidebarItemGroup label={m.sidebar_resources()} items={navigationItems.resourceItems} />
+ {#if managementItems.length > 0}
+ <SidebarItemGroup label={m.sidebar_management()} items={managementItems} />
+ {/if}
+ {#if resourceItems.length > 0}
+ <SidebarItemGroup label={m.sidebar_resources()} items={resourceItems} />
+ {/if}
{#if swarmItems.length > 0}
<SidebarItemGroup label={m.swarm_title()} items={swarmItems} />
{/if}
- {#if isAdmin}
- <SidebarItemGroup label={m.sidebar_administration()} items={navigationItems.settingsItems} />
+ {#if settingsItems.length > 0}
+ <SidebarItemGroup label={m.sidebar_administration()} items={settingsItems} />
{/if}
</Sidebar.Content>
<Sidebar.Footer>
- <SidebarUpdatebanner {isCollapsed} {versionInformation} user={effectiveUser} debug={false} />
+ <SidebarUpdatebanner {isCollapsed} {versionInformation} debug={false} />
{#if effectiveUser}
{#if isCollapsed}
<div class="px-0 pb-2">
diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.ts
index 9c56c2791..1a1246ce8 100644
--- a/frontend/src/lib/config/navigation-config.ts
+++ b/frontend/src/lib/config/navigation-config.ts
@@ -29,6 +29,8 @@ import {
} from '$lib/icons';
import { m } from '$lib/paraglide/messages';
import type { ShortcutKey } from '$lib/utils/keyboard-shortcut.utils';
+import type { User } from '$lib/types/user.type';
+import { GLOBAL_SCOPE, SUDO_PERMISSION } from '$lib/types/role.type';
export type NavigationItem = {
title: string;
@@ -36,6 +38,25 @@ export type NavigationItem = {
icon: any;
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.
+ */
+ 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';
};
export type NavigationSections = {
@@ -47,92 +68,299 @@ export type NavigationSections = {
export const navigationItems: NavigationSections = {
managementItems: [
- { title: m.dashboard_title(), url: '/dashboard', icon: DashboardIcon, shortcut: ['mod', '1'] },
- { title: m.projects_title(), url: '/projects', icon: ProjectsIcon, shortcut: ['mod', '2'] },
- { title: m.environments_title(), url: '/environments', icon: EnvironmentsIcon, shortcut: ['mod', '3'] },
+ {
+ title: m.dashboard_title(),
+ url: '/dashboard',
+ icon: DashboardIcon,
+ shortcut: ['mod', '1'],
+ scope: 'env',
+ requiredPermission: 'dashboard:read'
+ },
+ {
+ title: m.projects_title(),
+ url: '/projects',
+ icon: ProjectsIcon,
+ shortcut: ['mod', '2'],
+ scope: 'env',
+ requiredPermission: ['projects:list', 'projects:read']
+ },
+ {
+ title: m.environments_title(),
+ url: '/environments',
+ icon: EnvironmentsIcon,
+ shortcut: ['mod', '3'],
+ scope: 'global',
+ requiredPermission: ['environments:list', 'environments:read']
+ },
{
title: m.customize_title(),
url: '/customize',
icon: CustomizeIcon,
shortcut: ['mod', '4'],
+ scope: 'global',
+ requiredPermission: 'customize:manage',
items: [
- { title: m.templates_title(), url: '/customize/templates', icon: TemplateIcon },
- { title: m.registries_title(), url: '/customize/registries', icon: RegistryIcon },
- { title: m.variables_title(), url: '/customize/variables', icon: VariableIcon },
- { title: m.git_repositories_title(), url: '/customize/git-repositories', icon: GitBranchIcon }
+ {
+ title: m.templates_title(),
+ url: '/customize/templates',
+ icon: TemplateIcon,
+ scope: 'global',
+ requiredPermission: ['templates:list', 'templates:read']
+ },
+ {
+ title: m.registries_title(),
+ url: '/customize/registries',
+ icon: RegistryIcon,
+ scope: 'global',
+ requiredPermission: ['registries:list', 'registries:read']
+ },
+ {
+ title: m.variables_title(),
+ url: '/customize/variables',
+ icon: VariableIcon,
+ scope: 'global',
+ requiredPermission: ['templates:read']
+ },
+ {
+ title: m.git_repositories_title(),
+ url: '/customize/git-repositories',
+ icon: GitBranchIcon,
+ scope: 'global',
+ requiredPermission: ['git-repositories:list', 'git-repositories:read']
+ }
]
}
],
resourceItems: [
- { title: m.containers_title(), url: '/containers', icon: ContainersIcon, shortcut: ['mod', '5'] },
+ {
+ title: m.containers_title(),
+ url: '/containers',
+ icon: ContainersIcon,
+ shortcut: ['mod', '5'],
+ scope: 'env',
+ requiredPermission: ['containers:list', 'containers:read']
+ },
{
title: m.images_title(),
url: '/images',
icon: ImagesIcon,
shortcut: ['mod', '6'],
+ scope: 'env',
+ requiredPermission: ['images:list', 'images:read'],
items: [
- { title: m.builds(), url: '/images/builds', icon: HammerIcon },
- { title: m.vuln_title(), url: '/images/vulnerabilities', icon: ShieldAlertIcon }
+ { title: m.builds(), url: '/images/builds', icon: HammerIcon, scope: 'env', requiredPermission: 'images:build' },
+ {
+ title: m.vuln_title(),
+ url: '/images/vulnerabilities',
+ icon: ShieldAlertIcon,
+ scope: 'env',
+ requiredPermission: 'vulnerabilities:read'
+ }
]
},
- { title: m.images_updates(), url: '/updates', icon: UpdateIcon, shortcut: ['mod', 'u'] },
+ {
+ title: m.images_updates(),
+ url: '/updates',
+ icon: UpdateIcon,
+ shortcut: ['mod', 'u'],
+ scope: 'env',
+ requiredPermission: 'image-updates:read'
+ },
{
title: m.networks_title(),
url: '/networks',
icon: NetworksIcon,
shortcut: ['mod', '7'],
+ scope: 'env',
+ requiredPermission: ['networks:list', 'networks:read'],
items: [
- { title: m.ports_title(), url: '/ports', icon: HashIcon },
- { title: m.networks_topology_button(), url: '/networks/topology', icon: GitBranchIcon }
+ { title: m.ports_title(), url: '/ports', icon: HashIcon, scope: 'env', requiredPermission: 'containers:list' },
+ {
+ title: m.networks_topology_button(),
+ url: '/networks/topology',
+ icon: GitBranchIcon,
+ scope: 'env',
+ requiredPermission: 'networks:read'
+ }
]
},
- { title: m.volumes_title(), url: '/volumes', icon: VolumesIcon, shortcut: ['mod', '8'] }
+ {
+ title: m.volumes_title(),
+ url: '/volumes',
+ icon: VolumesIcon,
+ shortcut: ['mod', '8'],
+ scope: 'env',
+ requiredPermission: ['volumes:list', 'volumes:read']
+ }
],
swarmItems: [
- { title: 'Services', url: '/swarm/services', icon: DockIcon },
- { title: 'Nodes', url: '/swarm/nodes', icon: UsersIcon },
- { title: 'Tasks', url: '/swarm/tasks', icon: JobsIcon },
- { title: 'Stacks', url: '/swarm/stacks', icon: LayersIcon },
- { title: 'Cluster', url: '/swarm/cluster', icon: SettingsIcon },
- { title: 'Configs', url: '/swarm/configs', icon: TemplateIcon },
- { title: 'Secrets', url: '/swarm/secrets', icon: LockIcon }
+ { 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' }
],
settingsItems: [
{
title: m.events_title(),
url: '/events',
icon: EventsIcon,
- shortcut: ['mod', '9']
+ shortcut: ['mod', '9'],
+ scope: 'global',
+ requiredPermission: 'events:read'
},
{
title: m.settings_title(),
url: '/settings',
icon: SettingsIcon,
shortcut: ['mod', '0'],
+ scope: 'global',
+ requiredPermission: 'settings:read',
items: [
- { title: m.api_key_page_title(), url: '/settings/api-keys', icon: ApiKeyIcon, shortcut: ['mod', 'shift', '1'] },
- { title: m.appearance_title(), url: '/settings/appearance', icon: AppearanceIcon, shortcut: ['mod', 'shift', '2'] },
- { title: m.webhook_page_title(), url: '/settings/webhooks', icon: GlobeIcon },
+ {
+ title: m.api_key_page_title(),
+ url: '/settings/api-keys',
+ icon: ApiKeyIcon,
+ shortcut: ['mod', 'shift', '1'],
+ scope: 'global',
+ requiredPermission: 'apikeys:list'
+ },
+ {
+ title: m.appearance_title(),
+ url: '/settings/appearance',
+ icon: AppearanceIcon,
+ shortcut: ['mod', 'shift', '2'],
+ scope: 'global',
+ requiredPermission: 'settings:read'
+ },
+ {
+ title: m.webhook_page_title(),
+ url: '/settings/webhooks',
+ icon: GlobeIcon,
+ scope: 'env',
+ requiredPermission: 'webhooks:list'
+ },
{
title: m.authentication_title(),
url: '/settings/authentication',
icon: LockIcon,
- shortcut: ['mod', 'shift', '3']
+ shortcut: ['mod', 'shift', '3'],
+ scope: 'global',
+ requiredPermission: 'settings:read'
},
{
title: m.notifications_title(),
url: '/settings/notifications',
icon: NotificationsIcon,
- shortcut: ['mod', 'shift', '4']
+ shortcut: ['mod', 'shift', '4'],
+ scope: 'env',
+ requiredPermission: 'notifications:manage'
},
- { title: m.builds(), url: '/settings/builds', icon: HammerIcon, shortcut: ['mod', 'shift', '6'] },
- { title: m.timeouts_settings(), url: '/settings/timeouts', icon: JobsIcon, shortcut: ['mod', 'shift', '7'] },
- { title: m.users_title(), url: '/settings/users', icon: UsersIcon, shortcut: ['mod', 'shift', '8'] }
+ {
+ title: m.builds(),
+ url: '/settings/builds',
+ icon: HammerIcon,
+ shortcut: ['mod', 'shift', '6'],
+ scope: 'global',
+ requiredPermission: 'settings:read'
+ },
+ {
+ title: m.timeouts_settings(),
+ url: '/settings/timeouts',
+ icon: JobsIcon,
+ shortcut: ['mod', 'shift', '7'],
+ scope: 'global',
+ requiredPermission: 'settings:read'
+ },
+ {
+ title: m.users_title(),
+ url: '/settings/users',
+ icon: UsersIcon,
+ shortcut: ['mod', 'shift', '8'],
+ scope: 'global',
+ requiredPermission: ['users:read', 'users:list']
+ },
+ {
+ title: m.roles_title(),
+ url: '/settings/roles',
+ icon: ShieldAlertIcon,
+ scope: 'global',
+ requiredPermission: ['roles:read', 'roles:list']
+ }
]
}
]
};
+// Keep the settings sub-navigation alphabetical regardless of the order
+// entries are declared in the literal above. Sidebar, mobile nav, and the
+// settings landing page all read from navigationItems.settingsItems, so a
+// single sort here propagates everywhere.
+{
+ const settingsParent = navigationItems.settingsItems.find((item) => item.url === '/settings');
+ if (settingsParent?.items) {
+ settingsParent.items.sort((a, b) => a.title.localeCompare(b.title, undefined, { sensitivity: 'base' }));
+ }
+}
+
+// ---------- Permission-based filtering ----------
+
+/**
+ * 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.
+ *
+ * @param items navigation items to filter
+ * @param user the current user (or null when unauthenticated)
+ * @param currentEnvId the currently-selected env, for env-scoped checks
+ */
+export function filterByPermissions(
+ items: NavigationItem[] | undefined,
+ user: User | null,
+ currentEnvId: string | undefined
+): NavigationItem[] {
+ if (!items) return [];
+ if (!user) return [];
+ const out: NavigationItem[] = [];
+ for (const item of items) {
+ if (!canSeeItem(item, user, currentEnvId)) continue;
+ if (item.items && item.items.length > 0) {
+ const filteredChildren = filterByPermissions(item.items, user, currentEnvId);
+ // 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.
+ if (filteredChildren.length === 0 && item.items.length > 0) continue;
+ out.push({ ...item, items: filteredChildren });
+ } else {
+ out.push(item);
+ }
+ }
+ 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;
+}
+
export function getSettingsSubpageUrlsInNavOrder(): string[] {
const entry = navigationItems.settingsItems.find((item) => item.url === '/settings');
return entry?.items?.map((item) => item.url) ?? [];
@@ -143,6 +371,49 @@ 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: '/swarm', perms: ['swarm:read'], scope: 'env' });
+ routeAccessRulesForItems(navigationItems.swarmItems, out);
+ routeAccessRulesForItems(navigationItems.settingsItems, out);
+ return out;
+}
+
+export function getRouteFallbackRules(): RouteAccessRule[] {
+ return getRouteAccessRules().filter((rule) => {
+ return (
+ rule.prefix === '/dashboard' ||
+ rule.prefix === '/containers' ||
+ rule.prefix === '/projects' ||
+ 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]!,
diff --git a/frontend/src/lib/services/oidc-mapping-service.ts b/frontend/src/lib/services/oidc-mapping-service.ts
new file mode 100644
index 000000000..74c72184e
--- /dev/null
+++ b/frontend/src/lib/services/oidc-mapping-service.ts
@@ -0,0 +1,22 @@
+import BaseAPIService from './api-service';
+import type { OidcRoleMapping, CreateOidcRoleMapping, UpdateOidcRoleMapping } from '$lib/types/role.type';
+
+export default class OidcMappingAPIService extends BaseAPIService {
+ async list(): Promise<OidcRoleMapping[]> {
+ return this.handleResponse(this.api.get('/oidc/role-mappings')) as Promise<OidcRoleMapping[]>;
+ }
+
+ async create(mapping: CreateOidcRoleMapping): Promise<OidcRoleMapping> {
+ return this.handleResponse(this.api.post('/oidc/role-mappings', mapping)) as Promise<OidcRoleMapping>;
+ }
+
+ async update(id: string, mapping: UpdateOidcRoleMapping): Promise<OidcRoleMapping> {
+ return this.handleResponse(this.api.put(`/oidc/role-mappings/${id}`, mapping)) as Promise<OidcRoleMapping>;
+ }
+
+ async delete(id: string): Promise<void> {
+ return this.handleResponse(this.api.delete(`/oidc/role-mappings/${id}`)) as Promise<void>;
+ }
+}
+
+export const oidcMappingService = new OidcMappingAPIService();
diff --git a/frontend/src/lib/services/role-service.ts b/frontend/src/lib/services/role-service.ts
new file mode 100644
index 000000000..57dcf49f0
--- /dev/null
+++ b/frontend/src/lib/services/role-service.ts
@@ -0,0 +1,51 @@
+import BaseAPIService from './api-service';
+import type { Role, CreateRole, UpdateRole, RoleAssignment, SetUserAssignments, PermissionsManifest } from '$lib/types/role.type';
+import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import { transformPaginationParams } from '$lib/utils/params.util';
+
+export default class RoleAPIService extends BaseAPIService {
+ async getRoles(options?: SearchPaginationSortRequest): Promise<Paginated<Role>> {
+ const params = transformPaginationParams(options);
+ const res = await this.api.get('/roles', { params });
+ return res.data;
+ }
+
+ async getAll(): Promise<Role[]> {
+ // Unpaginated convenience for selects. Backend caps at a generous
+ // limit (1000) which is well above any realistic role count.
+ const res = await this.api.get('/roles', {
+ params: { limit: 1000, sort: 'name', order: 'asc' }
+ });
+ return res.data.data ?? [];
+ }
+
+ async get(id: string): Promise<Role> {
+ return this.handleResponse(this.api.get(`/roles/${id}`)) as Promise<Role>;
+ }
+
+ async create(role: CreateRole): Promise<Role> {
+ return this.handleResponse(this.api.post('/roles', role)) as Promise<Role>;
+ }
+
+ async update(id: string, role: UpdateRole): Promise<Role> {
+ return this.handleResponse(this.api.put(`/roles/${id}`, role)) as Promise<Role>;
+ }
+
+ async delete(id: string): Promise<void> {
+ return this.handleResponse(this.api.delete(`/roles/${id}`)) as Promise<void>;
+ }
+
+ async getPermissionsManifest(): Promise<PermissionsManifest> {
+ return this.handleResponse(this.api.get('/roles/available-permissions')) as Promise<PermissionsManifest>;
+ }
+
+ async getUserAssignments(userId: string): Promise<RoleAssignment[]> {
+ return this.handleResponse(this.api.get(`/users/${userId}/role-assignments`)) as Promise<RoleAssignment[]>;
+ }
+
+ async setUserAssignments(userId: string, payload: SetUserAssignments): Promise<RoleAssignment[]> {
+ return this.handleResponse(this.api.put(`/users/${userId}/role-assignments`, payload)) as Promise<RoleAssignment[]>;
+ }
+}
+
+export const roleService = new RoleAPIService();
diff --git a/frontend/src/lib/stores/user-store.ts b/frontend/src/lib/stores/user-store.ts
index e8ddf208e..27ee98894 100644
--- a/frontend/src/lib/stores/user-store.ts
+++ b/frontend/src/lib/stores/user-store.ts
@@ -1,4 +1,5 @@
import type { User } from '$lib/types/user.type';
+import { GLOBAL_SCOPE, SUDO_PERMISSION, BUILT_IN_ROLE_ADMIN } from '$lib/types/role.type';
import { writable, get } from 'svelte/store';
import { setLocale } from '$lib/utils/locale.util';
@@ -15,14 +16,56 @@ const clearUser = () => {
userStore.set(null);
};
-const isAdmin = () => {
+/**
+ * Build the effective permission Set for the given environment. Includes
+ * global permissions plus permissions scoped to `envId`.
+ *
+ * Pass `undefined` for `envId` to get only the global set (use this for
+ * checking org-level permissions, or as a fallback before an env is selected).
+ */
+const permissions = (envId?: string): Set<string> => {
const user = get(userStore);
- return !!user?.roles?.includes('admin');
+ if (!user?.permissionsByEnv) return new Set();
+ 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;
+};
+
+/** Returns true if the caller may perform `perm`. Sudo callers (`*` in global) always return true. */
+const hasPermission = (perm: string, envId?: string): boolean => {
+ const set = permissions(envId);
+ if (set.has(SUDO_PERMISSION)) return true;
+ return set.has(perm);
+};
+
+/** Returns true if the caller has ANY of the supplied permissions. */
+const hasAnyPermission = (perms: string[], envId?: string): boolean => {
+ if (perms.length === 0) return true;
+ const set = permissions(envId);
+ if (set.has(SUDO_PERMISSION)) return true;
+ return perms.some((p) => set.has(p));
+};
+
+/** Returns true if the caller holds the built-in Admin role globally OR is a sudo caller. */
+const isGlobalAdmin = (): boolean => {
+ const user = get(userStore);
+ if (!user) return false;
+ 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);
};
export default {
subscribe: userStore.subscribe,
setUser,
clearUser,
- isAdmin
+ permissions,
+ hasPermission,
+ hasAnyPermission,
+ isGlobalAdmin
};
diff --git a/frontend/src/lib/types/api-key.type.ts b/frontend/src/lib/types/api-key.type.ts
index 0ebc124b1..c6d730337 100644
--- a/frontend/src/lib/types/api-key.type.ts
+++ b/frontend/src/lib/types/api-key.type.ts
@@ -1,3 +1,5 @@
+import type { ApiKeyPermissionGrant } from '$lib/types/role.type';
+
export type ApiKey = {
id: string;
name: string;
@@ -5,10 +7,12 @@ export type ApiKey = {
keyPrefix: string;
userId: string;
isStatic: boolean;
+ isBootstrap: boolean;
expiresAt?: string;
lastUsedAt?: string;
createdAt: string;
updatedAt?: string;
+ permissions?: ApiKeyPermissionGrant[];
};
export type ApiKeyCreated = ApiKey & {
@@ -19,10 +23,12 @@ export type CreateApiKey = {
name: string;
description?: string;
expiresAt?: string;
+ permissions: ApiKeyPermissionGrant[];
};
export type UpdateApiKey = {
name?: string;
description?: string;
expiresAt?: string;
+ permissions?: ApiKeyPermissionGrant[];
};
diff --git a/frontend/src/lib/types/role.type.ts b/frontend/src/lib/types/role.type.ts
new file mode 100644
index 000000000..4ae7c0f4f
--- /dev/null
+++ b/frontend/src/lib/types/role.type.ts
@@ -0,0 +1,106 @@
+// Public RBAC types — mirrors backend types/role/role.go.
+
+export type RoleScope = 'global' | 'env';
+
+/** A named permission set. Built-in roles are immutable. */
+export type Role = {
+ id: string;
+ name: string;
+ description?: string;
+ permissions: string[];
+ builtIn: boolean;
+ assignedUserCount: number;
+ createdAt: string;
+ updatedAt?: string;
+};
+
+export type CreateRole = {
+ name: string;
+ description?: string;
+ permissions: string[];
+};
+
+export type UpdateRole = {
+ name: string;
+ description?: string;
+ permissions: string[];
+};
+
+/** One row in a user's role assignments. EnvironmentID omitted = global scope. */
+export type RoleAssignment = {
+ id: string;
+ userId: string;
+ roleId: string;
+ environmentId?: string;
+ source: 'manual' | 'oidc';
+ createdAt: string;
+};
+
+/** Compact assignment shape returned on the User payload. */
+export type RoleAssignmentSummary = {
+ roleId: string;
+ environmentId?: string;
+ source: 'manual' | 'oidc';
+};
+
+/** Payload for replacing a user's manual role assignments. */
+export type SetUserAssignments = {
+ assignments: { roleId: string; environmentId?: string }[];
+};
+
+export type OidcMappingSource = 'manual' | 'env';
+
+export type OidcRoleMapping = {
+ id: string;
+ claimValue: string;
+ roleId: string;
+ environmentId?: string;
+ source: OidcMappingSource;
+ createdAt: string;
+ updatedAt?: string;
+};
+
+export type CreateOidcRoleMapping = {
+ claimValue: string;
+ roleId: string;
+ environmentId?: string;
+};
+
+export type UpdateOidcRoleMapping = CreateOidcRoleMapping;
+
+/** The permission manifest from GET /roles/available-permissions. */
+export type PermissionsManifest = {
+ resources: PermissionResource[];
+};
+
+export type PermissionResource = {
+ key: string;
+ label: string;
+ scope: RoleScope;
+ actions: PermissionAction[];
+};
+
+export type PermissionAction = {
+ key: string;
+ permission: string;
+ label: string;
+ description?: string;
+};
+
+/** One permission grant on an API key. EnvironmentID omitted = global grant. */
+export type ApiKeyPermissionGrant = {
+ permission: string;
+ environmentId?: string;
+};
+
+/** Built-in role IDs, stable across migrations. */
+export const BUILT_IN_ROLE_ADMIN = 'role_admin';
+export const BUILT_IN_ROLE_EDITOR = 'role_editor';
+export const BUILT_IN_ROLE_DEPLOYER = 'role_deployer';
+export const BUILT_IN_ROLE_VIEWER = 'role_viewer';
+
+/** Sentinel used in PermissionsByEnv['global'] to mean "every permission". */
+export const SUDO_PERMISSION = '*';
+
+/** Map key used for global-scope permissions in PermissionsByEnv. */
+export const GLOBAL_SCOPE = 'global';
diff --git a/frontend/src/lib/types/settings.type.ts b/frontend/src/lib/types/settings.type.ts
index 5e92367eb..93047690a 100644
--- a/frontend/src/lib/types/settings.type.ts
+++ b/frontend/src/lib/types/settings.type.ts
@@ -72,8 +72,7 @@ export type Settings = {
oidcClientSecret?: string;
oidcIssuerUrl: string;
oidcScopes: string;
- oidcAdminClaim: string;
- oidcAdminValue: string;
+ oidcGroupsClaim: string;
oidcSkipTlsVerify: boolean;
oidcAutoRedirectToProvider: boolean;
oidcMergeAccounts: boolean;
diff --git a/frontend/src/lib/types/user.type.ts b/frontend/src/lib/types/user.type.ts
index 5d75bf314..45a54507a 100644
--- a/frontend/src/lib/types/user.type.ts
+++ b/frontend/src/lib/types/user.type.ts
@@ -1,4 +1,5 @@
import type { Locale } from '$lib/paraglide/runtime';
+import type { RoleAssignmentSummary } from '$lib/types/role.type';
export type User = {
id: string;
@@ -6,7 +7,15 @@ export type User = {
passwordHash?: string;
displayName?: string;
email?: string;
- roles: string[];
+ /** Role assignments held by this user. */
+ roleAssignments: RoleAssignmentSummary[];
+ /**
+ * Server-resolved effective permissions, keyed by environment ID. The
+ * 'global' key holds permissions that apply across every environment AND
+ * to org-level endpoints. The value `['*']` under 'global' is a sentinel
+ * meaning "every permission" (sudo callers).
+ */
+ permissionsByEnv: Record<string, string[]>;
canDelete?: boolean;
createdAt: string;
lastLogin?: string;
@@ -18,8 +27,15 @@ export type User = {
export type CreateUser = Omit<
User,
- 'id' | 'createdAt' | 'updatedAt' | 'lastLogin' | 'oidcSubjectId' | 'passwordHash' | 'requiresPasswordChange' | 'roles'
+ | 'id'
+ | 'createdAt'
+ | 'updatedAt'
+ | 'lastLogin'
+ | 'oidcSubjectId'
+ | 'passwordHash'
+ | 'requiresPasswordChange'
+ | 'roleAssignments'
+ | 'permissionsByEnv'
> & {
password: string;
- roles?: string[];
};
diff --git a/frontend/src/lib/utils/permissions.util.ts b/frontend/src/lib/utils/permissions.util.ts
new file mode 100644
index 000000000..c75522069
--- /dev/null
+++ b/frontend/src/lib/utils/permissions.util.ts
@@ -0,0 +1,63 @@
+import userStore from '$lib/stores/user-store';
+import { environmentStore } from '$lib/stores/environment.store.svelte';
+import { GLOBAL_SCOPE } from '$lib/types/role.type';
+import { get } from 'svelte/store';
+import type { User } from '$lib/types/user.type';
+
+/**
+ * Resolve the env ID to use for an RBAC check. When the caller doesn't pass
+ * one, fall back to the currently-selected environment from the store.
+ * Returns `undefined` when no env is selected — callers should treat that
+ * as "global-only check" (env-scoped permissions will deny).
+ */
+function resolveEnvId(envId?: string): string | undefined {
+ if (envId) return envId;
+ const selected = environmentStore.selected;
+ if (!selected?.id) return undefined;
+ return selected.id;
+}
+
+/**
+ * Check whether the current user holds `perm` on the given environment.
+ *
+ * Reactive callers (inside `.svelte` files) should wrap this in `$derived`
+ * along with a read of `environmentStore.selected?.id` so the value re-computes
+ * when the env switches.
+ */
+export function hasPermission(perm: string, envId?: string): boolean {
+ return userStore.hasPermission(perm, resolveEnvId(envId));
+}
+
+/** Returns true if the user has ANY of the supplied permissions on `envId`. */
+export function hasAnyPermission(perms: string[], envId?: string): boolean {
+ return userStore.hasAnyPermission(perms, resolveEnvId(envId));
+}
+
+/** Returns the full effective permission set for the given env (global ∪ env). */
+export function permissions(envId?: string): Set<string> {
+ return userStore.permissions(resolveEnvId(envId));
+}
+
+/** Returns true if the caller is a global admin (or sudo). */
+export function isGlobalAdmin(): boolean {
+ return userStore.isGlobalAdmin();
+}
+
+/**
+ * Returns true if the user holds AT LEAST one permission on any environment
+ * (or globally). Useful for the "no access at all" fallback redirect.
+ */
+export function hasAnyAccess(user: User | null): boolean {
+ if (!user?.permissionsByEnv) return false;
+ for (const perms of Object.values(user.permissionsByEnv)) {
+ if (perms.length > 0) return true;
+ }
+ return false;
+}
+
+// Keep imports tree-shake-friendly: re-export only what callers need.
+export { GLOBAL_SCOPE };
+
+// `get` is imported above to satisfy the (now-removed) hasAnyAccess fallback;
+// kept exported so callers can grab the raw store snapshot if needed.
+export { get };
diff --git a/frontend/src/lib/utils/redirect.util.ts b/frontend/src/lib/utils/redirect.util.ts
index efed3c49b..edd6fdfed 100644
--- a/frontend/src/lib/utils/redirect.util.ts
+++ b/frontend/src/lib/utils/redirect.util.ts
@@ -1,4 +1,6 @@
import type { User } from '$lib/types/user.type';
+import { GLOBAL_SCOPE, SUDO_PERMISSION, BUILT_IN_ROLE_ADMIN } from '$lib/types/role.type';
+import { getRouteAccessRules, getRouteFallbackRules, type RouteAccessRule } from '$lib/config/navigation-config';
const PROTECTED_PREFIXES = [
'/dashboard',
@@ -10,22 +12,97 @@ const PROTECTED_PREFIXES = [
'/images',
'/volumes',
'/networks',
- '/settings'
+ '/ports',
+ '/settings',
+ '/swarm',
+ '/updates'
];
const UNAUTHENTICATED_ONLY_PREFIXES = ['/login', '/oidc/login', '/oidc/callback', '/auth/oidc/callback', '/img', '/favicon.ico'];
-const ADMIN_ONLY_PREFIXES = ['/settings', '/events', '/customize/registries', '/customize/variables'];
+function isGlobalAdmin(user: User): boolean {
+ 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);
+}
/**
- * Checks if a path matches a prefix exactly or as a parent directory
+ * Exported global-admin check for use in `+page.ts` load functions, where the
+ * user is available via `await parent()` but the store-backed helper in
+ * `permissions.util.ts` is not appropriate (load runs before stores hydrate).
*/
+export function userIsGlobalAdmin(user: User | null | undefined): boolean {
+ return !!user && isGlobalAdmin(user);
+}
+
+/**
+ * True for routes reserved for global admins. Role creation/editing and OIDC
+ * mapping management are intentionally not delegatable to non-admin users —
+ * the matching backend routes are gated by RequireGlobalAdmin. Note that the
+ * bare `/settings/roles` list is still reachable for readers; only the
+ * `/new` and `/<id>` subroutes (the editor) are admin-only.
+ */
+function isAdminOnlyRoute(path: string): boolean {
+ return path === '/settings/roles/new' || /^\/settings\/roles\/[^/]+/.test(path);
+}
+
+/** Checks if a path matches a prefix exactly or as a parent directory. */
const matchesAny = (path: string, prefixes: string[]) =>
prefixes.some((prefix) => path === prefix || path.startsWith(`${prefix}/`));
-export function getAuthRedirectPath(path: string, user: User | null) {
+/** Returns the permission set the user effectively holds at `envId` (global ∪ env). */
+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;
+}
+
+/** Returns true if the user can satisfy any of `perms` at the given env scope. */
+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));
+}
+
+/** Returns true if the user holds any permission anywhere. */
+function hasAnyAccess(user: User): boolean {
+ if (!user.permissionsByEnv) return false;
+ for (const perms of Object.values(user.permissionsByEnv)) {
+ if (perms.length > 0) return true;
+ }
+ return false;
+}
+
+/**
+ * Pick a fallback route the user CAN reach. Walks the gated routes in a
+ * sensible priority order (dashboard first, then resources, then settings)
+ * and returns the first one the user satisfies. Returns `/no-access` if
+ * nothing matches — that page is always reachable.
+ */
+function pickFallbackRoute(user: User, envId?: string): string {
+ for (const rule of getRouteFallbackRules()) {
+ if (userCanReach(user, rule.perms, rule.scope, envId)) {
+ return rule.prefix;
+ }
+ }
+ return '/no-access';
+}
+
+/**
+ * getAuthRedirectPath decides where to send the caller based on the current
+ * path, authentication state, and effective permissions. Returns null when
+ * no redirect is needed.
+ *
+ * @param envId the currently-selected environment ID; used for env-scoped
+ * permission checks. Pass undefined if no env is selected.
+ */
+export function getAuthRedirectPath(path: string, user: User | null, envId?: string): string | null {
const isSignedIn = !!user;
- const isAdmin = user?.roles.includes('admin');
// 1. Handle root path
if (path === '/') {
@@ -42,9 +119,33 @@ export function getAuthRedirectPath(path: string, user: User | null) {
return '/dashboard';
}
- // 4. Redirect non-admins away from restricted management areas
- if (isSignedIn && !isAdmin && matchesAny(path, ADMIN_ONLY_PREFIXES)) {
- return '/dashboard';
+ if (!isSignedIn || !user) return null;
+
+ // 4. Users with zero permissions land on /no-access (unless already there).
+ if (path !== '/no-access' && !hasAnyAccess(user)) {
+ return '/no-access';
+ }
+
+ // 5. Admin-only routes (role editor) bounce non-admins back to the roles
+ // list — they can still read role definitions, just not edit them.
+ if (isAdminOnlyRoute(path) && !isGlobalAdmin(user)) {
+ return '/settings/roles';
+ }
+
+ // 6. Per-route permission gating. Walk the most-specific prefix first.
+ 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)) {
+ // Don't fall back to a route the user also can't reach — that
+ // produces an effective loop where every redirect target bounces
+ // to the same place. Pick the first reachable route in priority
+ // order, or /no-access if nothing fits.
+ const fallback = pickFallbackRoute(user, envId);
+ return fallback === path ? '/no-access' : fallback;
+ }
+ break;
+ }
}
return null;
diff --git a/frontend/src/lib/utils/settings.util.ts b/frontend/src/lib/utils/settings.util.ts
index e5aec036f..ac975f81b 100644
--- a/frontend/src/lib/utils/settings.util.ts
+++ b/frontend/src/lib/utils/settings.util.ts
@@ -31,8 +31,7 @@ const LOCAL_SETTING_KEYS = new Set([
'oidcClientSecret',
'oidcIssuerUrl',
'oidcScopes',
- 'oidcAdminClaim',
- 'oidcAdminValue',
+ 'oidcGroupsClaim',
'oidcProviderName',
'oidcProviderLogoUrl',
'edgeMTLSManagerCAAvailable'
diff --git a/frontend/src/routes/(app)/+layout.svelte b/frontend/src/routes/(app)/+layout.svelte
index 41e73f360..adb3a6fc2 100644
--- a/frontend/src/routes/(app)/+layout.svelte
+++ b/frontend/src/routes/(app)/+layout.svelte
@@ -10,7 +10,7 @@
import { getEffectiveNavigationSettings, navigationSettingsOverridesStore } from '$lib/utils/navigation.utils';
import { browser } from '$app/environment';
import { environmentStore } from '$lib/stores/environment.store.svelte';
- import { navigationItems, getManagementItems, type NavigationItem } from '$lib/config/navigation-config';
+ import { navigationItems, getManagementItems, filterByPermissions, type NavigationItem } from '$lib/config/navigation-config';
import { isEditableTarget, matchesShortcutEvent } from '$lib/utils/keyboard-shortcut.utils';
import { cn } from '$lib/utils';
let { data, children }: LayoutProps = $props();
@@ -29,17 +29,16 @@
return getEffectiveNavigationSettings();
});
const navigationMode = $derived(navigationSettings.mode);
- const isAdmin = $derived(!!user?.roles?.includes('admin'));
const currentEnvId = $derived(environmentStore.selected?.id || '0');
const managementItems = $derived(getManagementItems(currentEnvId));
- const settingsShortcutItems = $derived.by(() => (isAdmin ? (navigationItems.settingsItems ?? []) : []));
+ const settingsShortcutItems = $derived(filterByPermissions(navigationItems.settingsItems, user ?? null, currentEnvId));
const shortcutItems = $derived.by(() => {
const items: NavigationItem[] = [...managementItems, ...navigationItems.resourceItems, ...settingsShortcutItems];
return flattenNavigationItems(items).filter((item) => item.shortcut?.length);
});
$effect(() => {
- const redirectPath = getAuthRedirectPath(page.url.pathname, user);
+ const redirectPath = getAuthRedirectPath(page.url.pathname, user, currentEnvId);
if (redirectPath) {
goto(redirectPath);
}
diff --git a/frontend/src/routes/(app)/containers/+page.svelte b/frontend/src/routes/(app)/containers/+page.svelte
index 3f2caace2..df54f360c 100644
--- a/frontend/src/routes/(app)/containers/+page.svelte
+++ b/frontend/src/routes/(app)/containers/+page.svelte
@@ -8,8 +8,7 @@
import { untrack } from 'svelte';
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index';
import { environmentStore } from '$lib/stores/environment.store.svelte';
- import userStore from '$lib/stores/user-store';
- import { fromStore } from 'svelte/store';
+ import { hasPermission } from '$lib/utils/permissions.util';
import type { ContainerCreateRequest, ContainerStatusCounts } from '$lib/types/container.type';
import { createMutation } from '@tanstack/svelte-query';
import { BoxIcon } from '$lib/icons';
@@ -105,8 +104,7 @@
const containerStatusCounts = $derived(containers.counts ?? countsFallback);
- const storeUser = fromStore(userStore);
- const isAdmin = $derived(!!storeUser.current?.roles?.includes('admin'));
+ const canAutoUpdate = $derived(hasPermission('containers:autoupdate', envId));
const actionButtons: ActionButton[] = $derived(
[
@@ -118,7 +116,7 @@
loading: createContainerMutation.isPending,
disabled: createContainerMutation.isPending
},
- isAdmin
+ canAutoUpdate
? {
id: 'check-updates',
action: 'update',
diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
index 9d732ca51..fb89fc1e7 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
@@ -47,6 +47,7 @@
import type { IncludeFile } from '$lib/types/project.type';
import { projectService } from '$lib/services/project-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
let { data } = $props();
let container = $derived(data?.container as ContainerDetailsDto);
let stats = $state(null as ContainerStatsType | null);
@@ -140,8 +141,11 @@
);
const showNetworkTab = $derived(hasNetworks || hasPorts);
const hasMounts = $derived(!!(container?.mounts && container.mounts.length > 0));
+ const currentEnvId = $derived(environmentStore.selected?.id);
+ const canViewLogs = $derived(hasPermission('containers:logs', currentEnvId));
+ const canExecShell = $derived(hasPermission('containers:exec', currentEnvId));
const showStats = $derived(!!container?.state?.running);
- const showShell = $derived(!!container?.state?.running);
+ const showShell = $derived(!!container?.state?.running && canExecShell);
const hasHealthcheck = $derived(
!!(container?.config?.healthcheck?.test && container.config.healthcheck.test.length > 0) || !!container?.state?.health
);
@@ -213,7 +217,7 @@
const tabItems = $derived<TabItem[]>([
{ value: 'overview', label: m.common_overview(), icon: ContainersIcon },
...(showStats ? [{ value: 'stats', label: m.containers_nav_metrics(), icon: StatsIcon }] : []),
- { value: 'logs', label: m.containers_nav_logs(), icon: FileTextIcon },
+ ...(canViewLogs ? [{ value: 'logs', label: m.containers_nav_logs(), icon: FileTextIcon }] : []),
...(showShell ? [{ value: 'shell', label: m.common_shell(), icon: TerminalIcon }] : []),
...(hasHealthcheck ? [{ value: 'healthcheck', label: m.containers_nav_healthcheck(), icon: HealthIcon }] : []),
...(showConfiguration ? [{ value: 'config', label: m.common_configuration(), icon: SettingsIcon }] : []),
diff --git a/frontend/src/routes/(app)/containers/container-table.svelte b/frontend/src/routes/(app)/containers/container-table.svelte
index 271c0c59c..aa4584468 100644
--- a/frontend/src/routes/(app)/containers/container-table.svelte
+++ b/frontend/src/routes/(app)/containers/container-table.svelte
@@ -26,8 +26,7 @@
import ContainerStatsSync from './components/container-stats-sync.svelte';
import ContainerStatsCell from './components/container-stats-cell.svelte';
import { environmentStore } from '$lib/stores/environment.store.svelte';
- import userStore from '$lib/stores/user-store';
- import { fromStore } from 'svelte/store';
+ import { hasPermission } from '$lib/utils/permissions.util';
import IconImage from '$lib/components/icon-image.svelte';
import { getArcaneIconUrlFromLabels } from '$lib/utils/arcane-labels';
import { createContainerActions } from './container-table.actions';
@@ -149,9 +148,6 @@
Object.values(actionStatus).some((status) => status !== '') || Object.values(isBulkLoading).some((loading) => loading)
);
- const storeUser = fromStore(userStore);
- const isAdmin = $derived(!!storeUser.current?.roles?.includes('admin'));
-
let mobileFieldVisibility = $state<Record<string, boolean>>({});
let customSettings = $state<Record<string, unknown>>({});
let showInternal = $derived.by(() => {
@@ -184,6 +180,7 @@
});
const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const canUpdateContainers = $derived(hasPermission('containers:autoupdate', currentEnvId));
onMount(() => {
collapsedGroupsState = new PersistedState<Record<string, boolean>>('container-groups-collapsed', {});
@@ -426,7 +423,7 @@
icon={StopIcon}
/>
{/if}
- {#if !status && item.updateInfo?.hasUpdate && isAdmin}
+ {#if !status && item.updateInfo?.hasUpdate && canUpdateContainers}
<ArcaneButton
action="base"
tone="ghost"
@@ -449,7 +446,7 @@
imageId={item.imageId}
repo={imageRef.repo}
tag={imageRef.tag}
- onUpdateContainer={isAdmin ? () => handleUpdateContainer(item) : undefined}
+ onUpdateContainer={canUpdateContainers ? () => handleUpdateContainer(item) : undefined}
debugHasUpdate={false}
/>
{/snippet}
@@ -592,7 +589,7 @@
imageId={item.imageId}
repo={imageRef.repo}
tag={imageRef.tag}
- onUpdateContainer={isAdmin ? () => handleUpdateContainer(item) : undefined}
+ onUpdateContainer={canUpdateContainers ? () => handleUpdateContainer(item) : undefined}
debugHasUpdate={false}
/>
</div>
@@ -624,7 +621,7 @@
<DropdownMenu.Separator />
- {#if item.updateInfo?.hasUpdate && isAdmin}
+ {#if item.updateInfo?.hasUpdate && canUpdateContainers}
<DropdownMenu.Item onclick={() => handleUpdateContainer(item)} disabled={status === 'updating' || isAnyLoading}>
{#if status === 'updating'}
<Spinner class="size-4" />
diff --git a/frontend/src/routes/(app)/customize/git-repositories/+page.svelte b/frontend/src/routes/(app)/customize/git-repositories/+page.svelte
index 83ff2df12..d804441f2 100644
--- a/frontend/src/routes/(app)/customize/git-repositories/+page.svelte
+++ b/frontend/src/routes/(app)/customize/git-repositories/+page.svelte
@@ -9,6 +9,7 @@
import { gitRepositoryService } from '$lib/services/git-repository-service';
import { untrack } from 'svelte';
import { ResourcePageLayout, type ActionButton } from '$lib/layouts/index.js';
+ import { hasPermission } from '$lib/utils/permissions.util';
let { data } = $props();
@@ -74,22 +75,28 @@
}
}
- const actionButtons: ActionButton[] = [
- {
- id: 'create',
- action: 'create',
- label: m.common_add_button({ resource: m.resource_repository_cap() }),
- onclick: openCreateRepositoryDialog
- },
- {
+ const canCreateRepository = $derived(hasPermission('git-repositories:create'));
+
+ const actionButtons: ActionButton[] = $derived.by(() => {
+ const buttons: ActionButton[] = [];
+ if (canCreateRepository) {
+ buttons.push({
+ id: 'create',
+ action: 'create',
+ label: m.common_add_button({ resource: m.resource_repository_cap() }),
+ onclick: openCreateRepositoryDialog
+ });
+ }
+ buttons.push({
id: 'refresh',
action: 'restart',
label: m.common_refresh(),
onclick: refreshRepositories,
loading: isLoading.refresh,
disabled: isLoading.refresh
- }
- ];
+ });
+ return buttons;
+ });
</script>
<ResourcePageLayout title={m.git_repositories_title()} subtitle={m.git_repositories_subtitle()} {actionButtons}>
diff --git a/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte b/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte
index c12151a6c..963df1418 100644
--- a/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte
+++ b/frontend/src/routes/(app)/customize/git-repositories/repository-table.svelte
@@ -23,6 +23,8 @@
ExternalLinkIcon as LinkIcon,
EllipsisIcon
} from '$lib/icons';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
type FieldVisibility = Record<string, boolean>;
@@ -43,6 +45,8 @@
testing: false
});
+ const canDeleteRepository = $derived(hasPermission('git-repositories:delete'));
+
const bulkActions = $derived.by<BulkAction[]>(() => [
{
id: 'remove',
@@ -50,7 +54,7 @@
action: 'remove',
onClick: handleDeleteSelected,
loading: isLoading.removing,
- disabled: isLoading.removing,
+ disabled: !canDeleteRepository || isLoading.removing,
icon: Trash2Icon
}
]);
@@ -259,26 +263,32 @@
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Group>
- <DropdownMenu.Item onclick={() => handleTest(item.id, item.name)} disabled={isLoading.testing}>
- <TestTubeIcon class="size-4" />
- {m.git_repository_test_connection()}
- </DropdownMenu.Item>
+ <IfPermitted perm="git-repositories:test">
+ <DropdownMenu.Item onclick={() => handleTest(item.id, item.name)} disabled={isLoading.testing}>
+ <TestTubeIcon class="size-4" />
+ {m.git_repository_test_connection()}
+ </DropdownMenu.Item>
+ </IfPermitted>
- <DropdownMenu.Item onclick={() => onEditRepository(item)}>
- <PencilIcon class="size-4" />
- {m.common_edit()}
- </DropdownMenu.Item>
+ <IfPermitted perm="git-repositories:update">
+ <DropdownMenu.Item onclick={() => onEditRepository(item)}>
+ <PencilIcon class="size-4" />
+ {m.common_edit()}
+ </DropdownMenu.Item>
+ </IfPermitted>
- <DropdownMenu.Separator />
+ {#if canDeleteRepository}
+ <DropdownMenu.Separator />
- <DropdownMenu.Item
- variant="destructive"
- onclick={() => handleDeleteOne(item.id, item.name)}
- disabled={isLoading.removing}
- >
- <Trash2Icon class="size-4" />
- {m.common_remove()}
- </DropdownMenu.Item>
+ <DropdownMenu.Item
+ variant="destructive"
+ onclick={() => handleDeleteOne(item.id, item.name)}
+ disabled={isLoading.removing}
+ >
+ <Trash2Icon class="size-4" />
+ {m.common_remove()}
+ </DropdownMenu.Item>
+ {/if}
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/(app)/customize/registries/+page.svelte b/frontend/src/routes/(app)/customize/registries/+page.svelte
index dfe31f65d..a7fd55f50 100644
--- a/frontend/src/routes/(app)/customize/registries/+page.svelte
+++ b/frontend/src/routes/(app)/customize/registries/+page.svelte
@@ -13,6 +13,7 @@
import { untrack } from 'svelte';
import { ResourcePageLayout, type ActionButton } from '$lib/layouts/index.js';
import { createQuery } from '@tanstack/svelte-query';
+ import { hasPermission } from '$lib/utils/permissions.util';
let { data } = $props();
@@ -89,28 +90,35 @@
}
}
- const actionButtons: ActionButton[] = [
- {
- id: 'info',
- action: 'inspect',
- label: m.registries_info_title(),
- onclick: () => (isInfoDialogOpen = true)
- },
- {
- id: 'create',
- action: 'create',
- label: m.common_add_button({ resource: m.resource_registry_cap() }),
- onclick: openCreateRegistryDialog
- },
- {
+ const canCreateRegistry = $derived(hasPermission('registries:create'));
+
+ const actionButtons: ActionButton[] = $derived.by(() => {
+ const buttons: ActionButton[] = [
+ {
+ id: 'info',
+ action: 'inspect',
+ label: m.registries_info_title(),
+ onclick: () => (isInfoDialogOpen = true)
+ }
+ ];
+ if (canCreateRegistry) {
+ buttons.push({
+ id: 'create',
+ action: 'create',
+ label: m.common_add_button({ resource: m.resource_registry_cap() }),
+ onclick: openCreateRegistryDialog
+ });
+ }
+ buttons.push({
id: 'refresh',
action: 'restart',
label: m.common_refresh(),
onclick: refreshRegistries,
loading: isLoading.refresh,
disabled: isLoading.refresh
- }
- ];
+ });
+ return buttons;
+ });
</script>
<ResourcePageLayout title={m.registries_title()} subtitle={m.registries_subtitle()} {actionButtons}>
diff --git a/frontend/src/routes/(app)/customize/registries/registry-table.svelte b/frontend/src/routes/(app)/customize/registries/registry-table.svelte
index 57f72089a..d4ea388fb 100644
--- a/frontend/src/routes/(app)/customize/registries/registry-table.svelte
+++ b/frontend/src/routes/(app)/customize/registries/registry-table.svelte
@@ -16,6 +16,8 @@
import { m } from '$lib/paraglide/messages';
import { containerRegistryService } from '$lib/services/container-registry-service';
import { RegistryIcon, UserIcon, ExternalLinkIcon, EditIcon, TrashIcon, TestIcon, EllipsisIcon } from '$lib/icons';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
let {
registries = $bindable(),
@@ -34,6 +36,8 @@
let removingId = $state<string | null>(null);
let testingId = $state<string | null>(null);
+ const canDeleteRegistry = $derived(hasPermission('registries:delete'));
+
function maskAccessKeyId(keyId: string | undefined): string {
if (!keyId) return m.common_na();
if (keyId.length <= 4) return keyId;
@@ -199,7 +203,7 @@
action: 'remove',
onClick: handleDeleteSelected,
loading: isLoading.removing,
- disabled: isLoading.removing,
+ disabled: !canDeleteRegistry || isLoading.removing,
icon: TrashIcon
}
]);
@@ -294,34 +298,40 @@
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Group>
- <DropdownMenu.Item onclick={() => handleTest(item.id, item.url)} disabled={testingId === item.id}>
- {#if testingId === item.id}
- <Spinner class="size-4" />
- {:else}
- <TestIcon class="size-4" />
- {/if}
- {m.registries_test_connection()}
- </DropdownMenu.Item>
+ <IfPermitted perm="registries:test">
+ <DropdownMenu.Item onclick={() => handleTest(item.id, item.url)} disabled={testingId === item.id}>
+ {#if testingId === item.id}
+ <Spinner class="size-4" />
+ {:else}
+ <TestIcon class="size-4" />
+ {/if}
+ {m.registries_test_connection()}
+ </DropdownMenu.Item>
+ </IfPermitted>
- <DropdownMenu.Item onclick={() => onEditRegistry(item)}>
- <EditIcon class="size-4" />
- {m.common_edit()}
- </DropdownMenu.Item>
+ <IfPermitted perm="registries:update">
+ <DropdownMenu.Item onclick={() => onEditRegistry(item)}>
+ <EditIcon class="size-4" />
+ {m.common_edit()}
+ </DropdownMenu.Item>
+ </IfPermitted>
- <DropdownMenu.Separator />
+ {#if canDeleteRegistry}
+ <DropdownMenu.Separator />
- <DropdownMenu.Item
- variant="destructive"
- onclick={() => handleDeleteOne(item.id, item.url)}
- disabled={removingId === item.id}
- >
- {#if removingId === item.id}
- <Spinner class="size-4" />
- {:else}
- <TrashIcon class="size-4" />
- {/if}
- {m.common_remove()}
- </DropdownMenu.Item>
+ <DropdownMenu.Item
+ variant="destructive"
+ onclick={() => handleDeleteOne(item.id, item.url)}
+ disabled={removingId === item.id}
+ >
+ {#if removingId === item.id}
+ <Spinner class="size-4" />
+ {:else}
+ <TrashIcon class="size-4" />
+ {/if}
+ {m.common_remove()}
+ </DropdownMenu.Item>
+ {/if}
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/(app)/customize/templates/+page.svelte b/frontend/src/routes/(app)/customize/templates/+page.svelte
index 150e34b71..e7128862e 100644
--- a/frontend/src/routes/(app)/customize/templates/+page.svelte
+++ b/frontend/src/routes/(app)/customize/templates/+page.svelte
@@ -13,6 +13,7 @@
import { untrack } from 'svelte';
import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
import { RegistryIcon, TemplateIcon, FolderOpenIcon } from '$lib/icons';
+ import { hasPermission } from '$lib/utils/permissions.util';
let { data } = $props();
@@ -129,26 +130,35 @@
}
}
- const actionButtons: ActionButton[] = [
- {
- id: 'create',
- action: 'create',
- label: m.templates_create_template(),
- onclick: () => goto('/customize/templates/create')
- },
- {
- id: 'default',
- action: 'edit',
- label: m.templates_edit_default(),
- onclick: () => goto('/customize/templates/default')
- },
- {
+ const canCreateTemplate = $derived(hasPermission('templates:create'));
+ const canUpdateTemplate = $derived(hasPermission('templates:update'));
+
+ const actionButtons: ActionButton[] = $derived.by(() => {
+ const buttons: ActionButton[] = [];
+ if (canCreateTemplate) {
+ buttons.push({
+ id: 'create',
+ action: 'create',
+ label: m.templates_create_template(),
+ onclick: () => goto('/customize/templates/create')
+ });
+ }
+ if (canUpdateTemplate) {
+ buttons.push({
+ id: 'default',
+ action: 'edit',
+ label: m.templates_edit_default(),
+ onclick: () => goto('/customize/templates/default')
+ });
+ }
+ buttons.push({
id: 'refresh',
action: 'restart',
label: m.common_refresh(),
onclick: refreshTemplates
- }
- ];
+ });
+ return buttons;
+ });
const localTemplatesCount = $derived(templates.data?.filter((t) => !t.isRemote).length ?? 0);
const remoteTemplatesCount = $derived(templates.data?.filter((t) => t.isRemote).length ?? 0);
diff --git a/frontend/src/routes/(app)/customize/templates/template-table.svelte b/frontend/src/routes/(app)/customize/templates/template-table.svelte
index 73a00f76f..b4f01859e 100644
--- a/frontend/src/routes/(app)/customize/templates/template-table.svelte
+++ b/frontend/src/routes/(app)/customize/templates/template-table.svelte
@@ -17,6 +17,8 @@
import { templateTypeFilters } from '$lib/components/arcane-table/data';
import { templateService } from '$lib/services/template-service';
import { truncateString } from '$lib/utils/string.utils';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
import { PersistedState } from 'runed';
import { onMount } from 'svelte';
import IconImage from '$lib/components/icon-image.svelte';
@@ -45,6 +47,9 @@
let deletingId = $state<string | null>(null);
let downloadingId = $state<string | null>(null);
+ const canReadTemplate = $derived(hasPermission('templates:read'));
+ const canDeleteTemplate = $derived(hasPermission('templates:delete'));
+
async function handleDeleteTemplate(id: string, name: string) {
openConfirmDialog({
title: m.common_delete_title({ resource: m.resource_template() }),
@@ -283,14 +288,18 @@
{m.common_view_details()}
</DropdownMenu.Item>
- <DropdownMenu.Item onclick={() => goto(`/projects/new?templateId=${item.id}`)}>
- <MoveToFolderIcon class="size-4" />
- {m.compose_create_project()}
- </DropdownMenu.Item>
+ <IfPermitted perm="projects:create">
+ <DropdownMenu.Item onclick={() => goto(`/projects/new?templateId=${item.id}`)}>
+ <MoveToFolderIcon class="size-4" />
+ {m.compose_create_project()}
+ </DropdownMenu.Item>
+ </IfPermitted>
- <DropdownMenu.Separator />
+ {#if (item.isRemote && canReadTemplate) || (!item.isRemote && canDeleteTemplate)}
+ <DropdownMenu.Separator />
+ {/if}
- {#if item.isRemote}
+ {#if item.isRemote && canReadTemplate}
<DropdownMenu.Item onclick={() => handleDownloadTemplate(item.id, item.name)} disabled={downloadingId === item.id}>
{#if downloadingId === item.id}
<Spinner class="size-4" />
@@ -299,7 +308,7 @@
{/if}
{m.templates_download()}
</DropdownMenu.Item>
- {:else}
+ {:else if !item.isRemote && canDeleteTemplate}
<DropdownMenu.Item
variant="destructive"
onclick={() => handleDeleteTemplate(item.id, item.name)}
diff --git a/frontend/src/routes/(app)/customize/variables/+page.svelte b/frontend/src/routes/(app)/customize/variables/+page.svelte
index 9740bd908..b55d0c9ca 100644
--- a/frontend/src/routes/(app)/customize/variables/+page.svelte
+++ b/frontend/src/routes/(app)/customize/variables/+page.svelte
@@ -11,6 +11,7 @@
import { untrack } from 'svelte';
import { m } from '$lib/paraglide/messages';
import { SearchIcon, CloseIcon, AlertIcon, VariableIcon } from '$lib/icons';
+ import { hasPermission } from '$lib/utils/permissions.util';
let { data } = $props();
let envVars = $state<Variable[]>(untrack(() => [...data.variables]));
@@ -104,24 +105,30 @@
}
});
- const actionButtons = $derived<ActionButton[]>([
- {
- id: 'reset',
- action: 'restart',
- label: m.common_reset(),
- onclick: resetForm,
- disabled: !hasChanges || isLoading
- },
- {
- id: 'save',
- action: 'save',
- label: m.common_save(),
- loadingLabel: m.common_saving(),
- loading: isLoading,
- disabled: isLoading || !hasChanges,
- onclick: onSubmit
- }
- ]);
+ const canUpdateVariables = $derived(hasPermission('templates:update'));
+
+ const actionButtons = $derived<ActionButton[]>(
+ canUpdateVariables
+ ? [
+ {
+ id: 'reset',
+ action: 'restart',
+ label: m.common_reset(),
+ onclick: resetForm,
+ disabled: !hasChanges || isLoading
+ },
+ {
+ id: 'save',
+ action: 'save',
+ label: m.common_save(),
+ loadingLabel: m.common_saving(),
+ loading: isLoading,
+ disabled: isLoading || !hasChanges,
+ onclick: onSubmit
+ }
+ ]
+ : []
+ );
</script>
<ResourcePageLayout title={m.variables_title()} subtitle={m.variables_subtitle()} {actionButtons}>
@@ -168,14 +175,16 @@
<SearchIcon class="text-muted-foreground pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2" />
<Input type="text" placeholder={m.common_search()} bind:value={searchQuery} class="h-9 pl-10" />
</div>
- <ArcaneButton
- action="create"
- size="sm"
- onclick={addEnvVar}
- disabled={isLoading}
- customLabel={m.variables_add_button()}
- class="shrink-0"
- />
+ {#if canUpdateVariables}
+ <ArcaneButton
+ action="create"
+ size="sm"
+ onclick={addEnvVar}
+ disabled={isLoading}
+ customLabel={m.variables_add_button()}
+ class="shrink-0"
+ />
+ {/if}
</div>
</div>
</Card.Header>
@@ -234,17 +243,19 @@
/>
<InputGroup.Addon align="inline-end">
<CopyButton text={envVar.value} variant="ghost" tabindex={-1} />
- <InputGroup.Button
- variant="ghost"
- aria-label={m.common_remove()}
- size="icon-xs"
- onclick={() => removeEnvVar(actualIndex)}
- disabled={isLoading}
- class="text-destructive hover:text-destructive"
- title={m.common_remove()}
- >
- <CloseIcon />
- </InputGroup.Button>
+ {#if canUpdateVariables}
+ <InputGroup.Button
+ variant="ghost"
+ aria-label={m.common_remove()}
+ size="icon-xs"
+ onclick={() => removeEnvVar(actualIndex)}
+ disabled={isLoading}
+ class="text-destructive hover:text-destructive"
+ title={m.common_remove()}
+ >
+ <CloseIcon />
+ </InputGroup.Button>
+ {/if}
</InputGroup.Addon>
</InputGroup.Root>
</div>
diff --git a/frontend/src/routes/(app)/dashboard/+page.svelte b/frontend/src/routes/(app)/dashboard/+page.svelte
index 4c4626051..30301239d 100644
--- a/frontend/src/routes/(app)/dashboard/+page.svelte
+++ b/frontend/src/routes/(app)/dashboard/+page.svelte
@@ -450,7 +450,6 @@
<QuickActions
class="w-full justify-start lg:w-auto lg:justify-end"
compact
- user={data.user}
{stoppedContainers}
{runningContainers}
isLoading={{ starting: isLoading.starting, stopping: isLoading.stopping, pruning: isLoading.pruning }}
diff --git a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
index 210368d1b..5d9db3e0b 100644
--- a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
+++ b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
@@ -14,7 +14,7 @@
import { dashboardService } from '$lib/services/dashboard-service';
import { systemService } from '$lib/services/system-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
- import userStore from '$lib/stores/user-store';
+ import { hasAnyPermission, hasPermission } from '$lib/utils/permissions.util';
import type { SystemStats } from '$lib/types/system-stats.type';
import type {
DashboardActionItem,
@@ -31,7 +31,6 @@
import { getEnvironmentStatusVariant, isEnvironmentOnline, resolveEnvironmentStatus } from '$lib/utils/environment-status';
import { createStatsWebSocket, type ReconnectingWebSocket } from '$lib/utils/ws';
import bytes from '$lib/utils/bytes';
- import { fromStore } from 'svelte/store';
import {
ContainersIcon,
CpuIcon,
@@ -75,10 +74,15 @@
let upgradeDialogOpenById = $state<Record<string, boolean>>({});
let upgradeDialogUpgradingById = $state<Record<string, boolean>>({});
- const storeUser = fromStore(userStore);
const availableEnvironments = $derived(environmentStore.available);
const currentEnvironmentId = $derived(environmentStore.selected?.id ?? null);
- const currentUserIsAdmin = $derived(!!storeUser.current?.roles?.includes('admin'));
+
+ function canPruneInEnvironment(envId: string): boolean {
+ return hasAnyPermission(['images:prune', 'volumes:prune', 'networks:prune'], envId);
+ }
+ function canUpgradeEnvironment(): boolean {
+ return hasPermission('environments:update');
+ }
function shouldLoadEnvironment(environment: Environment): boolean {
return environment.enabled && isEnvironmentOnline(environment);
@@ -481,14 +485,17 @@
function canPruneEnvironment(item: DashboardEnvironmentOverview): boolean {
return (
- currentUserIsAdmin && item.environment.enabled && item.snapshotState === 'ready' && isEnvironmentOnline(item.environment)
+ canPruneInEnvironment(item.environment.id) &&
+ item.environment.enabled &&
+ item.snapshotState === 'ready' &&
+ isEnvironmentOnline(item.environment)
);
}
function getEnvironmentActionButtons(item: DashboardEnvironmentOverview, isCurrent: boolean): ActionButton[] {
const buttons: ActionButton[] = [];
- if (currentUserIsAdmin) {
+ if (canPruneInEnvironment(item.environment.id)) {
buttons.push({
id: `${item.environment.id}-prune`,
action: 'prune',
@@ -779,7 +786,7 @@
<DashboardEnvironmentUpgradeAction
{environment}
versionInfo={vInfo}
- isAdmin={currentUserIsAdmin}
+ canUpgrade={canUpgradeEnvironment()}
debug={debugUpgrade}
onRefreshRequested={refreshOverview}
render="trigger"
@@ -800,7 +807,7 @@
<DashboardEnvironmentUpgradeAction
{environment}
versionInfo={vInfo}
- isAdmin={currentUserIsAdmin}
+ canUpgrade={canUpgradeEnvironment()}
debug={debugUpgrade}
onRefreshRequested={refreshOverview}
render="dialog"
diff --git a/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte b/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte
index 614594e73..c4dab14e3 100644
--- a/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte
+++ b/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte
@@ -15,7 +15,7 @@
let {
environment,
versionInfo,
- isAdmin,
+ canUpgrade: canUpgradePermission,
debug = false,
onRefreshRequested,
render = 'both',
@@ -24,7 +24,7 @@
}: {
environment: Environment;
versionInfo: AppVersionInformation;
- isAdmin: boolean;
+ canUpgrade: boolean;
debug?: boolean;
onRefreshRequested?: () => void | Promise<void>;
render?: 'both' | 'trigger' | 'dialog';
@@ -32,7 +32,7 @@
upgrading?: boolean;
} = $props();
- const shouldCheckUpgrade = $derived(!!(versionInfo.updateAvailable && isAdmin && !debug));
+ const shouldCheckUpgrade = $derived(!!(versionInfo.updateAvailable && canUpgradePermission && !debug));
const isLocalEnvironment = $derived(environment.id === '0');
const upgradeAvailabilityQuery = createQuery(() => ({
@@ -45,7 +45,7 @@
staleTime: 0
}));
- const canUpgrade = $derived.by(() => {
+ const upgradeIsAvailable = $derived.by(() => {
if (debug) return true;
const result = upgradeAvailabilityQuery.data;
return !!result?.canUpgrade && !result?.error;
@@ -74,7 +74,9 @@
return '';
});
- const shouldShowUpgrade = $derived((versionInfo.updateAvailable && isAdmin && canUpgrade) || (debug && isAdmin));
+ const shouldShowUpgrade = $derived(
+ (versionInfo.updateAvailable && canUpgradePermission && upgradeIsAvailable) || (debug && canUpgradePermission)
+ );
const upgradeButtonText = $derived.by(() => {
if (upgrading) return m.upgrade_in_progress();
diff --git a/frontend/src/routes/(app)/environments/+page.svelte b/frontend/src/routes/(app)/environments/+page.svelte
index 5f9fa5e76..5b08af9e1 100644
--- a/frontend/src/routes/(app)/environments/+page.svelte
+++ b/frontend/src/routes/(app)/environments/+page.svelte
@@ -11,6 +11,7 @@
import { ResourcePageLayout, type ActionButton } from '$lib/layouts/index.js';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { simpleRefresh } from '$lib/utils/refresh.util';
+ import { hasPermission } from '$lib/utils/permissions.util';
import { DownloadIcon } from '$lib/icons';
let { data } = $props();
@@ -30,7 +31,8 @@
);
}
- const currentUserIsAdmin = $derived(!!data.user?.roles?.includes('admin'));
+ const canCreateEnvironment = $derived(hasPermission('environments:create'));
+ const canDeleteEnvironment = $derived(hasPermission('environments:delete'));
async function handleBulkDelete() {
if (selectedIds.length === 0) return;
@@ -82,7 +84,7 @@
}
const actionButtons: ActionButton[] = $derived([
- ...(selectedIds.length > 0 && currentUserIsAdmin
+ ...(selectedIds.length > 0 && canDeleteEnvironment
? [
{
id: 'remove-selected',
@@ -94,7 +96,7 @@
}
]
: []),
- ...(currentUserIsAdmin
+ ...(canCreateEnvironment
? [
{
id: 'create',
@@ -104,7 +106,7 @@
}
]
: []),
- ...(currentUserIsAdmin && data.settings?.edgeMTLSManagerCAAvailable
+ ...(canCreateEnvironment && data.settings?.edgeMTLSManagerCAAvailable
? [
{
id: 'download-edge-ca',
diff --git a/frontend/src/routes/(app)/environments/environment-table.svelte b/frontend/src/routes/(app)/environments/environment-table.svelte
index 108111460..dbada7260 100644
--- a/frontend/src/routes/(app)/environments/environment-table.svelte
+++ b/frontend/src/routes/(app)/environments/environment-table.svelte
@@ -21,7 +21,7 @@
import UpdateCenterDialog from '$lib/components/dialogs/update-center-dialog.svelte';
import EnvironmentUpgradeMenuItem from './environment-upgrade-menu-item.svelte';
import type { AppVersionInformation } from '$lib/types/application-configuration';
- import userStore from '$lib/stores/user-store';
+ import { hasPermission } from '$lib/utils/permissions.util';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { capitalizeFirstLetter } from '$lib/utils/string.utils';
import { getEnvironmentStatusVariant, isEnvironmentOnline, resolveEnvironmentStatus } from '$lib/utils/environment-status';
@@ -43,12 +43,7 @@
let selectedEnvironmentForUpgrade = $state<Environment | null>(null);
let selectedVersionInfoForUpgrade = $state<AppVersionInformation | null>(null);
- let currentUser = $state<{ roles?: string[] } | null>(null);
- $effect(() => {
- const unsub = userStore.subscribe((u) => (currentUser = u));
- return unsub;
- });
- const isAdmin = $derived(!!currentUser?.roles?.includes('admin'));
+ const canInstallUpdates = $derived(hasPermission('environments:update'));
const environmentTypeFilters: FilterOption[] = [
{ value: 'http', label: m.environments_edge_http_label(), icon: EnvironmentsIcon },
@@ -480,7 +475,7 @@
bind:open={showUpgradeDialog}
onConfirm={handleConfirmUpgrade}
versionInformation={selectedVersionInfoForUpgrade ?? undefined}
- canInstall={isAdmin}
+ canInstall={canInstallUpdates}
environmentName={selectedEnvironmentForUpgrade?.name}
environmentId={selectedEnvironmentForUpgrade?.id}
bind:upgrading={isLoading.upgrading}
diff --git a/frontend/src/routes/(app)/events/+page.svelte b/frontend/src/routes/(app)/events/+page.svelte
index e0ffcda9a..f2c411bf3 100644
--- a/frontend/src/routes/(app)/events/+page.svelte
+++ b/frontend/src/routes/(app)/events/+page.svelte
@@ -10,6 +10,7 @@
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';
import { createMutation, createQuery } from '@tanstack/svelte-query';
import { EventsIcon } from '$lib/icons';
+ import { hasPermission } from '$lib/utils/permissions.util';
let { data } = $props();
@@ -85,8 +86,10 @@
});
}
+ const canManageEvents = $derived(hasPermission('events:read'));
+
const actionButtons: ActionButton[] = $derived([
- ...(selectedIds.length > 0
+ ...(selectedIds.length > 0 && canManageEvents
? [
{
id: 'remove-selected',
diff --git a/frontend/src/routes/(app)/events/event-table.svelte b/frontend/src/routes/(app)/events/event-table.svelte
index c7adf58f4..7ef37bd31 100644
--- a/frontend/src/routes/(app)/events/event-table.svelte
+++ b/frontend/src/routes/(app)/events/event-table.svelte
@@ -17,6 +17,7 @@
import { m } from '$lib/paraglide/messages';
import { eventService } from '$lib/services/event-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
import { TrashIcon, InfoIcon, NotificationsIcon, TagIcon, EnvironmentsIcon, UserIcon, EllipsisIcon } from '$lib/icons';
let {
@@ -268,16 +269,18 @@
{m.common_view_details()}
</DropdownMenu.Item>
- <DropdownMenu.Separator />
+ <IfPermitted perm="events:read">
+ <DropdownMenu.Separator />
- <DropdownMenu.Item
- variant="destructive"
- onclick={() => handleDeleteEvent(item.id, item.title)}
- disabled={isLoading.removing}
- >
- <TrashIcon class="size-4" />
- {m.common_delete()}
- </DropdownMenu.Item>
+ <DropdownMenu.Item
+ variant="destructive"
+ onclick={() => handleDeleteEvent(item.id, item.title)}
+ disabled={isLoading.removing}
+ >
+ <TrashIcon class="size-4" />
+ {m.common_delete()}
+ </DropdownMenu.Item>
+ </IfPermitted>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/(app)/images/+page.svelte b/frontend/src/routes/(app)/images/+page.svelte
index 59fd40bd9..d9cb3d95f 100644
--- a/frontend/src/routes/(app)/images/+page.svelte
+++ b/frontend/src/routes/(app)/images/+page.svelte
@@ -10,6 +10,7 @@
import { m } from '$lib/paraglide/messages';
import { imageService } from '$lib/services/image-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
import { queryKeys } from '$lib/query/query-keys';
import type { ImageUsageCounts } from '$lib/types/image.type';
import { untrack } from 'svelte';
@@ -148,36 +149,55 @@
await Promise.all([imagesQuery.refetch(), imageUsageCountsQuery.refetch()]);
}
- const actionButtons: ActionButton[] = $derived([
- { id: 'pull', action: 'pull', label: m.images_pull_image(), onclick: () => (isPullDialogOpen = true) },
- { id: 'upload', action: 'create', label: m.images_upload_image(), onclick: () => (isUploadDialogOpen = true) },
- {
- id: 'check-updates',
- action: 'inspect',
- label: m.images_check_updates(),
- loadingLabel: m.common_action_checking(),
- onclick: handleTriggerBulkUpdateCheck,
- loading: isChecking,
- disabled: isChecking
- },
- {
+ const canPullImage = $derived(hasPermission('images:pull', envId));
+ const canUploadImage = $derived(hasPermission('images:upload', envId));
+ const canPruneImage = $derived(hasPermission('images:prune', envId));
+
+ const actionButtons: ActionButton[] = $derived.by(() => {
+ const buttons: ActionButton[] = [];
+ if (canPullImage) {
+ buttons.push({ id: 'pull', action: 'pull', label: m.images_pull_image(), onclick: () => (isPullDialogOpen = true) });
+ }
+ if (canUploadImage) {
+ buttons.push({
+ id: 'upload',
+ action: 'create',
+ label: m.images_upload_image(),
+ onclick: () => (isUploadDialogOpen = true)
+ });
+ }
+ if (canPullImage) {
+ buttons.push({
+ id: 'check-updates',
+ action: 'inspect',
+ label: m.images_check_updates(),
+ loadingLabel: m.common_action_checking(),
+ onclick: handleTriggerBulkUpdateCheck,
+ loading: isChecking,
+ disabled: isChecking
+ });
+ }
+ buttons.push({
id: 'refresh',
action: 'restart',
label: m.common_refresh(),
onclick: refresh,
loading: isRefreshing,
disabled: isRefreshing
- },
- {
- id: 'prune',
- action: 'remove',
- label: m.images_prune_unused(),
- loadingLabel: m.common_action_pruning(),
- onclick: () => (isConfirmPruneDialogOpen = true),
- loading: isPruning,
- disabled: isPruning
+ });
+ if (canPruneImage) {
+ buttons.push({
+ id: 'prune',
+ action: 'remove',
+ label: m.images_prune_unused(),
+ loadingLabel: m.common_action_pruning(),
+ onclick: () => (isConfirmPruneDialogOpen = true),
+ loading: isPruning,
+ disabled: isPruning
+ });
}
- ]);
+ return buttons;
+ });
const statCards: StatCardConfig[] = $derived([
{
diff --git a/frontend/src/routes/(app)/images/[imageId]/+page.svelte b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
index 200000097..a8d423b36 100644
--- a/frontend/src/routes/(app)/images/[imageId]/+page.svelte
+++ b/frontend/src/routes/(app)/images/[imageId]/+page.svelte
@@ -21,11 +21,17 @@
import { ResourceDetailLayout, type DetailAction } from '$lib/layouts';
import VulnerabilityScanPanel from '$lib/components/vulnerability/vulnerability-scan-panel.svelte';
import type { VulnerabilityScanResult } from '$lib/types/vulnerability.type';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
import { VolumesIcon, ClockIcon, TagIcon, LayersIcon, CpuIcon, InfoIcon, SettingsIcon, HashIcon } from '$lib/icons';
let { data } = $props();
let { image } = $derived(data);
+ const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const canDeleteImage = $derived(hasPermission('images:delete', currentEnvId));
+ const canScanImage = $derived(hasPermission('vulnerabilities:scan', currentEnvId));
+
let isLoading = $state({
pulling: false,
removing: false,
@@ -225,24 +231,30 @@
});
}
- const actions: DetailAction[] = $derived([
- {
- id: 'scan',
- action: 'base',
- label: m.vuln_scan(),
- loading: isLoading.scanning,
- disabled: isLoading.scanning,
- onclick: handleScanImage
- },
- {
- id: 'remove',
- action: 'remove',
- label: m.common_remove(),
- loading: isLoading.removing,
- disabled: isLoading.removing,
- onclick: () => handleImageRemove(image.id)
+ const actions: DetailAction[] = $derived.by(() => {
+ const list: DetailAction[] = [];
+ if (canScanImage) {
+ list.push({
+ id: 'scan',
+ action: 'base',
+ label: m.vuln_scan(),
+ loading: isLoading.scanning,
+ disabled: isLoading.scanning,
+ onclick: handleScanImage
+ });
+ }
+ if (canDeleteImage) {
+ list.push({
+ id: 'remove',
+ action: 'remove',
+ label: m.common_remove(),
+ loading: isLoading.removing,
+ disabled: isLoading.removing,
+ onclick: () => handleImageRemove(image.id)
+ });
}
- ]);
+ return list;
+ });
</script>
<ResourceDetailLayout
diff --git a/frontend/src/routes/(app)/images/builds/+page.svelte b/frontend/src/routes/(app)/images/builds/+page.svelte
index 8c1ef8bb9..c34ea6550 100644
--- a/frontend/src/routes/(app)/images/builds/+page.svelte
+++ b/frontend/src/routes/(app)/images/builds/+page.svelte
@@ -12,6 +12,7 @@
import { ResourceDetailLayout } from '$lib/layouts/index.js';
import TabbedPageLayout from '$lib/layouts/tabbed-page-layout.svelte';
import { sanitizeLogText } from '$lib/utils/log-text';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
import {
CodeIcon,
TerminalIcon,
@@ -1005,14 +1006,16 @@
{/if}
<span class="text-muted-foreground">{formatTimestamp(buildHistorySelected.createdAt)}</span>
</div>
- <ArcaneButton
- action="base"
- tone="outline"
- size="sm"
- icon={RedeployIcon}
- customLabel={m.build_rebuild()}
- onclick={() => buildHistorySelected && applyBuildConfig(buildHistorySelected)}
- />
+ <IfPermitted perm="images:build">
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ size="sm"
+ icon={RedeployIcon}
+ customLabel={m.build_rebuild()}
+ onclick={() => buildHistorySelected && applyBuildConfig(buildHistorySelected)}
+ />
+ </IfPermitted>
</div>
{#if buildHistorySelected.errorMessage}
<div class="border-destructive/20 bg-destructive/10 text-destructive rounded-lg border p-3 text-sm">
diff --git a/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte b/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte
index 3110b2f5a..dce1d3f15 100644
--- a/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte
+++ b/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte
@@ -14,6 +14,7 @@
import { toast } from 'svelte-sonner';
import { UseClipboard } from '$lib/hooks/use-clipboard.svelte';
import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
import { queryKeys } from '$lib/query/query-keys';
import type { FileEntry } from '$lib/types/file-browser.type';
import type { FileProvider } from '$lib/components/file-browser';
@@ -35,6 +36,7 @@
let currentPath = $state('/');
const envId = $derived(environmentStore.selected?.id || '0');
+ const canBuildImage = $derived(hasPermission('images:build', envId));
const queryClient = useQueryClient();
const filesQuery = createQuery(() => ({
@@ -218,15 +220,17 @@
<CopyIcon class="size-4" />
Copy current path
</DropdownMenu.Item>
- <DropdownMenu.Separator />
- <DropdownMenu.Item onclick={() => (showCreateFolder = true)}>
- <MoveToFolderIcon class="size-4" />
- {m.volumes_browser_new_folder()}
- </DropdownMenu.Item>
- <DropdownMenu.Item onclick={() => (showUpload = true)}>
- <UploadIcon class="size-4" />
- {m.volumes_browser_upload_files()}
- </DropdownMenu.Item>
+ {#if canBuildImage}
+ <DropdownMenu.Separator />
+ <DropdownMenu.Item onclick={() => (showCreateFolder = true)}>
+ <MoveToFolderIcon class="size-4" />
+ {m.volumes_browser_new_folder()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => (showUpload = true)}>
+ <UploadIcon class="size-4" />
+ {m.volumes_browser_upload_files()}
+ </DropdownMenu.Item>
+ {/if}
</DropdownMenu.Content>
</DropdownMenu.Root>
</div>
@@ -249,10 +253,12 @@
minimal
onNavigate={handleNavigate}
onRefresh={() => filesQuery.refetch()}
- onDelete={async (file) => {
- await deleteMutation.mutateAsync(file.path);
- await filesQuery.refetch();
- }}
+ onDelete={canBuildImage
+ ? async (file) => {
+ await deleteMutation.mutateAsync(file.path);
+ await filesQuery.refetch();
+ }
+ : undefined}
onDownload={async (file) => {
await downloadMutation.mutateAsync(file.path);
}}
@@ -306,13 +312,15 @@
</div>
<Dialog.Footer class="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<ArcaneButton action="cancel" tone="outline" type="button" onclick={() => (editorOpen = false)} />
- <ArcaneButton
- action="save"
- type="button"
- onclick={handleSaveFile}
- disabled={editorLoading || editorSaving || !!editorError}
- loading={editorSaving}
- />
+ {#if canBuildImage}
+ <ArcaneButton
+ action="save"
+ type="button"
+ onclick={handleSaveFile}
+ disabled={editorLoading || editorSaving || !!editorError}
+ loading={editorSaving}
+ />
+ {/if}
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>
diff --git a/frontend/src/routes/(app)/images/builds/components/build-controls.svelte b/frontend/src/routes/(app)/images/builds/components/build-controls.svelte
index 2debefcba..c5d7857e8 100644
--- a/frontend/src/routes/(app)/images/builds/components/build-controls.svelte
+++ b/frontend/src/routes/(app)/images/builds/components/build-controls.svelte
@@ -4,6 +4,7 @@
import * as Select from '$lib/components/ui/select/index.js';
import { Switch } from '$lib/components/ui/switch/index.js';
import { m } from '$lib/paraglide/messages';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
import type { BuildFormInputsStore, BuildProviderOption } from './build-form.types';
let {
@@ -57,14 +58,16 @@
<Label for="build-load" class="text-sm">{m.load()}</Label>
</div>
- <ArcaneButton
- action="start_all"
- type="button"
- size="sm"
- hoverEffect="lift"
- customLabel={m.build()}
- onclick={() => onBuild?.()}
- loading={isBuilding}
- disabled={isBuilding}
- />
+ <IfPermitted perm="images:build">
+ <ArcaneButton
+ action="start_all"
+ type="button"
+ size="sm"
+ hoverEffect="lift"
+ customLabel={m.build()}
+ onclick={() => onBuild?.()}
+ loading={isBuilding}
+ disabled={isBuilding}
+ />
+ </IfPermitted>
</div>
diff --git a/frontend/src/routes/(app)/images/image-table.svelte b/frontend/src/routes/(app)/images/image-table.svelte
index 9f41f8273..fd5da3da1 100644
--- a/frontend/src/routes/(app)/images/image-table.svelte
+++ b/frontend/src/routes/(app)/images/image-table.svelte
@@ -25,6 +25,8 @@
import { imageService } from '$lib/services/image-service';
import { vulnerabilityService } from '$lib/services/vulnerability-service';
import { isLikelyStaleFailedSummary, isVulnerabilityScanInProgress } from '$lib/utils/vulnerability-scan.util';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
import {
DownloadIcon,
@@ -58,6 +60,11 @@
checking: false
});
+ const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const canDeleteImage = $derived(hasPermission('images:delete', currentEnvId));
+ const canPullImage = $derived(hasPermission('images:pull', currentEnvId));
+ const canScanImage = $derived(hasPermission('vulnerabilities:scan', currentEnvId));
+
let isPullingInline = $state<Record<string, boolean>>({});
let isScanningInline = $state<Record<string, boolean>>({});
let scanRequestedAtByImage = $state<Record<string, string>>({});
@@ -413,7 +420,7 @@
action: 'remove',
onClick: handleDeleteSelected,
loading: isLoading.removing,
- disabled: isLoading.removing,
+ disabled: !canDeleteImage || isLoading.removing,
icon: TrashIcon
}
]);
@@ -689,39 +696,47 @@
{m.common_inspect()}
</DropdownMenu.Item>
- <DropdownMenu.Separator />
-
- <DropdownMenu.Item
- onclick={() => handleInlineImagePull(item.id, item.repoTags?.[0] || '')}
- disabled={isPullingInline[item.id] || !item.repoTags?.[0]}
- >
- {#if isPullingInline[item.id]}
- <Spinner class="size-4" />
- {:else}
- <DownloadIcon class="size-4" />
- {/if}
- {m.images_pull()}
- </DropdownMenu.Item>
+ {#if canPullImage || canScanImage}
+ <DropdownMenu.Separator />
+ {/if}
- <DropdownMenu.Item onclick={() => handleInlineVulnerabilityScan(item.id)} disabled={isScanningInline[item.id]}>
- {#if isScanningInline[item.id]}
- <Spinner class="size-4" />
- {:else}
- <ScanIcon class="size-4" />
- {/if}
- {m.vuln_scan()}
- </DropdownMenu.Item>
+ {#if canPullImage}
+ <DropdownMenu.Item
+ onclick={() => handleInlineImagePull(item.id, item.repoTags?.[0] || '')}
+ disabled={isPullingInline[item.id] || !item.repoTags?.[0]}
+ >
+ {#if isPullingInline[item.id]}
+ <Spinner class="size-4" />
+ {:else}
+ <DownloadIcon class="size-4" />
+ {/if}
+ {m.images_pull()}
+ </DropdownMenu.Item>
+ {/if}
- <DropdownMenu.Separator />
+ {#if canScanImage}
+ <DropdownMenu.Item onclick={() => handleInlineVulnerabilityScan(item.id)} disabled={isScanningInline[item.id]}>
+ {#if isScanningInline[item.id]}
+ <Spinner class="size-4" />
+ {:else}
+ <ScanIcon class="size-4" />
+ {/if}
+ {m.vuln_scan()}
+ </DropdownMenu.Item>
+ {/if}
- <DropdownMenu.Item variant="destructive" onclick={() => deleteImage(item.id)} disabled={isLoading.removing}>
- {#if isLoading.removing}
- <Spinner class="size-4" />
- {:else}
- <TrashIcon class="size-4" />
- {/if}
- {m.common_remove()}
- </DropdownMenu.Item>
+ {#if canDeleteImage}
+ <DropdownMenu.Separator />
+
+ <DropdownMenu.Item variant="destructive" onclick={() => deleteImage(item.id)} disabled={isLoading.removing}>
+ {#if isLoading.removing}
+ <Spinner class="size-4" />
+ {:else}
+ <TrashIcon class="size-4" />
+ {/if}
+ {m.common_remove()}
+ </DropdownMenu.Item>
+ {/if}
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/(app)/images/vulnerabilities/+page.svelte b/frontend/src/routes/(app)/images/vulnerabilities/+page.svelte
index ea1cb38b7..db6b381f4 100644
--- a/frontend/src/routes/(app)/images/vulnerabilities/+page.svelte
+++ b/frontend/src/routes/(app)/images/vulnerabilities/+page.svelte
@@ -17,6 +17,8 @@
import { toast } from 'svelte-sonner';
import { InspectIcon } from '$lib/icons';
import * as Tabs from '$lib/components/ui/tabs/index.js';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
let { data } = $props();
@@ -289,27 +291,34 @@
}
}
- const actionButtons: ActionButton[] = $derived([
- {
- id: 'scan-all',
- action: 'base',
- label: isLoading.scanningAll
- ? `${m.security_scanning()} (${scanProgress.current}/${scanProgress.total})`
- : m.security_scan_all(),
- onclick: scanAllImages,
- loading: isLoading.scanningAll,
- disabled: isLoading.scanningAll || isLoading.refreshing,
- icon: InspectIcon
- },
- {
+ const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const canScanVuln = $derived(hasPermission('vulnerabilities:scan', currentEnvId));
+
+ const actionButtons: ActionButton[] = $derived.by(() => {
+ const buttons: ActionButton[] = [];
+ if (canScanVuln) {
+ buttons.push({
+ id: 'scan-all',
+ action: 'base',
+ label: isLoading.scanningAll
+ ? `${m.security_scanning()} (${scanProgress.current}/${scanProgress.total})`
+ : m.security_scan_all(),
+ onclick: scanAllImages,
+ loading: isLoading.scanningAll,
+ disabled: isLoading.scanningAll || isLoading.refreshing,
+ icon: InspectIcon
+ });
+ }
+ buttons.push({
id: 'refresh',
action: 'restart',
label: m.common_refresh(),
onclick: refreshAll,
loading: isLoading.refreshing,
disabled: isLoading.refreshing || isLoading.scanningAll
- }
- ]);
+ });
+ return buttons;
+ });
</script>
<ResourcePageLayout title={m.security_title()} subtitle={m.security_subtitle()} {actionButtons}>
diff --git a/frontend/src/routes/(app)/images/vulnerabilities/ignored-vulnerabilities-table.svelte b/frontend/src/routes/(app)/images/vulnerabilities/ignored-vulnerabilities-table.svelte
index 27e960f32..a58e79116 100644
--- a/frontend/src/routes/(app)/images/vulnerabilities/ignored-vulnerabilities-table.svelte
+++ b/frontend/src/routes/(app)/images/vulnerabilities/ignored-vulnerabilities-table.svelte
@@ -4,6 +4,7 @@
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
import { ShieldAlertIcon, CodeIcon, ImagesIcon, EyeOnIcon } from '$lib/icons';
import { ArcaneButton } from '$lib/components/arcane-button';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
let {
ignoredVulnerabilities,
@@ -84,14 +85,16 @@
</div>
{/if}
</div>
- <ArcaneButton
- action="base"
- size="sm"
- icon={EyeOnIcon}
- customLabel={m.vuln_unignore()}
- onclick={() => onUnignore(item.id)}
- disabled={isLoading}
- />
+ <IfPermitted perm="vulnerabilities:manage">
+ <ArcaneButton
+ action="base"
+ size="sm"
+ icon={EyeOnIcon}
+ customLabel={m.vuln_unignore()}
+ onclick={() => onUnignore(item.id)}
+ disabled={isLoading}
+ />
+ </IfPermitted>
</div>
{/each}
diff --git a/frontend/src/routes/(app)/images/vulnerabilities/security-vulnerability-table.svelte b/frontend/src/routes/(app)/images/vulnerabilities/security-vulnerability-table.svelte
index 68d883c9b..0bed6f730 100644
--- a/frontend/src/routes/(app)/images/vulnerabilities/security-vulnerability-table.svelte
+++ b/frontend/src/routes/(app)/images/vulnerabilities/security-vulnerability-table.svelte
@@ -10,6 +10,8 @@
import { ShieldAlertIcon, CodeIcon, CheckIcon, ImagesIcon, EyeOffIcon } from '$lib/icons';
import { toast } from 'svelte-sonner';
import { onMount } from 'svelte';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
const DEFAULT_PAGE_SIZE = 20;
@@ -25,6 +27,9 @@
let imageNameFilterOptions = $state<string[]>([]);
+ const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const canManageVuln = $derived(hasPermission('vulnerabilities:manage', currentEnvId));
+
function getSeverityLabel(severity: string): string {
switch (severity) {
case 'CRITICAL':
@@ -295,14 +300,16 @@
{/snippet}
{#snippet rowActions({ item }: { item: VulnerabilityRow })}
- <button
- onclick={() => handleIgnoreVulnerability(item)}
- class="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs transition-colors"
- title={m.vuln_ignore()}
- >
- <EyeOffIcon class="h-3.5 w-3.5" />
- <span class="sr-only">{m.vuln_ignore()}</span>
- </button>
+ {#if canManageVuln}
+ <button
+ onclick={() => handleIgnoreVulnerability(item)}
+ class="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs transition-colors"
+ title={m.vuln_ignore()}
+ >
+ <EyeOffIcon class="h-3.5 w-3.5" />
+ <span class="sr-only">{m.vuln_ignore()}</span>
+ </button>
+ {/if}
{/snippet}
<ArcaneTable
@@ -315,5 +322,5 @@
persistKey="arcane-security-vuln-table"
selectionDisabled
{imageNameFilterOptions}
- {rowActions}
+ rowActions={canManageVuln ? rowActions : undefined}
/>
diff --git a/frontend/src/routes/(app)/no-access/+page.svelte b/frontend/src/routes/(app)/no-access/+page.svelte
new file mode 100644
index 000000000..f6fe2c5ec
--- /dev/null
+++ b/frontend/src/routes/(app)/no-access/+page.svelte
@@ -0,0 +1,14 @@
+<script lang="ts">
+ import ErrorView from '$lib/components/error.svelte';
+ import { m } from '$lib/paraglide/messages';
+
+ let {}: PageProps = $props();
+</script>
+
+<ErrorView
+ title={m.no_access_page_title()}
+ message={m.no_access_page_body()}
+ status={403}
+ actionHref="/logout"
+ actionLabel={m.common_logout()}
+/>
diff --git a/frontend/src/routes/(app)/projects/+page.svelte b/frontend/src/routes/(app)/projects/+page.svelte
index 5595394ad..c1b5582a0 100644
--- a/frontend/src/routes/(app)/projects/+page.svelte
+++ b/frontend/src/routes/(app)/projects/+page.svelte
@@ -8,6 +8,7 @@
import { projectService } from '$lib/services/project-service';
import { imageService } from '$lib/services/image-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
import { queryKeys } from '$lib/query/query-keys';
import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
import type { ProjectStatusCounts } from '$lib/types/project.type';
@@ -150,30 +151,39 @@
await goto(`${url.pathname}${url.search}`, { keepFocus: true, replaceState: true, noScroll: true });
}
- const actionButtons: ActionButton[] = $derived([
- {
- id: 'create',
- action: 'create',
- label: m.compose_create_project(),
- onclick: () => goto('/projects/new')
- },
- {
- id: 'check-updates',
- action: 'update',
- label: m.compose_update_projects(),
- onclick: handleCheckForUpdates,
- loading: checkUpdatesMutation.isPending,
- disabled: checkUpdatesMutation.isPending
- },
- {
+ const canCreateProject = $derived(hasPermission('projects:create', envId));
+ const canDeployProject = $derived(hasPermission('projects:deploy', envId));
+
+ const actionButtons: ActionButton[] = $derived.by(() => {
+ const buttons: ActionButton[] = [];
+ if (canCreateProject) {
+ buttons.push({
+ id: 'create',
+ action: 'create',
+ label: m.compose_create_project(),
+ onclick: () => goto('/projects/new')
+ });
+ }
+ if (canDeployProject) {
+ buttons.push({
+ id: 'check-updates',
+ action: 'update',
+ label: m.compose_update_projects(),
+ onclick: handleCheckForUpdates,
+ loading: checkUpdatesMutation.isPending,
+ disabled: checkUpdatesMutation.isPending
+ });
+ }
+ buttons.push({
id: 'refresh',
action: 'restart',
label: m.common_refresh(),
onclick: refreshCompose,
loading: isManualRefreshing,
disabled: isRefreshBlocked
- }
- ]);
+ });
+ return buttons;
+ });
const statCards: StatCardConfig[] = $derived([
{
diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
index 6150a3fba..5f1a4ea95 100644
--- a/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.svelte
@@ -34,11 +34,13 @@
import { imageService } from '$lib/services/image-service';
import { gitOpsSyncService } from '$lib/services/gitops-sync-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
import { queryKeys } from '$lib/query/query-keys';
import { RefreshIcon } from '$lib/icons';
import IconImage from '$lib/components/icon-image.svelte';
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import ProjectUpdateItem from '$lib/components/project-update-item.svelte';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
let { data } = $props();
let projectId = $derived(data.projectId);
@@ -59,6 +61,10 @@
});
const envId = $derived(environmentStore.selected?.id || '0');
+ const canUpdateProject = $derived(hasPermission('projects:update', envId));
+ const canViewProjectLogs = $derived(hasPermission('projects:logs', envId));
+ // Project lifecycle permissions are evaluated per-button inside
+ // <ActionButtons/> directly; no need to derive them here.
let includeFilesState = $state<Record<string, string>>({});
let loadedIncludeFileContents = $state<Record<string, string>>({});
@@ -139,14 +145,15 @@
let isGitOpsManaged = $derived(!!project?.gitOpsManagedBy);
let hasBuildDirective = $derived(!!project?.hasBuildDirective);
let canEditName = $derived(
- !project?.isArchived &&
+ canUpdateProject &&
+ !project?.isArchived &&
!isGitOpsManaged &&
!isLoading.saving &&
project?.status !== 'running' &&
project?.status !== 'partially running'
);
- let canEditCompose = $derived(!project?.isArchived && !isGitOpsManaged);
- let canEditEnv = $derived(!project?.isArchived);
+ let canEditCompose = $derived(canUpdateProject && !project?.isArchived && !isGitOpsManaged);
+ let canEditEnv = $derived(canUpdateProject && !project?.isArchived);
let composeFileName = $derived(project?.composeFileName || 'compose.yaml');
let archiveRequiresStopped = $derived(
!!project &&
@@ -208,7 +215,7 @@
)
);
- let canSave = $derived(!project?.isArchived && hasChanges && !hasAnyErrors);
+ let canSave = $derived(canUpdateProject && !project?.isArchived && hasChanges && !hasAnyErrors);
const tabItems = $derived<TabItem[]>([
{
@@ -222,12 +229,16 @@
label: m.common_configuration(),
icon: SettingsIcon
},
- {
- value: 'logs',
- label: m.compose_nav_logs(),
- icon: FileTextIcon,
- disabled: project?.status !== 'running'
- }
+ ...(canViewProjectLogs
+ ? [
+ {
+ value: 'logs',
+ label: m.compose_nav_logs(),
+ icon: FileTextIcon,
+ disabled: project?.status !== 'running'
+ }
+ ]
+ : [])
]);
let nameInputRef = $state<HTMLInputElement | null>(null);
@@ -744,7 +755,7 @@
{#snippet headerActions()}
<div class="flex items-center gap-2">
- {#if hasChanges}
+ {#if hasChanges && canUpdateProject}
<ArcaneButton
action="save"
loading={isLoading.saving}
@@ -766,28 +777,30 @@
class="xl:hidden"
/>
{/if}
- <ArcaneButton
- action="base"
- icon={BoxIcon}
- loading={isLoading.archiving}
- onclick={handleArchiveToggle}
- disabled={archiveRequiresStopped}
- title={archiveRequiresStopped ? m.projects_archive_requires_stopped() : undefined}
- customLabel={project.isArchived ? m.projects_unarchive() : m.projects_archive()}
- class="hidden xl:inline-flex"
- />
- <ArcaneButton
- action="base"
- icon={BoxIcon}
- size="icon"
- showLabel={false}
- loading={isLoading.archiving}
- onclick={handleArchiveToggle}
- disabled={archiveRequiresStopped}
- title={archiveRequiresStopped ? m.projects_archive_requires_stopped() : undefined}
- customLabel={project.isArchived ? m.projects_unarchive() : m.projects_archive()}
- class="xl:hidden"
- />
+ <IfPermitted perm="projects:archive">
+ <ArcaneButton
+ action="base"
+ icon={BoxIcon}
+ loading={isLoading.archiving}
+ onclick={handleArchiveToggle}
+ disabled={archiveRequiresStopped}
+ title={archiveRequiresStopped ? m.projects_archive_requires_stopped() : undefined}
+ customLabel={project.isArchived ? m.projects_unarchive() : m.projects_archive()}
+ class="hidden xl:inline-flex"
+ />
+ <ArcaneButton
+ action="base"
+ icon={BoxIcon}
+ size="icon"
+ showLabel={false}
+ loading={isLoading.archiving}
+ onclick={handleArchiveToggle}
+ disabled={archiveRequiresStopped}
+ title={archiveRequiresStopped ? m.projects_archive_requires_stopped() : undefined}
+ customLabel={project.isArchived ? m.projects_unarchive() : m.projects_archive()}
+ class="xl:hidden"
+ />
+ </IfPermitted>
<ActionButtons
id={project.id}
name={project.name}
@@ -849,16 +862,18 @@
</div>
</Alert.Description>
</div>
- <ArcaneButton
- action="base"
- tone="outline-primary"
- loading={isLoading.syncing}
- onclick={handleSyncFromGit}
- icon={RefreshIcon}
- customLabel={m.git_sync_from_git()}
- loadingLabel={m.common_syncing()}
- class="shrink-0"
- />
+ {#if canUpdateProject}
+ <ArcaneButton
+ action="base"
+ tone="outline-primary"
+ loading={isLoading.syncing}
+ onclick={handleSyncFromGit}
+ icon={RefreshIcon}
+ customLabel={m.git_sync_from_git()}
+ loadingLabel={m.common_syncing()}
+ class="shrink-0"
+ />
+ {/if}
</div>
</Alert.Root>
{/if}
diff --git a/frontend/src/routes/(app)/projects/components/ProjectContainersTable.svelte b/frontend/src/routes/(app)/projects/components/ProjectContainersTable.svelte
index f29e481ca..6cf355e39 100644
--- a/frontend/src/routes/(app)/projects/components/ProjectContainersTable.svelte
+++ b/frontend/src/routes/(app)/projects/components/ProjectContainersTable.svelte
@@ -18,6 +18,8 @@
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import { containerService } from '$lib/services/container-service';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
import * as ArcaneTooltip from '$lib/components/arcane-tooltip';
import IconImage from '$lib/components/icon-image.svelte';
import { getArcaneIconUrlFromLabels } from '$lib/utils/arcane-labels';
@@ -41,6 +43,12 @@
let { services = [], projectId, onRefresh }: Props = $props();
+ const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const canStartContainer = $derived(hasPermission('containers:start', currentEnvId));
+ const canStopContainer = $derived(hasPermission('containers:stop', currentEnvId));
+ const canRestartContainer = $derived(hasPermission('containers:restart', currentEnvId));
+ const canDeleteContainer = $derived(hasPermission('containers:delete', currentEnvId));
+
// Convert RuntimeService to a format compatible with ArcaneTable
type ServiceWithId = RuntimeService & { id: string };
@@ -270,7 +278,7 @@
action: 'start',
onClick: (ids) => handleBulkAction('start', ids),
loading: isBulkLoading.start,
- disabled: isAnyLoading,
+ disabled: !canStartContainer || isAnyLoading,
icon: StartIcon
},
{
@@ -279,7 +287,7 @@
action: 'stop',
onClick: (ids) => handleBulkAction('stop', ids),
loading: isBulkLoading.stop,
- disabled: isAnyLoading,
+ disabled: !canStopContainer || isAnyLoading,
icon: StopIcon
},
{
@@ -288,7 +296,7 @@
action: 'restart',
onClick: (ids) => handleBulkAction('restart', ids),
loading: isBulkLoading.restart,
- disabled: isAnyLoading,
+ disabled: !canRestartContainer || isAnyLoading,
icon: RefreshIcon
},
{
@@ -297,7 +305,7 @@
action: 'remove',
onClick: (ids) => handleBulkAction('remove', ids),
loading: isBulkLoading.remove,
- disabled: isAnyLoading,
+ disabled: !canDeleteContainer || isAnyLoading,
icon: TrashIcon
}
]);
@@ -441,19 +449,21 @@
<InspectIcon class="size-4" />
{m.common_inspect()}
</DropdownMenu.Item>
- <DropdownMenu.Separator />
- <DropdownMenu.Item
- variant="destructive"
- onclick={() => handleRemoveContainer(item.containerId!, item.containerName || item.name)}
- disabled={actionStatus[item.id] === 'removing' || isAnyLoading}
- >
- {#if actionStatus[item.id] === 'removing'}
- <Spinner class="size-4" />
- {:else}
- <TrashIcon class="size-4" />
- {/if}
- {m.common_remove()}
- </DropdownMenu.Item>
+ {#if canDeleteContainer}
+ <DropdownMenu.Separator />
+ <DropdownMenu.Item
+ variant="destructive"
+ onclick={() => handleRemoveContainer(item.containerId!, item.containerName || item.name)}
+ disabled={actionStatus[item.id] === 'removing' || isAnyLoading}
+ >
+ {#if actionStatus[item.id] === 'removing'}
+ <Spinner class="size-4" />
+ {:else}
+ <TrashIcon class="size-4" />
+ {/if}
+ {m.common_remove()}
+ </DropdownMenu.Item>
+ {/if}
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
@@ -499,44 +509,50 @@
<DropdownMenu.Separator />
- <DropdownMenu.Item
- onclick={() => performContainerAction('stop', item.containerId!)}
- disabled={status === 'stopping' || isAnyLoading}
- >
- {#if status === 'stopping'}
- <Spinner class="size-4" />
- {:else}
- <StopIcon class="size-4" />
- {/if}
- {m.common_stop()}
- </DropdownMenu.Item>
-
- <DropdownMenu.Item
- onclick={() => performContainerAction('restart', item.containerId!)}
- disabled={status === 'restarting' || isAnyLoading}
- >
- {#if status === 'restarting'}
- <Spinner class="size-4" />
- {:else}
- <RefreshIcon class="size-4" />
- {/if}
- {m.common_restart()}
- </DropdownMenu.Item>
-
- <DropdownMenu.Separator />
-
- <DropdownMenu.Item
- variant="destructive"
- onclick={() => handleRemoveContainer(item.containerId!, item.containerName || item.name)}
- disabled={status === 'removing' || isAnyLoading}
- >
- {#if status === 'removing'}
- <Spinner class="size-4" />
- {:else}
- <TrashIcon class="size-4" />
- {/if}
- {m.common_remove()}
- </DropdownMenu.Item>
+ {#if canStopContainer}
+ <DropdownMenu.Item
+ onclick={() => performContainerAction('stop', item.containerId!)}
+ disabled={status === 'stopping' || isAnyLoading}
+ >
+ {#if status === 'stopping'}
+ <Spinner class="size-4" />
+ {:else}
+ <StopIcon class="size-4" />
+ {/if}
+ {m.common_stop()}
+ </DropdownMenu.Item>
+ {/if}
+
+ {#if canRestartContainer}
+ <DropdownMenu.Item
+ onclick={() => performContainerAction('restart', item.containerId!)}
+ disabled={status === 'restarting' || isAnyLoading}
+ >
+ {#if status === 'restarting'}
+ <Spinner class="size-4" />
+ {:else}
+ <RefreshIcon class="size-4" />
+ {/if}
+ {m.common_restart()}
+ </DropdownMenu.Item>
+ {/if}
+
+ {#if canDeleteContainer}
+ <DropdownMenu.Separator />
+
+ <DropdownMenu.Item
+ variant="destructive"
+ onclick={() => handleRemoveContainer(item.containerId!, item.containerName || item.name)}
+ disabled={status === 'removing' || isAnyLoading}
+ >
+ {#if status === 'removing'}
+ <Spinner class="size-4" />
+ {:else}
+ <TrashIcon class="size-4" />
+ {/if}
+ {m.common_remove()}
+ </DropdownMenu.Item>
+ {/if}
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/(app)/projects/new/+page.svelte b/frontend/src/routes/(app)/projects/new/+page.svelte
index 737f0ffd6..5af9ca154 100644
--- a/frontend/src/routes/(app)/projects/new/+page.svelte
+++ b/frontend/src/routes/(app)/projects/new/+page.svelte
@@ -25,10 +25,15 @@
import CodePanel from '../components/CodePanel.svelte';
import EditableName from '../components/EditableName.svelte';
import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
import { ComposeEditorSplit } from '$lib/components/compose';
let { data } = $props();
+ const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const canCreateProject = $derived(hasPermission('projects:create', currentEnvId));
+
let saving = $state(false);
let converting = $state(false);
let creatingTemplate = $state(false);
@@ -216,7 +221,7 @@
>
<ArcaneTooltip.Trigger>
<span>
- {#if !hasEditorErrors}
+ {#if !hasEditorErrors && canCreateProject}
<ArcaneButton
action="create"
tone="ghost"
@@ -282,25 +287,27 @@
<GitBranchIcon class="size-4" />
{m.git_from_git_repo()}
</DropdownMenu.Item>
- <DropdownMenu.Separator />
- <DropdownMenu.Item
- class={dropdownItemClass}
- disabled={!$inputs.name.value ||
- !$inputs.composeContent.value ||
- hasEditorErrors ||
- saving ||
- converting ||
- creatingTemplate ||
- isLoadingTemplateContent}
- onclick={handleCreateTemplate}
- >
- {#if creatingTemplate}
- <Spinner class="size-4" />
- {:else}
- <AddIcon class="size-4" />
- {/if}
- {m.templates_create_template()}
- </DropdownMenu.Item>
+ <IfPermitted perm="templates:create">
+ <DropdownMenu.Separator />
+ <DropdownMenu.Item
+ class={dropdownItemClass}
+ disabled={!$inputs.name.value ||
+ !$inputs.composeContent.value ||
+ hasEditorErrors ||
+ saving ||
+ converting ||
+ creatingTemplate ||
+ isLoadingTemplateContent}
+ onclick={handleCreateTemplate}
+ >
+ {#if creatingTemplate}
+ <Spinner class="size-4" />
+ {:else}
+ <AddIcon class="size-4" />
+ {/if}
+ {m.templates_create_template()}
+ </DropdownMenu.Item>
+ </IfPermitted>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/(app)/projects/projects-table.svelte b/frontend/src/routes/(app)/projects/projects-table.svelte
index 09c62fd74..1fa718f30 100644
--- a/frontend/src/routes/(app)/projects/projects-table.svelte
+++ b/frontend/src/routes/(app)/projects/projects-table.svelte
@@ -19,6 +19,8 @@
import { projectService } from '$lib/services/project-service';
import { FolderOpenIcon, LayersIcon, CalendarIcon, ProjectsIcon, GitBranchIcon, RefreshIcon } from '$lib/icons';
import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
import IconImage from '$lib/components/icon-image.svelte';
import type { ActionStatus } from './projects-table.helpers';
import { createProjectActions } from './projects-table.actions';
@@ -107,6 +109,11 @@
let mobileFieldVisibility = $state<Record<string, boolean>>({});
const envId = $derived(environmentStore.selected?.id);
+ const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const canUpdateProject = $derived(hasPermission('projects:update', currentEnvId));
+ const canDeployProject = $derived(hasPermission('projects:deploy', currentEnvId));
+ const canDownProject = $derived(hasPermission('projects:down', currentEnvId));
+ const canArchiveProject = $derived(hasPermission('projects:archive', currentEnvId));
const {
performProjectAction,
@@ -175,7 +182,7 @@
action: 'up',
onClick: handleBulkUp,
loading: isBulkLoading.up,
- disabled: isAnyLoading || hasArchivedSelection,
+ disabled: !canDeployProject || isAnyLoading || hasArchivedSelection,
disabledReason: hasArchivedSelection ? m.projects_archived_badge() : undefined,
icon: StartIcon
},
@@ -185,7 +192,7 @@
action: 'down',
onClick: handleBulkDown,
loading: isBulkLoading.down,
- disabled: isAnyLoading || hasArchivedSelection,
+ disabled: !canDownProject || isAnyLoading || hasArchivedSelection,
disabledReason: hasArchivedSelection ? m.projects_archived_badge() : undefined,
icon: StopIcon
},
@@ -195,7 +202,7 @@
action: 'redeploy',
onClick: handleBulkRedeploy,
loading: isBulkLoading.redeploy,
- disabled: isAnyLoading || hasRedeployDisabledSelection || hasArchivedSelection,
+ disabled: !canDeployProject || isAnyLoading || hasRedeployDisabledSelection || hasArchivedSelection,
disabledReason: hasArchivedSelection
? m.projects_archived_badge()
: hasRedeployDisabledSelection
@@ -209,7 +216,7 @@
action: 'base',
onClick: handleBulkArchive,
loading: isBulkLoading.archive,
- disabled: isAnyLoading || hasArchivedSelection || hasRunningSelection,
+ disabled: !canArchiveProject || isAnyLoading || hasArchivedSelection || hasRunningSelection,
disabledReason: hasRunningSelection
? m.projects_archive_requires_stopped()
: hasArchivedSelection
@@ -379,7 +386,7 @@
{m.common_edit()}
</DropdownMenu.Item>
- {#if item.gitOpsManagedBy}
+ {#if item.gitOpsManagedBy && canUpdateProject}
<DropdownMenu.Item
onclick={() => handleSyncFromGit(item.id, item.gitOpsManagedBy!)}
disabled={status === 'syncing' || isAnyLoading}
@@ -396,107 +403,119 @@
<DropdownMenu.Separator />
{#if item.status !== 'running'}
- <DropdownMenu.Item
- onclick={() => performProjectAction('start', item.id)}
- disabled={item.isArchived || status === 'starting' || isAnyLoading}
- title={item.isArchived ? m.projects_archived_badge() : undefined}
- >
- {#if status === 'starting'}
- <Spinner class="size-4" />
- {:else}
- <StartIcon class="size-4" />
- {/if}
- {m.common_up()}
- </DropdownMenu.Item>
+ {#if canDeployProject}
+ <DropdownMenu.Item
+ onclick={() => performProjectAction('start', item.id)}
+ disabled={item.isArchived || status === 'starting' || isAnyLoading}
+ title={item.isArchived ? m.projects_archived_badge() : undefined}
+ >
+ {#if status === 'starting'}
+ <Spinner class="size-4" />
+ {:else}
+ <StartIcon class="size-4" />
+ {/if}
+ {m.common_up()}
+ </DropdownMenu.Item>
+ {/if}
{:else}
- <DropdownMenu.Item
- onclick={() => performProjectAction('stop', item.id)}
- disabled={item.isArchived || status === 'stopping' || isAnyLoading}
- title={item.isArchived ? m.projects_archived_badge() : undefined}
- >
- {#if status === 'stopping'}
- <Spinner class="size-4" />
- {:else}
- <StopIcon class="size-4" />
- {/if}
- {m.common_down()}
- </DropdownMenu.Item>
+ {#if canDownProject}
+ <DropdownMenu.Item
+ onclick={() => performProjectAction('stop', item.id)}
+ disabled={item.isArchived || status === 'stopping' || isAnyLoading}
+ title={item.isArchived ? m.projects_archived_badge() : undefined}
+ >
+ {#if status === 'stopping'}
+ <Spinner class="size-4" />
+ {:else}
+ <StopIcon class="size-4" />
+ {/if}
+ {m.common_down()}
+ </DropdownMenu.Item>
+ {/if}
- <DropdownMenu.Item
- onclick={() => performProjectAction('restart', item.id)}
- disabled={item.isArchived || status === 'restarting' || isAnyLoading}
- title={item.isArchived ? m.projects_archived_badge() : undefined}
- >
- {#if status === 'restarting'}
- <Spinner class="size-4" />
- {:else}
- <RestartIcon class="size-4" />
- {/if}
- {m.common_restart()}
- </DropdownMenu.Item>
+ <IfPermitted perm="projects:restart">
+ <DropdownMenu.Item
+ onclick={() => performProjectAction('restart', item.id)}
+ disabled={item.isArchived || status === 'restarting' || isAnyLoading}
+ title={item.isArchived ? m.projects_archived_badge() : undefined}
+ >
+ {#if status === 'restarting'}
+ <Spinner class="size-4" />
+ {:else}
+ <RestartIcon class="size-4" />
+ {/if}
+ {m.common_restart()}
+ </DropdownMenu.Item>
+ </IfPermitted>
{/if}
- {#if item.redeployDisabled}
- <DropdownMenu.Item disabled title={m.common_redeploy_disabled_arcane_self()}>
- <RedeployIcon class="size-4 opacity-50" />
- {m.compose_pull_redeploy()}
- </DropdownMenu.Item>
- {:else}
- <DropdownMenu.Item
- onclick={() => performProjectAction('redeploy', item.id)}
- disabled={item.isArchived || status === 'redeploying' || isAnyLoading}
- title={item.isArchived ? m.projects_archived_badge() : undefined}
- >
- {#if status === 'redeploying'}
- <Spinner class="size-4" />
- {:else}
- <RedeployIcon class="size-4" />
- {/if}
- {m.compose_pull_redeploy()}
- </DropdownMenu.Item>
+ {#if canDeployProject}
+ {#if item.redeployDisabled}
+ <DropdownMenu.Item disabled title={m.common_redeploy_disabled_arcane_self()}>
+ <RedeployIcon class="size-4 opacity-50" />
+ {m.compose_pull_redeploy()}
+ </DropdownMenu.Item>
+ {:else}
+ <DropdownMenu.Item
+ onclick={() => performProjectAction('redeploy', item.id)}
+ disabled={item.isArchived || status === 'redeploying' || isAnyLoading}
+ title={item.isArchived ? m.projects_archived_badge() : undefined}
+ >
+ {#if status === 'redeploying'}
+ <Spinner class="size-4" />
+ {:else}
+ <RedeployIcon class="size-4" />
+ {/if}
+ {m.compose_pull_redeploy()}
+ </DropdownMenu.Item>
+ {/if}
{/if}
<DropdownMenu.Separator />
- {#if item.isArchived}
- <DropdownMenu.Item
- onclick={() => performProjectAction('unarchive', item.id)}
- disabled={status === 'unarchiving' || isAnyLoading}
- >
- {#if status === 'unarchiving'}
- <Spinner class="size-4" />
- {:else}
- <BoxIcon class="size-4" />
- {/if}
- {m.projects_unarchive()}
- </DropdownMenu.Item>
- {:else}
+ {#if canArchiveProject}
+ {#if item.isArchived}
+ <DropdownMenu.Item
+ onclick={() => performProjectAction('unarchive', item.id)}
+ disabled={status === 'unarchiving' || isAnyLoading}
+ >
+ {#if status === 'unarchiving'}
+ <Spinner class="size-4" />
+ {:else}
+ <BoxIcon class="size-4" />
+ {/if}
+ {m.projects_unarchive()}
+ </DropdownMenu.Item>
+ {:else}
+ <DropdownMenu.Item
+ onclick={() => performProjectAction('archive', item.id)}
+ disabled={isProjectArchiveBlocked(item) || status === 'archiving' || isAnyLoading}
+ title={isProjectArchiveBlocked(item) ? m.projects_archive_requires_stopped() : undefined}
+ >
+ {#if status === 'archiving'}
+ <Spinner class="size-4" />
+ {:else}
+ <BoxIcon class="size-4" />
+ {/if}
+ {m.projects_archive()}
+ </DropdownMenu.Item>
+ {/if}
+ {/if}
+
+ <IfPermitted perm="projects:delete">
<DropdownMenu.Item
- onclick={() => performProjectAction('archive', item.id)}
- disabled={isProjectArchiveBlocked(item) || status === 'archiving' || isAnyLoading}
- title={isProjectArchiveBlocked(item) ? m.projects_archive_requires_stopped() : undefined}
+ variant="destructive"
+ onclick={() => handleDestroyProject(item.id)}
+ disabled={status === 'destroying' || isAnyLoading}
>
- {#if status === 'archiving'}
+ {#if status === 'destroying'}
<Spinner class="size-4" />
{:else}
- <BoxIcon class="size-4" />
+ <TrashIcon class="size-4" />
{/if}
- {m.projects_archive()}
+ {m.compose_destroy()}
</DropdownMenu.Item>
- {/if}
-
- <DropdownMenu.Item
- variant="destructive"
- onclick={() => handleDestroyProject(item.id)}
- disabled={status === 'destroying' || isAnyLoading}
- >
- {#if status === 'destroying'}
- <Spinner class="size-4" />
- {:else}
- <TrashIcon class="size-4" />
- {/if}
- {m.compose_destroy()}
- </DropdownMenu.Item>
+ </IfPermitted>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/(app)/settings/api-keys/+page.svelte b/frontend/src/routes/(app)/settings/api-keys/+page.svelte
index 49884107d..72bdc5073 100644
--- a/frontend/src/routes/(app)/settings/api-keys/+page.svelte
+++ b/frontend/src/routes/(app)/settings/api-keys/+page.svelte
@@ -5,7 +5,7 @@
import ApiKeyTable from './api-key-table.svelte';
import ApiKeyFormSheet from '$lib/components/sheets/api-key-form-sheet.svelte';
import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
- import type { ApiKey, ApiKeyCreated } from '$lib/types/api-key.type';
+ import type { ApiKey, ApiKeyCreated, CreateApiKey } from '$lib/types/api-key.type';
import { apiKeyService } from '$lib/services/api-key-service';
import { SettingsPageLayout, type SettingsActionButton } from '$lib/layouts/index.js';
import * as ResponsiveDialog from '$lib/components/ui/responsive-dialog/index.js';
@@ -51,7 +51,7 @@
isEditMode,
apiKeyId
}: {
- apiKey: { name: string; description?: string; expiresAt?: string };
+ apiKey: CreateApiKey;
isEditMode: boolean;
apiKeyId?: string;
}) {
@@ -129,11 +129,20 @@
<ApiKeyFormSheet
bind:open={isDialogOpen.create}
apiKeyToEdit={null}
+ manifest={data.permissionsManifest}
+ availablePermissions={[]}
onSubmit={handleApiKeySubmit}
isLoading={isLoading.creating}
/>
- <ApiKeyFormSheet bind:open={isDialogOpen.edit} {apiKeyToEdit} onSubmit={handleApiKeySubmit} isLoading={isLoading.editing} />
+ <ApiKeyFormSheet
+ bind:open={isDialogOpen.edit}
+ {apiKeyToEdit}
+ manifest={data.permissionsManifest}
+ availablePermissions={apiKeyToEdit?.permissions ?? []}
+ onSubmit={handleApiKeySubmit}
+ isLoading={isLoading.editing}
+ />
<ResponsiveDialog.Root
bind:open={isDialogOpen.showKey}
diff --git a/frontend/src/routes/(app)/settings/api-keys/+page.ts b/frontend/src/routes/(app)/settings/api-keys/+page.ts
index 9f13b1987..85ee03601 100644
--- a/frontend/src/routes/(app)/settings/api-keys/+page.ts
+++ b/frontend/src/routes/(app)/settings/api-keys/+page.ts
@@ -1,4 +1,5 @@
import { apiKeyService } from '$lib/services/api-key-service';
+import { roleService } from '$lib/services/role-service';
import { queryKeys } from '$lib/query/query-keys';
import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';
@@ -18,13 +19,21 @@ export const load: PageLoad = async ({ parent }) => {
}
} satisfies SearchPaginationSortRequest);
- const apiKeys = await queryClient.fetchQuery({
- queryKey: queryKeys.apiKeys.list(apiKeyRequestOptions),
- queryFn: () => apiKeyService.getApiKeys(apiKeyRequestOptions)
- });
+ const [apiKeys, permissionsManifest] = await Promise.all([
+ queryClient.fetchQuery({
+ queryKey: queryKeys.apiKeys.list(apiKeyRequestOptions),
+ queryFn: () => apiKeyService.getApiKeys(apiKeyRequestOptions)
+ }),
+ queryClient.fetchQuery({
+ queryKey: ['permissions', 'manifest'],
+ queryFn: () => roleService.getPermissionsManifest(),
+ staleTime: Infinity
+ })
+ ]);
return {
apiKeys,
- apiKeyRequestOptions
+ apiKeyRequestOptions,
+ permissionsManifest
};
};
diff --git a/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte b/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte
index ca7966d5d..272ba983c 100644
--- a/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte
+++ b/frontend/src/routes/(app)/settings/api-keys/api-key-table.svelte
@@ -15,6 +15,7 @@
import { apiKeyService } from '$lib/services/api-key-service';
import * as m from '$lib/paraglide/messages.js';
import { ApiKeyIcon, TrashIcon, EditIcon, EllipsisIcon } from '$lib/icons';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
let {
apiKeys = $bindable(),
@@ -58,11 +59,19 @@
return apiKey.isStatic;
}
+ function isBootstrapApiKey(apiKey: ApiKey): boolean {
+ return apiKey.isBootstrap;
+ }
+
const selectedStaticApiKeyCount = $derived.by(
- () => apiKeys.data.filter((apiKey) => selectedIds.includes(apiKey.id) && isStaticApiKey(apiKey)).length
+ () =>
+ apiKeys.data.filter((apiKey) => selectedIds.includes(apiKey.id) && (isStaticApiKey(apiKey) || isBootstrapApiKey(apiKey)))
+ .length
);
const selectedDeletableApiKeyIds = $derived.by(() =>
- apiKeys.data.filter((apiKey) => selectedIds.includes(apiKey.id) && !isStaticApiKey(apiKey)).map((apiKey) => apiKey.id)
+ apiKeys.data
+ .filter((apiKey) => selectedIds.includes(apiKey.id) && !isStaticApiKey(apiKey) && !isBootstrapApiKey(apiKey))
+ .map((apiKey) => apiKey.id)
);
async function handleDeleteSelected() {
@@ -260,20 +269,24 @@
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Group>
- <DropdownMenu.Item onclick={() => onEditApiKey(item)} disabled={isStaticApiKey(item)}>
- <EditIcon class="size-4" />
- {m.common_edit()}
- </DropdownMenu.Item>
+ <IfPermitted perm="apikeys:update">
+ <DropdownMenu.Item onclick={() => onEditApiKey(item)} disabled={isStaticApiKey(item) || isBootstrapApiKey(item)}>
+ <EditIcon class="size-4" />
+ {m.common_edit()}
+ </DropdownMenu.Item>
+ </IfPermitted>
<DropdownMenu.Separator />
- <DropdownMenu.Item
- variant="destructive"
- onclick={() => handleDeleteApiKey(item.id, item.name)}
- disabled={isStaticApiKey(item)}
- >
- <TrashIcon class="size-4" />
- {m.common_delete()}
- </DropdownMenu.Item>
+ <IfPermitted perm="apikeys:delete">
+ <DropdownMenu.Item
+ variant="destructive"
+ onclick={() => handleDeleteApiKey(item.id, item.name)}
+ disabled={isStaticApiKey(item) || isBootstrapApiKey(item)}
+ >
+ <TrashIcon class="size-4" />
+ {m.common_delete()}
+ </DropdownMenu.Item>
+ </IfPermitted>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/(app)/settings/authentication/+page.svelte b/frontend/src/routes/(app)/settings/authentication/+page.svelte
index f918d8744..9007c1528 100644
--- a/frontend/src/routes/(app)/settings/authentication/+page.svelte
+++ b/frontend/src/routes/(app)/settings/authentication/+page.svelte
@@ -18,8 +18,68 @@
import * as Collapsible from '$lib/components/ui/collapsible';
import SettingsRow from '$lib/components/settings/settings-row.svelte';
import { cn } from '$lib/utils';
+ import OidcMappingTable from './oidc-mapping-table.svelte';
+ import OidcMappingFormSheet from '$lib/components/sheets/oidc-mapping-form-sheet.svelte';
+ import type { OidcRoleMapping, CreateOidcRoleMapping, UpdateOidcRoleMapping } from '$lib/types/role.type';
+ import { oidcMappingService } from '$lib/services/oidc-mapping-service';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import { untrack } from 'svelte';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
let { data }: PageProps = $props();
+
+ // OIDC role mappings — co-located with the OIDC settings so admins
+ // configure the groups claim and the mappings that read it in one place.
+ let oidcMappings = $state<OidcRoleMapping[]>(untrack(() => data.oidcMappings ?? []));
+ let mappingSheetOpen = $state(false);
+ let editingMapping = $state<OidcRoleMapping | null>(null);
+ let mappingSaving = $state(false);
+
+ async function refreshMappings() {
+ oidcMappings = await oidcMappingService.list();
+ }
+
+ function openCreateMapping() {
+ editingMapping = null;
+ mappingSheetOpen = true;
+ }
+
+ function openEditMapping(mapping: OidcRoleMapping) {
+ editingMapping = mapping;
+ mappingSheetOpen = true;
+ }
+
+ async function submitMapping(formData: { claimValue: string; roleId: string; environmentId?: string }) {
+ mappingSaving = true;
+ const payload: CreateOidcRoleMapping | UpdateOidcRoleMapping = formData;
+
+ if (editingMapping) {
+ const id = editingMapping.id;
+ handleApiResultWithCallbacks({
+ result: await tryCatch(oidcMappingService.update(id, payload)),
+ message: m.common_update_failed({ resource: m.resource_oidc_mapping() }),
+ setLoadingState: (v) => (mappingSaving = v),
+ onSuccess: async () => {
+ toast.success(m.common_update_success({ resource: m.resource_oidc_mapping_cap() }));
+ await refreshMappings();
+ mappingSheetOpen = false;
+ editingMapping = null;
+ }
+ });
+ } else {
+ handleApiResultWithCallbacks({
+ result: await tryCatch(oidcMappingService.create(payload)),
+ message: m.common_create_failed({ resource: m.resource_oidc_mapping() }),
+ setLoadingState: (v) => (mappingSaving = v),
+ onSuccess: async () => {
+ toast.success(m.common_create_success({ resource: m.resource_oidc_mapping_cap() }));
+ await refreshMappings();
+ mappingSheetOpen = false;
+ }
+ });
+ }
+ }
const currentSettings = $derived<Settings>($settingsStore || data.settings!);
const isReadOnly = $derived.by(() => $settingsStore.uiConfigDisabled);
const isAutoLoginEnabled = $derived(settingsStore.autoLoginEnabled.isEnabled());
@@ -41,8 +101,7 @@
oidcClientSecret: z.string(),
oidcIssuerUrl: z.string(),
oidcScopes: z.string(),
- oidcAdminClaim: z.string(),
- oidcAdminValue: z.string(),
+ oidcGroupsClaim: z.string(),
oidcProviderName: z.string(),
oidcProviderLogoUrl: z.string()
})
@@ -73,8 +132,7 @@
oidcClientSecret: '',
oidcIssuerUrl: currentSettings.oidcIssuerUrl,
oidcScopes: currentSettings.oidcScopes,
- oidcAdminClaim: currentSettings.oidcAdminClaim,
- oidcAdminValue: currentSettings.oidcAdminValue,
+ oidcGroupsClaim: currentSettings.oidcGroupsClaim,
oidcProviderName: currentSettings.oidcProviderName,
oidcProviderLogoUrl: currentSettings.oidcProviderLogoUrl
});
@@ -95,8 +153,7 @@
oidcClientSecret: '',
oidcIssuerUrl: ($settingsStore || data.settings!).oidcIssuerUrl,
oidcScopes: ($settingsStore || data.settings!).oidcScopes,
- oidcAdminClaim: ($settingsStore || data.settings!).oidcAdminClaim,
- oidcAdminValue: ($settingsStore || data.settings!).oidcAdminValue,
+ oidcGroupsClaim: ($settingsStore || data.settings!).oidcGroupsClaim,
oidcProviderName: ($settingsStore || data.settings!).oidcProviderName,
oidcProviderLogoUrl: ($settingsStore || data.settings!).oidcProviderLogoUrl
}),
@@ -115,8 +172,7 @@
$formInputs.oidcClientId.value !== currentSettings.oidcClientId ||
$formInputs.oidcIssuerUrl.value !== currentSettings.oidcIssuerUrl ||
$formInputs.oidcScopes.value !== currentSettings.oidcScopes ||
- $formInputs.oidcAdminClaim.value !== currentSettings.oidcAdminClaim ||
- $formInputs.oidcAdminValue.value !== currentSettings.oidcAdminValue ||
+ $formInputs.oidcGroupsClaim.value !== currentSettings.oidcGroupsClaim ||
$formInputs.oidcProviderName.value !== currentSettings.oidcProviderName ||
$formInputs.oidcProviderLogoUrl.value !== currentSettings.oidcProviderLogoUrl ||
$formInputs.oidcClientSecret.value !== ''
@@ -159,8 +215,7 @@
oidcClientId: formData.oidcClientId,
oidcIssuerUrl: formData.oidcIssuerUrl,
oidcScopes: formData.oidcScopes,
- oidcAdminClaim: formData.oidcAdminClaim,
- oidcAdminValue: formData.oidcAdminValue,
+ oidcGroupsClaim: formData.oidcGroupsClaim,
oidcProviderName: formData.oidcProviderName,
oidcProviderLogoUrl: formData.oidcProviderLogoUrl,
...(formData.oidcClientSecret && { oidcClientSecret: formData.oidcClientSecret })
@@ -364,31 +419,15 @@
error={$formInputs.oidcScopes.error}
/>
- <div class="space-y-3 pt-2">
- <div>
- <h4 class="text-sm font-semibold">{m.oidc_admin_role_mapping_title()}</h4>
- <p class="text-muted-foreground mt-0.5 text-xs">{m.oidc_admin_role_mapping_description()}</p>
- </div>
- <div class="grid gap-5 sm:grid-cols-2">
- <TextInputWithLabel
- id="oidcAdminClaim"
- label={m.oidc_admin_claim_label()}
- placeholder={m.oidc_admin_claim_placeholder()}
- disabled={isOidcEnvForced}
- bind:value={$formInputs.oidcAdminClaim.value}
- error={$formInputs.oidcAdminClaim.error}
- />
- <TextInputWithLabel
- id="oidcAdminValue"
- label={m.oidc_admin_value_label()}
- placeholder={m.oidc_admin_value_placeholder()}
- disabled={isOidcEnvForced}
- bind:value={$formInputs.oidcAdminValue.value}
- error={$formInputs.oidcAdminValue.error}
- helpText={m.oidc_admin_value_help()}
- />
- </div>
- </div>
+ <TextInputWithLabel
+ id="oidcGroupsClaim"
+ label={m.oidc_groups_claim_label()}
+ placeholder={m.oidc_groups_claim_placeholder()}
+ disabled={isOidcEnvForced}
+ bind:value={$formInputs.oidcGroupsClaim.value}
+ error={$formInputs.oidcGroupsClaim.error}
+ helpText={m.oidc_groups_claim_help()}
+ />
<div class="divide-border/40 divide-y pt-2 [&>*]:py-5 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0">
<SettingsRow
@@ -445,6 +484,37 @@
{/if}
</Collapsible.Root>
</div>
+
+ <IfPermitted adminOnly>
+ <div class="border-border/40 space-y-4 border-t pt-6">
+ <div class="flex items-start justify-between gap-4">
+ <div>
+ <h4 class="text-sm font-semibold">{m.oidc_role_mappings_title()}</h4>
+ <p class="text-muted-foreground mt-0.5 text-xs">{m.oidc_role_mappings_description()}</p>
+ </div>
+ <ArcaneButton
+ action="create"
+ tone="outline"
+ size="sm"
+ onclick={openCreateMapping}
+ customLabel={m.common_create_button({ resource: m.resource_oidc_mapping_cap() })}
+ />
+ </div>
+ {#if oidcMappings.length > 0}
+ <OidcMappingTable
+ mappings={oidcMappings}
+ roles={data.roles}
+ environments={data.environments}
+ onRefresh={refreshMappings}
+ onEdit={openEditMapping}
+ />
+ {:else}
+ <div class="border-border/40 bg-muted/20 rounded-lg border border-dashed p-6 text-center">
+ <p class="text-muted-foreground text-sm">{m.oidc_mappings_empty_body()}</p>
+ </div>
+ {/if}
+ </div>
+ </IfPermitted>
{/if}
</div>
@@ -530,5 +600,14 @@
</AlertDialog.Footer>
</AlertDialog.Content>
</AlertDialog.Root>
+
+ <OidcMappingFormSheet
+ bind:open={mappingSheetOpen}
+ mappingToEdit={editingMapping}
+ isLoading={mappingSaving}
+ roles={data.roles}
+ environments={data.environments}
+ onSubmit={submitMapping}
+ />
{/snippet}
</SettingsPageLayout>
diff --git a/frontend/src/routes/(app)/settings/authentication/+page.ts b/frontend/src/routes/(app)/settings/authentication/+page.ts
new file mode 100644
index 000000000..285d4a038
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/authentication/+page.ts
@@ -0,0 +1,27 @@
+import { oidcMappingService } from '$lib/services/oidc-mapping-service';
+import { roleService } from '$lib/services/role-service';
+import { environmentManagementService } from '$lib/services/env-mgmt-service';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = async ({ parent }) => {
+ const parentData = await parent();
+
+ // OIDC mappings live alongside the OIDC config in this page. We load them
+ // here (instead of a standalone /settings/oidc-mappings route) so admins
+ // configure groups claim + the mappings that read from it in one place.
+ const [mappings, roles, environmentsPage] = await Promise.all([
+ oidcMappingService.list(),
+ roleService.getAll(),
+ environmentManagementService.getEnvironments({
+ pagination: { page: 1, limit: 1000 },
+ sort: { column: 'name', direction: 'asc' }
+ })
+ ]);
+
+ return {
+ ...parentData,
+ oidcMappings: mappings,
+ roles,
+ environments: environmentsPage.data
+ };
+};
diff --git a/frontend/src/routes/(app)/settings/authentication/oidc-mapping-table.svelte b/frontend/src/routes/(app)/settings/authentication/oidc-mapping-table.svelte
new file mode 100644
index 000000000..a8595c5cf
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/authentication/oidc-mapping-table.svelte
@@ -0,0 +1,253 @@
+<script lang="ts">
+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import { toast } from 'svelte-sonner';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import type { OidcRoleMapping, Role } from '$lib/types/role.type';
+ import type { Environment } from '$lib/types/environment.type';
+ import { BUILT_IN_ROLE_ADMIN, BUILT_IN_ROLE_EDITOR, BUILT_IN_ROLE_DEPLOYER, BUILT_IN_ROLE_VIEWER } from '$lib/types/role.type';
+ import type { ColumnSpec, MobileFieldVisibility } from '$lib/components/arcane-table';
+ import { UniversalMobileCard } from '$lib/components/arcane-table';
+ import { m } from '$lib/paraglide/messages';
+ import { oidcMappingService } from '$lib/services/oidc-mapping-service';
+ import { ShieldAlertIcon, TrashIcon, EditIcon, EllipsisIcon } from '$lib/icons';
+
+ let {
+ mappings,
+ roles,
+ environments,
+ onRefresh,
+ onEdit
+ }: {
+ mappings: OidcRoleMapping[];
+ roles: Role[];
+ environments: Environment[];
+ onRefresh: () => Promise<void>;
+ onEdit: (mapping: OidcRoleMapping) => void;
+ } = $props();
+
+ let isLoading = $state({
+ removing: false
+ });
+
+ type BadgeVariant = 'red' | 'blue' | 'purple' | 'gray' | 'green' | 'amber';
+ type IconVariant = 'emerald' | 'red' | 'amber' | 'blue' | 'purple' | 'gray' | 'sky' | 'orange';
+
+ const rolesById = $derived.by(() => {
+ const lookup: Record<string, Role> = {};
+ for (const role of roles) lookup[role.id] = role;
+ return lookup;
+ });
+
+ const envsById = $derived.by(() => {
+ const lookup: Record<string, Environment> = {};
+ for (const env of environments) lookup[env.id] = env;
+ return lookup;
+ });
+
+ function getRoleBadgeVariant(role: Role | undefined): BadgeVariant {
+ if (!role) return 'gray';
+ if (!role.builtIn) return 'green';
+ switch (role.id) {
+ case BUILT_IN_ROLE_ADMIN:
+ return 'red';
+ case BUILT_IN_ROLE_EDITOR:
+ return 'blue';
+ case BUILT_IN_ROLE_DEPLOYER:
+ return 'purple';
+ case BUILT_IN_ROLE_VIEWER:
+ return 'gray';
+ default:
+ return 'green';
+ }
+ }
+
+ function getRoleIconVariant(role: Role | undefined): IconVariant {
+ const v = getRoleBadgeVariant(role);
+ return v === 'green' ? 'emerald' : v;
+ }
+
+ function getRoleName(roleId: string): string {
+ return rolesById[roleId]?.name ?? roleId;
+ }
+
+ function getEnvName(environmentId: string | undefined): string {
+ if (!environmentId) return m.users_role_assignments_scope_global();
+ return envsById[environmentId]?.name ?? environmentId;
+ }
+
+ // ArcaneTable expects Paginated<T>; this list is unpaginated so we synthesize it.
+ const paginatedMappings = $derived.by<Paginated<OidcRoleMapping>>(() => ({
+ data: mappings,
+ pagination: {
+ totalPages: 1,
+ totalItems: mappings.length,
+ currentPage: 1,
+ itemsPerPage: Math.max(mappings.length, 1)
+ }
+ }));
+
+ let requestOptions = $state<SearchPaginationSortRequest>({
+ pagination: { page: 1, limit: 1000 },
+ sort: { column: 'claimValue', direction: 'asc' }
+ });
+
+ let selectedIds = $state<string[]>([]);
+
+ async function handleDeleteMapping(mapping: OidcRoleMapping) {
+ const safeClaim = mapping.claimValue?.trim() || m.common_unknown();
+ openConfirmDialog({
+ // TODO: i18n — add oidc_mappings_delete_title key
+ title: 'Delete OIDC mapping?',
+ message: m.oidc_mappings_delete_message({ claim: safeClaim }),
+ confirm: {
+ label: m.common_delete(),
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+ handleApiResultWithCallbacks({
+ result: await tryCatch(oidcMappingService.delete(mapping.id)),
+ // TODO: i18n — add oidc_mappings_delete_failed key
+ message: 'Failed to delete mapping',
+ setLoadingState: (value) => (isLoading.removing = value),
+ onSuccess: async () => {
+ // TODO: i18n — add oidc_mappings_delete_success key
+ toast.success('Mapping deleted');
+ await onRefresh();
+ }
+ });
+ }
+ }
+ });
+ }
+
+ const columns = [
+ { id: 'claimValue', accessorKey: 'claimValue', title: m.oidc_mappings_col_claim(), sortable: true, cell: ClaimCell },
+ {
+ id: 'roleId',
+ accessorKey: 'roleId',
+ title: 'Role' /* TODO: i18n — add oidc_mappings_col_role key */,
+ sortable: true,
+ cell: RoleCell
+ },
+ {
+ id: 'environmentId',
+ accessorKey: 'environmentId',
+ title: m.oidc_mappings_col_scope(),
+ sortable: true,
+ cell: ScopeCell
+ }
+ ] satisfies ColumnSpec<OidcRoleMapping>[];
+
+ const mobileFields = [
+ { id: 'roleId', label: 'Role' /* TODO: i18n — add oidc_mappings_col_role key */, defaultVisible: true },
+ { id: 'environmentId', label: m.oidc_mappings_col_scope(), defaultVisible: true }
+ ];
+
+ let mobileFieldVisibility = $state<Record<string, boolean>>({});
+</script>
+
+{#snippet ClaimCell({ item }: { item: OidcRoleMapping })}
+ <div class="flex items-center gap-2">
+ <code class="bg-muted rounded px-2 py-1 text-xs">{item.claimValue}</code>
+ {#if item.source === 'env'}
+ <StatusBadge text="ENV" variant="amber" size="sm" minWidth="none" />
+ {/if}
+ </div>
+{/snippet}
+
+{#snippet RoleCell({ item }: { item: OidcRoleMapping })}
+ {@const role = rolesById[item.roleId]}
+ <StatusBadge text={getRoleName(item.roleId)} variant={getRoleBadgeVariant(role)} />
+{/snippet}
+
+{#snippet ScopeCell({ item }: { item: OidcRoleMapping })}
+ <span class={item.environmentId ? '' : 'text-muted-foreground italic'}>{getEnvName(item.environmentId)}</span>
+{/snippet}
+
+{#snippet OidcMappingMobileCardSnippet({
+ item,
+ mobileFieldVisibility
+}: {
+ item: OidcRoleMapping;
+ mobileFieldVisibility: MobileFieldVisibility;
+})}
+ {@const role = rolesById[item.roleId]}
+ <UniversalMobileCard
+ {item}
+ icon={{ component: ShieldAlertIcon, variant: getRoleIconVariant(role) }}
+ title={(item: OidcRoleMapping) => item.claimValue}
+ subtitle={() => null}
+ badges={[
+ (item: OidcRoleMapping) => ({
+ variant: getRoleBadgeVariant(rolesById[item.roleId]),
+ text: getRoleName(item.roleId)
+ })
+ ]}
+ fields={[
+ {
+ label: m.oidc_mappings_col_scope(),
+ getValue: (item: OidcRoleMapping) => getEnvName(item.environmentId),
+ icon: ShieldAlertIcon,
+ iconVariant: 'gray' as const,
+ show: mobileFieldVisibility['environmentId'] ?? true
+ }
+ ]}
+ rowActions={RowActions}
+ />
+{/snippet}
+
+{#snippet RowActions({ item }: { item: OidcRoleMapping })}
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <ArcaneButton {...props} action="base" tone="ghost" size="icon" class="size-8">
+ <span class="sr-only">{m.common_open_menu()}</span>
+ <EllipsisIcon class="size-4" />
+ </ArcaneButton>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Group>
+ <DropdownMenu.Item disabled={item.source === 'env'} onclick={() => onEdit(item)}>
+ <EditIcon class="size-4" />
+ {m.common_edit()}
+ </DropdownMenu.Item>
+
+ <DropdownMenu.Separator />
+
+ <DropdownMenu.Item
+ variant="destructive"
+ disabled={isLoading.removing || item.source === 'env'}
+ onclick={() => handleDeleteMapping(item)}
+ >
+ <TrashIcon class="size-4" />
+ {m.common_delete()}
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+{/snippet}
+
+<ArcaneTable
+ persistKey="arcane-oidc-mappings-table"
+ items={paginatedMappings}
+ bind:requestOptions
+ bind:selectedIds
+ bind:mobileFieldVisibility
+ selectionDisabled
+ withoutPagination
+ onRefresh={async () => {
+ await onRefresh();
+ return paginatedMappings;
+ }}
+ {columns}
+ {mobileFields}
+ rowActions={RowActions}
+ mobileCard={OidcMappingMobileCardSnippet}
+/>
diff --git a/frontend/src/routes/(app)/settings/roles/+page.svelte b/frontend/src/routes/(app)/settings/roles/+page.svelte
new file mode 100644
index 000000000..4e8f83882
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/roles/+page.svelte
@@ -0,0 +1,48 @@
+<script lang="ts">
+ import { ShieldAlertIcon } from '$lib/icons';
+ import { goto } from '$app/navigation';
+ import { untrack } from 'svelte';
+ import RolesTable from './roles-table.svelte';
+ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import { m } from '$lib/paraglide/messages';
+ import { roleService } from '$lib/services/role-service';
+ import { SettingsPageLayout, type SettingsActionButton } from '$lib/layouts/index.js';
+ import userStore from '$lib/stores/user-store';
+
+ let { data } = $props();
+
+ const isAdmin = $derived(userStore.isGlobalAdmin());
+
+ let roles = $state(untrack(() => data.roles));
+ let selectedIds = $state<string[]>([]);
+ let requestOptions = $state<SearchPaginationSortRequest>(untrack(() => data.rolesRequestOptions));
+
+ async function refreshRoles() {
+ roles = await roleService.getRoles(requestOptions);
+ }
+
+ const actionButtons: SettingsActionButton[] = $derived.by(() =>
+ !isAdmin
+ ? []
+ : [
+ {
+ id: 'create',
+ action: 'create',
+ label: m.common_create_button({ resource: m.resource_role_cap() }),
+ onclick: () => goto('/settings/roles/new')
+ }
+ ]
+ );
+</script>
+
+<SettingsPageLayout
+ title={m.roles_title()}
+ description={m.roles_subtitle()}
+ icon={ShieldAlertIcon}
+ pageType="management"
+ {actionButtons}
+>
+ {#snippet mainContent()}
+ <RolesTable bind:roles bind:selectedIds bind:requestOptions onRolesChanged={refreshRoles} />
+ {/snippet}
+</SettingsPageLayout>
diff --git a/frontend/src/routes/(app)/settings/roles/+page.ts b/frontend/src/routes/(app)/settings/roles/+page.ts
new file mode 100644
index 000000000..5cdecb749
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/roles/+page.ts
@@ -0,0 +1,35 @@
+import { roleService } from '$lib/services/role-service';
+import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
+import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = async ({ parent }) => {
+ const { queryClient } = await parent();
+
+ const rolesRequestOptions = resolveInitialTableRequest('arcane-roles-table', {
+ pagination: {
+ page: 1,
+ limit: 20
+ },
+ sort: {
+ column: 'name',
+ direction: 'asc'
+ }
+ } satisfies SearchPaginationSortRequest);
+
+ const roles = await queryClient.fetchQuery({
+ queryKey: ['roles', 'list', rolesRequestOptions],
+ queryFn: () => roleService.getRoles(rolesRequestOptions)
+ });
+
+ const permissionsManifest = await queryClient.fetchQuery({
+ queryKey: ['roles', 'permissions-manifest'],
+ queryFn: () => roleService.getPermissionsManifest()
+ });
+
+ return {
+ roles,
+ permissionsManifest,
+ rolesRequestOptions
+ };
+};
diff --git a/frontend/src/routes/(app)/settings/roles/[id]/+page.svelte b/frontend/src/routes/(app)/settings/roles/[id]/+page.svelte
new file mode 100644
index 000000000..2ef12e35b
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/roles/[id]/+page.svelte
@@ -0,0 +1,56 @@
+<script lang="ts">
+ import { toast } from 'svelte-sonner';
+ import { goto } from '$app/navigation';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import RoleEditor from '$lib/components/role-editor/role-editor.svelte';
+ import type { UpdateRole, CreateRole } from '$lib/types/role.type';
+ import { m } from '$lib/paraglide/messages';
+ import { roleService } from '$lib/services/role-service';
+ import { SettingsPageLayout } from '$lib/layouts/index.js';
+ import { ShieldAlertIcon } from '$lib/icons';
+
+ let { data } = $props();
+
+ let isLoading = $state(false);
+
+ async function handleSubmit(payload: UpdateRole) {
+ isLoading = true;
+ const safeName = payload.name?.trim() || data.role.name || m.common_unknown();
+ handleApiResultWithCallbacks({
+ result: await tryCatch(roleService.update(data.role.id, payload)),
+ message: m.common_update_failed({ resource: `${m.resource_role()} "${safeName}"` }),
+ setLoadingState: (value) => (isLoading = value),
+ onSuccess: async () => {
+ toast.success(m.common_update_success({ resource: `${m.resource_role()} "${safeName}"` }));
+ await goto('/settings/roles');
+ }
+ });
+ }
+
+ async function handleClone() {
+ isLoading = true;
+ const clonePayload: CreateRole = {
+ name: `${data.role.name} (copy)`,
+ description: data.role.description,
+ permissions: [...data.role.permissions]
+ };
+
+ const result = await tryCatch(roleService.create(clonePayload));
+ handleApiResultWithCallbacks({
+ result,
+ message: m.roles_clone_failed(),
+ setLoadingState: (value) => (isLoading = value),
+ onSuccess: async (newRole) => {
+ toast.success(m.roles_clone_success({ name: newRole.name }));
+ await goto(`/settings/roles/${newRole.id}`);
+ }
+ });
+ }
+</script>
+
+<SettingsPageLayout title={m.roles_edit_title()} description={m.roles_subtitle()} icon={ShieldAlertIcon} pageType="form">
+ {#snippet mainContent()}
+ <RoleEditor role={data.role} manifest={data.permissionsManifest} {isLoading} onSubmit={handleSubmit} onClone={handleClone} />
+ {/snippet}
+</SettingsPageLayout>
diff --git a/frontend/src/routes/(app)/settings/roles/[id]/+page.ts b/frontend/src/routes/(app)/settings/roles/[id]/+page.ts
new file mode 100644
index 000000000..b65a97d20
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/roles/[id]/+page.ts
@@ -0,0 +1,37 @@
+import { error, redirect } from '@sveltejs/kit';
+import { roleService } from '$lib/services/role-service';
+import { userIsGlobalAdmin } from '$lib/utils/redirect.util';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = async ({ parent, params }) => {
+ const { queryClient, user } = await parent();
+
+ // Role editing is reserved for global admins (matches RequireGlobalAdmin on
+ // PUT /roles/{id}). Guard here so the role payload isn't fetched for users
+ // who'll be redirected by the layout effect anyway.
+ if (!userIsGlobalAdmin(user)) {
+ throw redirect(302, '/settings/roles');
+ }
+
+ const [role, permissionsManifest] = await Promise.all([
+ queryClient
+ .fetchQuery({
+ queryKey: ['roles', 'detail', params.id],
+ queryFn: () => roleService.get(params.id)
+ })
+ .catch(() => null),
+ queryClient.fetchQuery({
+ queryKey: ['roles', 'permissions-manifest'],
+ queryFn: () => roleService.getPermissionsManifest()
+ })
+ ]);
+
+ if (!role) {
+ throw error(404, 'Role not found');
+ }
+
+ return {
+ role,
+ permissionsManifest
+ };
+};
diff --git a/frontend/src/routes/(app)/settings/roles/new/+page.svelte b/frontend/src/routes/(app)/settings/roles/new/+page.svelte
new file mode 100644
index 000000000..604bd5ba1
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/roles/new/+page.svelte
@@ -0,0 +1,36 @@
+<script lang="ts">
+ import { toast } from 'svelte-sonner';
+ import { goto } from '$app/navigation';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import RoleEditor from '$lib/components/role-editor/role-editor.svelte';
+ import type { CreateRole } from '$lib/types/role.type';
+ import { m } from '$lib/paraglide/messages';
+ import { roleService } from '$lib/services/role-service';
+ import { SettingsPageLayout } from '$lib/layouts/index.js';
+ import { ShieldAlertIcon } from '$lib/icons';
+
+ let { data } = $props();
+
+ let isLoading = $state(false);
+
+ async function handleSubmit(payload: CreateRole) {
+ isLoading = true;
+ const safeName = payload.name?.trim() || m.common_unknown();
+ handleApiResultWithCallbacks({
+ result: await tryCatch(roleService.create(payload)),
+ message: m.common_create_failed({ resource: `${m.resource_role()} "${safeName}"` }),
+ setLoadingState: (value) => (isLoading = value),
+ onSuccess: async () => {
+ toast.success(m.common_create_success({ resource: `${m.resource_role()} "${safeName}"` }));
+ await goto('/settings/roles');
+ }
+ });
+ }
+</script>
+
+<SettingsPageLayout title={m.roles_create_title()} description={m.roles_subtitle()} icon={ShieldAlertIcon} pageType="form">
+ {#snippet mainContent()}
+ <RoleEditor role={null} manifest={data.permissionsManifest} {isLoading} onSubmit={handleSubmit} />
+ {/snippet}
+</SettingsPageLayout>
diff --git a/frontend/src/routes/(app)/settings/roles/new/+page.ts b/frontend/src/routes/(app)/settings/roles/new/+page.ts
new file mode 100644
index 000000000..c9d89ac7f
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/roles/new/+page.ts
@@ -0,0 +1,25 @@
+import { redirect } from '@sveltejs/kit';
+import { roleService } from '$lib/services/role-service';
+import { userIsGlobalAdmin } from '$lib/utils/redirect.util';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = async ({ parent }) => {
+ const { queryClient, user } = await parent();
+
+ // Role creation is reserved for global admins (matches RequireGlobalAdmin
+ // on POST /roles). Guard here so non-admins are bounced before the
+ // permissions manifest is fetched.
+ if (!userIsGlobalAdmin(user)) {
+ throw redirect(302, '/settings/roles');
+ }
+
+ const permissionsManifest = await queryClient.fetchQuery({
+ queryKey: ['roles', 'permissions-manifest'],
+ queryFn: () => roleService.getPermissionsManifest()
+ });
+
+ return {
+ permissionsManifest,
+ role: null
+ };
+};
diff --git a/frontend/src/routes/(app)/settings/roles/roles-table.svelte b/frontend/src/routes/(app)/settings/roles/roles-table.svelte
new file mode 100644
index 000000000..84b472d17
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/roles/roles-table.svelte
@@ -0,0 +1,308 @@
+<script lang="ts">
+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import { toast } from 'svelte-sonner';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import * as ArcaneTooltip from '$lib/components/arcane-tooltip';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import StatusBadge from '$lib/components/badges/status-badge.svelte';
+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import { goto } from '$app/navigation';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
+ import type { Role } from '$lib/types/role.type';
+ import { BUILT_IN_ROLE_ADMIN, BUILT_IN_ROLE_EDITOR, BUILT_IN_ROLE_DEPLOYER, BUILT_IN_ROLE_VIEWER } from '$lib/types/role.type';
+ import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '$lib/components/arcane-table';
+ import { UniversalMobileCard } from '$lib/components/arcane-table';
+ import { m } from '$lib/paraglide/messages';
+ import { roleService } from '$lib/services/role-service';
+ import { ShieldAlertIcon, TrashIcon, EditIcon, EllipsisIcon } from '$lib/icons';
+ import userStore from '$lib/stores/user-store';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
+
+ let {
+ roles = $bindable(),
+ selectedIds = $bindable(),
+ requestOptions = $bindable(),
+ onRolesChanged
+ }: {
+ roles: Paginated<Role>;
+ selectedIds: string[];
+ requestOptions: SearchPaginationSortRequest;
+ onRolesChanged: () => Promise<void>;
+ } = $props();
+
+ const isAdmin = $derived(userStore.isGlobalAdmin());
+
+ let isLoading = $state({
+ removing: false
+ });
+
+ type BadgeVariant = 'red' | 'blue' | 'purple' | 'gray' | 'green' | 'amber';
+ type IconVariant = 'emerald' | 'red' | 'amber' | 'blue' | 'purple' | 'gray' | 'sky' | 'orange';
+
+ function getRoleBadgeVariant(role: Role): BadgeVariant {
+ if (!role.builtIn) return 'green';
+ switch (role.id) {
+ case BUILT_IN_ROLE_ADMIN:
+ return 'red';
+ case BUILT_IN_ROLE_EDITOR:
+ return 'blue';
+ case BUILT_IN_ROLE_DEPLOYER:
+ return 'purple';
+ case BUILT_IN_ROLE_VIEWER:
+ return 'gray';
+ default:
+ return 'green';
+ }
+ }
+
+ function getRoleIconVariant(role: Role): IconVariant {
+ const v = getRoleBadgeVariant(role);
+ return v === 'green' ? 'emerald' : v;
+ }
+
+ const selectedRoles = $derived.by(() =>
+ (selectedIds ?? []).map((id) => roles.data.find((role) => role.id === id)).filter((role): role is Role => Boolean(role))
+ );
+
+ const deletableSelectedIds = $derived.by(() => selectedRoles.filter((role) => !role.builtIn).map((role) => role.id));
+ const hasBuiltInSelection = $derived.by(() => selectedRoles.some((role) => role.builtIn));
+
+ async function handleDeleteSelected() {
+ if (deletableSelectedIds.length === 0) return;
+
+ openConfirmDialog({
+ // TODO: i18n — add roles_delete_selected_title key
+ title: `Delete ${deletableSelectedIds.length} role${deletableSelectedIds.length === 1 ? '' : 's'}?`,
+ message: m.roles_delete_message({ name: m.common_unknown() }),
+ confirm: {
+ label: m.common_delete(),
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+ let successCount = 0;
+ let failureCount = 0;
+
+ for (const roleId of deletableSelectedIds) {
+ const result = await tryCatch(roleService.delete(roleId));
+ handleApiResultWithCallbacks({
+ result,
+ message: m.common_delete_failed({ resource: `${m.resource_role()} "${roleId}"` }),
+ setLoadingState: () => {},
+ onSuccess: () => {
+ successCount++;
+ }
+ });
+
+ if (result.error) {
+ failureCount++;
+ }
+ }
+
+ isLoading.removing = false;
+
+ if (successCount > 0) {
+ toast.success(m.common_bulk_delete_success({ count: successCount, resource: m.roles_title() }));
+ await onRolesChanged();
+ }
+
+ if (failureCount > 0) {
+ toast.error(m.common_bulk_delete_failed({ count: failureCount, resource: m.roles_title() }));
+ }
+
+ selectedIds = [];
+ }
+ }
+ });
+ }
+
+ async function handleDeleteRole(role: Role) {
+ if (role.builtIn) return;
+
+ const safeName = role.name?.trim() || m.common_unknown();
+ openConfirmDialog({
+ // TODO: i18n — add roles_delete_title key
+ title: `Delete role "${safeName}"?`,
+ message: m.roles_delete_message({ name: safeName }),
+ confirm: {
+ label: m.common_delete(),
+ destructive: true,
+ action: async () => {
+ isLoading.removing = true;
+ handleApiResultWithCallbacks({
+ result: await tryCatch(roleService.delete(role.id)),
+ message: m.common_delete_failed({ resource: `${m.resource_role()} "${safeName}"` }),
+ setLoadingState: (value) => (isLoading.removing = value),
+ onSuccess: async () => {
+ toast.success(m.common_delete_success({ resource: `${m.resource_role()} "${safeName}"` }));
+ await onRolesChanged();
+ }
+ });
+ }
+ }
+ });
+ }
+
+ const columns = [
+ // TODO: i18n — add roles_name_label and roles_description_label keys
+ { accessorKey: 'name', title: 'Name', sortable: true, cell: NameCell },
+ { accessorKey: 'description', title: 'Description', sortable: false, cell: DescriptionCell },
+ { id: 'type', accessorKey: 'builtIn', title: m.roles_col_type(), sortable: false, cell: TypeCell },
+ {
+ id: 'assignedUsers',
+ accessorKey: 'assignedUserCount',
+ title: m.roles_col_assigned_users(),
+ sortable: true,
+ cell: AssignedUsersCell
+ },
+ {
+ id: 'permissions',
+ accessorKey: 'permissions',
+ title: m.roles_col_permissions(),
+ sortable: false,
+ cell: PermissionsCell
+ }
+ ] satisfies ColumnSpec<Role>[];
+
+ const mobileFields = [
+ // TODO: i18n — add roles_description_label key
+ { id: 'description', label: 'Description', defaultVisible: true },
+ { id: 'permissions', label: m.roles_col_permissions(), defaultVisible: true },
+ { id: 'assignedUsers', label: m.roles_col_assigned_users(), defaultVisible: true }
+ ];
+
+ const bulkActions = $derived.by<BulkAction[]>(() => [
+ {
+ id: 'remove',
+ label: m.common_remove_selected_count({ count: selectedIds?.length ?? 0 }),
+ action: 'remove',
+ onClick: handleDeleteSelected,
+ loading: isLoading.removing,
+ disabled: isLoading.removing || deletableSelectedIds.length === 0 || hasBuiltInSelection || !isAdmin,
+ icon: TrashIcon
+ }
+ ]);
+
+ let mobileFieldVisibility = $state<Record<string, boolean>>({});
+</script>
+
+{#snippet NameCell({ item }: { item: Role })}
+ <div class="flex items-center gap-2">
+ <span class="font-medium">{item.name}</span>
+ </div>
+{/snippet}
+
+{#snippet DescriptionCell({ item }: { item: Role })}
+ {#if item.description}
+ <span class="text-sm">{item.description}</span>
+ {:else}
+ <span class="text-muted-foreground">-</span>
+ {/if}
+{/snippet}
+
+{#snippet TypeCell({ item }: { item: Role })}
+ <StatusBadge text={item.builtIn ? m.roles_built_in() : m.roles_custom()} variant={item.builtIn ? 'amber' : 'blue'} />
+{/snippet}
+
+{#snippet AssignedUsersCell({ item }: { item: Role })}
+ <span class="tabular-nums">{item.assignedUserCount === 1 ? '1 user' : `${item.assignedUserCount} users`}</span>
+{/snippet}
+
+{#snippet PermissionsCell({ item }: { item: Role })}
+ <ArcaneTooltip.Root>
+ <ArcaneTooltip.Trigger>
+ <span class="tabular-nums underline decoration-dotted underline-offset-4">{item.permissions.length}</span>
+ </ArcaneTooltip.Trigger>
+ <ArcaneTooltip.Content>
+ <p class="max-w-xs text-xs break-words">{item.permissions.join(', ')}</p>
+ </ArcaneTooltip.Content>
+ </ArcaneTooltip.Root>
+{/snippet}
+
+{#snippet RoleMobileCardSnippet({ item, mobileFieldVisibility }: { item: Role; mobileFieldVisibility: MobileFieldVisibility })}
+ <UniversalMobileCard
+ {item}
+ icon={{ component: ShieldAlertIcon, variant: getRoleIconVariant(item) }}
+ title={(item: Role) => item.name}
+ subtitle={(item: Role) => ((mobileFieldVisibility['description'] ?? true) && item.description ? item.description : null)}
+ badges={[
+ (item: Role) => ({
+ variant: item.builtIn ? 'amber' : 'blue',
+ text: item.builtIn ? m.roles_built_in() : m.roles_custom()
+ })
+ ]}
+ fields={[
+ {
+ label: m.roles_col_permissions(),
+ getValue: (item: Role) => String(item.permissions.length),
+ icon: ShieldAlertIcon,
+ iconVariant: 'gray' as const,
+ show: mobileFieldVisibility['permissions'] ?? true
+ },
+ {
+ label: m.roles_col_assigned_users(),
+ // TODO: i18n — roles_assigned_users_count has a malformed ICU plural in en.json
+ getValue: (item: Role) => (item.assignedUserCount === 1 ? '1 user' : `${item.assignedUserCount} users`),
+ icon: ShieldAlertIcon,
+ iconVariant: 'gray' as const,
+ show: mobileFieldVisibility['assignedUsers'] ?? true
+ }
+ ]}
+ rowActions={RowActions}
+ />
+{/snippet}
+
+{#snippet RowActions({ item }: { item: Role })}
+ {#if isAdmin}
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <ArcaneButton {...props} action="base" tone="ghost" size="icon" class="size-8">
+ <span class="sr-only">{m.common_open_menu()}</span>
+ <EllipsisIcon class="size-4" />
+ </ArcaneButton>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Group>
+ <IfPermitted adminOnly>
+ <DropdownMenu.Item onclick={() => goto(`/settings/roles/${item.id}`)}>
+ <EditIcon class="size-4" />
+ {m.common_edit()}
+ </DropdownMenu.Item>
+
+ <DropdownMenu.Separator />
+
+ <DropdownMenu.Item
+ variant="destructive"
+ disabled={item.builtIn || isLoading.removing}
+ onclick={() => handleDeleteRole(item)}
+ >
+ <TrashIcon class="size-4" />
+ {m.common_delete()}
+ </DropdownMenu.Item>
+ </IfPermitted>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ {/if}
+{/snippet}
+
+<ArcaneTable
+ persistKey="arcane-roles-table"
+ items={roles}
+ bind:requestOptions
+ bind:selectedIds
+ bind:mobileFieldVisibility
+ {bulkActions}
+ onRefresh={async (options) => {
+ requestOptions = options;
+ await onRolesChanged();
+ return roles;
+ }}
+ {columns}
+ {mobileFields}
+ rowActions={RowActions}
+ mobileCard={RoleMobileCardSnippet}
+/>
diff --git a/frontend/src/routes/(app)/settings/users/+page.svelte b/frontend/src/routes/(app)/settings/users/+page.svelte
index afa885a71..79a899b37 100644
--- a/frontend/src/routes/(app)/settings/users/+page.svelte
+++ b/frontend/src/routes/(app)/settings/users/+page.svelte
@@ -10,6 +10,8 @@
import type { CreateUser } from '$lib/types/user.type';
import { m } from '$lib/paraglide/messages';
import { userService } from '$lib/services/user-service';
+ import { roleService } from '$lib/services/role-service';
+ import userStore from '$lib/stores/user-store';
import { untrack } from 'svelte';
import { SettingsPageLayout, type SettingsActionButton } from '$lib/layouts/index.js';
@@ -26,6 +28,16 @@
let userToEdit = $state<User | null>(null);
+ // Role assignment is admin-only on the server. Non-admins editing users can
+ // still update profile fields but must not call the assignments endpoint.
+ const isAdmin = $derived(userStore.isGlobalAdmin());
+
+ // availableRoleAssignments for the edit form — strip the source field, the
+ // editor only needs (roleId, environmentId) tuples.
+ const editingAssignments = $derived(
+ userToEdit?.roleAssignments?.map((a) => ({ roleId: a.roleId, environmentId: a.environmentId })) ?? []
+ );
+
let isLoading = $state({
creating: false,
editing: false,
@@ -47,7 +59,10 @@
isEditMode,
userId
}: {
- user: Partial<User> & { password?: string };
+ user: Omit<Partial<User>, 'roleAssignments'> & {
+ password?: string;
+ roleAssignments?: { roleId: string; environmentId?: string }[];
+ };
isEditMode: boolean;
userId?: string;
}) {
@@ -57,12 +72,18 @@
try {
if (isEditMode && userId) {
const safeUsername = userToEdit?.username || m.common_unknown();
- const result = await tryCatch(userService.update(userId, user));
+ // Split: profile fields go to PUT /users/{id}; role assignments
+ // go to PUT /users/{id}/role-assignments (separate endpoint).
+ const { roleAssignments, ...profile } = user;
+ const result = await tryCatch(userService.update(userId, profile));
handleApiResultWithCallbacks({
result,
message: m.common_update_failed({ resource: `${m.resource_user()} "${safeUsername}"` }),
setLoadingState: (value) => (isLoading[loading] = value),
onSuccess: async () => {
+ if (isAdmin && roleAssignments) {
+ await roleService.setUserAssignments(userId, { assignments: roleAssignments });
+ }
toast.success(m.common_update_success({ resource: `${m.resource_user()} "${safeUsername}"` }));
users = await userService.getUsers(requestOptions);
isDialogOpen.edit = false;
@@ -82,8 +103,7 @@
username: user.username!,
displayName: user.displayName,
email: user.email,
- password: user.password!,
- roles: user.roles ?? ['user']
+ password: user.password!
};
const result = await tryCatch(userService.create(createUser));
@@ -91,7 +111,10 @@
result,
message: m.common_create_failed({ resource: `${m.resource_user()} "${safeUsername}"` }),
setLoadingState: (value) => (isLoading[loading] = value),
- onSuccess: async () => {
+ onSuccess: async (created) => {
+ if (isAdmin && user.roleAssignments && created?.id) {
+ await roleService.setUserAssignments(created.id, { assignments: user.roleAssignments });
+ }
toast.success(m.common_create_success({ resource: `${m.resource_user()} "${safeUsername}"` }));
users = await userService.getUsers(requestOptions);
isDialogOpen.create = false;
@@ -127,6 +150,7 @@
bind:users
bind:selectedIds
bind:requestOptions
+ roles={data.roles}
onUsersChanged={async () => {
users = await userService.getUsers(requestOptions);
}}
@@ -135,11 +159,22 @@
{/snippet}
{#snippet additionalContent()}
- <UserFormSheet bind:open={isDialogOpen.create} userToEdit={null} onSubmit={handleUserSubmit} isLoading={isLoading.creating} />
+ <UserFormSheet
+ bind:open={isDialogOpen.create}
+ userToEdit={null}
+ roles={data.roles}
+ environments={data.environments}
+ availableRoleAssignments={[]}
+ onSubmit={handleUserSubmit}
+ isLoading={isLoading.creating}
+ />
<UserFormSheet
bind:open={isDialogOpen.edit}
{userToEdit}
+ roles={data.roles}
+ environments={data.environments}
+ availableRoleAssignments={editingAssignments}
onSubmit={handleUserSubmit}
isLoading={isLoading.editing}
allowUsernameEdit={true}
diff --git a/frontend/src/routes/(app)/settings/users/+page.ts b/frontend/src/routes/(app)/settings/users/+page.ts
index bc8955355..9a3ff9674 100644
--- a/frontend/src/routes/(app)/settings/users/+page.ts
+++ b/frontend/src/routes/(app)/settings/users/+page.ts
@@ -1,4 +1,6 @@
import { userService } from '$lib/services/user-service';
+import { roleService } from '$lib/services/role-service';
+import { environmentManagementService } from '$lib/services/env-mgmt-service';
import { queryKeys } from '$lib/query/query-keys';
import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
import { resolveInitialTableRequest } from '$lib/utils/table-persistence.util';
@@ -18,13 +20,27 @@ export const load: PageLoad = async ({ parent }) => {
}
} satisfies SearchPaginationSortRequest);
- const users = await queryClient.fetchQuery({
- queryKey: queryKeys.users.list(userRequestOptions),
- queryFn: () => userService.getUsers(userRequestOptions)
- });
+ const [users, roles, environmentsPage] = await Promise.all([
+ queryClient.fetchQuery({
+ queryKey: queryKeys.users.list(userRequestOptions),
+ queryFn: () => userService.getUsers(userRequestOptions)
+ }),
+ queryClient.fetchQuery({
+ queryKey: ['roles', 'all'],
+ queryFn: () => roleService.getAll(),
+ staleTime: 30_000
+ }),
+ queryClient.fetchQuery({
+ queryKey: ['environments', 'all-for-role-assignments'],
+ queryFn: () => environmentManagementService.getEnvironments({ pagination: { page: 1, limit: 1000 } }),
+ staleTime: 30_000
+ })
+ ]);
return {
users,
- userRequestOptions
+ userRequestOptions,
+ roles,
+ environments: environmentsPage.data
};
};
diff --git a/frontend/src/routes/(app)/settings/users/user-table.svelte b/frontend/src/routes/(app)/settings/users/user-table.svelte
index fd0aaffce..53b4b164e 100644
--- a/frontend/src/routes/(app)/settings/users/user-table.svelte
+++ b/frontend/src/routes/(app)/settings/users/user-table.svelte
@@ -9,26 +9,33 @@
import { tryCatch } from '$lib/utils/try-catch';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
import type { User } from '$lib/types/user.type';
+ import type { Role } from '$lib/types/role.type';
+ import { BUILT_IN_ROLE_ADMIN, BUILT_IN_ROLE_EDITOR, BUILT_IN_ROLE_DEPLOYER, BUILT_IN_ROLE_VIEWER } from '$lib/types/role.type';
import type { ColumnSpec, MobileFieldVisibility, BulkAction } from '$lib/components/arcane-table';
import { UniversalMobileCard } from '$lib/components/arcane-table';
import { m } from '$lib/paraglide/messages';
import { userService } from '$lib/services/user-service';
import { UserIcon, TrashIcon, EditIcon, EllipsisIcon } from '$lib/icons';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
let {
users = $bindable(),
selectedIds = $bindable(),
requestOptions = $bindable(),
+ roles,
onUsersChanged,
onEditUser
}: {
users: Paginated<User>;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
+ roles: Role[];
onUsersChanged: () => Promise<void>;
onEditUser: (user: User) => void;
} = $props();
+ const rolesById = $derived(new Map(roles.map((r) => [r.id, r])));
+
let isLoading = $state({
removing: false
});
@@ -118,27 +125,72 @@
});
}
- function getRoleBadgeVariant(roles: string[]) {
- if (roles?.includes('admin')) return 'red';
- return 'green';
+ type BadgeVariant = 'red' | 'blue' | 'purple' | 'gray' | 'green';
+
+ /** True when the user holds the built-in Admin role globally. */
+ function isGlobalAdmin(user: User): boolean {
+ return !!user.roleAssignments?.some((a) => a.roleId === BUILT_IN_ROLE_ADMIN && !a.environmentId);
+ }
+
+ /** Color variant for a role badge keyed off the role ID (not its localized name). */
+ function roleVariant(roleId: string): BadgeVariant {
+ switch (roleId) {
+ case BUILT_IN_ROLE_ADMIN:
+ return 'red';
+ case BUILT_IN_ROLE_EDITOR:
+ return 'blue';
+ case BUILT_IN_ROLE_DEPLOYER:
+ return 'purple';
+ case BUILT_IN_ROLE_VIEWER:
+ return 'gray';
+ default:
+ return 'green'; // custom roles
+ }
}
- function getRoleText(roles: string[]) {
- if (roles?.includes('admin')) return m.common_admin();
- return m.common_user();
+ function roleName(roleId: string): string {
+ return rolesById.get(roleId)?.name ?? m.common_unknown();
+ }
+
+ /**
+ * Resolves what to render in the Role column for a given user. Three states:
+ * - no assignments → single "No access" gray badge
+ * - holds global Admin → single "Admin" red badge (collapses any other rows)
+ * - everything else → one badge per distinct role, with a tooltip
+ * listing which environments each scope applies to
+ */
+ function rolesSummary(user: User): { text: string; variant: BadgeVariant; tooltip?: string }[] {
+ const assignments = user.roleAssignments ?? [];
+ if (assignments.length === 0) {
+ return [{ text: m.users_role_summary_none(), variant: 'gray' }];
+ }
+ if (isGlobalAdmin(user)) {
+ return [{ text: m.common_admin(), variant: 'red' }];
+ }
+ // Group by roleId so a user assigned the same role on multiple envs gets
+ // one badge with a tooltip listing the env count.
+ const byRole = new Map<string, number>();
+ for (const a of assignments) {
+ byRole.set(a.roleId, (byRole.get(a.roleId) ?? 0) + 1);
+ }
+ return Array.from(byRole.entries()).map(([roleId, count]) => ({
+ text: roleName(roleId),
+ variant: roleVariant(roleId),
+ tooltip: count > 1 ? m.users_role_summary_env_count({ count }) : undefined
+ }));
}
const columns = [
{ accessorKey: 'username', title: m.common_username(), sortable: true, cell: UsernameCell },
{ accessorKey: 'displayName', title: m.common_display_name(), sortable: true, cell: DisplayNameCell },
{ accessorKey: 'email', title: m.common_email(), sortable: true, cell: EmailCell },
- { accessorKey: 'roles', title: m.common_role(), sortable: true, cell: RoleCell }
+ { accessorKey: 'roleAssignments', title: m.common_role(), sortable: false, cell: RoleCell }
] satisfies ColumnSpec<User>[];
const mobileFields = [
{ id: 'displayName', label: m.common_display_name(), defaultVisible: true },
{ id: 'email', label: m.common_email(), defaultVisible: true },
- { id: 'roles', label: m.common_role(), defaultVisible: true }
+ { id: 'roleAssignments', label: m.common_role(), defaultVisible: true }
];
const bulkActions = $derived.by<BulkAction[]>(() => [
@@ -169,7 +221,11 @@
{/snippet}
{#snippet RoleCell({ item }: { item: User })}
- <StatusBadge text={getRoleText(item.roles)} variant={getRoleBadgeVariant(item.roles)} />
+ <div class="flex flex-wrap items-center gap-1">
+ {#each rolesSummary(item) as badge (badge.text)}
+ <StatusBadge text={badge.text} variant={badge.variant} tooltip={badge.tooltip} />
+ {/each}
+ </div>
{/snippet}
{#snippet UserMobileCardSnippet({ item, mobileFieldVisibility }: { item: User; mobileFieldVisibility: MobileFieldVisibility })}
@@ -179,13 +235,18 @@
title={(item: User) => item.username}
subtitle={(item: User) => ((mobileFieldVisibility['email'] ?? true) && item.email ? item.email : null)}
badges={[
- (item: User) =>
- (mobileFieldVisibility['roles'] ?? true)
- ? {
- variant: getRoleBadgeVariant(item.roles) === 'red' ? 'red' : 'green',
- text: getRoleText(item.roles)
- }
- : null
+ (item: User) => {
+ if (!(mobileFieldVisibility['roleAssignments'] ?? true)) return null;
+ const summary = rolesSummary(item);
+ // Mobile cards take a single badge; show the first (or a "+N" hint
+ // when the user has multiple distinct roles).
+ const [head, ...rest] = summary;
+ if (!head) return null;
+ if (rest.length === 0) {
+ return { variant: head.variant, text: head.text };
+ }
+ return { variant: head.variant, text: `${head.text} +${rest.length}` };
+ }
]}
fields={[
{
@@ -213,22 +274,26 @@
<DropdownMenu.Content align="end">
<DropdownMenu.Group>
{#if !item.oidcSubjectId}
- <DropdownMenu.Item onclick={() => onEditUser(item)}>
- <EditIcon class="size-4" />
- {m.common_edit()}
- </DropdownMenu.Item>
+ <IfPermitted perm="users:update">
+ <DropdownMenu.Item onclick={() => onEditUser(item)}>
+ <EditIcon class="size-4" />
+ {m.common_edit()}
+ </DropdownMenu.Item>
- <DropdownMenu.Separator />
+ <DropdownMenu.Separator />
+ </IfPermitted>
{/if}
- <DropdownMenu.Item
- variant="destructive"
- disabled={!canDeleteUser(item) || isLoading.removing}
- onclick={() => handleDeleteUser(item)}
- >
- <TrashIcon class="size-4" />
- {m.common_delete()}
- </DropdownMenu.Item>
+ <IfPermitted perm="users:delete">
+ <DropdownMenu.Item
+ variant="destructive"
+ disabled={!canDeleteUser(item) || isLoading.removing}
+ onclick={() => handleDeleteUser(item)}
+ >
+ <TrashIcon class="size-4" />
+ {m.common_delete()}
+ </DropdownMenu.Item>
+ </IfPermitted>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/(app)/settings/webhooks/webhook-table.svelte b/frontend/src/routes/(app)/settings/webhooks/webhook-table.svelte
index 21f82aaf1..d1c1e6ce6 100644
--- a/frontend/src/routes/(app)/settings/webhooks/webhook-table.svelte
+++ b/frontend/src/routes/(app)/settings/webhooks/webhook-table.svelte
@@ -15,6 +15,7 @@
import { webhookService } from '$lib/services/webhook-service';
import { TrashIcon, EllipsisIcon, GlobeIcon } from '$lib/icons';
import * as m from '$lib/paraglide/messages.js';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
let {
webhooks = $bindable(),
@@ -298,14 +299,18 @@
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Group>
- <DropdownMenu.Item onclick={() => handleToggleWebhook(item)} disabled={isLoading.toggling}>
- {item.enabled ? m.webhook_disable() : m.webhook_enable()}
- </DropdownMenu.Item>
+ <IfPermitted perm="webhooks:update">
+ <DropdownMenu.Item onclick={() => handleToggleWebhook(item)} disabled={isLoading.toggling}>
+ {item.enabled ? m.webhook_disable() : m.webhook_enable()}
+ </DropdownMenu.Item>
+ </IfPermitted>
<DropdownMenu.Separator />
- <DropdownMenu.Item variant="destructive" onclick={() => handleDeleteWebhook(item.id, item.name)}>
- <TrashIcon class="size-4" />
- {m.common_delete()}
- </DropdownMenu.Item>
+ <IfPermitted perm="webhooks:delete">
+ <DropdownMenu.Item variant="destructive" onclick={() => handleDeleteWebhook(item.id, item.name)}>
+ <TrashIcon class="size-4" />
+ {m.common_delete()}
+ </DropdownMenu.Item>
+ </IfPermitted>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/(app)/swarm/cluster/+page.svelte b/frontend/src/routes/(app)/swarm/cluster/+page.svelte
index ee722745c..fc43a3bfd 100644
--- a/frontend/src/routes/(app)/swarm/cluster/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/cluster/+page.svelte
@@ -12,7 +12,8 @@
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';
import { m } from '$lib/paraglide/messages';
import { swarmService } from '$lib/services/swarm-service';
- import userStore from '$lib/stores/user-store';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
import type {
SwarmInfo,
SwarmInitRequest,
@@ -22,13 +23,12 @@
} from '$lib/types/swarm.type';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
- import { fromStore } from 'svelte/store';
import { toast } from 'svelte-sonner';
let {}: PageProps = $props();
- const storeUser = fromStore(userStore);
- const isAdmin = $derived(!!storeUser.current?.roles?.includes('admin'));
+ const currentEnvId = $derived(environmentStore.selected?.id);
+ const canManageSwarm = $derived(hasPermission('swarm:nodes', currentEnvId));
let swarmInfo = $state<SwarmInfo | null>(null);
let joinTokens = $state<SwarmJoinTokensResponse | null>(null);
@@ -304,7 +304,7 @@
size="sm"
customLabel={m.common_actions()}
onclick={() => (securityDialogOpen = true)}
- disabled={!isAdmin}
+ disabled={!canManageSwarm}
/>
</Card.Action>
</Card.Header>
@@ -336,7 +336,7 @@
size="sm"
customLabel={m.swarm_cluster_rotate_tokens()}
onclick={handleRotateTokens}
- disabled={!isAdmin || !isSwarmInitialized || isLoading.rotateTokens}
+ disabled={!canManageSwarm || !isSwarmInitialized || isLoading.rotateTokens}
loading={isLoading.rotateTokens}
/>
</Card.Action>
@@ -440,7 +440,7 @@
action="create"
customLabel={m.swarm_cluster_initialize_action()}
onclick={handleInit}
- disabled={!isAdmin || isLoading.init}
+ disabled={!canManageSwarm || isLoading.init}
loading={isLoading.init}
/>
</Card.Content>
@@ -466,7 +466,7 @@
action="create"
customLabel={m.swarm_cluster_join_action()}
onclick={handleJoin}
- disabled={!isAdmin || isLoading.join}
+ disabled={!canManageSwarm || isLoading.join}
loading={isLoading.join}
/>
</Card.Content>
@@ -512,7 +512,7 @@
action="save"
customLabel={m.swarm_cluster_update_spec_action()}
onclick={handleUpdateSpec}
- disabled={!isAdmin || isLoading.updateSpec}
+ disabled={!canManageSwarm || isLoading.updateSpec}
loading={isLoading.updateSpec}
/>
</div>
@@ -543,7 +543,7 @@
action="save"
customLabel={m.swarm_cluster_unlock_action()}
onclick={handleUnlock}
- disabled={!isAdmin || isLoading.unlock}
+ disabled={!canManageSwarm || isLoading.unlock}
loading={isLoading.unlock}
/>
</div>
@@ -558,7 +558,7 @@
action="remove"
customLabel={m.swarm_cluster_leave_action()}
onclick={handleLeave}
- disabled={!isAdmin || isLoading.leave}
+ disabled={!canManageSwarm || isLoading.leave}
loading={isLoading.leave}
/>
</div>
diff --git a/frontend/src/routes/(app)/swarm/configs/+page.svelte b/frontend/src/routes/(app)/swarm/configs/+page.svelte
index 8f681ae81..0c1ef62f0 100644
--- a/frontend/src/routes/(app)/swarm/configs/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/configs/+page.svelte
@@ -9,19 +9,20 @@
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';
import { m } from '$lib/paraglide/messages';
import { swarmService } from '$lib/services/swarm-service';
- import userStore from '$lib/stores/user-store';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
import type { SwarmConfigSummary } from '$lib/types/swarm.type';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
- import { fromStore } from 'svelte/store';
import { toast } from 'svelte-sonner';
import { formatDistanceToNow } from 'date-fns';
import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
let {}: PageProps = $props();
- const storeUser = fromStore(userStore);
- const isAdmin = $derived(!!storeUser.current?.roles?.includes('admin'));
+ const currentEnvId = $derived(environmentStore.selected?.id);
+ const canManageConfigs = $derived(hasPermission('swarm:configs', currentEnvId));
let configs = $state<SwarmConfigSummary[]>([]);
let selectedConfigId = $state('');
@@ -195,13 +196,15 @@
placeholder={m.swarm_configs_data_placeholder()}
class="font-mono text-xs"
/>
- <ArcaneButton
- action="create"
- customLabel={m.swarm_configs_create_button()}
- onclick={createConfig}
- disabled={!isAdmin || isLoading.create}
- loading={isLoading.create}
- />
+ <IfPermitted perm="swarm:configs">
+ <ArcaneButton
+ action="create"
+ customLabel={m.swarm_configs_create_button()}
+ onclick={createConfig}
+ disabled={!canManageConfigs || isLoading.create}
+ loading={isLoading.create}
+ />
+ </IfPermitted>
</Card.Content>
</Card.Root>
@@ -252,7 +255,7 @@
customLabel={m.swarm_configs_delete_button()}
icon={TrashIcon}
onclick={() => removeConfig(config)}
- disabled={!isAdmin || isLoading.delete}
+ disabled={!canManageConfigs || isLoading.delete}
loading={isLoading.delete}
/>
</div>
diff --git a/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte b/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte
index e03343d18..5ec062b94 100644
--- a/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte
+++ b/frontend/src/routes/(app)/swarm/nodes/nodes-table.svelte
@@ -26,8 +26,8 @@
import { tryCatch } from '$lib/utils/try-catch';
import { extractApiErrorMessage, handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { goto } from '$app/navigation';
- import userStore from '$lib/stores/user-store';
- import { fromStore } from 'svelte/store';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
import SwarmNodeAgentDialog from './swarm-node-agent-dialog.svelte';
import SwarmNodeLabelDialog from './swarm-node-label-dialog.svelte';
import { getSwarmNodeAgentActionLabel, getSwarmNodeAgentLabel, getSwarmNodeAgentVariant } from './agent-status';
@@ -40,8 +40,8 @@
requestOptions: SearchPaginationSortRequest;
} = $props();
- const storeUser = fromStore(userStore);
- const isAdmin = $derived(!!storeUser.current?.roles?.includes('admin'));
+ const currentEnvId = $derived(environmentStore.selected?.id);
+ const canManageNodes = $derived(hasPermission('swarm:nodes', currentEnvId));
let isLoading = $state(false);
let isAgentDialogOpen = $state(false);
let selectedNode = $state<SwarmNodeSummary | null>(null);
@@ -275,7 +275,7 @@
{#each Object.entries(item.labels ?? {}) as [key, value] (key)}
<div class="group relative overflow-hidden rounded-[var(--radius)]">
<StatusBadge text={`${key}${value ? `=${value}` : ''}`} variant="blue" minWidth="none" class="max-w-[200px] truncate" />
- {#if isAdmin}
+ {#if canManageNodes}
<button
class="absolute inset-0 flex cursor-pointer items-center justify-end rounded-[var(--radius)] bg-blue-500/10 pr-1 opacity-0 backdrop-blur-[1px] transition-opacity group-hover:opacity-100 dark:bg-blue-400/20"
onclick={() => removeLabel(item, key)}
@@ -288,7 +288,7 @@
{/if}
</div>
{/each}
- {#if isAdmin}
+ {#if canManageNodes}
<button
class="border-border hover:border-primary hover:text-primary inline-flex items-center gap-1 rounded border border-dashed px-2 py-0.5 text-[11px] font-medium transition-colors"
onclick={() => openAddLabelDialog(item)}
@@ -377,31 +377,31 @@
<InspectIcon class="size-4" />
{m.common_inspect()}
</DropdownMenu.Item>
- <DropdownMenu.Item onclick={() => openAgentDialog(item)} disabled={!isAdmin}>
+ <DropdownMenu.Item onclick={() => openAgentDialog(item)} disabled={!canManageNodes}>
<EdgeConnectionIcon class="size-4" />
{getSwarmNodeAgentActionLabel(item.agent?.state)}
</DropdownMenu.Item>
<DropdownMenu.Separator />
- <DropdownMenu.Item onclick={() => promoteNode(item)} disabled={!isAdmin || isLoading || item.role === 'manager'}>
+ <DropdownMenu.Item onclick={() => promoteNode(item)} disabled={!canManageNodes || isLoading || item.role === 'manager'}>
{m.swarm_node_promote()}
</DropdownMenu.Item>
- <DropdownMenu.Item onclick={() => demoteNode(item)} disabled={!isAdmin || isLoading || item.role !== 'manager'}>
+ <DropdownMenu.Item onclick={() => demoteNode(item)} disabled={!canManageNodes || isLoading || item.role !== 'manager'}>
{m.swarm_node_demote()}
</DropdownMenu.Item>
<DropdownMenu.Item
onclick={() => setAvailability(item, 'drain')}
- disabled={!isAdmin || isLoading || item.availability === 'drain'}
+ disabled={!canManageNodes || isLoading || item.availability === 'drain'}
>
{m.swarm_node_drain()}
</DropdownMenu.Item>
<DropdownMenu.Item
onclick={() => setAvailability(item, 'active')}
- disabled={!isAdmin || isLoading || item.availability === 'active'}
+ disabled={!canManageNodes || isLoading || item.availability === 'active'}
>
{m.swarm_node_activate()}
</DropdownMenu.Item>
<DropdownMenu.Separator />
- <DropdownMenu.Item variant="destructive" onclick={() => removeNode(item)} disabled={!isAdmin || isLoading}>
+ <DropdownMenu.Item variant="destructive" onclick={() => removeNode(item)} disabled={!canManageNodes || isLoading}>
<TrashIcon class="size-4" />
{m.common_delete()}
</DropdownMenu.Item>
diff --git a/frontend/src/routes/(app)/swarm/secrets/+page.svelte b/frontend/src/routes/(app)/swarm/secrets/+page.svelte
index c1c18fdfa..ab5aafc0e 100644
--- a/frontend/src/routes/(app)/swarm/secrets/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/secrets/+page.svelte
@@ -9,19 +9,20 @@
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';
import { m } from '$lib/paraglide/messages';
import { swarmService } from '$lib/services/swarm-service';
- import userStore from '$lib/stores/user-store';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
import type { SwarmSecretSummary } from '$lib/types/swarm.type';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
- import { fromStore } from 'svelte/store';
import { toast } from 'svelte-sonner';
import { formatDistanceToNow } from 'date-fns';
import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
let {}: PageProps = $props();
- const storeUser = fromStore(userStore);
- const isAdmin = $derived(!!storeUser.current?.roles?.includes('admin'));
+ const currentEnvId = $derived(environmentStore.selected?.id);
+ const canManageSecrets = $derived(hasPermission('swarm:secrets', currentEnvId));
let secrets = $state<SwarmSecretSummary[]>([]);
let selectedSecretId = $state('');
@@ -195,13 +196,15 @@
placeholder={m.swarm_secrets_data_placeholder()}
class="font-mono text-xs"
/>
- <ArcaneButton
- action="create"
- customLabel={m.swarm_secrets_create_button()}
- onclick={createSecret}
- disabled={!isAdmin || isLoading.create}
- loading={isLoading.create}
- />
+ <IfPermitted perm="swarm:secrets">
+ <ArcaneButton
+ action="create"
+ customLabel={m.swarm_secrets_create_button()}
+ onclick={createSecret}
+ disabled={!canManageSecrets || isLoading.create}
+ loading={isLoading.create}
+ />
+ </IfPermitted>
</Card.Content>
</Card.Root>
@@ -252,7 +255,7 @@
customLabel={m.swarm_secrets_delete_button()}
icon={TrashIcon}
onclick={() => removeSecret(secret)}
- disabled={!isAdmin || isLoading.delete}
+ disabled={!canManageSecrets || isLoading.delete}
loading={isLoading.delete}
/>
</div>
diff --git a/frontend/src/routes/(app)/swarm/services/+page.svelte b/frontend/src/routes/(app)/swarm/services/+page.svelte
index 5ff38bd63..0d465e771 100644
--- a/frontend/src/routes/(app)/swarm/services/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/services/+page.svelte
@@ -12,6 +12,8 @@
import type { SwarmServiceCreateSpec } from '$lib/types/swarm.type';
import SwarmServicesTable from './services-table.svelte';
import CreateServiceDialog from '$lib/components/dialogs/create-service-dialog.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
let { data } = $props();
@@ -39,6 +41,9 @@
const totalServices = $derived(services?.pagination?.totalItems ?? services?.data?.length ?? 0);
+ const currentEnvId = $derived(environmentStore.selected?.id);
+ const canCreateService = $derived(hasPermission('swarm:services', currentEnvId));
+
async function handleCreateService(spec: SwarmServiceCreateSpec) {
handleApiResultWithCallbacks({
result: await tryCatch(swarmService.createService({ spec })),
@@ -52,22 +57,26 @@
});
}
- const actionButtons: ActionButton[] = $derived([
- {
- id: 'create',
- action: 'create',
- label: m.common_create_button({ resource: m.swarm_service() }),
- onclick: () => (showCreateDialog = true)
- },
- {
+ const actionButtons: ActionButton[] = $derived.by(() => {
+ const buttons: ActionButton[] = [];
+ if (canCreateService) {
+ buttons.push({
+ id: 'create',
+ action: 'create',
+ label: m.common_create_button({ resource: m.swarm_service() }),
+ onclick: () => (showCreateDialog = true)
+ });
+ }
+ buttons.push({
id: 'refresh',
action: 'restart',
label: m.common_refresh(),
onclick: refresh,
loading: isLoading.refresh,
disabled: isLoading.refresh
- }
- ]);
+ });
+ return buttons;
+ });
const statCards: StatCardConfig[] = $derived([
{
diff --git a/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.svelte b/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.svelte
index aeb5350fb..bdbde7ef6 100644
--- a/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/services/[serviceId]/+page.svelte
@@ -51,6 +51,8 @@
getSwarmServiceModeVariant,
isSwarmServiceModeScalable
} from '$lib/utils/swarm-service-mode.utils';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
let { data } = $props();
let service = $derived(data?.service as SwarmServiceInspect);
@@ -169,9 +171,12 @@
const showNetworkTab = $derived(hasPorts || hasNetworks);
const hasMounts = $derived(mounts.length > 0);
+ const envId = $derived(environmentStore.selected?.id || '0');
+ const canViewServiceLogs = $derived(hasPermission('swarm:services:logs', envId));
+
const tabItems = $derived<TabItem[]>([
{ value: 'overview', label: m.common_overview(), icon: DockIcon },
- { value: 'logs', label: m.common_logs(), icon: FileTextIcon },
+ ...(canViewServiceLogs ? [{ value: 'logs', label: m.common_logs(), icon: FileTextIcon }] : []),
{ value: 'tasks', label: m.swarm_tasks_title(), icon: JobsIcon },
...(showConfiguration ? [{ value: 'config', label: m.common_configuration(), icon: SettingsIcon }] : []),
...(showNetworkTab ? [{ value: 'network', label: m.containers_nav_networks(), icon: NetworksIcon }] : []),
diff --git a/frontend/src/routes/(app)/swarm/services/services-table.svelte b/frontend/src/routes/(app)/swarm/services/services-table.svelte
index 22cba4008..8cd40551c 100644
--- a/frontend/src/routes/(app)/swarm/services/services-table.svelte
+++ b/frontend/src/routes/(app)/swarm/services/services-table.svelte
@@ -16,6 +16,7 @@
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { goto } from '$app/navigation';
import { getSwarmServiceModeLabel, getSwarmServiceModeVariant } from '$lib/utils/swarm-service-mode.utils';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
let {
services = $bindable(),
@@ -248,10 +249,12 @@
{m.common_inspect()}
</DropdownMenu.Item>
<DropdownMenu.Separator />
- <DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)} disabled={isAnyLoading}>
- <TrashIcon class="size-4" />
- {m.common_delete()}
- </DropdownMenu.Item>
+ <IfPermitted perm="swarm:services">
+ <DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)} disabled={isAnyLoading}>
+ <TrashIcon class="size-4" />
+ {m.common_delete()}
+ </DropdownMenu.Item>
+ </IfPermitted>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/(app)/swarm/stacks/+page.svelte b/frontend/src/routes/(app)/swarm/stacks/+page.svelte
index 897214e9a..eef6f3476 100644
--- a/frontend/src/routes/(app)/swarm/stacks/+page.svelte
+++ b/frontend/src/routes/(app)/swarm/stacks/+page.svelte
@@ -8,6 +8,8 @@
import { parallelRefresh } from '$lib/utils/refresh.util';
import SwarmStacksTable from './stacks-table.svelte';
import { goto } from '$app/navigation';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
let { data } = $props();
@@ -34,22 +36,29 @@
const totalStacks = $derived(stacks?.pagination?.totalItems ?? stacks?.data?.length ?? 0);
- const actionButtons: ActionButton[] = $derived([
- {
- id: 'create',
- action: 'create',
- label: m.common_create_button({ resource: m.swarm_stack() }),
- onclick: () => goto('/swarm/stacks/new')
- },
- {
+ const currentEnvId = $derived(environmentStore.selected?.id);
+ const canCreateStack = $derived(hasPermission('swarm:stacks', currentEnvId));
+
+ const actionButtons: ActionButton[] = $derived.by(() => {
+ const buttons: ActionButton[] = [];
+ if (canCreateStack) {
+ buttons.push({
+ id: 'create',
+ action: 'create',
+ label: m.common_create_button({ resource: m.swarm_stack() }),
+ onclick: () => goto('/swarm/stacks/new')
+ });
+ }
+ buttons.push({
id: 'refresh',
action: 'restart',
label: m.common_refresh(),
onclick: refresh,
loading: isLoading.refresh,
disabled: isLoading.refresh
- }
- ]);
+ });
+ return buttons;
+ });
const statCards: StatCardConfig[] = $derived([
{
diff --git a/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte b/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte
index 1685df224..aae468676 100644
--- a/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte
+++ b/frontend/src/routes/(app)/swarm/stacks/stacks-table.svelte
@@ -15,6 +15,7 @@
import { tryCatch } from '$lib/utils/try-catch';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { goto } from '$app/navigation';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
let {
stacks = $bindable(),
@@ -141,10 +142,12 @@
{m.common_inspect()}
</DropdownMenu.Item>
<DropdownMenu.Separator />
- <DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)} disabled={isLoading}>
- <TrashIcon class="size-4" />
- {m.common_delete()}
- </DropdownMenu.Item>
+ <IfPermitted perm="swarm:stacks">
+ <DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)} disabled={isLoading}>
+ <TrashIcon class="size-4" />
+ {m.common_delete()}
+ </DropdownMenu.Item>
+ </IfPermitted>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/(app)/updates/container-updates-table.svelte b/frontend/src/routes/(app)/updates/container-updates-table.svelte
index a2787160f..6a09c3c8b 100644
--- a/frontend/src/routes/(app)/updates/container-updates-table.svelte
+++ b/frontend/src/routes/(app)/updates/container-updates-table.svelte
@@ -16,8 +16,7 @@
} from '$lib/services/container-service';
import { ContainersIcon, UpdateIcon } from '$lib/icons';
import { getContainerDisplayName } from '../containers/container-table.helpers';
- import userStore from '$lib/stores/user-store';
- import { fromStore } from 'svelte/store';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
type ContainerUpdateRow = {
id: string;
@@ -43,9 +42,6 @@
let mobileFieldVisibility = $state<MobileFieldVisibility>({});
let updatingContainerIds = $state<Record<string, boolean>>({});
- const storeUser = fromStore(userStore);
- const isAdmin = $derived(!!storeUser.current?.roles?.includes('admin'));
-
function formatUpdateValue(updateInfo: ImageUpdateInfoDto | undefined, mode: 'current' | 'latest') {
if (!updateInfo) return '-';
@@ -164,7 +160,7 @@
{/snippet}
{#snippet ActionsCell({ item }: { item: ContainerUpdateRow })}
- {#if isAdmin}
+ <IfPermitted perm="containers:autoupdate">
<ArcaneButton
action="update"
size="sm"
@@ -174,7 +170,7 @@
disabled={!!updatingContainerIds[item.containerId]}
icon={UpdateIcon}
/>
- {/if}
+ </IfPermitted>
{/snippet}
{#snippet ContainerUpdatesMobileCard({ item }: { item: ContainerUpdateRow })}
diff --git a/frontend/src/routes/(app)/volumes/+page.svelte b/frontend/src/routes/(app)/volumes/+page.svelte
index 9c88c0e13..7d9c11a89 100644
--- a/frontend/src/routes/(app)/volumes/+page.svelte
+++ b/frontend/src/routes/(app)/volumes/+page.svelte
@@ -7,6 +7,7 @@
import { m } from '$lib/paraglide/messages';
import { volumeService } from '$lib/services/volume-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
import { queryKeys } from '$lib/query/query-keys';
import { untrack } from 'svelte';
import { ResourcePageLayout, type ActionButton, type StatCardConfig } from '$lib/layouts/index.js';
@@ -59,24 +60,30 @@
const isRefreshing = $derived(volumesQuery.isFetching && !volumesQuery.isPending);
const volumeUsageCounts = $derived(volumes.counts ?? countsFallback);
- const actionButtons: ActionButton[] = $derived([
- {
- id: 'create',
- action: 'create',
- label: m.common_create_button({ resource: m.resource_volume_cap() }),
- onclick: () => (isCreateDialogOpen = true),
- loading: createVolumeMutation.isPending,
- disabled: createVolumeMutation.isPending
- },
- {
+ const canCreateVolume = $derived(hasPermission('volumes:create', envId));
+
+ const actionButtons: ActionButton[] = $derived.by(() => {
+ const buttons: ActionButton[] = [];
+ if (canCreateVolume) {
+ buttons.push({
+ id: 'create',
+ action: 'create',
+ label: m.common_create_button({ resource: m.resource_volume_cap() }),
+ onclick: () => (isCreateDialogOpen = true),
+ loading: createVolumeMutation.isPending,
+ disabled: createVolumeMutation.isPending
+ });
+ }
+ buttons.push({
id: 'refresh',
action: 'restart',
label: m.common_refresh(),
onclick: refresh,
loading: isRefreshing,
disabled: isRefreshing
- }
- ]);
+ });
+ return buttons;
+ });
const statCards: StatCardConfig[] = $derived([
{
diff --git a/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte b/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte
index f79662604..b71023ab2 100644
--- a/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte
+++ b/frontend/src/routes/(app)/volumes/[volumeName]/+page.svelte
@@ -18,6 +18,8 @@
import { VolumeBrowser } from '$lib/components/file-browser';
import BackupList from '../components/volume-backup-table.svelte';
import settingsStore from '$lib/stores/config-store';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
let { data } = $props();
let volume = $state(untrack(() => data.volume));
@@ -26,6 +28,9 @@
const backupVolumeName = $derived.by(() => $settingsStore?.backupVolumeName || 'arcane-backups');
const isBackupVolume = $derived(volume?.name === backupVolumeName);
+ const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const canDeleteVolume = $derived(hasPermission('volumes:delete', currentEnvId));
+
let isLoading = $state({ remove: false });
const createdDate = $derived(volume.createdAt ? format(new Date(volume.createdAt), 'PP p') : m.common_unknown());
@@ -65,16 +70,20 @@
});
}
- const actions: DetailAction[] = $derived([
- {
- id: 'remove',
- action: 'remove',
- label: m.common_remove(),
- loading: isLoading.remove,
- disabled: isLoading.remove || isBackupVolume,
- onclick: () => handleRemoveVolumeConfirm(volume.name)
- }
- ]);
+ const actions: DetailAction[] = $derived(
+ canDeleteVolume
+ ? [
+ {
+ id: 'remove',
+ action: 'remove' as const,
+ label: m.common_remove(),
+ loading: isLoading.remove,
+ disabled: isLoading.remove || isBackupVolume,
+ onclick: () => handleRemoveVolumeConfirm(volume.name)
+ }
+ ]
+ : []
+ );
function onTabChange(value: string) {
selectedTab = value;
diff --git a/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte b/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
index b9a1b8d01..ecb9d6b38 100644
--- a/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
+++ b/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
@@ -31,9 +31,15 @@
import { ScrollArea } from '$lib/components/ui/scroll-area';
import * as Checkbox from '$lib/components/ui/checkbox';
import * as Alert from '$lib/components/ui/alert';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
let { volumeName }: { volumeName: string } = $props();
+ const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const canBackupVolume = $derived(hasPermission('volumes:backup', currentEnvId));
+
let backupsPaginated = $state<VolumeBackupListResponse>({
data: [],
pagination: {
@@ -243,38 +249,44 @@
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end">
<DropdownMenu.Group>
- <DropdownMenu.Item onclick={() => handleRestore(item)}>
- <RestartIcon class="size-4" />
- Restore
- </DropdownMenu.Item>
- <DropdownMenu.Item onclick={() => openRestoreFilesDialog(item)}>
- <FileTextIcon class="size-4" />
- Restore files
- </DropdownMenu.Item>
+ {#if canBackupVolume}
+ <DropdownMenu.Item onclick={() => handleRestore(item)}>
+ <RestartIcon class="size-4" />
+ Restore
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => openRestoreFilesDialog(item)}>
+ <FileTextIcon class="size-4" />
+ Restore files
+ </DropdownMenu.Item>
+ {/if}
<DropdownMenu.Item onclick={() => volumeBackupService.downloadBackup(item.id)}>
<DownloadIcon class="size-4" />
{m.templates_download()}
</DropdownMenu.Item>
- <DropdownMenu.Separator />
- <DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)}>
- <TrashIcon class="size-4" />
- {m.common_remove()}
- </DropdownMenu.Item>
+ <IfPermitted perm="volumes:delete">
+ <DropdownMenu.Separator />
+ <DropdownMenu.Item variant="destructive" onclick={() => handleDelete(item)}>
+ <TrashIcon class="size-4" />
+ {m.common_remove()}
+ </DropdownMenu.Item>
+ </IfPermitted>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
{/snippet}
{#snippet ToolbarActions()}
- <ArcaneButton
- action="create"
- customLabel={m.volumes_backup_create()}
- loading={creating}
- disabled={creating}
- onclick={handleCreate}
- size="sm"
- icon={AddIcon}
- />
+ {#if canBackupVolume}
+ <ArcaneButton
+ action="create"
+ customLabel={m.volumes_backup_create()}
+ loading={creating}
+ disabled={creating}
+ onclick={handleCreate}
+ size="sm"
+ icon={AddIcon}
+ />
+ {/if}
{/snippet}
{#snippet BackupMobileCardSnippet({
@@ -397,12 +409,14 @@
backupFilesSearch = '';
}}
/>
- <ArcaneButton
- action="create"
- customLabel="Restore files"
- onclick={handleRestoreFiles}
- loading={restoringFiles}
- disabled={restoringFiles || selectedPaths.length === 0}
- />
+ {#if canBackupVolume}
+ <ArcaneButton
+ action="create"
+ customLabel="Restore files"
+ onclick={handleRestoreFiles}
+ loading={restoringFiles}
+ disabled={restoringFiles || selectedPaths.length === 0}
+ />
+ {/if}
{/snippet}
</ResponsiveDialog>
diff --git a/frontend/src/routes/(app)/volumes/volume-table.svelte b/frontend/src/routes/(app)/volumes/volume-table.svelte
index 5ef4d3a48..daf111f5f 100644
--- a/frontend/src/routes/(app)/volumes/volume-table.svelte
+++ b/frontend/src/routes/(app)/volumes/volume-table.svelte
@@ -22,6 +22,8 @@
import settingsStore from '$lib/stores/config-store';
import { onMount } from 'svelte';
import { SvelteMap } from 'svelte/reactivity';
+ import { environmentStore } from '$lib/stores/environment.store.svelte';
+ import { hasPermission } from '$lib/utils/permissions.util';
let {
volumes = $bindable(),
@@ -38,6 +40,9 @@
let isLoading = $state({
removing: false
});
+
+ const currentEnvId = $derived(environmentStore.selected?.id || '0');
+ const canDeleteVolume = $derived(hasPermission('volumes:delete', currentEnvId));
let customSettings = $state<Record<string, unknown>>({});
let showInternal = $derived.by(() => {
return (customSettings['showInternalVolumes'] as boolean) ?? false;
@@ -201,7 +206,7 @@
action: 'remove',
onClick: () => handleDeleteSelected(deletableSelectedIds),
loading: isLoading.removing,
- disabled: isLoading.removing || deletableSelectedIds.length === 0,
+ disabled: !canDeleteVolume || isLoading.removing || deletableSelectedIds.length === 0,
icon: TrashIcon
}
]);
@@ -318,16 +323,18 @@
{m.common_inspect()}
</DropdownMenu.Item>
- <DropdownMenu.Separator />
+ {#if canDeleteVolume}
+ <DropdownMenu.Separator />
- <DropdownMenu.Item
- variant="destructive"
- onclick={() => handleRemoveVolumeConfirm(item.name)}
- disabled={item.inUse || isBackupVolume(item)}
- >
- <TrashIcon class="size-4" />
- {m.common_remove()}
- </DropdownMenu.Item>
+ <DropdownMenu.Item
+ variant="destructive"
+ onclick={() => handleRemoveVolumeConfirm(item.name)}
+ disabled={item.inUse || isBackupVolume(item)}
+ >
+ <TrashIcon class="size-4" />
+ {m.common_remove()}
+ </DropdownMenu.Item>
+ {/if}
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
diff --git a/frontend/src/routes/(auth)/oidc/callback/+page.svelte b/frontend/src/routes/(auth)/oidc/callback/+page.svelte
index f53f5e071..f61aff06e 100644
--- a/frontend/src/routes/(auth)/oidc/callback/+page.svelte
+++ b/frontend/src/routes/(auth)/oidc/callback/+page.svelte
@@ -86,6 +86,9 @@
};
},
onSuccess: async ({ authResult, redirectTo }) => {
+ // Build a placeholder user from the OIDC response. The real user
+ // (with role assignments + permissions) is fetched by invalidateAll
+ // below, which re-runs the root +layout.ts loader.
const user: User = {
id: authResult.user!.sub || authResult.user!.email || '',
username: authResult.user!.preferred_username || authResult.user!.email || '',
@@ -97,17 +100,28 @@
authResult.user!.preferred_username ||
authResult.user!.email ||
m.common_unknown(),
- roles: authResult.user!.groups || ['user'],
+ roleAssignments: [],
+ permissionsByEnv: {},
createdAt: new Date().toISOString()
};
userStore.setUser(user);
+ // invalidateAll re-runs the root +layout.ts loader, which fetches
+ // settings (with a graceful catch). We don't fetch them here directly
+ // — a user with zero/limited permissions would 403 on settings:read
+ // and crash this handler, leaving them stuck on a white screen.
await invalidateAll();
- const settings = await queryClient.fetchQuery({
- queryKey: queryKeys.settings.global(),
- queryFn: () => settingsService.getSettings()
- });
- settingsStore.set(settings);
+ try {
+ const settings = await queryClient.fetchQuery({
+ queryKey: queryKeys.settings.global(),
+ queryFn: () => settingsService.getSettings()
+ });
+ settingsStore.set(settings);
+ } catch (err) {
+ // User lacks settings:read or settings fetch failed — not fatal;
+ // the root layout already pulls public settings as a fallback.
+ console.warn('Skipping post-login settings fetch:', err);
+ }
toast.success('Successfully logged in!');
await goto(redirectTo, { replaceState: true });
},
@@ -163,6 +177,12 @@
<p class="mt-2 text-sm">{error}</p>
<p class="text-muted-foreground mt-4 text-xs">{m.auth_redirecting_to_login()}</p>
</div>
+ {:else}
+ <!-- Defensive fallback: if neither branch matches (e.g. an
+ unexpected throw inside onSuccess), the user would otherwise
+ see a blank page with no way out. Always show a logout link. -->
+ <p class="text-muted-foreground text-sm">{m.auth_processing_login()}</p>
+ <a href="/logout" class="text-primary mt-6 text-xs underline">{m.common_logout()}</a>
{/if}
</div>
</div>
diff --git a/tests/spec/api-keys.spec.ts b/tests/spec/api-keys.spec.ts
index a1123c79f..531eec264 100644
--- a/tests/spec/api-keys.spec.ts
+++ b/tests/spec/api-keys.spec.ts
@@ -67,6 +67,10 @@ test.describe('API Keys Page', () => {
await descInput.fill('E2E test API key');
}
+ // Select at least one permission (form requires min 1)
+ await createDialog.getByPlaceholder(/Filter permissions/i).fill('containers:list');
+ await createDialog.getByRole('checkbox', { name: 'Select all' }).check();
+
// Submit the form
await createDialog.getByRole('button', { name: /Create API Key/i }).click();
@@ -131,6 +135,11 @@ test.describe('API Keys Page', () => {
const apiKeyName = `delete-test-${Date.now()}`;
await createDialog.getByLabel(/Name/i).fill(apiKeyName);
+
+ // Select at least one permission (form requires min 1)
+ await createDialog.getByPlaceholder(/Filter permissions/i).fill('containers:list');
+ await createDialog.getByRole('checkbox', { name: 'Select all' }).check();
+
await createDialog.getByRole('button', { name: /Create API Key/i }).click();
// Wait for creation success and close reveal dialog
diff --git a/tests/spec/cli.spec.ts b/tests/spec/cli.spec.ts
index 85f678be8..9c4853a77 100644
--- a/tests/spec/cli.spec.ts
+++ b/tests/spec/cli.spec.ts
@@ -335,13 +335,18 @@ test.describe('arcane-cli e2e', () => {
let created: CreatedApiKey | undefined;
try {
+ // API keys must carry at least one permission grant in the new
+ // RBAC model — the CLI flag mirrors the backend's minItems:1
+ // requirement. Pick a low-risk read-only perm for the e2e key.
created = await runCLIJSON<CreatedApiKey>(config.configPath, [
'admin',
'api-keys',
'create',
name,
'--description',
- 'Created by CLI e2e'
+ 'Created by CLI e2e',
+ '--permission',
+ 'apikeys:list'
]);
expect(created.id).toBeTruthy();
expect(created.key).toMatch(/^arc_/);
diff --git a/types/apikey/apikey.go b/types/apikey/apikey.go
index bbb165d10..98ba54482 100644
--- a/types/apikey/apikey.go
+++ b/types/apikey/apikey.go
@@ -2,25 +2,35 @@ package apikey
import "time"
+// PermissionGrant is one permission granted to an API key, optionally scoped
+// to a single environment. Omit EnvironmentID for a global grant.
+type PermissionGrant struct {
+ Permission string `json:"permission" minLength:"1" doc:"Permission string" example:"containers:list"`
+ EnvironmentID *string `json:"environmentId,omitempty" doc:"Environment ID to scope the grant to; omit for a global grant"`
+}
+
// Create represents the request body for creating an API key.
type CreateApiKey struct {
- Name string `json:"name" minLength:"1" maxLength:"255" doc:"Name of the API key" example:"My API Key"`
- Description *string `json:"description,omitempty" maxLength:"1000" doc:"Optional description of the API key"`
- ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"Optional expiration date for the API key"`
+ Name string `json:"name" minLength:"1" maxLength:"255" doc:"Name of the API key" example:"My API Key"`
+ Description *string `json:"description,omitempty" maxLength:"1000" doc:"Optional description of the API key"`
+ ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"Optional expiration date for the API key"`
+ Permissions []PermissionGrant `json:"permissions" minItems:"1" doc:"Permissions granted to this key. Cannot exceed the creator's own permissions."`
}
// ApiKey represents an API key without the secret.
type ApiKey struct {
- ID string `json:"id" doc:"Unique identifier of the API key"`
- Name string `json:"name" doc:"Name of the API key"`
- Description *string `json:"description,omitempty" doc:"Description of the API key"`
- KeyPrefix string `json:"keyPrefix" doc:"Prefix of the API key for identification"`
- UserID *string `json:"userId,omitempty" doc:"ID of the user who owns the API key"`
- IsStatic bool `json:"isStatic" doc:"Whether the API key is environment-managed and protected from deletion"`
- ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"Expiration date of the API key"`
- LastUsedAt *time.Time `json:"lastUsedAt,omitempty" doc:"Last time the API key was used"`
- CreatedAt time.Time `json:"createdAt" doc:"Creation timestamp"`
- UpdatedAt *time.Time `json:"updatedAt,omitempty" doc:"Last update timestamp"`
+ ID string `json:"id" doc:"Unique identifier of the API key"`
+ Name string `json:"name" doc:"Name of the API key"`
+ Description *string `json:"description,omitempty" doc:"Description of the API key"`
+ KeyPrefix string `json:"keyPrefix" doc:"Prefix of the API key for identification"`
+ UserID *string `json:"userId,omitempty" doc:"ID of the user who owns the API key"`
+ IsStatic bool `json:"isStatic" doc:"Whether the API key is environment-managed and protected from deletion"`
+ IsBootstrap bool `json:"isBootstrap" doc:"Whether the API key is an auto-generated environment bootstrap key (locked from manual edit / delete)"`
+ ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"Expiration date of the API key"`
+ LastUsedAt *time.Time `json:"lastUsedAt,omitempty" doc:"Last time the API key was used"`
+ CreatedAt time.Time `json:"createdAt" doc:"Creation timestamp"`
+ UpdatedAt *time.Time `json:"updatedAt,omitempty" doc:"Last update timestamp"`
+ Permissions []PermissionGrant `json:"permissions" doc:"Permissions held by this key"`
}
// ApiKeyCreatedDto represents a newly created API key with the full secret.
@@ -31,7 +41,8 @@ type ApiKeyCreatedDto struct {
// Update represents the request body for updating an API key.
type UpdateApiKey struct {
- Name *string `json:"name,omitempty" maxLength:"255" doc:"New name for the API key"`
- Description *string `json:"description,omitempty" maxLength:"1000" doc:"New description for the API key"`
- ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"New expiration date for the API key"`
+ Name *string `json:"name,omitempty" maxLength:"255" doc:"New name for the API key"`
+ Description *string `json:"description,omitempty" maxLength:"1000" doc:"New description for the API key"`
+ ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"New expiration date for the API key"`
+ Permissions []PermissionGrant `json:"permissions,omitempty" doc:"Replace the key's permission grants. Omit to leave unchanged. Cannot exceed the updater's own permissions."`
}
diff --git a/types/role/role.go b/types/role/role.go
new file mode 100644
index 000000000..f0c156288
--- /dev/null
+++ b/types/role/role.go
@@ -0,0 +1,125 @@
+// Package role holds the public DTOs for Arcane's RBAC API: roles,
+// per-user role assignments, OIDC group→role mappings, and the
+// permission manifest exposed to the frontend.
+package role
+
+import "time"
+
+// Role represents a named permission set returned by the API.
+type Role struct {
+ ID string `json:"id" doc:"Unique identifier of the role" example:"role_admin"`
+ Name string `json:"name" doc:"Display name of the role" example:"Admin"`
+ Description *string `json:"description,omitempty" doc:"Optional human description"`
+ Permissions []string `json:"permissions" doc:"Permission strings granted by this role" example:"[\"containers:start\",\"projects:deploy\"]"`
+ BuiltIn bool `json:"builtIn" doc:"True for built-in roles (Admin/Editor/Deployer/Viewer); built-ins cannot be edited or deleted"`
+ AssignedUserCount int `json:"assignedUserCount" doc:"How many users currently hold an assignment to this role"`
+ CreatedAt time.Time `json:"createdAt" doc:"Creation timestamp"`
+ UpdatedAt *time.Time `json:"updatedAt,omitempty" doc:"Last update timestamp"`
+}
+
+// CreateRole is the request body for creating a custom role.
+type CreateRole struct {
+ Name string `json:"name" minLength:"1" maxLength:"100" doc:"Display name of the role" example:"Deploy Bot"`
+ Description *string `json:"description,omitempty" maxLength:"500" doc:"Optional human description"`
+ Permissions []string `json:"permissions" minItems:"1" doc:"Permission strings granted by this role"`
+}
+
+// UpdateRole is the request body for editing a custom role. Built-in roles
+// cannot be updated and will return 403.
+type UpdateRole struct {
+ Name string `json:"name" minLength:"1" maxLength:"100" doc:"Display name of the role"`
+ Description *string `json:"description,omitempty" maxLength:"500" doc:"Optional human description"`
+ Permissions []string `json:"permissions" minItems:"1" doc:"Permission strings granted by this role"`
+}
+
+// RoleAssignment binds a user to a role, optionally scoped to one environment.
+// EnvironmentID == nil means the assignment is global — it applies to every
+// environment and to org-level endpoints.
+type RoleAssignment struct {
+ ID string `json:"id" doc:"Unique identifier of the assignment"`
+ UserID string `json:"userId" doc:"ID of the user holding this assignment"`
+ RoleID string `json:"roleId" doc:"ID of the granted role"`
+ EnvironmentID *string `json:"environmentId,omitempty" doc:"Environment ID this assignment is scoped to; omit for a global assignment"`
+ Source string `json:"source" doc:"How the assignment was created" enum:"manual,oidc"`
+ CreatedAt time.Time `json:"createdAt" doc:"Creation timestamp"`
+}
+
+// SetUserAssignments replaces every manual role assignment for one user. OIDC-
+// sourced assignments are not affected and are managed via OIDC role mappings.
+type SetUserAssignments struct {
+ Assignments []UserAssignmentInput `json:"assignments" doc:"Desired manual role assignments for the user"`
+}
+
+// UserAssignmentInput is one row in a SetUserAssignments request.
+type UserAssignmentInput struct {
+ RoleID string `json:"roleId" doc:"ID of the role to grant"`
+ EnvironmentID *string `json:"environmentId,omitempty" doc:"Environment ID to scope the assignment to; omit for a global assignment"`
+}
+
+// OidcRoleMapping maps an OIDC group/claim value to a role assignment. On
+// every OIDC login, mappings whose ClaimValue is present in the user's
+// configured groups claim are converted into source='oidc' role assignments.
+type OidcRoleMapping struct {
+ ID string `json:"id" doc:"Unique identifier of the mapping"`
+ ClaimValue string `json:"claimValue" doc:"OIDC claim value that triggers this mapping" example:"docker-admins"`
+ RoleID string `json:"roleId" doc:"Role to assign when the claim matches"`
+ EnvironmentID *string `json:"environmentId,omitempty" doc:"Environment ID to scope the assignment to; omit for a global assignment"`
+ Source string `json:"source" enum:"manual,env" doc:"How this mapping was created. 'manual' rows are UI/API-managed and freely editable; 'env' rows are declared via OIDC_ROLE_MAPPINGS and are read-only at runtime."`
+ CreatedAt time.Time `json:"createdAt"`
+ UpdatedAt *time.Time `json:"updatedAt,omitempty"`
+}
+
+// OidcRoleMappingSpec is the schema for one entry in the OIDC_ROLE_MAPPINGS
+// env var. Operators can declare OIDC group→role mappings at deploy time;
+// each spec is reconciled into a source='env' row at boot. Distinct from
+// OidcRoleMapping (the API DTO) so the env-var format can evolve without
+// breaking the API and vice versa.
+type OidcRoleMappingSpec struct {
+ ClaimValue string `json:"claimValue" doc:"OIDC claim value to match"`
+ RoleID string `json:"roleId" doc:"Role ID to assign when the claim matches"`
+ EnvironmentID *string `json:"environmentId,omitempty" doc:"Environment ID to scope the assignment to; omit for a global assignment"`
+}
+
+// CreateOidcRoleMapping is the request body for adding a mapping.
+type CreateOidcRoleMapping struct {
+ ClaimValue string `json:"claimValue" minLength:"1" doc:"OIDC claim value to match"`
+ RoleID string `json:"roleId" minLength:"1" doc:"Role to grant"`
+ EnvironmentID *string `json:"environmentId,omitempty" doc:"Environment ID to scope the assignment to; omit for a global assignment"`
+}
+
+// UpdateOidcRoleMapping is the request body for editing a mapping.
+type UpdateOidcRoleMapping struct {
+ ClaimValue string `json:"claimValue" minLength:"1"`
+ RoleID string `json:"roleId" minLength:"1"`
+ EnvironmentID *string `json:"environmentId,omitempty"`
+}
+
+// PermissionsManifest describes every permission the server recognizes,
+// 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"`
+}
+
+// PermissionResource is one resource group in the manifest (e.g. "containers").
+type PermissionResource struct {
+ Key string `json:"key" doc:"Stable resource key" example:"containers"`
+ Label string `json:"label" doc:"Human-readable label" example:"Containers"`
+ Scope string `json:"scope" enum:"global,env" doc:"'global' for org-level perms; 'env' for per-environment perms"`
+ Actions []PermissionAction `json:"actions" doc:"Actions available on this resource"`
+}
+
+// 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"`
+}
+
+// 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 {
+ Permission string `json:"permission" doc:"Permission string to grant" example:"containers:list"`
+ EnvironmentID *string `json:"environmentId,omitempty" doc:"Environment ID to scope the grant to; omit for a global grant"`
+}
diff --git a/types/settings/settings.go b/types/settings/settings.go
index c535eb4a1..051ac3f65 100644
--- a/types/settings/settings.go
+++ b/types/settings/settings.go
@@ -312,15 +312,11 @@ type Update struct {
// Required: false
OidcScopes *string `json:"oidcScopes,omitempty"`
- // OidcAdminClaim is the OIDC claim name used to identify administrators.
+ // OidcGroupsClaim is the OIDC claim path read on every login to drive
+ // role assignment via oidc_role_mappings. Default: "groups".
//
// Required: false
- OidcAdminClaim *string `json:"oidcAdminClaim,omitempty"`
-
- // OidcAdminValue is the OIDC claim value that identifies administrators.
- //
- // Required: false
- OidcAdminValue *string `json:"oidcAdminValue,omitempty"`
+ OidcGroupsClaim *string `json:"oidcGroupsClaim,omitempty"`
// OidcSkipTlsVerify indicates if TLS verification should be skipped for OIDC.
//
diff --git a/types/user/user.go b/types/user/user.go
index b4ae1811f..0266ed646 100644
--- a/types/user/user.go
+++ b/types/user/user.go
@@ -1,36 +1,46 @@
package user
// CreateUser represents the request body for creating a new user.
+// Role assignments are managed separately via PUT /users/{userId}/role-assignments.
type CreateUser struct {
- Username string `json:"username" minLength:"1" maxLength:"255" doc:"Username of the user" example:"johndoe"`
- Password string `json:"password" minLength:"8" doc:"Password of the user"` //nolint:gosec // API schema requires password field name
- DisplayName *string `json:"displayName,omitempty" maxLength:"255" doc:"Display name of the user" example:"John Doe"`
- Email *string `json:"email,omitempty" doc:"Email address of the user" example:"[email protected]"`
- Roles []string `json:"roles,omitempty" doc:"Roles assigned to the user" example:"[\"user\"]"`
- Locale *string `json:"locale,omitempty" doc:"Locale preference of the user" example:"en-US"`
+ Username string `json:"username" minLength:"1" maxLength:"255" doc:"Username of the user" example:"johndoe"`
+ Password string `json:"password" minLength:"8" doc:"Password of the user"` //nolint:gosec // API schema requires password field name
+ DisplayName *string `json:"displayName,omitempty" maxLength:"255" doc:"Display name of the user" example:"John Doe"`
+ Email *string `json:"email,omitempty" doc:"Email address of the user" example:"[email protected]"`
+ Locale *string `json:"locale,omitempty" doc:"Locale preference of the user" example:"en-US"`
}
// UpdateUser represents the request body for updating a user.
+// Role assignments are managed separately via PUT /users/{userId}/role-assignments.
type UpdateUser struct {
- Username *string `json:"username,omitempty" minLength:"1" maxLength:"255" doc:"Username of the user"`
- DisplayName *string `json:"displayName,omitempty" maxLength:"255" doc:"Display name of the user"`
- Email *string `json:"email,omitempty" doc:"Email address of the user"`
- Roles []string `json:"roles,omitempty" doc:"Roles assigned to the user"`
- Locale *string `json:"locale,omitempty" doc:"Locale preference of the user"`
- Password *string `json:"password,omitempty" minLength:"8" doc:"New password for the user"` //nolint:gosec // API schema requires password field name
+ Username *string `json:"username,omitempty" minLength:"1" maxLength:"255" doc:"Username of the user"`
+ DisplayName *string `json:"displayName,omitempty" maxLength:"255" doc:"Display name of the user"`
+ Email *string `json:"email,omitempty" doc:"Email address of the user"`
+ Locale *string `json:"locale,omitempty" doc:"Locale preference of the user"`
+ Password *string `json:"password,omitempty" minLength:"8" doc:"New password for the user"` //nolint:gosec // API schema requires password field name
+}
+
+// RoleAssignmentSummary is a compact form of a user's role assignment used
+// inside the User payload (so the frontend can render the assignments table
+// without a separate request).
+type RoleAssignmentSummary struct {
+ RoleID string `json:"roleId" doc:"Role ID granted by this assignment"`
+ EnvironmentID *string `json:"environmentId,omitempty" doc:"Environment ID this assignment is scoped to; omit for a global assignment"`
+ Source string `json:"source" doc:"How the assignment was created" enum:"manual,oidc"`
}
// User represents a user in API responses.
type User struct {
- ID string `json:"id" doc:"Unique identifier of the user" example:"550e8400-e29b-41d4-a716-446655440000"`
- Username string `json:"username" doc:"Username of the user" example:"johndoe"`
- DisplayName *string `json:"displayName,omitempty" doc:"Display name of the user" example:"John Doe"`
- Email *string `json:"email,omitempty" doc:"Email address of the user" example:"[email protected]"`
- Roles []string `json:"roles" doc:"Roles assigned to the user" example:"[\"user\", \"admin\"]"`
- 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"`
- CreatedAt string `json:"createdAt,omitempty" doc:"Date and time when the user was created"`
- UpdatedAt string `json:"updatedAt,omitempty" doc:"Date and time when the user was last updated"`
- RequiresPasswordChange bool `json:"requiresPasswordChange" doc:"Whether the user must change their password"`
+ ID string `json:"id" doc:"Unique identifier of the user" example:"550e8400-e29b-41d4-a716-446655440000"`
+ Username string `json:"username" doc:"Username of the user" example:"johndoe"`
+ DisplayName *string `json:"displayName,omitempty" doc:"Display name of the user" example:"John Doe"`
+ 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)."`
+ 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"`
+ CreatedAt string `json:"createdAt,omitempty" doc:"Date and time when the user was created"`
+ UpdatedAt string `json:"updatedAt,omitempty" doc:"Date and time when the user was last updated"`
+ RequiresPasswordChange bool `json:"requiresPasswordChange" doc:"Whether the user must change their password"`
}