Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: properly contstrain rbac endpoints (#2950)
Kyle Mendell651cc3146d9d
diff --git a/.vscode/PLAN.md b/.vscode/PLAN.mdnew file mode 100644index 000000000..f32c49dc2--- /dev/null+++ b/.vscode/PLAN.md@@ -0,0 +1,36 @@+Plan: Enforce per-environment permissions on the remote-environment proxy+TL;DR — Fix an authorization bypass where any authenticated user can perform write actions on remote/edge environments regardless of their role. The manager's EnvironmentMiddleware proxies /api/environments/{id}/... to agents after checking only authentication; the agent runs with SudoPermissionSet(), so no permission is ever enforced. Fix: enforce the caller's per-environment permission in the proxy before forwarding, using each operation's required permission as a single source of truth (attached to huma.Operation.Metadata). Local env ("0") is already correctly enforced and stays unchanged.++Phase 1 — Make each operation's permission introspectable (single source of truth)+Add a shared registration helper in role.go (or a sibling file), e.g. RegisterEnvScoped(api, op, perm, handler), that stores perm in op.Metadata[MetaRequiredPermission], attaches RequirePermission(api, perm), and calls huma.Register. The required perm argument makes it impossible to register without one.+Migrate the env-scoped (/environments/{id}/...) handler registrations to the helper — containers, images, image_updates, volumes, networks, ports, system, swarm, projects, dashboard, vulnerabilities (mechanical: drop the Middlewares: line, pass perm as an arg). All of these use a single RequirePermission today; none under /environments/{id}/ uses RequireGlobalAdmin.+Expose a shared slice of the 6 proxied WS routes + their permissions from handler.go:243 (project logs, container logs/stats/terminal, swarm service logs, system stats) so both route registration and the matcher use one source.+Phase 2 — Build the authorization matcher+After SetupAPI in api.go:138, build a (method, env-suffix-path-template) → permission matcher by walking api.OpenAPI().Paths reading Metadata[MetaRequiredPermission], plus the WS slice from step 3. Normalize Huma {x} and Echo :x params to one wildcard form; static segments win over wildcards (so /containers/counts ≠ /containers/{containerId}).+Phase 3 — Enforce in the proxy+Give the proxy the caller's PermissionSet: change AuthValidator in environment_middleware.go:52 to return (\*authz.PermissionSet, bool), and update router_bootstrap.go:90 to resolve it via the existing RoleService.ResolvePermissions / ResolveApiKeyPermissions (env/agent-bootstrap tokens → SudoPermissionSet()). Reuse, no duplication.+In EnvironmentMiddleware.Handle, right after auth-validation and before any proxy branch (covers edge-tunnel + HTTP + WS): look up the required permission for (method, suffix); if the caller isn't Sudo and !ps.Allows(perm, remoteEnvID) → 403 (matching the file's existing JSON error shape). No mapping found → default-deny 403.+Wire the matcher through NewEnvProxyMiddlewareWithParam[AndRegistry] and the bootstrap call.+Phase 4 — Tests & verification+Unit tests: matcher static-vs-{param} precedence; remote write denied for read-only role; remote read allowed; agent/env token still allowed; local path untouched; WS terminal denied without containers:exec.+Guard test: every /environments/{id}/... Huma op carries permission metadata (also catches any unprotected env-scoped endpoint).+Run cd backend && go test ./api/... ./internal/services/... ./internal/middleware/... ./internal/bootstrap/... ./pkg/authz/....+Manual: run the issue's repro against a remote env → expect 403; confirm an allowed role works and local is unaffected.+Relevant files++environment_middleware.go:95 — authz check in Handle; AuthValidator signature; constructor takes the matcher.+router_bootstrap.go:90 — resolve PermissionSet; build/pass matcher.+api.go:138 — build matcher from api.OpenAPI() metadata.+role.go:19 — RegisterEnvScoped helper + MetaRequiredPermission key.+handler.go:243 — shared WS route→permission slice.+backend/api/handlers/{containers,images,image_updates,volumes,networks,ports,system,swarm,projects,dashboard,vulnerabilities}.go — migrate env-scoped registrations.+Decisions (confirmed)++Single source of truth via operation metadata + shared helper (Approach A).+Covers all env-scoped resources, not just containers.+Unmapped env-scoped path to a remote env → default-deny (403).+Scope boundaries++Excluded: local env enforcement (already correct), org-level endpoints (not proxied), management paths under /environments/{id}/ already handled locally (isManagementPathInternal), and the frontend (backend enforcement is authoritative; UI gating is out of scope here).+Audit item during implementation: confirm no buildables/playwright/direct-Echo routes sit under /environments/{id}/ that default-deny would wrongly block (initial grep found none).+Want me to proceed with this plan, or adjust anything (e.g., migrate all Huma registrations to the helper for uniformity vs. only the env-scoped ones)?diff --git a/backend/api/env_scoped_permission_test.go b/backend/api/env_scoped_permission_test.gonew file mode 100644index 000000000..307294d1b--- /dev/null+++ b/backend/api/env_scoped_permission_test.go@@ -0,0 +1,73 @@+package api++import (+ "net/http"+ "sort"+ "strings"+ "testing"++ "github.com/danielgtaylor/huma/v2"++ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+)++// TestEnvScopedOperationsDeclarePermission guards the remote-environment proxy+// authorization model: every operation served under /environments/{id}/<sub>+// must declare its required permission via middleware.RegisterWithPermission,+// which records it in the operation metadata. The proxy reads this metadata to+// enforce the same permission it enforces locally before forwarding a request+// to an agent. An operation missing this metadata would be denied by the proxy+// (default-deny), so this test fails loudly if any env-scoped operation is+// registered with a bare huma.Register instead of RegisterWithPermission.+func TestEnvScopedOperationsDeclarePermission(t *testing.T) {+ api := SetupAPIForSpec()+ oapi := api.OpenAPI()+ if oapi == nil || oapi.Paths == nil {+ t.Fatal("expected an OpenAPI document with paths")+ }++ var missing []string+ for path, item := range oapi.Paths {+ if !strings.HasPrefix(path, "/environments/{id}/") {+ continue+ }+ for method, op := range envScopedTestOperations(item) {+ if op == nil {+ continue+ }+ // Operations that explicitly opt out of authentication (an empty,+ // non-nil Security list) are intentionally public and require no+ // permission metadata.+ if op.Security != nil && len(op.Security) == 0 {+ continue+ }+ // Operations registered with RegisterWithoutPermission are+ // intentionally permission-free (auth-only) and carry a marker.+ if _, ok := op.Metadata[authz.MetaProxyNoPermission]; ok {+ continue+ }+ perm, ok := op.Metadata[authz.MetaRequiredPermission].(string)+ if !ok || perm == "" {+ missing = append(missing, method+" "+path)+ }+ }+ }++ if len(missing) > 0 {+ sort.Strings(missing)+ t.Errorf("%d env-scoped operation(s) missing required-permission metadata; register them with middleware.RegisterWithPermission:\n %s",+ len(missing), strings.Join(missing, "\n "))+ }+}++func envScopedTestOperations(item *huma.PathItem) map[string]*huma.Operation {+ return map[string]*huma.Operation{+ http.MethodGet: item.Get,+ http.MethodPost: item.Post,+ http.MethodPut: item.Put,+ http.MethodDelete: item.Delete,+ http.MethodPatch: item.Patch,+ http.MethodHead: item.Head,+ http.MethodOptions: item.Options,+ }+}diff --git a/backend/api/handlers/activities.go b/backend/api/handlers/activities.goindex 3c35f2210..9f6f7669e 100644--- a/backend/api/handlers/activities.go+++ b/backend/api/handlers/activities.go@@ -90,7 +90,7 @@ func RegisterActivities(api huma.API, activityService *services.ActivityService,environmentService: environmentService,}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-activities",Method: http.MethodGet,Path: "/environments/{id}/activities",@@ -101,10 +101,9 @@ func RegisterActivities(api huma.API, activityService *services.ActivityService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermActivitiesRead),- }, h.ListActivities)+ }, authz.PermActivitiesRead, h.ListActivities)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-activity",Method: http.MethodGet,Path: "/environments/{id}/activities/{activityId}",@@ -115,8 +114,7 @@ func RegisterActivities(api huma.API, activityService *services.ActivityService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermActivitiesRead),- }, h.GetActivity)+ }, authz.PermActivitiesRead, h.GetActivity)huma.Register(api, huma.Operation{OperationID: "stream-all-activities",@@ -132,7 +130,7 @@ func RegisterActivities(api huma.API, activityService *services.ActivityService,Middlewares: humamw.RequirePermission(api, authz.PermActivitiesRead),}, h.StreamAllActivities)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "cancel-activity",Method: http.MethodPost,Path: "/environments/{id}/activities/{activityId}/cancel",@@ -143,10 +141,9 @@ func RegisterActivities(api huma.API, activityService *services.ActivityService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermActivitiesCancel),- }, h.CancelActivity)+ }, authz.PermActivitiesCancel, h.CancelActivity)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "clear-activity-history",Method: http.MethodDelete,Path: "/environments/{id}/activities/history",@@ -157,8 +154,7 @@ func RegisterActivities(api huma.API, activityService *services.ActivityService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermActivitiesDelete),- }, h.ClearHistory)+ }, authz.PermActivitiesDelete, h.ClearHistory)}func (h *ActivityHandler) ListActivities(ctx context.Context, input *ListActivitiesInput) (*ListActivitiesOutput, error) {diff --git a/backend/api/handlers/build_workspaces.go b/backend/api/handlers/build_workspaces.goindex ab4de5921..b9ff7ae49 100644--- a/backend/api/handlers/build_workspaces.go+++ b/backend/api/handlers/build_workspaces.go@@ -24,7 +24,7 @@ type BuildWorkspaceHandler struct {func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorkspaceService) {h := &BuildWorkspaceHandler{service: workspaceService}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "builds-browse",Method: "GET",Path: "/environments/{id}/builds/browse",@@ -32,10 +32,9 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorksDescription: "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)+ }, authz.PermBuildWorkspacesManage, h.BrowseDirectory)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "builds-browse-content",Method: "GET",Path: "/environments/{id}/builds/browse/content",@@ -43,10 +42,9 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorksDescription: "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)+ }, authz.PermBuildWorkspacesManage, h.GetFileContent)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "builds-browse-download",Method: "GET",Path: "/environments/{id}/builds/browse/download",@@ -54,10 +52,9 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorksDescription: "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)+ }, authz.PermBuildWorkspacesManage, h.DownloadFile)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "builds-browse-upload",Method: "POST",Path: "/environments/{id}/builds/browse/upload",@@ -82,10 +79,9 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorks},},},- Middlewares: humamw.RequirePermission(api, authz.PermBuildWorkspacesManage),- }, h.UploadFile)+ }, authz.PermBuildWorkspacesManage, h.UploadFile)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "builds-browse-mkdir",Method: "POST",Path: "/environments/{id}/builds/browse/mkdir",@@ -93,10 +89,9 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorksDescription: "Create a directory under the builds workspace root",Tags: []string{"Builds"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermBuildWorkspacesManage),- }, h.CreateDirectory)+ }, authz.PermBuildWorkspacesManage, h.CreateDirectory)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "builds-browse-delete",Method: "DELETE",Path: "/environments/{id}/builds/browse",@@ -104,8 +99,7 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorksDescription: "Delete a file or directory under the builds workspace root",Tags: []string{"Builds"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermBuildWorkspacesManage),- }, h.DeleteFile)+ }, authz.PermBuildWorkspacesManage, h.DeleteFile)}type BrowseBuildsInput struct {diff --git a/backend/api/handlers/containers.go b/backend/api/handlers/containers.goindex 81657f4f8..0bf2690cf 100644--- a/backend/api/handlers/containers.go+++ b/backend/api/handlers/containers.go@@ -151,7 +151,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, dappCtx: appCtx.contextInternal(),}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-containers",Method: http.MethodGet,Path: "/environments/{id}/containers",@@ -159,70 +159,63 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, dDescription: "Paginated list of containers",Tags: []string{"Containers"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermContainersList),- }, h.ListContainers)+ }, authz.PermContainersList, h.ListContainers)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "container-status-counts",Method: http.MethodGet,Path: "/environments/{id}/containers/counts",Summary: "Container status counts",Tags: []string{"Containers"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermContainersList),- }, h.GetContainerStatusCounts)+ }, authz.PermContainersList, h.GetContainerStatusCounts)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "create-container",Method: http.MethodPost,Path: "/environments/{id}/containers",Summary: "Create container",Tags: []string{"Containers"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermContainersCreate),- }, h.CreateContainer)+ }, authz.PermContainersCreate, h.CreateContainer)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-container",Method: http.MethodGet,Path: "/environments/{id}/containers/{containerId}",Summary: "Get container",Tags: []string{"Containers"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermContainersRead),- }, h.GetContainer)+ }, authz.PermContainersRead, h.GetContainer)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "start-container",Method: http.MethodPost,Path: "/environments/{id}/containers/{containerId}/start",Summary: "Start container",Tags: []string{"Containers"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermContainersStart),- }, h.StartContainer)+ }, authz.PermContainersStart, h.StartContainer)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "stop-container",Method: http.MethodPost,Path: "/environments/{id}/containers/{containerId}/stop",Summary: "Stop container",Tags: []string{"Containers"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermContainersStop),- }, h.StopContainer)+ }, authz.PermContainersStop, h.StopContainer)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "restart-container",Method: http.MethodPost,Path: "/environments/{id}/containers/{containerId}/restart",Summary: "Restart container",Tags: []string{"Containers"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermContainersRestart),- }, h.RestartContainer)+ }, authz.PermContainersRestart, h.RestartContainer)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "redeploy-container",Method: http.MethodPost,Path: "/environments/{id}/containers/{containerId}/redeploy",@@ -230,20 +223,18 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, dDescription: "Pull latest image and recreate container",Tags: []string{"Containers"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermContainersRedeploy),- }, h.RedeployContainer)+ }, authz.PermContainersRedeploy, h.RedeployContainer)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "delete-container",Method: http.MethodDelete,Path: "/environments/{id}/containers/{containerId}",Summary: "Delete container",Tags: []string{"Containers"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermContainersDelete),- }, h.DeleteContainer)+ }, authz.PermContainersDelete, h.DeleteContainer)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "set-container-auto-update",Method: http.MethodPut,Path: "/environments/{id}/containers/{containerId}/auto-update",@@ -251,8 +242,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, dDescription: "Enable or disable auto-update for a specific container",Tags: []string{"Containers", "Updater"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermContainersAutoUpdate),- }, h.SetAutoUpdate)+ }, authz.PermContainersAutoUpdate, h.SetAutoUpdate)}func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContainersInput) (*ListContainersOutput, error) {diff --git a/backend/api/handlers/dashboard.go b/backend/api/handlers/dashboard.goindex 02cdf992c..db3e4203c 100644--- a/backend/api/handlers/dashboard.go+++ b/backend/api/handlers/dashboard.go@@ -55,7 +55,7 @@ func RegisterDashboard(api huma.API, dashboardService *services.DashboardServiceenvironmentService: environmentService,}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-dashboard",Method: http.MethodGet,Path: "/environments/{id}/dashboard",@@ -66,8 +66,7 @@ func RegisterDashboard(api huma.API, dashboardService *services.DashboardService{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermDashboardRead),- }, h.GetDashboard)+ }, authz.PermDashboardRead, h.GetDashboard)huma.Register(api, huma.Operation{OperationID: "stream-all-dashboards",diff --git a/backend/api/handlers/environments.go b/backend/api/handlers/environments.goindex c3a549520..1381d7627 100644--- a/backend/api/handlers/environments.go+++ b/backend/api/handlers/environments.go@@ -279,7 +279,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.EnvironmentMiddlewares: humamw.RequirePermission(api, authz.PermEnvironmentsDelete),}, h.DeleteEnvironment)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "testConnection",Method: "POST",Path: "/environments/{id}/test",@@ -290,10 +290,9 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsRead),- }, h.TestConnection)+ }, authz.PermEnvironmentsRead, h.TestConnection)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "updateHeartbeat",Method: "POST",Path: "/environments/{id}/heartbeat",@@ -304,10 +303,9 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsSync),- }, h.UpdateHeartbeat)+ }, authz.PermEnvironmentsSync, h.UpdateHeartbeat)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "pairAgent",Method: "POST",Path: "/environments/{id}/agent/pair",@@ -318,10 +316,9 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsPair),- }, h.PairAgent)+ }, authz.PermEnvironmentsPair, h.PairAgent)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "syncEnvironment",Method: "POST",Path: "/environments/{id}/sync",@@ -332,8 +329,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsSync),- }, h.SyncEnvironment)+ }, authz.PermEnvironmentsSync, h.SyncEnvironment)huma.Register(api, huma.Operation{OperationID: "pairEnvironment",@@ -346,7 +342,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.EnvironmentSecurity: []map[string][]string{},}, h.PairEnvironment)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "getDeploymentSnippets",Method: "GET",Path: "/environments/{id}/deployment",@@ -357,10 +353,9 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsPair),- }, h.GetDeploymentSnippets)+ }, authz.PermEnvironmentsPair, h.GetDeploymentSnippets)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "downloadEnvironmentMTLSBundle",Method: "GET",Path: "/environments/{id}/deployment/mtls/bundle",@@ -371,10 +366,9 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsPair),- }, h.DownloadEnvironmentMTLSBundle)+ }, authz.PermEnvironmentsPair, h.DownloadEnvironmentMTLSBundle)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "downloadEnvironmentMTLSFile",Method: "GET",Path: "/environments/{id}/deployment/mtls/{fileName}",@@ -385,10 +379,9 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsPair),- }, h.DownloadEnvironmentMTLSFile)+ }, authz.PermEnvironmentsPair, h.DownloadEnvironmentMTLSFile)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "getEnvironmentVersion",Method: "GET",Path: "/environments/{id}/version",@@ -399,8 +392,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsRead),- }, h.GetEnvironmentVersion)+ }, authz.PermEnvironmentsRead, h.GetEnvironmentVersion)huma.Register(api, huma.Operation{OperationID: "downloadEdgeMTLSCA",diff --git a/backend/api/handlers/helpers.go b/backend/api/handlers/helpers.goindex 468668381..45bd41153 100644--- a/backend/api/handlers/helpers.go+++ b/backend/api/handlers/helpers.go@@ -87,8 +87,7 @@ func registerSecuredInternal[I, O any](handler func(context.Context, *I) (*O, error),) {op.Security = defaultOperationSecurityInternal()- op.Middlewares = humamw.RequirePermission(api, permission)- huma.Register(api, op, handler)+ humamw.RegisterWithPermission(api, op, permission, handler)}func registerCustomizeSecuredInternal[I, O any](diff --git a/backend/api/handlers/image_updates.go b/backend/api/handlers/image_updates.goindex 3b9ccb74d..02431c36f 100644--- a/backend/api/handlers/image_updates.go+++ b/backend/api/handlers/image_updates.go@@ -83,75 +83,68 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServappCtx: appCtx.contextInternal(),}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "check-image-update",Method: http.MethodGet,Path: "/environments/{id}/image-updates/check",Summary: "Check image update by reference",Tags: []string{"Image Updates"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesCheck),- }, h.CheckImageUpdate)+ }, authz.PermImageUpdatesCheck, h.CheckImageUpdate)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "check-image-update-by-id",Method: http.MethodGet,Path: "/environments/{id}/image-updates/check/{imageId}",Summary: "Check image update by ID",Tags: []string{"Image Updates"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesCheck),- }, h.CheckImageUpdateByID)+ }, authz.PermImageUpdatesCheck, h.CheckImageUpdateByID)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "check-image-update-by-id-post",Method: http.MethodPost,Path: "/environments/{id}/image-updates/check/{imageId}",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)+ }, authz.PermImageUpdatesCheck, h.CheckImageUpdateByID)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "check-multiple-images",Method: http.MethodPost,Path: "/environments/{id}/image-updates/check-batch",Summary: "Check multiple images",Tags: []string{"Image Updates"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesCheck),- }, h.CheckMultipleImages)+ }, authz.PermImageUpdatesCheck, h.CheckMultipleImages)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "check-all-images",Method: http.MethodPost,Path: "/environments/{id}/image-updates/check-all",Summary: "Check all images",Tags: []string{"Image Updates"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesCheck),- }, h.CheckAllImages)+ }, authz.PermImageUpdatesCheck, h.CheckAllImages)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-update-info-by-refs",Method: http.MethodGet,Path: "/environments/{id}/image-updates/by-refs",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)+ }, authz.PermImageUpdatesRead, h.GetUpdateInfoByRefs)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-update-summary",Method: http.MethodGet,Path: "/environments/{id}/image-updates/summary",Summary: "Get update summary",Tags: []string{"Image Updates"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesRead),- }, h.GetUpdateSummary)+ }, authz.PermImageUpdatesRead, h.GetUpdateSummary)}func (h *ImageUpdateHandler) CheckImageUpdate(ctx context.Context, input *CheckImageUpdateInput) (*CheckImageUpdateOutput, error) {diff --git a/backend/api/handlers/images.go b/backend/api/handlers/images.goindex 93532e7ee..043bdf957 100644--- a/backend/api/handlers/images.go+++ b/backend/api/handlers/images.go@@ -166,7 +166,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, iappCtx: appCtx.contextInternal(),}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-images",Method: http.MethodGet,Path: "/environments/{id}/images",@@ -177,10 +177,9 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermImagesList),- }, h.ListImages)+ }, authz.PermImagesList, h.ListImages)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-image-usage-counts",Method: http.MethodGet,Path: "/environments/{id}/images/counts",@@ -191,10 +190,9 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermImagesList),- }, h.GetImageUsageCounts)+ }, authz.PermImagesList, h.GetImageUsageCounts)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-image",Method: http.MethodGet,Path: "/environments/{id}/images/{imageId}",@@ -205,10 +203,9 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermImagesRead),- }, h.GetImage)+ }, authz.PermImagesRead, h.GetImage)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "remove-image",Method: http.MethodDelete,Path: "/environments/{id}/images/{imageId}",@@ -219,10 +216,9 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermImagesDelete),- }, h.RemoveImage)+ }, authz.PermImagesDelete, h.RemoveImage)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "pull-image",Method: http.MethodPost,Path: "/environments/{id}/images/pull",@@ -233,10 +229,9 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermImagesPull),- }, h.PullImage)+ }, authz.PermImagesPull, h.PullImage)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "build-image",Method: http.MethodPost,Path: "/environments/{id}/images/build",@@ -247,10 +242,9 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermImagesBuild),- }, h.BuildImage)+ }, authz.PermImagesBuild, h.BuildImage)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-image-builds",Method: http.MethodGet,Path: "/environments/{id}/images/builds",@@ -261,10 +255,9 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermImagesList),- }, h.ListImageBuilds)+ }, authz.PermImagesList, h.ListImageBuilds)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-image-build",Method: http.MethodGet,Path: "/environments/{id}/images/builds/{buildId}",@@ -275,10 +268,9 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermImagesRead),- }, h.GetImageBuild)+ }, authz.PermImagesRead, h.GetImageBuild)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "prune-images",Method: http.MethodPost,Path: "/environments/{id}/images/prune",@@ -289,10 +281,9 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermImagesPrune),- }, h.PruneImages)+ }, authz.PermImagesPrune, h.PruneImages)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "upload-image",Method: http.MethodPost,Path: "/environments/{id}/images/upload",@@ -320,8 +311,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i},},},- Middlewares: humamw.RequirePermission(api, authz.PermImagesUpload),- }, h.UploadImage)+ }, authz.PermImagesUpload, h.UploadImage)}// ListImages returns a paginated list of images.diff --git a/backend/api/handlers/job_schedules.go b/backend/api/handlers/job_schedules.goindex 334197beb..60a0180ef 100644--- a/backend/api/handlers/job_schedules.go+++ b/backend/api/handlers/job_schedules.go@@ -52,7 +52,7 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *serenvironmentService: envSvc,}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-job-schedules",Method: http.MethodGet,Path: "/environments/{id}/job-schedules",@@ -63,10 +63,9 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *ser{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermJobsManage),- }, h.Get)+ }, authz.PermJobsManage, h.Get)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "update-job-schedules",Method: http.MethodPut,Path: "/environments/{id}/job-schedules",@@ -77,10 +76,9 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *ser{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermJobsManage),- }, h.Update)+ }, authz.PermJobsManage, h.Update)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-jobs",Method: http.MethodGet,Path: "/environments/{id}/jobs",@@ -91,10 +89,9 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *ser{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermJobsManage),- }, h.ListJobs)+ }, authz.PermJobsManage, h.ListJobs)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "run-job",Method: http.MethodPost,Path: "/environments/{id}/jobs/{jobId}/run",@@ -105,8 +102,7 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *ser{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermJobsManage),- }, h.RunJob)+ }, authz.PermJobsManage, h.RunJob)}type JobSchedulesHandler struct {diff --git a/backend/api/handlers/networks.go b/backend/api/handlers/networks.goindex 06bf39838..935734fe3 100644--- a/backend/api/handlers/networks.go+++ b/backend/api/handlers/networks.go@@ -145,75 +145,68 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerSappCtx: appCtx.contextInternal(),}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-networks",Method: http.MethodGet,Path: "/environments/{id}/networks",Summary: "List networks",Tags: []string{"Networks"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermNetworksList),- }, h.ListNetworks)+ }, authz.PermNetworksList, h.ListNetworks)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "network-counts",Method: http.MethodGet,Path: "/environments/{id}/networks/counts",Summary: "Network counts",Tags: []string{"Networks"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermNetworksList),- }, h.GetNetworkCounts)+ }, authz.PermNetworksList, h.GetNetworkCounts)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "create-network",Method: http.MethodPost,Path: "/environments/{id}/networks",Summary: "Create network",Tags: []string{"Networks"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermNetworksCreate),- }, h.CreateNetwork)+ }, authz.PermNetworksCreate, h.CreateNetwork)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-network-topology",Method: http.MethodGet,Path: "/environments/{id}/networks/topology",Summary: "Get network topology",Tags: []string{"Networks"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermNetworksRead),- }, h.GetNetworkTopology)+ }, authz.PermNetworksRead, h.GetNetworkTopology)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-network",Method: http.MethodGet,Path: "/environments/{id}/networks/{networkId}",Summary: "Get network",Tags: []string{"Networks"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermNetworksRead),- }, h.GetNetwork)+ }, authz.PermNetworksRead, h.GetNetwork)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "delete-network",Method: http.MethodDelete,Path: "/environments/{id}/networks/{networkId}",Summary: "Delete network",Tags: []string{"Networks"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermNetworksDelete),- }, h.DeleteNetwork)+ }, authz.PermNetworksDelete, h.DeleteNetwork)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "prune-networks",Method: http.MethodPost,Path: "/environments/{id}/networks/prune",Summary: "Prune networks",Tags: []string{"Networks"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermNetworksPrune),- }, h.PruneNetworks)+ }, authz.PermNetworksPrune, h.PruneNetworks)}func (h *NetworkHandler) ListNetworks(ctx context.Context, input *ListNetworksInput) (*ListNetworksOutput, error) {diff --git a/backend/api/handlers/notifications.go b/backend/api/handlers/notifications.goindex 30f77e5b8..b98986e13 100644--- a/backend/api/handlers/notifications.go+++ b/backend/api/handlers/notifications.go@@ -105,55 +105,50 @@ func RegisterNotifications(api huma.API, notificationSvc *services.NotificationSconfig: cfg,}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-all-notification-settings",Method: http.MethodGet,Path: "/environments/{id}/notifications/settings",Summary: "Get all notification settings",Tags: []string{"Notifications"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermNotificationsManage),- }, h.GetAllNotificationSettings)+ }, authz.PermNotificationsManage, h.GetAllNotificationSettings)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-notification-settings",Method: http.MethodGet,Path: "/environments/{id}/notifications/settings/{provider}",Summary: "Get notification settings by provider",Tags: []string{"Notifications"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermNotificationsManage),- }, h.GetNotificationSettings)+ }, authz.PermNotificationsManage, h.GetNotificationSettings)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "create-or-update-notification-settings",Method: http.MethodPost,Path: "/environments/{id}/notifications/settings",Summary: "Create or update notification settings",Tags: []string{"Notifications"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermNotificationsManage),- }, h.CreateOrUpdateNotificationSettings)+ }, authz.PermNotificationsManage, h.CreateOrUpdateNotificationSettings)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "delete-notification-settings",Method: http.MethodDelete,Path: "/environments/{id}/notifications/settings/{provider}",Summary: "Delete notification settings",Tags: []string{"Notifications"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermNotificationsManage),- }, h.DeleteNotificationSettings)+ }, authz.PermNotificationsManage, h.DeleteNotificationSettings)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "test-notification",Method: http.MethodPost,Path: "/environments/{id}/notifications/test/{provider}",Summary: "Test notification",Tags: []string{"Notifications"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermNotificationsManage),- }, h.TestNotification)+ }, authz.PermNotificationsManage, h.TestNotification)huma.Register(api, huma.Operation{OperationID: "dispatch-notification",diff --git a/backend/api/handlers/ports.go b/backend/api/handlers/ports.goindex 993fd4b9b..2737c2e7d 100644--- a/backend/api/handlers/ports.go+++ b/backend/api/handlers/ports.go@@ -38,15 +38,14 @@ type ListPortsOutput struct {func RegisterPorts(api huma.API, portSvc *services.PortService) {h := &PortHandler{portService: portSvc}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-ports",Method: http.MethodGet,Path: "/environments/{id}/ports",Summary: "List port mappings",Tags: []string{"Ports"},Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},- Middlewares: humamw.RequirePermission(api, authz.PermContainersList),- }, h.ListPorts)+ }, authz.PermContainersList, h.ListPorts)}func (h *PortHandler) ListPorts(ctx context.Context, input *ListPortsInput) (*ListPortsOutput, error) {diff --git a/backend/api/handlers/projects.go b/backend/api/handlers/projects.goindex 216a38a43..8029ebb66 100644--- a/backend/api/handlers/projects.go+++ b/backend/api/handlers/projects.go@@ -229,7 +229,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, actappCtx: appCtx.contextInternal(),}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-projects",Method: http.MethodGet,Path: "/environments/{id}/projects",@@ -240,10 +240,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsList),- }, h.ListProjects)+ }, authz.PermProjectsList, h.ListProjects)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-project-status-counts",Method: http.MethodGet,Path: "/environments/{id}/projects/counts",@@ -254,10 +253,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsList),- }, h.GetProjectStatusCounts)+ }, authz.PermProjectsList, h.GetProjectStatusCounts)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "deploy-project",Method: http.MethodPost,Path: "/environments/{id}/projects/{projectId}/up",@@ -268,10 +266,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsDeploy),- }, h.DeployProject)+ }, authz.PermProjectsDeploy, h.DeployProject)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "down-project",Method: http.MethodPost,Path: "/environments/{id}/projects/{projectId}/down",@@ -282,10 +279,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsDown),- }, h.DownProject)+ }, authz.PermProjectsDown, h.DownProject)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "create-project",Method: http.MethodPost,Path: "/environments/{id}/projects",@@ -296,10 +292,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsCreate),- }, h.CreateProject)+ }, authz.PermProjectsCreate, h.CreateProject)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-project",Method: http.MethodGet,Path: "/environments/{id}/projects/{projectId}",@@ -310,10 +305,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsRead),- }, h.GetProject)+ }, authz.PermProjectsRead, h.GetProject)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-project-compose",Method: http.MethodGet,Path: "/environments/{id}/projects/{projectId}/compose",@@ -324,10 +318,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsRead),- }, h.GetProjectCompose)+ }, authz.PermProjectsRead, h.GetProjectCompose)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-project-files",Method: http.MethodGet,Path: "/environments/{id}/projects/{projectId}/files",@@ -338,10 +331,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsRead),- }, h.GetProjectFiles)+ }, authz.PermProjectsRead, h.GetProjectFiles)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-project-runtime",Method: http.MethodGet,Path: "/environments/{id}/projects/{projectId}/runtime",@@ -352,10 +344,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsRead),- }, h.GetProjectRuntime)+ }, authz.PermProjectsRead, h.GetProjectRuntime)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-project-updates",Method: http.MethodGet,Path: "/environments/{id}/projects/{projectId}/updates",@@ -366,10 +357,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsRead),- }, h.GetProjectUpdates)+ }, authz.PermProjectsRead, h.GetProjectUpdates)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-project-file",Method: http.MethodGet,Path: "/environments/{id}/projects/{projectId}/file",@@ -380,10 +370,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsRead),- }, h.GetProjectFile)+ }, authz.PermProjectsRead, h.GetProjectFile)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "redeploy-project",Method: http.MethodPost,Path: "/environments/{id}/projects/{projectId}/redeploy",@@ -394,10 +383,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsDeploy),- }, h.RedeployProject)+ }, authz.PermProjectsDeploy, h.RedeployProject)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "destroy-project",Method: http.MethodDelete,Path: "/environments/{id}/projects/{projectId}/destroy",@@ -408,10 +396,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsDelete),- }, h.DestroyProject)+ }, authz.PermProjectsDelete, h.DestroyProject)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "update-project",Method: http.MethodPut,Path: "/environments/{id}/projects/{projectId}",@@ -422,10 +409,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsUpdate),- }, h.UpdateProject)+ }, authz.PermProjectsUpdate, h.UpdateProject)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "update-project-include",Method: http.MethodPut,Path: "/environments/{id}/projects/{projectId}/includes",@@ -436,10 +422,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsUpdate),- }, h.UpdateProjectInclude)+ }, authz.PermProjectsUpdate, h.UpdateProjectInclude)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "restart-project",Method: http.MethodPost,Path: "/environments/{id}/projects/{projectId}/restart",@@ -450,10 +435,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsRestart),- }, h.RestartProject)+ }, authz.PermProjectsRestart, h.RestartProject)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "update-project-services",Method: http.MethodPost,Path: "/environments/{id}/projects/{projectId}/update-services",@@ -464,10 +448,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsUpdate),- }, h.UpdateProjectServices)+ }, authz.PermProjectsUpdate, h.UpdateProjectServices)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "archive-project",Method: http.MethodPost,Path: "/environments/{id}/projects/{projectId}/archive",@@ -478,10 +461,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsArchive),- }, h.ArchiveProject)+ }, authz.PermProjectsArchive, h.ArchiveProject)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "unarchive-project",Method: http.MethodPost,Path: "/environments/{id}/projects/{projectId}/unarchive",@@ -492,10 +474,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsArchive),- }, h.UnarchiveProject)+ }, authz.PermProjectsArchive, h.UnarchiveProject)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "pull-project-images",Method: http.MethodPost,Path: "/environments/{id}/projects/{projectId}/pull",@@ -506,10 +487,9 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsDeploy),- }, h.PullProjectImages)+ }, authz.PermProjectsDeploy, h.PullProjectImages)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "build-project-images",Method: http.MethodPost,Path: "/environments/{id}/projects/{projectId}/build",@@ -520,8 +500,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermProjectsDeploy),- }, h.BuildProjectImages)+ }, authz.PermProjectsDeploy, h.BuildProjectImages)}// ListProjects returns a paginated list of projects.diff --git a/backend/api/handlers/settings.go b/backend/api/handlers/settings.goindex 73e00c9c9..75bf56320 100644--- a/backend/api/handlers/settings.go+++ b/backend/api/handlers/settings.go@@ -131,7 +131,7 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, sSecurity: []map[string][]string{},}, h.GetPublicSettings)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-settings",Method: http.MethodGet,Path: "/environments/{id}/settings",@@ -142,10 +142,9 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermSettingsRead),- }, h.GetSettings)+ }, authz.PermSettingsRead, h.GetSettings)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "update-settings",Method: http.MethodPut,Path: "/environments/{id}/settings",@@ -156,8 +155,7 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermSettingsWrite),- }, h.UpdateSettings)+ }, authz.PermSettingsWrite, h.UpdateSettings)// Top-level settings endpoints (not environment-scoped)huma.Register(api, huma.Operation{diff --git a/backend/api/handlers/swarm.go b/backend/api/handlers/swarm.goindex f57a79d8c..f2efb07da 100644--- a/backend/api/handlers/swarm.go+++ b/backend/api/handlers/swarm.go@@ -520,59 +520,59 @@ func RegisterSwarm(api huma.API, swarmSvc *services.SwarmService, environmentSvccfg: 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": {}}}, 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)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.ListServices)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.GetService)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmServices, h.CreateService)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmServices, h.UpdateService)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmServices, h.DeleteService)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.ListServiceTasks)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmServices, h.RollbackService)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmServices, h.ScaleService)++ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.ListNodes)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.GetNode)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmNodes, h.GetNodeAgentDeployment)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmNodes, h.UpdateNode)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmNodes, h.DeleteNode)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmNodes, h.PromoteNode)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmNodes, h.DemoteNode)+ humamw.RegisterWithPermission(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": {}}}}, 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)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.ListTasks)++ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.ListStacks)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmStacks, h.DeployStack)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.GetStack)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmStacks, h.GetStackSource)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmStacks, h.UpdateStackSource)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmStacks, h.DeleteStack)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.ListStackServices)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.ListStackTasks)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.RenderStackConfig)++ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.GetSwarmStatus)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.GetSwarmInfo)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmInit, h.InitSwarm)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmJoin, h.JoinSwarm)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmLeave, h.LeaveSwarm)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmUnlock, h.UnlockSwarm)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmUnlock, h.GetUnlockKey)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmUnlock, h.GetJoinTokens)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmUnlock, h.RotateJoinTokens)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmSpec, h.UpdateSwarmSpec)++ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.ListConfigs)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.GetConfig)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmConfigs, h.CreateConfig)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmConfigs, h.UpdateConfig)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmConfigs, h.DeleteConfig)++ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.ListSecrets)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmRead, h.GetSecret)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmSecrets, h.CreateSecret)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmSecrets, h.UpdateSecret)+ humamw.RegisterWithPermission(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": {}}}}, authz.PermSwarmSecrets, h.DeleteSecret)}// ListServices lists swarm services for an environment and returns a paginated response.diff --git a/backend/api/handlers/system.go b/backend/api/handlers/system.goindex f751b638a..f0f4184f4 100644--- a/backend/api/handlers/system.go+++ b/backend/api/handlers/system.go@@ -147,7 +147,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, sappCtx: appCtx.contextInternal(),}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "system-health",Method: http.MethodHead,Path: "/environments/{id}/system/health",@@ -159,9 +159,9 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s{"BearerAuth": {}},{"ApiKeyAuth": {}},},- }, h.Health)+ }, authz.PermSystemRead, h.Health)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-docker-info",Method: http.MethodGet,Path: "/environments/{id}/system/docker/info",@@ -172,10 +172,9 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermSystemRead),- }, h.GetDockerInfo)+ }, authz.PermSystemRead, h.GetDockerInfo)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "prune-all",Method: http.MethodPost,Path: "/environments/{id}/system/prune",@@ -186,10 +185,9 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermSystemPrune),- }, h.PruneAll)+ }, authz.PermSystemPrune, h.PruneAll)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "start-all-containers",Method: http.MethodPost,Path: "/environments/{id}/system/containers/start-all",@@ -200,10 +198,9 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermContainersStart),- }, h.StartAllContainers)+ }, authz.PermContainersStart, h.StartAllContainers)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "start-all-stopped-containers",Method: http.MethodPost,Path: "/environments/{id}/system/containers/start-stopped",@@ -214,10 +211,9 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermContainersStart),- }, h.StartAllStoppedContainers)+ }, authz.PermContainersStart, h.StartAllStoppedContainers)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "stop-all-containers",Method: http.MethodPost,Path: "/environments/{id}/system/containers/stop-all",@@ -228,10 +224,9 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermContainersStop),- }, h.StopAllContainers)+ }, authz.PermContainersStop, h.StopAllContainers)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "convert-docker-run",Method: http.MethodPost,Path: "/environments/{id}/system/convert",@@ -242,10 +237,9 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermContainersCreate),- }, h.ConvertDockerRun)+ }, authz.PermContainersCreate, h.ConvertDockerRun)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "check-upgrade",Method: http.MethodGet,Path: "/environments/{id}/system/upgrade/check",@@ -256,10 +250,9 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermSystemRead),- }, h.CheckUpgradeAvailable)+ }, authz.PermSystemRead, h.CheckUpgradeAvailable)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "trigger-upgrade",Method: http.MethodPost,Path: "/environments/{id}/system/upgrade",@@ -271,10 +264,9 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermSystemUpgrade),- }, h.TriggerUpgrade)+ }, authz.PermSystemUpgrade, h.TriggerUpgrade)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "trigger-update-all",Method: http.MethodPost,Path: "/environments/{id}/system/upgrade/all",@@ -286,10 +278,9 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermSystemUpgrade),- }, h.TriggerUpdateAll)+ }, authz.PermSystemUpgrade, h.TriggerUpdateAll)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "update-all-status",Method: http.MethodGet,Path: "/environments/{id}/system/upgrade/all/status",@@ -300,8 +291,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermSystemRead),- }, h.GetUpdateAllStatus)+ }, authz.PermSystemRead, h.GetUpdateAllStatus)}// rejectIfAgentModeInternal blocks manager-only operations when running as an agent.diff --git a/backend/api/handlers/templates.go b/backend/api/handlers/templates.goindex 6f81fd5bd..de2583947 100644--- a/backend/api/handlers/templates.go+++ b/backend/api/handlers/templates.go@@ -377,7 +377,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,Middlewares: humamw.RequirePermission(api, authz.PermTemplatesDelete),}, h.DeleteRegistry)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "getGlobalVariables",Method: "GET",Path: "/environments/{id}/templates/variables",@@ -388,10 +388,9 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermTemplatesRead),- }, h.GetGlobalVariables)+ }, authz.PermTemplatesRead, h.GetGlobalVariables)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "updateGlobalVariables",Method: "PUT",Path: "/environments/{id}/templates/variables",@@ -402,8 +401,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermTemplatesUpdate),- }, h.UpdateGlobalVariables)+ }, authz.PermTemplatesUpdate, h.UpdateGlobalVariables)}// ============================================================================diff --git a/backend/api/handlers/updater.go b/backend/api/handlers/updater.goindex c23176806..a32bf0b25 100644--- a/backend/api/handlers/updater.go+++ b/backend/api/handlers/updater.go@@ -65,7 +65,7 @@ func RegisterUpdater(api huma.API, updaterService *services.UpdaterService, appCappCtx: appCtx.contextInternal(),}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "run-updater",Method: http.MethodPost,Path: "/environments/{id}/updater/run",@@ -76,10 +76,9 @@ func RegisterUpdater(api huma.API, updaterService *services.UpdaterService, appC{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesCheck),- }, h.RunUpdater)+ }, authz.PermImageUpdatesCheck, h.RunUpdater)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-updater-status",Method: http.MethodGet,Path: "/environments/{id}/updater/status",@@ -90,10 +89,9 @@ func RegisterUpdater(api huma.API, updaterService *services.UpdaterService, appC{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesRead),- }, h.GetUpdaterStatus)+ }, authz.PermImageUpdatesRead, h.GetUpdaterStatus)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-updater-history",Method: http.MethodGet,Path: "/environments/{id}/updater/history",@@ -104,10 +102,9 @@ func RegisterUpdater(api huma.API, updaterService *services.UpdaterService, appC{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesRead),- }, h.GetUpdaterHistory)+ }, authz.PermImageUpdatesRead, h.GetUpdaterHistory)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "update-container",Method: http.MethodPost,Path: "/environments/{id}/containers/{containerId}/update",@@ -118,8 +115,7 @@ func RegisterUpdater(api huma.API, updaterService *services.UpdaterService, appC{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermImageUpdatesCheck),- }, h.UpdateContainer)+ }, authz.PermImageUpdatesCheck, h.UpdateContainer)}// RunUpdater applies pending container updates.diff --git a/backend/api/handlers/volumes.go b/backend/api/handlers/volumes.goindex c1428e8ea..1244eb43b 100644--- a/backend/api/handlers/volumes.go+++ b/backend/api/handlers/volumes.go@@ -310,7 +310,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,appCtx: appCtx.contextInternal(),}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-volume-usage-counts",Method: http.MethodGet,Path: "/environments/{id}/volumes/counts",@@ -321,10 +321,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesList),- }, h.GetVolumeUsageCounts)+ }, authz.PermVolumesList, h.GetVolumeUsageCounts)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-volumes",Method: http.MethodGet,Path: "/environments/{id}/volumes",@@ -335,10 +334,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesList),- }, h.ListVolumes)+ }, authz.PermVolumesList, h.ListVolumes)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-volume",Method: http.MethodGet,Path: "/environments/{id}/volumes/{volumeName}",@@ -349,10 +347,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesRead),- }, h.GetVolume)+ }, authz.PermVolumesRead, h.GetVolume)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "create-volume",Method: http.MethodPost,Path: "/environments/{id}/volumes",@@ -363,10 +360,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesCreate),- }, h.CreateVolume)+ }, authz.PermVolumesCreate, h.CreateVolume)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "remove-volume",Method: http.MethodDelete,Path: "/environments/{id}/volumes/{volumeName}",@@ -377,10 +373,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesDelete),- }, h.RemoveVolume)+ }, authz.PermVolumesDelete, h.RemoveVolume)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "prune-volumes",Method: http.MethodPost,Path: "/environments/{id}/volumes/prune",@@ -391,10 +386,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesPrune),- }, h.PruneVolumes)+ }, authz.PermVolumesPrune, h.PruneVolumes)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-volume-usage",Method: http.MethodGet,Path: "/environments/{id}/volumes/{volumeName}/usage",@@ -405,10 +399,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesRead),- }, h.GetVolumeUsage)+ }, authz.PermVolumesRead, h.GetVolumeUsage)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-volume-sizes",Method: http.MethodGet,Path: "/environments/{id}/volumes/sizes",@@ -419,12 +412,11 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesList),- }, h.GetVolumeSizes)+ }, authz.PermVolumesList, h.GetVolumeSizes)// --- Volume Browsing Endpoints ---- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "browse-volume-directory",Method: http.MethodGet,Path: "/environments/{id}/volumes/{volumeName}/browse",@@ -434,10 +426,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),- }, h.BrowseDirectory)+ }, authz.PermVolumesBrowse, h.BrowseDirectory)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-volume-file-content",Method: http.MethodGet,Path: "/environments/{id}/volumes/{volumeName}/browse/content",@@ -447,10 +438,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),- }, h.GetFileContent)+ }, authz.PermVolumesBrowse, h.GetFileContent)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "download-volume-file",Method: http.MethodGet,Path: "/environments/{id}/volumes/{volumeName}/browse/download",@@ -460,10 +450,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),- }, h.DownloadFile)+ }, authz.PermVolumesBrowse, h.DownloadFile)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "upload-volume-file",Method: http.MethodPost,Path: "/environments/{id}/volumes/{volumeName}/browse/upload",@@ -490,10 +479,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,},},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesUpload),- }, h.UploadFile)+ }, authz.PermVolumesUpload, h.UploadFile)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "create-volume-directory",Method: http.MethodPost,Path: "/environments/{id}/volumes/{volumeName}/browse/mkdir",@@ -503,10 +491,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesUpload),- }, h.CreateDirectory)+ }, authz.PermVolumesUpload, h.CreateDirectory)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "delete-volume-file",Method: http.MethodDelete,Path: "/environments/{id}/volumes/{volumeName}/browse",@@ -516,12 +503,11 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesDelete),- }, h.DeleteFile)+ }, authz.PermVolumesDelete, h.DeleteFile)// --- Volume Backup Endpoints ---- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-volume-backups",Method: http.MethodGet,Path: "/environments/{id}/volumes/{volumeName}/backups",@@ -531,10 +517,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),- }, h.ListBackups)+ }, authz.PermVolumesBrowse, h.ListBackups)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "create-volume-backup",Method: http.MethodPost,Path: "/environments/{id}/volumes/{volumeName}/backups",@@ -544,10 +529,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesBackup),- }, h.CreateBackup)+ }, authz.PermVolumesBackup, h.CreateBackup)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "restore-volume-backup",Method: http.MethodPost,Path: "/environments/{id}/volumes/{volumeName}/backups/{backupId}/restore",@@ -557,10 +541,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesBackup),- }, h.RestoreBackup)+ }, authz.PermVolumesBackup, h.RestoreBackup)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "restore-volume-backup-files",Method: http.MethodPost,Path: "/environments/{id}/volumes/{volumeName}/backups/{backupId}/restore-files",@@ -570,10 +553,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesBackup),- }, h.RestoreBackupFiles)+ }, authz.PermVolumesBackup, h.RestoreBackupFiles)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "delete-volume-backup",Method: http.MethodDelete,Path: "/environments/{id}/volumes/backups/{backupId}",@@ -583,10 +565,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesBackup),- }, h.DeleteBackup)+ }, authz.PermVolumesBackup, h.DeleteBackup)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "download-volume-backup",Method: http.MethodGet,Path: "/environments/{id}/volumes/backups/{backupId}/download",@@ -596,10 +577,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),- }, h.DownloadBackup)+ }, authz.PermVolumesBrowse, h.DownloadBackup)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "backup-has-path",Method: http.MethodGet,Path: "/environments/{id}/volumes/backups/{backupId}/has-path",@@ -609,10 +589,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),- }, h.BackupHasPath)+ }, authz.PermVolumesBrowse, h.BackupHasPath)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-backup-files",Method: http.MethodGet,Path: "/environments/{id}/volumes/backups/{backupId}/files",@@ -622,10 +601,9 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesBrowse),- }, h.ListBackupFiles)+ }, authz.PermVolumesBrowse, h.ListBackupFiles)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "upload-volume-backup",Method: http.MethodPost,Path: "/environments/{id}/volumes/{volumeName}/backups/upload",@@ -652,8 +630,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,},},},- Middlewares: humamw.RequirePermission(api, authz.PermVolumesUpload),- }, h.UploadAndRestore)+ }, authz.PermVolumesUpload, h.UploadAndRestore)}// ListVolumes returns a paginated list of volumes.diff --git a/backend/api/handlers/vulnerabilities.go b/backend/api/handlers/vulnerabilities.goindex c7cd49a18..ba00851b5 100644--- a/backend/api/handlers/vulnerabilities.go+++ b/backend/api/handlers/vulnerabilities.go@@ -130,7 +130,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.VulnerabappCtx: appCtx.contextInternal(),}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "scan-image-vulnerabilities",Method: http.MethodPost,Path: "/environments/{id}/images/{imageId}/vulnerabilities/scan",@@ -141,10 +141,9 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVulnsScan),- }, h.ScanImage)+ }, authz.PermVulnsScan, h.ScanImage)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-image-vulnerabilities",Method: http.MethodGet,Path: "/environments/{id}/images/{imageId}/vulnerabilities",@@ -155,10 +154,9 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),- }, h.GetScanResult)+ }, authz.PermVulnsRead, h.GetScanResult)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-image-vulnerability-summary",Method: http.MethodGet,Path: "/environments/{id}/images/{imageId}/vulnerabilities/summary",@@ -169,10 +167,9 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),- }, h.GetScanSummary)+ }, authz.PermVulnsRead, h.GetScanSummary)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-image-vulnerability-summaries",Method: http.MethodPost,Path: "/environments/{id}/images/vulnerabilities/summaries",@@ -183,10 +180,9 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),- }, h.GetScanSummaries)+ }, authz.PermVulnsRead, h.GetScanSummaries)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-image-vulnerabilities",Method: http.MethodGet,Path: "/environments/{id}/images/{imageId}/vulnerabilities/list",@@ -197,10 +193,9 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),- }, h.ListImageVulnerabilities)+ }, authz.PermVulnsRead, h.ListImageVulnerabilities)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-vulnerability-scanner-status",Method: http.MethodGet,Path: "/environments/{id}/vulnerabilities/scanner-status",@@ -211,10 +206,9 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),- }, h.GetScannerStatus)+ }, authz.PermVulnsRead, h.GetScannerStatus)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-environment-vulnerability-summary",Method: http.MethodGet,Path: "/environments/{id}/vulnerabilities/summary",@@ -225,10 +219,9 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),- }, h.GetEnvironmentSummary)+ }, authz.PermVulnsRead, h.GetEnvironmentSummary)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-environment-vulnerabilities",Method: http.MethodGet,Path: "/environments/{id}/vulnerabilities/all",@@ -239,10 +232,9 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),- }, h.ListAllVulnerabilities)+ }, authz.PermVulnsRead, h.ListAllVulnerabilities)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-environment-vulnerability-image-options",Method: http.MethodGet,Path: "/environments/{id}/vulnerabilities/image-options",@@ -253,10 +245,9 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),- }, h.ListAllVulnerabilityImageOptions)+ }, authz.PermVulnsRead, h.ListAllVulnerabilityImageOptions)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "ignore-vulnerability",Method: http.MethodPost,Path: "/environments/{id}/vulnerabilities/ignore",@@ -267,10 +258,9 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVulnsManage),- }, h.IgnoreVulnerability)+ }, authz.PermVulnsManage, h.IgnoreVulnerability)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "unignore-vulnerability",Method: http.MethodDelete,Path: "/environments/{id}/vulnerabilities/ignore/{ignoreId}",@@ -281,10 +271,9 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVulnsManage),- }, h.UnignoreVulnerability)+ }, authz.PermVulnsManage, h.UnignoreVulnerability)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-ignored-vulnerabilities",Method: http.MethodGet,Path: "/environments/{id}/vulnerabilities/ignored",@@ -295,8 +284,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermVulnsRead),- }, h.ListIgnoredVulnerabilities)+ }, authz.PermVulnsRead, h.ListIgnoredVulnerabilities)}// ScanImage initiates a vulnerability scan for an image.diff --git a/backend/api/handlers/webhooks.go b/backend/api/handlers/webhooks.goindex 6ef4ba230..db295d714 100644--- a/backend/api/handlers/webhooks.go+++ b/backend/api/handlers/webhooks.go@@ -60,7 +60,7 @@ type UpdateWebhookOutput struct {func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {h := &WebhookHandler{webhookService: webhookService}- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "list-webhooks",Method: http.MethodGet,Path: "/environments/{id}/webhooks",@@ -71,10 +71,9 @@ func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermWebhooksList),- }, h.ListWebhooks)+ }, authz.PermWebhooksList, h.ListWebhooks)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "create-webhook",Method: http.MethodPost,Path: "/environments/{id}/webhooks",@@ -85,10 +84,9 @@ func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermWebhooksCreate),- }, h.CreateWebhook)+ }, authz.PermWebhooksCreate, h.CreateWebhook)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "update-webhook",Method: http.MethodPatch,Path: "/environments/{id}/webhooks/{webhookId}",@@ -99,10 +97,9 @@ func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermWebhooksUpdate),- }, h.UpdateWebhook)+ }, authz.PermWebhooksUpdate, h.UpdateWebhook)- huma.Register(api, huma.Operation{+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "delete-webhook",Method: http.MethodDelete,Path: "/environments/{id}/webhooks/{webhookId}",@@ -113,8 +110,7 @@ func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {{"BearerAuth": {}},{"ApiKeyAuth": {}},},- Middlewares: humamw.RequirePermission(api, authz.PermWebhooksDelete),- }, h.DeleteWebhook)+ }, authz.PermWebhooksDelete, h.DeleteWebhook)}// ListWebhooks returns all webhooks for an environment (tokens are masked).diff --git a/backend/api/middleware/role.go b/backend/api/middleware/role.goindex 10900f10c..41aaa551f 100644--- a/backend/api/middleware/role.go+++ b/backend/api/middleware/role.go@@ -1,6 +1,7 @@package middlewareimport (+ "context""log/slog""net/http"@@ -9,6 +10,48 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/authz")+// MetaRequiredPermission is re-exported from the authz package for callers that+// reference it via this middleware package. The authoritative definition (and+// the matcher that consumes it) lives in authz.+const MetaRequiredPermission = authz.MetaRequiredPermission++// RegisterWithPermission registers a Huma operation that requires perm. It+// attaches the RequirePermission middleware AND records perm in the operation+// metadata (authz.MetaRequiredPermission) so the remote environment proxy can+// enforce the same permission for environment-scoped operations before+// forwarding a request to an agent.+//+// Use this instead of huma.Register with an inline RequirePermission middleware+// for every operation served under /environments/{id}/..., so the required+// permission stays the single source of truth for both local enforcement and+// remote-proxy enforcement. It is safe to use for org-level operations too; the+// recorded metadata is simply unused by the proxy for non-environment paths.+func RegisterWithPermission[I, O any](api huma.API, op huma.Operation, perm string, handler func(context.Context, *I) (*O, error)) {+ if op.Metadata == nil {+ op.Metadata = map[string]any{}+ }+ op.Metadata[authz.MetaRequiredPermission] = perm+ op.Middlewares = append(op.Middlewares, RequirePermission(api, perm)...)+ huma.Register(api, op, handler)+}++// RegisterWithoutPermission registers an environment-scoped Huma operation that+// requires authentication but no specific permission. It records a metadata+// marker (authz.MetaProxyNoPermission) so the remote environment proxy allows+// the operation for any authenticated caller instead of denying it by default,+// and so the env-scoped permission guard test recognizes the operation as+// intentionally permission-free.+//+// Use this ONLY for intentionally low-sensitivity endpoints (for example a+// health check). Operations that act on resources must use RegisterWithPermission.+func RegisterWithoutPermission[I, O any](api huma.API, op huma.Operation, handler func(context.Context, *I) (*O, error)) {+ if op.Metadata == nil {+ op.Metadata = map[string]any{}+ }+ op.Metadata[authz.MetaProxyNoPermission] = true+ huma.Register(api, op, handler)+}+// 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,diff --git a/backend/api/ws/handler.go b/backend/api/ws/handler.goindex 01137743d..1ac057ba2 100644--- a/backend/api/ws/handler.go+++ b/backend/api/ws/handler.go@@ -18,7 +18,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/services"- "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/system"wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"@@ -241,12 +240,9 @@ func NewWebSocketHandler(},}wsGroup := group.Group("/environments/:id/ws", authMiddleware.WithAdminNotRequired().Add())- 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))+ for _, r := range handler.proxiedRoutes() {+ wsGroup.GET(r.path, r.handler, middleware.RequirePermission(r.perm))+ }handler.registerDiagnosticsRoutesInternal(group, authMiddleware)}diff --git a/backend/api/ws/proxy_permissions.go b/backend/api/ws/proxy_permissions.gonew file mode 100644index 000000000..22b5ad8a8--- /dev/null+++ b/backend/api/ws/proxy_permissions.go@@ -0,0 +1,45 @@+package ws++import (+ "net/http"++ "github.com/labstack/echo/v4"++ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+)++// proxiedWSRoute couples a proxied WebSocket route (relative to the+// /environments/{id}/ws group) with its handler and the permission it requires.+// It is the single source of truth for both Echo route registration and the+// remote environment proxy permission matcher, so the two can never drift.+type proxiedWSRoute struct {+ path string+ handler echo.HandlerFunc+ perm string+}++// proxiedRoutes returns the WebSocket streams that are proxied to remote+// environments, each paired with its required permission.+func (h *WebSocketHandler) proxiedRoutes() []proxiedWSRoute {+ return []proxiedWSRoute{+ {"/projects/:projectId/logs", h.ProjectLogs, authz.PermProjectsLogs},+ {"/containers/:containerId/logs", h.ContainerLogs, authz.PermContainersLogs},+ {"/containers/:containerId/stats", h.ContainerStats, authz.PermContainersRead},+ {"/containers/:containerId/terminal", h.ContainerExec, authz.PermContainersExec},+ {"/swarm/services/:serviceId/logs", h.ServiceLogs, authz.PermSwarmServicesLogs},+ {"/system/stats", h.SystemStats, authz.PermSystemRead},+ }+}++// AddProxiedPermissions registers the permissions required by proxied WebSocket+// routes with the environment proxy permission matcher. These streams are+// served by Echo (not Huma), so they are absent from the OpenAPI document and+// must be registered with the matcher separately. The paths are stored relative+// to /environments/{id} (i.e. prefixed with "/ws"), matching the resource+// suffix the proxy computes for forwarded requests.+func AddProxiedPermissions(m *authz.PermissionMatcher) {+ var h WebSocketHandler+ for _, r := range h.proxiedRoutes() {+ m.Add(http.MethodGet, "/ws"+r.path, r.perm)+ }+}diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex fc4b7b07e..7b6bc86c6 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -20,6 +20,8 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/di""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/v2/internal/models"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie""github.com/getarcaneapp/arcane/types/v2"@@ -88,20 +90,40 @@ func requestLoggerMiddlewareInternal() echo.MiddlewareFunc {}func createAuthValidatorInternal(appServices *di.Services) middleware.AuthValidator {- return func(ctx context.Context, c echo.Context) bool {+ resolveUser := func(ctx context.Context, user *models.User) *authz.PermissionSet {+ ps, err := appServices.Role.ResolvePermissions(ctx, user)+ if err != nil || ps == nil {+ slog.WarnContext(ctx, "failed to resolve user permissions for env proxy", "error", err)+ return authz.NewPermissionSet()+ }+ return ps+ }+ resolveKey := func(ctx context.Context, keyID string) *authz.PermissionSet {+ ps, err := appServices.Role.ResolveApiKeyPermissions(ctx, keyID)+ if err != nil || ps == nil {+ slog.WarnContext(ctx, "failed to resolve api key permissions for env proxy", "error", err)+ return authz.NewPermissionSet()+ }+ return ps+ }+ return func(ctx context.Context, c echo.Context) (*authz.PermissionSet, bool) {req := c.Request()// Check for API key authenticationif apiKey := req.Header.Get("X-Api-Key"); apiKey != "" {- // User-owned API key- if user, err := appServices.ApiKey.ValidateApiKey(ctx, apiKey); err == nil && user != nil {- return true+ // User-owned API key: personal keys inherit the owner's role+ // permissions; scoped keys are limited to their own grants.+ if user, key, err := appServices.ApiKey.ValidateApiKeyWithID(ctx, apiKey); err == nil && user != nil {+ if key != nil && key.Kind != models.ApiKeyKindPersonal {+ return resolveKey(ctx, key.ID), true+ }+ return resolveUser(ctx, user), true}// Environment bootstrap key (user_id = NULL): used by the proxy when forwarding// requests to a remote env whose apiUrl resolves back to this manager.if _, err := appServices.ApiKey.GetEnvironmentByApiKey(ctx, apiKey); err == nil {- return true+ return authz.SudoPermissionSet(), true}- return false+ return nil, false}// Check for Bearer token authentication@@ -113,11 +135,14 @@ func createAuthValidatorInternal(appServices *di.Services) middleware.AuthValida}if token == "" {- return false+ return nil, false}user, _, err := appServices.Auth.VerifyToken(ctx, token)- return err == nil && user != nil+ if err != nil || user == nil {+ return nil, false+ }+ return resolveUser(ctx, user), true}}@@ -180,16 +205,26 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *di.Servichandlers.RegisterFederatedTokenExchange(apiGroup, appServices.Federated) //nolint:contextcheck // public RFC 8693 form endpoint uses request context.handlers.RegisterAgentEventIngestion(apiGroup, appServices.Event, cfg) //nolint:contextcheck // internal agent-token route; intentionally outside user/RBAC auth.+ permissionMatcher := authz.NewPermissionMatcher()+//nolint:contextcheck // Echo middleware reads context from echo.Context.Request().Context(), not a parameter.envProxyMiddleware := middleware.NewEnvProxyMiddlewareWithParam(types.LOCAL_DOCKER_ENVIRONMENT_ID,"id",envResolver,createAuthValidatorInternal(appServices),+ permissionMatcher,)apiGroup.Use(envProxyMiddleware)- _ = api.SetupAPI(e, apiGroup, handlerAppCtx, cfg, appServices) //nolint:contextcheck // app lifecycle context is intentionally wrapped for detached activity work.+ humaAPI := api.SetupAPI(e, apiGroup, handlerAppCtx, cfg, appServices) //nolint:contextcheck // app lifecycle context is intentionally wrapped for detached activity work.++ // Populate the proxy permission matcher from the registered API surface so+ // remote-environment requests are authorized with the same permissions+ // enforced locally. The matcher pointer is shared with the proxy middleware+ // constructed above; population completes here, before the server serves traffic.+ permissionMatcher.CollectFromHumaAPI(humaAPI)+ ws.AddProxiedPermissions(permissionMatcher)for _, register := range registerBuildableRoutes {register(apiGroup, appServices)diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.goindex 60ccc9129..00af81915 100644--- a/backend/internal/common/errors.go+++ b/backend/internal/common/errors.go@@ -383,6 +383,12 @@ func (e *EnvironmentUnauthorizedError) Error() string {return "Authentication required to access remote environments"}+type EnvironmentForbiddenError struct{}++func (e *EnvironmentForbiddenError) Error() string {+ return "You don't have permission to perform this action on this environment"+}+type EnvironmentInvalidProxyTargetError struct {Err error}diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.goindex 6120e2c68..f4ae3111a 100644--- a/backend/internal/middleware/environment_middleware.go+++ b/backend/internal/middleware/environment_middleware.go@@ -13,6 +13,7 @@ import ("time""github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"wsutil "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"httputils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"@@ -47,9 +48,12 @@ var managementEndpointSet = map[string]struct{}{// Returns: apiURL, accessToken, enabled, errortype EnvResolver func(ctx context.Context, id string) (string, *string, bool, error)-// AuthValidator validates authentication for a request.-// Returns true if the request is authenticated, false otherwise.-type AuthValidator func(ctx context.Context, c echo.Context) bool+// AuthValidator validates authentication for a request and resolves the+// caller's effective permission set. The boolean result reports whether the+// request is authenticated; the permission set is used to authorize proxied+// requests against the target environment. Sudo permission sets (environment+// access tokens, internal agent proxies) bypass authorization.+type AuthValidator func(ctx context.Context, c echo.Context) (*authz.PermissionSet, bool)// EnvironmentMiddleware proxies requests for remote environments to their respective agents.type EnvironmentMiddleware struct {@@ -59,11 +63,12 @@ type EnvironmentMiddleware struct {authValidator AuthValidatorhttpClient *http.Clientregistry *edge.TunnelRegistry+ matcher *authz.PermissionMatcher}// NewEnvProxyMiddlewareWithParam creates middleware that proxies requests to remote environments.-func NewEnvProxyMiddlewareWithParam(localID, paramName string, resolver EnvResolver, authValidator AuthValidator) echo.MiddlewareFunc {- return NewEnvProxyMiddlewareWithParamAndRegistry(localID, paramName, resolver, authValidator, edge.GetRegistry())+func NewEnvProxyMiddlewareWithParam(localID, paramName string, resolver EnvResolver, authValidator AuthValidator, matcher *authz.PermissionMatcher) echo.MiddlewareFunc {+ return NewEnvProxyMiddlewareWithParamAndRegistry(localID, paramName, resolver, authValidator, matcher, edge.GetRegistry())}// NewEnvProxyMiddlewareWithParamAndRegistry creates middleware with an injected tunnel registry.@@ -72,6 +77,7 @@ func NewEnvProxyMiddlewareWithParamAndRegistry(paramName string,resolver EnvResolver,authValidator AuthValidator,+ matcher *authz.PermissionMatcher,registry *edge.TunnelRegistry,) echo.MiddlewareFunc {if registry == nil {@@ -85,6 +91,7 @@ func NewEnvProxyMiddlewareWithParamAndRegistry(authValidator: authValidator,httpClient: &http.Client{Timeout: proxyTimeout},registry: registry,+ matcher: matcher,}return func(next echo.HandlerFunc) echo.HandlerFunc {return func(c echo.Context) error {@@ -106,11 +113,16 @@ func (m *EnvironmentMiddleware) Handle(c echo.Context, next echo.HandlerFunc) er}// SECURITY: Validate authentication BEFORE proxying to remote environments.- if m.authValidator != nil && !m.authValidator(c.Request().Context(), c) {- return c.JSON(http.StatusUnauthorized, map[string]any{- "success": false,- "data": map[string]any{"error": (&common.EnvironmentUnauthorizedError{}).Error()},- })+ var perms *authz.PermissionSet+ if m.authValidator != nil {+ ps, ok := m.authValidator(c.Request().Context(), c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]any{+ "success": false,+ "data": map[string]any{"error": (&common.EnvironmentUnauthorizedError{}).Error()},+ })+ }+ perms = ps}apiURL, accessToken, enabled, err := m.resolver(c.Request().Context(), envID)@@ -128,6 +140,18 @@ func (m *EnvironmentMiddleware) Handle(c echo.Context, next echo.HandlerFunc) er})}+ // SECURITY: Enforce the caller's per-environment permission BEFORE proxying.+ // Remote agents run with a sudo permission set and perform no authorization+ // of their own, so authorization for proxied requests must happen here,+ // mirroring the per-operation RequirePermission checks used for the local+ // environment.+ if m.proxyPermissionDenied(c, perms, envID) {+ return c.JSON(http.StatusForbidden, map[string]any{+ "success": false,+ "data": map[string]any{"error": (&common.EnvironmentForbiddenError{}).Error()},+ })+ }+isEdgeEnvironment := isEdgeEnvironmentURLInternal(apiURL)if handled, err := m.proxyActiveEdgeTunnelInternal(c, envID, accessToken); handled {@@ -151,6 +175,50 @@ func (m *EnvironmentMiddleware) Handle(c echo.Context, next echo.HandlerFunc) erreturn m.proxyHTTP(c, target, accessToken)}+// proxyPermissionDenied reports whether the caller lacks permission to perform+// the proxied request against environment envID. It mirrors the per-operation+// RequirePermission checks enforced for the local environment: the permission+// required for the (method, path) is looked up in the matcher and evaluated+// against the caller's permission set for the target environment.+//+// Sudo callers (environment access tokens and internal agent proxies) bypass+// the check. Requests whose (method, path) has no known permission mapping are+// denied (default-deny), so a newly added proxied route cannot silently bypass+// authorization before it is mapped.+func (m *EnvironmentMiddleware) proxyPermissionDenied(c echo.Context, ps *authz.PermissionSet, envID string) bool {+ if m.matcher == nil {+ return false+ }+ if ps != nil && ps.Sudo {+ return false+ }++ method := c.Request().Method+ suffix := m.buildResourceSuffix(c.Request().URL.Path, envID)+ perm, ok := m.matcher.Lookup(method, suffix)+ if !ok {+ slog.WarnContext(c.Request().Context(), "Denying proxied request with no known permission mapping",+ "method", method, "path", suffix, "environment_id", envID)+ return true+ }+ if perm == "" {+ // Explicitly public proxied route (e.g. public settings): allowed for+ // any authenticated caller, matching local enforcement.+ return false+ }++ scopeEnvID := ""+ if authz.IsEnvScoped(perm) {+ scopeEnvID = envID+ }+ if !ps.Allows(perm, scopeEnvID) {+ slog.DebugContext(c.Request().Context(), "Denying proxied request: permission denied",+ "method", method, "path", suffix, "permission", perm, "environment_id", envID)+ return true+ }+ return false+}+func (m *EnvironmentMiddleware) proxyActiveEdgeTunnelInternal(c echo.Context, envID string, accessToken *string) (bool, error) {tunnel, ok := m.getActiveEdgeTunnelInternal(envID)if !ok {diff --git a/backend/internal/middleware/environment_middleware_authz_test.go b/backend/internal/middleware/environment_middleware_authz_test.gonew file mode 100644index 000000000..6c80126f6--- /dev/null+++ b/backend/internal/middleware/environment_middleware_authz_test.go@@ -0,0 +1,134 @@+package middleware++import (+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/labstack/echo/v4"++ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+)++const proxyTestEnvID = "remote-1"++func newProxyAuthzMiddleware(matcher *authz.PermissionMatcher) *EnvironmentMiddleware {+ return &EnvironmentMiddleware{localID: "0", paramName: "id", matcher: matcher}+}++func newProxyRequestContext(method, path string) echo.Context {+ e := echo.New()+ req := httptest.NewRequest(method, path, nil)+ return e.NewContext(req, httptest.NewRecorder())+}++func containerMatcher() *authz.PermissionMatcher {+ m := authz.NewPermissionMatcher()+ m.Add(http.MethodGet, "/containers", authz.PermContainersList)+ m.Add(http.MethodPost, "/containers/{containerId}/restart", authz.PermContainersRestart)+ m.AddPublic(http.MethodGet, "/settings/public")+ return m+}++func TestProxyPermissionDeniedBlocksWriteForReadOnlyUser(t *testing.T) {+ m := newProxyAuthzMiddleware(containerMatcher())+ ps := authz.NewPermissionSet()+ ps.AddEnv(proxyTestEnvID, authz.PermContainersList, authz.PermContainersRead)++ c := newProxyRequestContext(http.MethodPost, "/api/environments/"+proxyTestEnvID+"/containers/abc/restart")+ if !m.proxyPermissionDenied(c, ps, proxyTestEnvID) {+ t.Fatal("expected restart to be denied for a read-only user")+ }+}++func TestProxyPermissionDeniedAllowsWriteForPermittedUser(t *testing.T) {+ m := newProxyAuthzMiddleware(containerMatcher())+ ps := authz.NewPermissionSet()+ ps.AddEnv(proxyTestEnvID, authz.PermContainersRestart)++ c := newProxyRequestContext(http.MethodPost, "/api/environments/"+proxyTestEnvID+"/containers/abc/restart")+ if m.proxyPermissionDenied(c, ps, proxyTestEnvID) {+ t.Fatal("expected restart to be allowed for a user with containers:restart")+ }+}++func TestProxyPermissionDeniedAllowsRead(t *testing.T) {+ m := newProxyAuthzMiddleware(containerMatcher())+ ps := authz.NewPermissionSet()+ ps.AddEnv(proxyTestEnvID, authz.PermContainersList)++ c := newProxyRequestContext(http.MethodGet, "/api/environments/"+proxyTestEnvID+"/containers")+ if m.proxyPermissionDenied(c, ps, proxyTestEnvID) {+ t.Fatal("expected list to be allowed for a user with containers:list")+ }+}++func TestProxyPermissionDeniedDeniesPermissionFromDifferentEnv(t *testing.T) {+ m := newProxyAuthzMiddleware(containerMatcher())+ // Caller holds containers:restart, but only for a DIFFERENT environment.+ ps := authz.NewPermissionSet()+ ps.AddEnv("other-env", authz.PermContainersRestart)++ c := newProxyRequestContext(http.MethodPost, "/api/environments/"+proxyTestEnvID+"/containers/abc/restart")+ if !m.proxyPermissionDenied(c, ps, proxyTestEnvID) {+ t.Fatal("expected denial: permission is scoped to a different environment")+ }+}++func TestProxyPermissionDeniedSudoBypasses(t *testing.T) {+ m := newProxyAuthzMiddleware(containerMatcher())+ c := newProxyRequestContext(http.MethodPost, "/api/environments/"+proxyTestEnvID+"/containers/abc/restart")+ if m.proxyPermissionDenied(c, authz.SudoPermissionSet(), proxyTestEnvID) {+ t.Fatal("expected sudo permission set to bypass the permission check")+ }+}++func TestProxyPermissionDeniedDefaultDeniesUnmappedRoute(t *testing.T) {+ m := newProxyAuthzMiddleware(containerMatcher())+ ps := authz.NewPermissionSet()+ ps.AddEnv(proxyTestEnvID, authz.PermContainersRestart, authz.PermContainersList)++ c := newProxyRequestContext(http.MethodPost, "/api/environments/"+proxyTestEnvID+"/unknown/resource")+ if !m.proxyPermissionDenied(c, ps, proxyTestEnvID) {+ t.Fatal("expected an unmapped proxied route to be denied by default")+ }+}++func TestProxyPermissionDeniedAllowsPublicRoute(t *testing.T) {+ m := newProxyAuthzMiddleware(containerMatcher())+ ps := authz.NewPermissionSet() // no permissions at all++ c := newProxyRequestContext(http.MethodGet, "/api/environments/"+proxyTestEnvID+"/settings/public")+ if m.proxyPermissionDenied(c, ps, proxyTestEnvID) {+ t.Fatal("expected an explicitly public route to be allowed for any authenticated caller")+ }+}++// wsTerminalMatcher mirrors ws.AddProxiedPermissions for the container terminal+// stream: the proxy computes the suffix "/ws/containers/{id}/terminal" for a+// forwarded WebSocket request, and the matcher requires containers:exec for it.+func wsTerminalMatcher() *authz.PermissionMatcher {+ m := authz.NewPermissionMatcher()+ m.Add(http.MethodGet, "/ws/containers/{containerId}/terminal", authz.PermContainersExec)+ return m+}++func TestProxyPermissionDeniedWSTerminalRequiresExec(t *testing.T) {+ m := newProxyAuthzMiddleware(wsTerminalMatcher())++ // A caller who can read and list containers but lacks containers:exec must+ // not be able to open a terminal stream on the remote environment.+ ps := authz.NewPermissionSet()+ ps.AddEnv(proxyTestEnvID, authz.PermContainersRead, authz.PermContainersList)++ c := newProxyRequestContext(http.MethodGet, "/api/environments/"+proxyTestEnvID+"/ws/containers/abc/terminal")+ if !m.proxyPermissionDenied(c, ps, proxyTestEnvID) {+ t.Fatal("expected WS terminal to be denied without containers:exec")+ }++ // Granting containers:exec allows the same stream.+ ps.AddEnv(proxyTestEnvID, authz.PermContainersExec)+ if m.proxyPermissionDenied(c, ps, proxyTestEnvID) {+ t.Fatal("expected WS terminal to be allowed with containers:exec")+ }+}diff --git a/backend/internal/middleware/environment_middleware_test.go b/backend/internal/middleware/environment_middleware_test.goindex 729fc80d4..803cfef57 100644--- a/backend/internal/middleware/environment_middleware_test.go+++ b/backend/internal/middleware/environment_middleware_test.go@@ -6,6 +6,7 @@ import ("net/http/httptest""testing"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/labstack/echo/v4""github.com/stretchr/testify/assert"@@ -19,10 +20,10 @@ func newTestEnvironmentMiddleware() *EnvironmentMiddleware {_ = ctxreturn "edge://oracle-1", nil, true, nil},- authValidator: func(ctx context.Context, c echo.Context) bool {+ authValidator: func(ctx context.Context, c echo.Context) (*authz.PermissionSet, bool) {_ = ctx_ = c- return true+ return authz.SudoPermissionSet(), true},httpClient: &http.Client{Timeout: proxyTimeout},registry: edge.NewTunnelRegistry(),@@ -228,6 +229,46 @@ func TestEnvironmentMiddleware_KeepsActivityEndpointsLocal(t *testing.T) {}}+func TestEnvironmentMiddleware_LocalEnvironmentSkipsProxyPermissionCheck(t *testing.T) {+ // The local environment ("0") is served directly and is never proxied, so+ // the proxy's per-environment authorization must not apply to it. Set up a+ // matcher that would require containers:list and a caller with no+ // permissions at all: if local requests were subject to proxy authz, this+ // would be a 403. It must instead fall through to the local handler, where+ // the operation's own RequirePermission middleware enforces access.+ matcher := authz.NewPermissionMatcher()+ matcher.Add(http.MethodGet, "/containers", authz.PermContainersList)++ mw := &EnvironmentMiddleware{+ localID: "0",+ paramName: "id",+ matcher: matcher,+ authValidator: func(ctx context.Context, c echo.Context) (*authz.PermissionSet, bool) {+ _ = ctx+ _ = c+ return authz.NewPermissionSet(), true+ },+ httpClient: &http.Client{Timeout: proxyTimeout},+ registry: edge.NewTunnelRegistry(),+ }++ router := echo.New()+ api := attachMiddleware(router, mw)++ localHandlerHit := false+ api.GET("/environments/:id/containers", func(c echo.Context) error {+ localHandlerHit = true+ return c.JSON(http.StatusOK, map[string]any{"success": true})+ })++ req := httptest.NewRequest(http.MethodGet, "/api/environments/0/containers", nil)+ recorder := httptest.NewRecorder()+ router.ServeHTTP(recorder, req)++ assert.Equal(t, http.StatusOK, recorder.Code)+ assert.True(t, localHandlerHit, "local environment request must reach the local handler, not be proxy-authorized")+}+func TestEnvironmentMiddleware_ProxyWebSocketRejectsEdgeTargetsWithoutTunnel(t *testing.T) {middleware := newTestEnvironmentMiddleware()e := echo.New()diff --git a/backend/pkg/authz/permission_matcher.go b/backend/pkg/authz/permission_matcher.gonew file mode 100644index 000000000..93eaedcb5--- /dev/null+++ b/backend/pkg/authz/permission_matcher.go@@ -0,0 +1,124 @@+package authz++import "strings"++// PermissionMatcher maps an HTTP method and environment-relative resource path+// to the permission required to perform it. It mirrors the per-operation+// RequirePermission checks enforced for the local environment so the remote+// environment proxy can enforce the same permission before forwarding a request+// to an agent (which itself runs with a sudo permission set and performs no+// authorization).+//+// Paths registered and looked up are the resource suffix AFTER the+// /environments/{id} prefix, e.g. "/containers/{containerId}/start" for the+// REST API or "/ws/containers/{containerId}/terminal" for WebSocket streams.+//+// The matcher is populated once during startup and is read-only afterwards, so+// concurrent Lookup calls during request serving need no synchronization.+type PermissionMatcher struct {+ routes []permRoute+}++type permRoute struct {+ method string+ segments []string // literal segment, or "*" for a path parameter+ perm string+}++// NewPermissionMatcher returns an empty matcher.+func NewPermissionMatcher() *PermissionMatcher {+ return &PermissionMatcher{}+}++// Add registers the permission required for method + pathTemplate. pathTemplate+// is the resource suffix after /environments/{id}. Path parameters may use+// either Huma's "{name}" or Echo's ":name" syntax; both are treated as+// single-segment wildcards.+func (m *PermissionMatcher) Add(method, pathTemplate, perm string) {+ m.routes = append(m.routes, permRoute{+ method: strings.ToUpper(method),+ segments: templateSegmentsInternal(pathTemplate),+ perm: perm,+ })+}++// AddPublic registers method + pathTemplate as a proxied route that requires no+// permission (an intentionally public endpoint). Lookup reports it as found+// with an empty permission string, which the proxy treats as "allow".+func (m *PermissionMatcher) AddPublic(method, pathTemplate string) {+ m.Add(method, pathTemplate, "")+}++// Lookup returns the permission required for method + suffixPath, where+// suffixPath is the resource path after /environments/{id} (for example+// "/containers/abc123/start"). When multiple templates match, the most specific+// one wins — a route with more literal (non-wildcard) segments is preferred, so+// static routes such as "/containers/counts" take precedence over+// parameterized routes such as "/containers/{containerId}".+//+// The boolean result reports whether any route matched. Callers should treat a+// false result as "deny" for proxied resource paths.+func (m *PermissionMatcher) Lookup(method, suffixPath string) (string, bool) {+ if i := strings.IndexByte(suffixPath, '?'); i >= 0 {+ suffixPath = suffixPath[:i]+ }+ reqSegs := pathSegmentsInternal(suffixPath)+ method = strings.ToUpper(method)++ bestScore := -1+ bestPerm := ""+ found := false+ for i := range m.routes {+ r := m.routes[i]+ if r.method != method || len(r.segments) != len(reqSegs) {+ continue+ }+ score := 0+ match := true+ for j, seg := range r.segments {+ if seg == "*" {+ continue+ }+ if seg != reqSegs[j] {+ match = false+ break+ }+ score+++ }+ if match && score > bestScore {+ bestScore = score+ bestPerm = r.perm+ found = true+ }+ }+ return bestPerm, found+}++// pathSegmentsInternal splits a path into its non-empty segments, ignoring+// leading and trailing slashes.+func pathSegmentsInternal(p string) []string {+ p = strings.Trim(p, "/")+ if p == "" {+ return nil+ }+ return strings.Split(p, "/")+}++// templateSegmentsInternal splits a path template into segments, normalizing+// any path parameter ("{name}" or ":name") to the "*" wildcard.+func templateSegmentsInternal(t string) []string {+ segs := pathSegmentsInternal(t)+ for i, s := range segs {+ if isParamSegmentInternal(s) {+ segs[i] = "*"+ }+ }+ return segs+}++func isParamSegmentInternal(s string) bool {+ if strings.HasPrefix(s, ":") {+ return true+ }+ return strings.HasPrefix(s, "{") && strings.HasSuffix(s, "}")+}diff --git a/backend/pkg/authz/permission_matcher_huma.go b/backend/pkg/authz/permission_matcher_huma.gonew file mode 100644index 000000000..7398c536b--- /dev/null+++ b/backend/pkg/authz/permission_matcher_huma.go@@ -0,0 +1,119 @@+package authz++import (+ "net/http"+ "strings"++ "github.com/danielgtaylor/huma/v2"+)++// MetaRequiredPermission is the huma.Operation.Metadata key under which the+// environment-scoped registration helper records the permission an operation+// requires. The remote environment proxy reads this metadata (via the OpenAPI+// document) to enforce the same permission locally before forwarding a request+// to an agent.+const MetaRequiredPermission = "arcane:requiredPermission"++// MetaProxyNoPermission is the huma.Operation.Metadata key that marks an+// environment-scoped operation as intentionally requiring no specific+// permission (only authentication). The remote environment proxy allows such+// operations for any authenticated caller instead of denying them by default.+const MetaProxyNoPermission = "arcane:proxyNoPermission"++const envPathPrefixInternal = "/environments/{id}"++// CollectFromHumaAPI walks every operation registered on humaAPI and records,+// for each environment-scoped operation, the permission it requires. The+// permission is read from the operation metadata set by the registration+// helper (see MetaRequiredPermission).+//+// Operation paths are stored as the resource suffix after /environments/{id}+// (for example "/containers/{containerId}/start") so the remote environment+// proxy can match them against forwarded request paths.+func (m *PermissionMatcher) CollectFromHumaAPI(humaAPI huma.API) {+ oapi := humaAPI.OpenAPI()+ if oapi == nil || oapi.Paths == nil {+ return+ }+ for path, item := range oapi.Paths {+ if item == nil {+ continue+ }+ suffix, ok := envResourceSuffixInternal(path)+ if !ok {+ continue+ }+ for method, op := range operationsByMethodInternal(item) {+ if op == nil {+ continue+ }+ if perm, ok := requiredPermissionInternal(op); ok {+ m.Add(method, suffix, perm)+ continue+ }+ // An environment-scoped operation that declares no required+ // permission is only allowed through the proxy when it is+ // intentionally permission-free: either an explicitly public+ // endpoint (empty Security) or one registered with+ // RegisterWithoutPermission. Anything else is left unmapped and+ // denied by default.+ if isPublicOperationInternal(op) || isProxyNoPermissionInternal(op) {+ m.AddPublic(method, suffix)+ }+ }+ }+}++// envResourceSuffixInternal returns the resource path after /environments/{id}+// for environment-scoped operation paths, e.g. "/containers" for+// "/environments/{id}/containers". It returns ok=false for paths that are not+// environment-scoped resource paths (including the bare "/environments/{id}").+func envResourceSuffixInternal(path string) (string, bool) {+ if !strings.HasPrefix(path, envPathPrefixInternal+"/") {+ return "", false+ }+ return strings.TrimPrefix(path, envPathPrefixInternal), true+}++func requiredPermissionInternal(op *huma.Operation) (string, bool) {+ if op.Metadata == nil {+ return "", false+ }+ perm, ok := op.Metadata[MetaRequiredPermission].(string)+ if !ok || perm == "" {+ return "", false+ }+ return perm, true+}++// isPublicOperationInternal reports whether op explicitly opts out of all+// security requirements (an empty, non-nil Security list). Such operations are+// intentionally public and are allowed through the proxy without a permission+// check. A nil Security list means the operation inherits the global security+// requirement and is therefore NOT public.+func isPublicOperationInternal(op *huma.Operation) bool {+ return op.Security != nil && len(op.Security) == 0+}++// isProxyNoPermissionInternal reports whether op is marked as intentionally+// requiring no specific permission (only authentication) via the+// MetaProxyNoPermission metadata key set by RegisterWithoutPermission.+func isProxyNoPermissionInternal(op *huma.Operation) bool {+ if op.Metadata == nil {+ return false+ }+ v, ok := op.Metadata[MetaProxyNoPermission].(bool)+ return ok && v+}++func operationsByMethodInternal(item *huma.PathItem) map[string]*huma.Operation {+ return map[string]*huma.Operation{+ http.MethodGet: item.Get,+ http.MethodPost: item.Post,+ http.MethodPut: item.Put,+ http.MethodDelete: item.Delete,+ http.MethodPatch: item.Patch,+ http.MethodHead: item.Head,+ http.MethodOptions: item.Options,+ }+}diff --git a/backend/pkg/authz/permission_matcher_test.go b/backend/pkg/authz/permission_matcher_test.gonew file mode 100644index 000000000..ef0f3347a--- /dev/null+++ b/backend/pkg/authz/permission_matcher_test.go@@ -0,0 +1,77 @@+package authz++import "testing"++func TestPermissionMatcherLookupExactAndWildcard(t *testing.T) {+ m := NewPermissionMatcher()+ m.Add("POST", "/containers/{containerId}/start", "containers:start")+ m.Add("GET", "/containers/{containerId}", "containers:read")++ if perm, ok := m.Lookup("POST", "/containers/abc123/start"); !ok || perm != "containers:start" {+ t.Fatalf("expected containers:start, got %q ok=%v", perm, ok)+ }+ if perm, ok := m.Lookup("GET", "/containers/abc123"); !ok || perm != "containers:read" {+ t.Fatalf("expected containers:read, got %q ok=%v", perm, ok)+ }+}++func TestPermissionMatcherStaticBeatsWildcard(t *testing.T) {+ m := NewPermissionMatcher()+ // Order intentionally puts the wildcard route first to prove specificity,+ // not registration order, decides the winner.+ m.Add("GET", "/containers/{containerId}", "containers:read")+ m.Add("GET", "/containers/counts", "containers:list")++ if perm, ok := m.Lookup("GET", "/containers/counts"); !ok || perm != "containers:list" {+ t.Fatalf("expected static route to win with containers:list, got %q ok=%v", perm, ok)+ }+ if perm, ok := m.Lookup("GET", "/containers/xyz"); !ok || perm != "containers:read" {+ t.Fatalf("expected wildcard route containers:read, got %q ok=%v", perm, ok)+ }+}++func TestPermissionMatcherMethodAndLengthMismatch(t *testing.T) {+ m := NewPermissionMatcher()+ m.Add("POST", "/containers/{containerId}/start", "containers:start")++ if _, ok := m.Lookup("DELETE", "/containers/abc/start"); ok {+ t.Fatal("expected no match for wrong method")+ }+ if _, ok := m.Lookup("POST", "/containers/abc/start/extra"); ok {+ t.Fatal("expected no match for longer path")+ }+ if _, ok := m.Lookup("POST", "/containers/abc"); ok {+ t.Fatal("expected no match for shorter path")+ }+}++func TestPermissionMatcherNormalizesEchoParamsAndStripsQuery(t *testing.T) {+ m := NewPermissionMatcher()+ m.Add("GET", "/volumes/:volumeName/browse", "volumes:browse")++ if perm, ok := m.Lookup("GET", "/volumes/data/browse?path=/etc"); !ok || perm != "volumes:browse" {+ t.Fatalf("expected volumes:browse with echo param + query string, got %q ok=%v", perm, ok)+ }+}++func TestPermissionMatcherPublicRoute(t *testing.T) {+ m := NewPermissionMatcher()+ m.AddPublic("GET", "/settings/public")++ perm, ok := m.Lookup("GET", "/settings/public")+ if !ok {+ t.Fatal("expected public route to be found")+ }+ if perm != "" {+ t.Fatalf("expected empty permission for public route, got %q", perm)+ }+}++func TestPermissionMatcherUnmappedReturnsNotFound(t *testing.T) {+ m := NewPermissionMatcher()+ m.Add("GET", "/containers", "containers:list")++ if _, ok := m.Lookup("GET", "/images"); ok {+ t.Fatal("expected unmapped path to return not found")+ }+}diff --git a/cli/internal/integrationtest/action_error_handling_test.go b/cli/internal/integrationtest/action_error_handling_test.gonew file mode 100644index 000000000..4ec70cd80--- /dev/null+++ b/cli/internal/integrationtest/action_error_handling_test.go@@ -0,0 +1,77 @@+package integrationtest++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++// TestContainerStartSurfacesServerError verifies that `containers start` reports+// a non-2xx response from the action endpoint as an error instead of printing a+// false success. This is a regression guard: the manager's remote-environment+// proxy returns 403 when the caller lacks the required per-environment+// permission, and the CLI must not swallow that and exit 0.+func TestContainerStartSurfacesServerError(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/api/environments/0/containers/abc123":+ // Resolution succeeds so the action POST below is reached.+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"success":true,"data":{"id":"abc123","name":"nginx"}}`))+ case r.Method == http.MethodPost && r.URL.Path == "/api/environments/0/containers/abc123/start":+ w.WriteHeader(http.StatusForbidden)+ _, _ = w.Write([]byte(`{"success":false,"data":{"error":"permission denied: containers:start"}}`))+ default:+ w.WriteHeader(http.StatusNotFound)+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))+ }+ }))+ defer srv.Close()++ configPath := writeCLIIntegrationConfigInternal(t, srv.URL)+ outBuf, errOut, err := executeCLIIntegrationCommandInternal(+ t,+ []string{"--config", configPath, "containers", "start", "abc123"},+ )+ if err == nil {+ t.Fatalf("expected an error for a 403 start response, got success\nstdout=%s\nstderr=%s", outBuf, errOut)+ }+ if !strings.Contains(err.Error(), "403") {+ t.Fatalf("expected the error to mention status 403, got: %v", err)+ }+ if strings.Contains(outBuf, "successfully") {+ t.Fatalf("expected no success message on a denied start, got stdout=%s", outBuf)+ }+}++// TestSystemContainersStartAllSurfacesServerError verifies the same guard for a+// system command that does not resolve a resource first: it must report the+// server's error rather than claiming success.+func TestSystemContainersStartAllSurfacesServerError(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method == http.MethodPost && r.URL.Path == "/api/environments/0/system/containers/start-all" {+ w.WriteHeader(http.StatusForbidden)+ _, _ = w.Write([]byte(`{"success":false,"data":{"error":"permission denied: containers:start"}}`))+ return+ }+ w.WriteHeader(http.StatusNotFound)+ _, _ = w.Write([]byte(`{"success":false,"error":"not found"}`))+ }))+ defer srv.Close()++ configPath := writeCLIIntegrationConfigInternal(t, srv.URL)+ outBuf, errOut, err := executeCLIIntegrationCommandInternal(+ t,+ []string{"--config", configPath, "system", "containers-start-all"},+ )+ if err == nil {+ t.Fatalf("expected an error for a 403 response, got success\nstdout=%s\nstderr=%s", outBuf, errOut)+ }+ if !strings.Contains(err.Error(), "403") {+ t.Fatalf("expected the error to mention status 403, got: %v", err)+ }+ if strings.Contains(outBuf, "Started all containers") {+ t.Fatalf("expected no success message on a denied start-all, got stdout=%s", outBuf)+ }+}diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.goindex 1f19daadc..ad83fd303 100644--- a/cli/pkg/containers/cmd.go+++ b/cli/pkg/containers/cmd.go@@ -360,6 +360,10 @@ func runContainerPostAction[T any](cmd *cobra.Command, containerRef string, cfg}defer func() { _ = resp.Body.Close() }()+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {+ return fmt.Errorf("%s: %w", cfg.failureMessage, err)+ }+var result base.ApiResponse[T]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {return fmt.Errorf("failed to parse response: %w", err)diff --git a/cli/pkg/system/cmd.go b/cli/pkg/system/cmd.goindex a870c521c..46e7c7ead 100644--- a/cli/pkg/system/cmd.go+++ b/cli/pkg/system/cmd.go@@ -46,6 +46,10 @@ var pruneCmd = &cobra.Command{}defer func() { _ = resp.Body.Close() }()+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {+ return fmt.Errorf("failed to prune: %w", err)+ }+var result base.ApiResponse[system.PruneAllResult]if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {return fmt.Errorf("failed to parse response: %w", err)@@ -121,6 +125,10 @@ var containersStartAllCmd = &cobra.Command{}defer func() { _ = resp.Body.Close() }()+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {+ return fmt.Errorf("failed to start all containers: %w", err)+ }+output.Success("Started all containers")return nil},@@ -142,6 +150,10 @@ var containersStopAllCmd = &cobra.Command{}defer func() { _ = resp.Body.Close() }()+ if err := cmdutil.EnsureSuccessStatus(resp); err != nil {+ return fmt.Errorf("failed to stop all containers: %w", err)+ }+output.Success("Stopped all containers")return nil},diff --git a/tests/spec/cli.spec.ts b/tests/spec/cli.spec.tsindex 46a9d8da2..e499f4327 100644--- a/tests/spec/cli.spec.ts+++ b/tests/spec/cli.spec.ts@@ -525,3 +525,180 @@ test.describe('arcane-cli e2e', () => {});});});++// Regression coverage for the remote-environment proxy authorization model.+//+// The manager proxies /api/environments/{id}/... to the target agent, which runs+// with a sudo permission set and performs no authorization of its own. The+// manager must therefore enforce the caller's per-environment permission BEFORE+// forwarding — otherwise any authenticated user could perform write actions on a+// remote environment regardless of role.+//+// These tests drive the real arcane-cli against a remote (edge) environment that+// has no connected agent. With no live tunnel, the outcome distinguishes the two+// states cleanly:+// - a DENIED request returns 403 — the permission check runs before the tunnel+// lookup, so it short-circuits regardless of connectivity;+// - an AUTHORIZED request gets past the permission check and reaches the tunnel+// stage, which returns 502 ("edge agent is not connected").+// The 403-vs-502 split is exactly what proves the permission is enforced per+// environment and is not a blanket block. The local environment ("0") is served+// directly (never proxied) and must remain unaffected.+test.describe('arcane-cli remote environment RBAC', () => {+ let adminKey = staticApiKey ?? '';+ let createdAdminKey = false;+ let remoteEnvId = '';+ let readonlyKey = '';+ let readonlyKeyId = '';++ async function adminFetch(path: string, init: RequestInit = {}): Promise<Response> {+ const headers = new Headers(init.headers);+ headers.set('X-API-KEY', adminKey);+ if (init.body) {+ headers.set('Content-Type', headers.get('Content-Type') ?? 'application/json');+ }+ return fetch(new URL(path, baseURL), { ...init, headers });+ }++ async function withAdminConfig<T>(+ environment: string,+ fn: (config: CLIConfig) => Promise<T>+ ): Promise<T> {+ const config = await createCLIConfig(baseURL, adminKey, environment);+ try {+ return await fn(config);+ } finally {+ await config.cleanup();+ }+ }++ async function withReadonlyConfig<T>(+ environment: string,+ fn: (config: CLIConfig) => Promise<T>+ ): Promise<T> {+ const config = await createCLIConfig(baseURL, readonlyKey, environment);+ try {+ return await fn(config);+ } finally {+ await config.cleanup();+ }+ }++ // runExpectingFailure runs the CLI expecting a non-zero exit, returning the+ // thrown error message (which includes stdout + stderr) for assertions. It+ // fails the test if the command unexpectedly succeeds.+ async function runExpectingFailure(configPath: string, args: string[]): Promise<string> {+ const message = await runCLI(configPath, args)+ .then(() => null)+ .catch((error: unknown) => (error instanceof Error ? error.message : String(error)));+ expect(message, `expected \`arcane-cli ${args.join(' ')}\` to fail`).toBeTruthy();+ return message as string;+ }++ test.beforeAll(async () => {+ if (!adminKey) {+ const created = await createTestApiKeys(1);+ adminKey = created.apiKeys[0].key;+ createdAdminKey = true;+ }++ const suffix = `${Date.now()}`.slice(-6);++ // Create a remote edge environment. No agent will ever connect to it; it+ // exists only so the proxy treats requests to it as remote (edge://) and+ // reaches either the permission check (403) or the tunnel lookup (502).+ const envResponse = await adminFetch('/api/environments', {+ method: 'POST',+ body: JSON.stringify({+ name: `cli-rbac-${suffix}`,+ apiUrl: `edge://cli-rbac-${suffix}`,+ isEdge: true,+ enabled: true+ })+ });+ expect(+ envResponse.ok,+ `failed to create remote env: ${envResponse.status} ${await envResponse.clone().text()}`+ ).toBeTruthy();+ const envBody = (await envResponse.json()) as { data: { id: string } };+ remoteEnvId = envBody.data.id;+ expect(remoteEnvId).toBeTruthy();++ // Create a read-only scoped API key via the CLI: it can read volumes but+ // has no volumes:create grant, so the proxy must reject writes with it.+ await withAdminConfig('0', async (config) => {+ const created = await runCLIJSON<CreatedApiKey>(config.configPath, [+ 'admin',+ 'api-keys',+ 'create',+ `cli-rbac-readonly-${suffix}`,+ '--description',+ 'Read-only key for remote RBAC e2e',+ '--permission',+ 'environments:read',+ '--permission',+ 'volumes:list',+ '--permission',+ 'volumes:read'+ ]);+ readonlyKey = created.key;+ readonlyKeyId = created.id;+ });+ expect(readonlyKey).toMatch(/^arc_/);+ });++ test.afterAll(async () => {+ if (readonlyKeyId) {+ await adminFetch(`/api/api-keys/${readonlyKeyId}`, { method: 'DELETE' }).catch(+ () => undefined+ );+ }+ if (remoteEnvId) {+ await adminFetch(`/api/environments/${remoteEnvId}`, { method: 'DELETE' }).catch(+ () => undefined+ );+ }+ if (createdAdminKey) {+ await deleteTestApiKeys();+ }+ });++ test('denies a remote write for a read-only key (403)', async () => {+ await withReadonlyConfig(remoteEnvId, async (config) => {+ const error = await runExpectingFailure(config.configPath, [+ 'volumes',+ 'create',+ '--name',+ `cli-rbac-vol-${Date.now()}`+ ]);+ expect(error).toContain('status 403');+ });+ });++ test('authorizes a remote write for an admin key, reaching the disconnected agent (502, not 403)', async () => {+ await withAdminConfig(remoteEnvId, async (config) => {+ const error = await runExpectingFailure(config.configPath, [+ 'volumes',+ 'create',+ '--name',+ `cli-rbac-vol-${Date.now()}`+ ]);+ // The admin key passes the permission check, so the request reaches the+ // edge tunnel stage and fails only because no agent is connected.+ expect(error).toContain('status 502');+ expect(error).not.toContain('status 403');+ });+ });++ test('leaves the local environment unaffected for a read-only key', async () => {+ await withReadonlyConfig('0', async (config) => {+ const volumes = await runCLIJSON<{ data: unknown[] }>(config.configPath, [+ 'volumes',+ 'list',+ '--limit',+ '5'+ ]);+ expect(Array.isArray(volumes.data)).toBe(true);+ });+ });+});