Skip to content

Modern Docker Management, Designed for Everyone

refactor: consolidate internal helpers (#3320)

Kyle Mendelle76541e6ec41
diff --git a/backend/api/api.go b/backend/api/api.go
index aba6ef39b..8e8ddcbd2 100644
--- a/backend/api/api.go
+++ b/backend/api/api.go
@@ -62,11 +62,7 @@ func customSchemaNamer(t reflect.Type, hint string) string {
} else if dockerPrefix, ok := dockerSchemaPrefix(pkgPath, shortPkg); ok {
name = dockerPrefix + name
}
- if innerPkg, ok := genericInnerPackageName(pkgPath, typeStr); ok {
- return strings.Replace(name, "UsageCounts", innerPkg+"UsageCounts", 1)
- }
-
- return name
+ return qualifyGenericArcaneArgumentsInternal(pkgPath, typeStr, name)
}
func packagePathForType(t reflect.Type) string {
@@ -121,24 +117,54 @@ func dockerSchemaPrefix(pkgPath, shortPkg string) (string, bool) {
return prefix, true
}
-func genericInnerPackageName(pkgPath, typeName string) (string, bool) {
- if !strings.HasPrefix(pkgPath, arcaneTypesPrefix+"base") {
- return "", false
+func qualifyGenericArcaneArgumentsInternal(pkgPath, typeName, schemaName string) string {
+ openBracket := strings.IndexByte(typeName, '[')
+ if !strings.HasPrefix(pkgPath, arcaneTypesPrefix) || openBracket < 0 {
+ return schemaName
}
- if !strings.Contains(typeName, "[") || !strings.Contains(typeName, arcaneTypesPrefix) {
- return "", false
+
+ outerPackage := strings.TrimPrefix(pkgPath, arcaneTypesPrefix)
+ if separator := strings.LastIndexByte(outerPackage, '/'); separator >= 0 {
+ outerPackage = outerPackage[separator+1:]
}
- _, after, ok := strings.Cut(typeName, arcaneTypesPrefix)
+ plainSchemaName := huma.DefaultSchemaNamer(reflect.TypeFor[struct{}](), typeName)
+ schemaPrefix, ok := strings.CutSuffix(schemaName, plainSchemaName)
if !ok {
- return "", false
+ return schemaName
}
- before, _, ok := strings.Cut(after, ".")
- if !ok || before == "" {
- return "", false
+
+ rewrittenTypeName := typeName
+ searchOffset := openBracket + 1
+ for {
+ prefixIndex := strings.Index(rewrittenTypeName[searchOffset:], arcaneTypesPrefix)
+ if prefixIndex == -1 {
+ break
+ }
+ prefixIndex += searchOffset
+
+ afterPrefix := rewrittenTypeName[prefixIndex+len(arcaneTypesPrefix):]
+ separator := strings.IndexByte(afterPrefix, '.')
+ if separator < 0 {
+ break
+ }
+
+ innerPackage := afterPrefix[:separator]
+ if nestedSeparator := strings.LastIndexByte(innerPackage, '/'); nestedSeparator >= 0 {
+ innerPackage = innerPackage[nestedSeparator+1:]
+ }
+
+ replacement := ""
+ if innerPackage != outerPackage {
+ replacement = capitalizeFirst(innerPackage)
+ }
+
+ argumentTypeIndex := prefixIndex + len(arcaneTypesPrefix) + separator + 1
+ rewrittenTypeName = rewrittenTypeName[:prefixIndex] + replacement + rewrittenTypeName[argumentTypeIndex:]
+ searchOffset = prefixIndex + len(replacement)
}
- return capitalizeFirst(before), true
+ return schemaPrefix + huma.DefaultSchemaNamer(reflect.TypeFor[struct{}](), rewrittenTypeName)
}
func capitalizeFirst(s string) string {
@@ -293,7 +319,8 @@ func SetupAPIForSpec() huma.API {
// Add new handlers here as they are migrated from Gin.
func registerHandlersInternal(api huma.API, svc *di.Services, handlerAppCtx handlers.ActivityAppContext, cfg *config.Config) {
// svc is nil during OpenAPI spec generation (SetupAPIForSpec); an empty
- // container keeps every field a true-nil pointer so handler nil-guards hold.
+ // container supplies typed nil dependencies because handlers are registered
+ // for schema discovery but are never invoked.
if svc == nil {
svc = &di.Services{}
}
@@ -312,7 +339,11 @@ func registerHandlersInternal(api huma.API, svc *di.Services, handlerAppCtx hand
handlers.RegisterEnvironments(api, svc.Environment, svc.Settings, svc.ApiKey, svc.Event, cfg)
handlers.RegisterContainerRegistries(api, svc.ContainerRegistry, svc.Environment)
handlers.RegisterTemplates(api, svc.Template)
- handlers.RegisterVariables(api, svc.Variable, svc.Environment)
+ if cfg != nil && cfg.AgentMode {
+ handlers.RegisterMaterializedVariables(api, svc.Variable, svc.Environment)
+ } else {
+ handlers.RegisterVariables(api, svc.Variable, svc.Environment)
+ }
handlers.RegisterImages(api, svc.Docker, svc.Image, svc.ImageUpdate, svc.Settings, svc.Build, svc.Activity, handlerAppCtx)
handlers.RegisterBuildWorkspaces(api, svc.BuildWorkspace)
handlers.RegisterImageUpdates(api, svc.ImageUpdate, svc.Image, handlerAppCtx)
diff --git a/backend/api/api_test.go b/backend/api/api_test.go
index 041ddecb7..466717ce4 100644
--- a/backend/api/api_test.go
+++ b/backend/api/api_test.go
@@ -2,17 +2,28 @@ package api
import (
"bytes"
+ "context"
"reflect"
"strings"
"testing"
"time"
humav2 "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/v2/api/handlers"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/config"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/di"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
basetypes "github.com/getarcaneapp/arcane/types/v2/base"
+ containertypes "github.com/getarcaneapp/arcane/types/v2/container"
envtypes "github.com/getarcaneapp/arcane/types/v2/env"
imagetypes "github.com/getarcaneapp/arcane/types/v2/image"
+ networktypes "github.com/getarcaneapp/arcane/types/v2/network"
+ projecttypes "github.com/getarcaneapp/arcane/types/v2/project"
volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"
+ "github.com/labstack/echo/v4"
+ dockercontainer "github.com/moby/moby/api/types/container"
dockernetwork "github.com/moby/moby/api/types/network"
+ "github.com/stretchr/testify/require"
)
func TestCustomSchemaNamer_PrefixesArcaneTypesByPackage(t *testing.T) {
@@ -37,6 +48,12 @@ func TestCustomSchemaNamer_PointerMatchesValue(t *testing.T) {
if valueName != pointerName {
t.Fatalf("expected pointer and value names to match, got %q and %q", valueName, pointerName)
}
+
+ genericValueName := customSchemaNamer(reflect.TypeFor[basetypes.ApiResponse[containertypes.StatusCounts]](), "")
+ genericPointerName := customSchemaNamer(reflect.TypeFor[*basetypes.ApiResponse[containertypes.StatusCounts]](), "")
+ if genericValueName != genericPointerName {
+ t.Fatalf("expected generic pointer and value names to match, got %q and %q", genericValueName, genericPointerName)
+ }
}
func TestCustomSchemaNamer_PrefixesDockerTypes(t *testing.T) {
@@ -46,7 +63,7 @@ func TestCustomSchemaNamer_PrefixesDockerTypes(t *testing.T) {
}
}
-func TestCustomSchemaNamer_DisambiguatesGenericUsageCounts(t *testing.T) {
+func TestCustomSchemaNamer_DisambiguatesGenericDomainTypes(t *testing.T) {
volumeResp := customSchemaNamer(reflect.TypeFor[basetypes.ApiResponse[volumetypes.UsageCounts]](), "")
imageResp := customSchemaNamer(reflect.TypeFor[basetypes.ApiResponse[imagetypes.UsageCounts]](), "")
@@ -59,6 +76,33 @@ func TestCustomSchemaNamer_DisambiguatesGenericUsageCounts(t *testing.T) {
if volumeResp == imageResp {
t.Fatalf("expected unique generic schema names, got %q", volumeResp)
}
+
+ containerResp := customSchemaNamer(reflect.TypeFor[basetypes.ApiResponse[containertypes.StatusCounts]](), "")
+ projectResp := customSchemaNamer(reflect.TypeFor[basetypes.ApiResponse[projecttypes.StatusCounts]](), "")
+ if !strings.Contains(containerResp, "ContainerStatusCounts") {
+ t.Fatalf("expected ContainerStatusCounts in name, got %q", containerResp)
+ }
+ if !strings.Contains(projectResp, "ProjectStatusCounts") {
+ t.Fatalf("expected ProjectStatusCounts in name, got %q", projectResp)
+ }
+ if containerResp == projectResp {
+ t.Fatalf("expected unique generic schema names, got %q", containerResp)
+ }
+
+ baseResp := customSchemaNamer(reflect.TypeFor[basetypes.ApiResponse[basetypes.MessageResponse]](), "")
+ if strings.Contains(baseResp, "BaseApiResponseBase") {
+ t.Fatalf("expected base generic argument without redundant package prefix, got %q", baseResp)
+ }
+
+ multiArgument := customSchemaNamer(reflect.TypeFor[basetypes.PaginatedWithCounts[networktypes.Summary, networktypes.UsageCounts]](), "")
+ if multiArgument != "BasePaginatedWithCountsNetworkSummaryNetworkUsageCounts" {
+ t.Fatalf("expected both generic arguments to be package-qualified in order, got %q", multiArgument)
+ }
+
+ mixedPackages := customSchemaNamer(reflect.TypeFor[basetypes.PaginatedWithCounts[dockercontainer.Summary, imagetypes.Summary]](), "")
+ if mixedPackages != "BasePaginatedWithCountsSummaryImageSummary" {
+ t.Fatalf("expected only the Arcane argument to be qualified in place, got %q", mixedPackages)
+ }
}
func TestSetupAPIForSpec_DefaultSecurity(t *testing.T) {
@@ -217,3 +261,64 @@ func TestSetupAPIForSpec_DoesNotRegisterPublicCreateEvent(t *testing.T) {
t.Fatal("expected POST /events to be absent from the public API")
}
}
+
+func TestVariableMaterializationRoutesAreAgentOnly(t *testing.T) {
+ managerAPI := SetupAPIForSpec()
+ require.NotNil(t, managerAPI.OpenAPI().Paths["/variables"])
+ require.Nil(t, managerAPI.OpenAPI().Paths["/environments/{id}/templates/variables"])
+
+ managerMatcher := authz.NewPermissionMatcher()
+ managerMatcher.CollectFromHumaAPI(managerAPI)
+ _, found := managerMatcher.Lookup("GET", "/templates/variables")
+ require.False(t, found)
+ _, found = managerMatcher.Lookup("PUT", "/templates/variables")
+ require.False(t, found)
+
+ router := echo.New()
+ agentAPI := SetupAPI(
+ router,
+ router.Group("/api"),
+ handlers.NewActivityAppContext(context.Background()),
+ &config.Config{AgentMode: true},
+ &di.Services{},
+ )
+ require.Nil(t, agentAPI.OpenAPI().Paths["/variables"])
+ materialized := agentAPI.OpenAPI().Paths["/environments/{id}/templates/variables"]
+ require.NotNil(t, materialized)
+ require.NotNil(t, materialized.Get)
+ require.NotNil(t, materialized.Put)
+}
+
+func TestEasyJoinRoutesDeclareSwarmJoinPermission(t *testing.T) {
+ api := SetupAPIForSpec()
+ tests := []struct {
+ path string
+ method string
+ }{
+ {path: "/environments/{id}/swarm/join-candidates", method: "GET"},
+ {path: "/environments/{id}/swarm/join-environments", method: "POST"},
+ }
+
+ matcher := authz.NewPermissionMatcher()
+ matcher.CollectFromHumaAPI(api)
+ for _, tt := range tests {
+ t.Run(tt.method+" "+tt.path, func(t *testing.T) {
+ pathItem := api.OpenAPI().Paths[tt.path]
+ require.NotNil(t, pathItem)
+ var operation *humav2.Operation
+ switch tt.method {
+ case "GET":
+ operation = pathItem.Get
+ case "POST":
+ operation = pathItem.Post
+ }
+ require.NotNil(t, operation)
+ require.Equal(t, authz.PermSwarmJoin, operation.Metadata[authz.MetaRequiredPermission])
+
+ suffix := strings.TrimPrefix(tt.path, "/environments/{id}")
+ permission, found := matcher.Lookup(tt.method, suffix)
+ require.True(t, found)
+ require.Equal(t, authz.PermSwarmJoin, permission)
+ })
+ }
+}
diff --git a/backend/api/handlers/activities.go b/backend/api/handlers/activities.go
index 8da4790c1..80ab386d1 100644
--- a/backend/api/handlers/activities.go
+++ b/backend/api/handlers/activities.go
@@ -99,10 +99,7 @@ func RegisterActivities(api huma.API, activityService *services.ActivityService,
Summary: "List background activities",
Description: "Get current and recent background activities for an environment",
Tags: []string{"Activities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermActivitiesRead, h.ListActivities)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -112,10 +109,7 @@ func RegisterActivities(api huma.API, activityService *services.ActivityService,
Summary: "Get background activity",
Description: "Get a background activity with its recent output messages",
Tags: []string{"Activities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermActivitiesRead, h.GetActivity)
huma.Register(api, huma.Operation{
@@ -125,10 +119,7 @@ func RegisterActivities(api huma.API, activityService *services.ActivityService,
Summary: "Stream background activities across all environments",
Description: "Stream background activity updates for the local environment and all enabled remote environments as JSON lines",
Tags: []string{"Activities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireAnyEnvironmentPermission(api, authz.PermActivitiesRead),
}, h.StreamAllActivities)
@@ -139,10 +130,7 @@ func RegisterActivities(api huma.API, activityService *services.ActivityService,
Summary: "Cancel a background activity",
Description: "Request cancellation of a running or queued background activity",
Tags: []string{"Activities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermActivitiesCancel, h.CancelActivity)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -152,10 +140,7 @@ func RegisterActivities(api huma.API, activityService *services.ActivityService,
Summary: "Clear background activity history",
Description: "Delete completed background activity history for an environment",
Tags: []string{"Activities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermActivitiesDelete, h.ClearHistory)
}
@@ -163,9 +148,6 @@ func (h *ActivityHandler) ListActivities(ctx context.Context, input *ListActivit
if input.EnvironmentID != "0" {
return h.proxyListActivitiesInternal(ctx, input)
}
- if h.activityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.Status != "" {
@@ -197,9 +179,6 @@ func (h *ActivityHandler) GetActivity(ctx context.Context, input *GetActivityInp
if input.EnvironmentID != "0" {
return h.proxyGetActivityInternal(ctx, input)
}
- if h.activityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if input.ActivityID == "" {
return nil, huma.Error400BadRequest("activity id is required")
}
@@ -225,9 +204,6 @@ func (h *ActivityHandler) ClearHistory(ctx context.Context, input *ClearActivity
if input.EnvironmentID != "0" {
return h.proxyClearHistoryInternal(ctx, input)
}
- if h.activityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
deleted, err := h.activityService.DeleteHistory(ctx, input.EnvironmentID)
if err != nil {
@@ -246,9 +222,6 @@ func (h *ActivityHandler) CancelActivity(ctx context.Context, input *CancelActiv
if input.EnvironmentID != "0" {
return h.proxyCancelActivityInternal(ctx, input)
}
- if h.activityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if input.ActivityID == "" {
return nil, huma.Error400BadRequest("activity id is required")
}
@@ -276,9 +249,6 @@ func (h *ActivityHandler) CancelActivity(ctx context.Context, input *CancelActiv
}
func (h *ActivityHandler) proxyCancelActivityInternal(ctx context.Context, input *CancelActivityInput) (*CancelActivityOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
path := fmt.Sprintf("/api/environments/0/activities/%s/cancel", url.PathEscape(input.ActivityID))
if requestedBy := h.cancelRequestedByInternal(ctx, input.RequestedBy); requestedBy != "" {
path += "?requestedBy=" + url.QueryEscape(requestedBy)
@@ -307,10 +277,6 @@ func (h *ActivityHandler) cancelRequestedByInternal(ctx context.Context, forward
}
func (h *ActivityHandler) StreamAllActivities(ctx context.Context, input *StreamAllActivitiesInput) (*huma.StreamResponse, error) {
- if h.activityService == nil || h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
return &huma.StreamResponse{
Body: func(humaCtx huma.Context) { //nolint:contextcheck // streaming work must use humaCtx.Context()
httpx.SetJSONStreamHeaders(humaCtx)
@@ -540,9 +506,6 @@ func (h *ActivityHandler) runRemoteActivityStreamPollerInternal(ctx context.Cont
}
func (h *ActivityHandler) proxyListActivitiesInternal(ctx context.Context, input *ListActivitiesInput) (*ListActivitiesOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
path := "/api/environments/0/activities?" + activityListQueryInternal(input).Encode()
out, err := proxyRemoteJSONInternal[base.Paginated[activity.Activity]](ctx, h.environmentService, input.EnvironmentID, http.MethodGet, path, nil)
if err != nil {
@@ -553,9 +516,6 @@ func (h *ActivityHandler) proxyListActivitiesInternal(ctx context.Context, input
}
func (h *ActivityHandler) proxyListActivitiesForEnvironmentInternal(ctx context.Context, environment models.Environment, input *ListActivitiesInput) (*ListActivitiesOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
path := "/api/environments/0/activities?" + activityListQueryInternal(input).Encode()
var out base.Paginated[activity.Activity]
if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, environment, http.MethodGet, path, nil, &out); err != nil {
@@ -566,9 +526,6 @@ func (h *ActivityHandler) proxyListActivitiesForEnvironmentInternal(ctx context.
}
func (h *ActivityHandler) proxyGetActivityInternal(ctx context.Context, input *GetActivityInput) (*GetActivityOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
path := fmt.Sprintf("/api/environments/0/activities/%s?limit=%d", url.PathEscape(input.ActivityID), input.Limit)
out, err := proxyRemoteJSONInternal[base.ApiResponse[activity.Detail]](ctx, h.environmentService, input.EnvironmentID, http.MethodGet, path, nil)
if err != nil {
@@ -579,9 +536,6 @@ func (h *ActivityHandler) proxyGetActivityInternal(ctx context.Context, input *G
}
func (h *ActivityHandler) proxyClearHistoryInternal(ctx context.Context, input *ClearActivityHistoryInput) (*ClearActivityHistoryOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
out, err := proxyRemoteJSONInternal[base.ApiResponse[activity.ClearHistoryResult]](ctx, h.environmentService, input.EnvironmentID, http.MethodDelete, "/api/environments/0/activities/history", nil)
if err != nil {
return nil, err
diff --git a/backend/api/handlers/apikeys.go b/backend/api/handlers/apikeys.go
index fe77e9859..979dc8626 100644
--- a/backend/api/handlers/apikeys.go
+++ b/backend/api/handlers/apikeys.go
@@ -21,13 +21,6 @@ type ApiKeyHandler struct {
// --- Huma Input/Output Wrappers ---
-// ApiKeyPaginatedResponse is the paginated response for API keys.
-type ApiKeyPaginatedResponse struct {
- Success bool `json:"success"`
- Data []apikey.ApiKey `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListApiKeysInput struct {
Search string `query:"search" doc:"Search query for filtering by name or description"`
Sort string `query:"sort" doc:"Column to sort by"`
@@ -37,7 +30,7 @@ type ListApiKeysInput struct {
}
type ListApiKeysOutput struct {
- Body ApiKeyPaginatedResponse
+ Body base.Paginated[apikey.ApiKey]
}
type CreateApiKeyInput struct {
@@ -94,10 +87,7 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {
Summary: "List API keys",
Description: "Get a paginated list of API keys",
Tags: []string{"API Keys"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermApiKeysList),
}, h.ListApiKeys)
@@ -108,10 +98,7 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {
Summary: "Create an API key",
Description: "Create a new API key for programmatic access",
Tags: []string{"API Keys"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermApiKeysCreate),
}, h.CreateApiKey)
@@ -122,10 +109,7 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {
Summary: "Get an API key",
Description: "Get details of a specific API key by ID",
Tags: []string{"API Keys"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermApiKeysRead),
}, h.GetApiKey)
@@ -136,10 +120,7 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {
Summary: "Update an API key",
Description: "Update an existing API key's details",
Tags: []string{"API Keys"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermApiKeysUpdate),
}, h.UpdateApiKey)
@@ -150,10 +131,7 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {
Summary: "Delete an API key",
Description: "Delete an API key by ID",
Tags: []string{"API Keys"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermApiKeysDelete),
}, h.DeleteApiKey)
@@ -166,10 +144,7 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {
Summary: "List my API keys",
Description: "List API keys owned by the current user",
Tags: []string{"API Keys"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, h.ListMyApiKeys)
// Personal keys inherit the owner's permissions, so creating or deleting
@@ -202,10 +177,6 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {
// ListApiKeys returns a paginated list of API keys.
func (h *ApiKeyHandler) ListApiKeys(ctx context.Context, input *ListApiKeysInput) (*ListApiKeysOutput, error) {
- if h.apiKeyService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
apiKeys, paginationResp, err := h.apiKeyService.ListApiKeys(ctx, params)
@@ -214,7 +185,7 @@ func (h *ApiKeyHandler) ListApiKeys(ctx context.Context, input *ListApiKeysInput
}
return &ListApiKeysOutput{
- Body: ApiKeyPaginatedResponse{
+ Body: base.Paginated[apikey.ApiKey]{
Success: true,
Data: apiKeys,
Pagination: toPaginationResponseInternal(paginationResp),
@@ -225,10 +196,6 @@ func (h *ApiKeyHandler) ListApiKeys(ctx context.Context, input *ListApiKeysInput
// CreateApiKey creates a new scoped API key. Requested grants are capped by
// the calling credential's effective permissions.
func (h *ApiKeyHandler) CreateApiKey(ctx context.Context, input *CreateApiKeyInput) (*CreateApiKeyOutput, error) {
- if h.apiKeyService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -253,10 +220,6 @@ func (h *ApiKeyHandler) CreateApiKey(ctx context.Context, input *CreateApiKeyInp
// GetApiKey returns details of a specific API key.
func (h *ApiKeyHandler) GetApiKey(ctx context.Context, input *GetApiKeyInput) (*GetApiKeyOutput, error) {
- if h.apiKeyService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
apiKey, err := h.apiKeyService.GetApiKey(ctx, input.ID)
if err != nil {
return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())
@@ -272,10 +235,6 @@ func (h *ApiKeyHandler) GetApiKey(ctx context.Context, input *GetApiKeyInput) (*
// UpdateApiKey updates an existing API key.
func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInput) (*UpdateApiKeyOutput, error) {
- if h.apiKeyService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if _, err := requireUserInternal(ctx); err != nil {
return nil, err
}
@@ -308,10 +267,6 @@ func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInp
// DeleteApiKey deletes an API key.
func (h *ApiKeyHandler) DeleteApiKey(ctx context.Context, input *DeleteApiKeyInput) (*DeleteApiKeyOutput, error) {
- if h.apiKeyService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if err := h.apiKeyService.DeleteApiKey(ctx, input.ID); err != nil {
if errors.Is(err, services.ErrApiKeyNotFound) {
return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())
@@ -334,10 +289,6 @@ func (h *ApiKeyHandler) DeleteApiKey(ctx context.Context, input *DeleteApiKeyInp
// ListMyApiKeys lists API keys owned by the current user (self-service).
func (h *ApiKeyHandler) ListMyApiKeys(ctx context.Context, input *struct{}) (*ListMyApiKeysOutput, error) {
- if h.apiKeyService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -360,10 +311,6 @@ func (h *ApiKeyHandler) ListMyApiKeys(ctx context.Context, input *struct{}) (*Li
// (self-service). Personal keys inherit the owner's role permissions, and may
// only be minted from an interactive session — never by another API key.
func (h *ApiKeyHandler) CreateMyApiKey(ctx context.Context, input *CreateMyApiKeyInput) (*CreateApiKeyOutput, error) {
- if h.apiKeyService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
// Defense in depth alongside the BearerAuth-only Security requirement:
// only session auth sets a session ID, so API-key and sudo callers stop here.
if _, ok := humamw.GetCurrentSessionIDFromContext(ctx); !ok {
@@ -392,10 +339,6 @@ func (h *ApiKeyHandler) CreateMyApiKey(ctx context.Context, input *CreateMyApiKe
// ownership before removal so the endpoint can't be used to delete other
// users' keys.
func (h *ApiKeyHandler) DeleteMyApiKey(ctx context.Context, input *DeleteApiKeyInput) (*DeleteApiKeyOutput, error) {
- if h.apiKeyService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
// Defense in depth alongside the BearerAuth-only Security requirement:
// only session auth sets a session ID, so API-key and sudo callers stop here.
if _, ok := humamw.GetCurrentSessionIDFromContext(ctx); !ok {
diff --git a/backend/api/handlers/appimages.go b/backend/api/handlers/appimages.go
index 7f402d1b1..a28075023 100644
--- a/backend/api/handlers/appimages.go
+++ b/backend/api/handlers/appimages.go
@@ -104,10 +104,6 @@ func RegisterAppImages(api huma.API, appImagesService *services.ApplicationImage
// GetLogo returns the application logo image.
func (h *AppImagesHandler) GetLogo(ctx context.Context, input *GetLogoInput) (*GetAppImageOutput, error) {
- if h.appImagesService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
name := "logo"
if input.Full {
name = "logo-full"
@@ -118,37 +114,21 @@ func (h *AppImagesHandler) GetLogo(ctx context.Context, input *GetLogoInput) (*G
// GetLogoEmail returns the application logo image for emails (PNG).
func (h *AppImagesHandler) GetLogoEmail(ctx context.Context, input *struct{}) (*GetAppImageOutput, error) {
- if h.appImagesService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
return h.getImage("logo-email")
}
// GetFavicon returns the application favicon image.
func (h *AppImagesHandler) GetFavicon(ctx context.Context, input *struct{}) (*GetAppImageOutput, error) {
- if h.appImagesService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
return h.getImage("favicon")
}
// GetDefaultProfile returns the default user profile image.
func (h *AppImagesHandler) GetDefaultProfile(ctx context.Context, input *struct{}) (*GetAppImageOutput, error) {
- if h.appImagesService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
return h.getImage("profile")
}
// GetPWAIcon returns a PWA icon image.
func (h *AppImagesHandler) GetPWAIcon(ctx context.Context, input *GetPWAIconInput) (*GetAppImageOutput, error) {
- if h.appImagesService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
return h.getImageByFilenameInternal(input.Filename)
}
diff --git a/backend/api/handlers/auth.go b/backend/api/handlers/auth.go
index 4123030cb..1c3bb4d70 100644
--- a/backend/api/handlers/auth.go
+++ b/backend/api/handlers/auth.go
@@ -137,10 +137,7 @@ func RegisterAuth(api huma.API, userService *services.UserService, authService *
Summary: "Get current user",
Description: "Get the currently authenticated user's information",
Tags: []string{"Auth"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, h.GetCurrentUser)
huma.Register(api, huma.Operation{
@@ -160,10 +157,7 @@ func RegisterAuth(api huma.API, userService *services.UserService, authService *
Summary: "Change password",
Description: "Change the current user's password",
Tags: []string{"Auth"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, h.ChangePassword)
huma.Register(api, huma.Operation{
@@ -173,10 +167,7 @@ func RegisterAuth(api huma.API, userService *services.UserService, authService *
Summary: "Logout all other sessions",
Description: "Revoke every session for the current user except the one making this request",
Tags: []string{"Auth"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, h.LogoutAllOtherSessions)
huma.Register(api, huma.Operation{
@@ -186,10 +177,7 @@ func RegisterAuth(api huma.API, userService *services.UserService, authService *
Summary: "Update own profile",
Description: "Update the current user's display name and email. Forbidden for OIDC-managed accounts.",
Tags: []string{"Auth"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, h.UpdateMyProfile)
huma.Register(api, huma.Operation{
@@ -199,10 +187,7 @@ func RegisterAuth(api huma.API, userService *services.UserService, authService *
Summary: "Upload own avatar",
Description: "Upload a custom profile picture (PNG, JPEG or WebP). Replaces any existing avatar.",
Tags: []string{"Auth"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
RequestBody: &huma.RequestBody{
Required: true,
Content: map[string]*huma.MediaType{
@@ -225,19 +210,12 @@ func RegisterAuth(api huma.API, userService *services.UserService, authService *
Summary: "Delete own avatar",
Description: "Remove the current user's custom profile picture, reverting to the default avatar.",
Tags: []string{"Auth"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, h.DeleteMyAvatar)
}
// Login authenticates a user and returns tokens.
func (h *AuthHandler) Login(ctx context.Context, input *LoginInput) (*LoginOutput, error) {
- if h.authService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
localAuthEnabled, err := h.authService.IsLocalAuthEnabled(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.AuthSettingsCheckError{Err: err}).Error())
@@ -308,10 +286,6 @@ func (h *AuthHandler) Logout(ctx context.Context, input *struct{}) (*LogoutOutpu
// Uses ToUserResponseDto (not the generic struct mapper) so the RBAC fields
// (RoleAssignments, PermissionsByEnv) are resolved via RoleService.
func (h *AuthHandler) GetCurrentUser(ctx context.Context, input *struct{}) (*GetCurrentUserOutput, error) {
- if h.userService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
userID, exists := humamw.GetUserIDFromContext(ctx)
if !exists {
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
@@ -337,10 +311,6 @@ func (h *AuthHandler) GetCurrentUser(ctx context.Context, input *struct{}) (*Get
// RefreshToken obtains a new access token using a refresh token.
func (h *AuthHandler) RefreshToken(ctx context.Context, input *RefreshTokenInput) (*RefreshTokenOutput, error) {
- if h.authService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
tokenPair, err := h.authService.RefreshToken(ctx, input.Body.RefreshToken, sessionMetaFromContextInternal(ctx, input.UserAgent))
if err != nil {
switch {
@@ -376,10 +346,6 @@ func sessionMetaFromContextInternal(ctx context.Context, userAgent string) auth.
// ChangePassword changes the current user's password.
func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordInput) (*ChangePasswordOutput, error) {
- if h.authService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
userModel, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -413,10 +379,6 @@ func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordI
// LogoutAllOtherSessions revokes every active session for the current user
// except the session making this request.
func (h *AuthHandler) LogoutAllOtherSessions(ctx context.Context, input *struct{}) (*LogoutAllOtherSessionsOutput, error) {
- if h.authService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
userModel, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -440,10 +402,6 @@ func (h *AuthHandler) LogoutAllOtherSessions(ctx context.Context, input *struct{
// UpdateMyProfile lets the current user update their own displayName and email.
// OIDC-managed accounts are read-only here.
func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfileInput) (*UpdateMyProfileOutput, error) {
- if h.userService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
currentUser, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -501,10 +459,6 @@ func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfil
// UploadMyAvatar lets the current user upload a custom profile picture.
// Accepts PNG, JPEG, or WebP images up to the configured avatar upload limit.
func (h *AuthHandler) UploadMyAvatar(ctx context.Context, input *UploadMyAvatarInput) (*UploadMyAvatarOutput, error) {
- if h.userService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
currentUser, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -584,10 +538,6 @@ func (h *AuthHandler) avatarMaxUploadSizeMbInternal(ctx context.Context) int {
// DeleteMyAvatar removes the current user's custom profile picture.
func (h *AuthHandler) DeleteMyAvatar(ctx context.Context, input *struct{}) (*DeleteMyAvatarOutput, error) {
- if h.userService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
currentUser, err := requireUserInternal(ctx)
if err != nil {
return nil, err
diff --git a/backend/api/handlers/build_workspaces.go b/backend/api/handlers/build_workspaces.go
index b9ff7ae49..f46897ecd 100644
--- a/backend/api/handlers/build_workspaces.go
+++ b/backend/api/handlers/build_workspaces.go
@@ -8,7 +8,6 @@ import (
"github.com/danielgtaylor/huma/v2"
humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"
- "github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
"github.com/getarcaneapp/arcane/types/v2/base"
@@ -31,7 +30,7 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorks
Summary: "Browse build workspace files",
Description: "List files and directories under the builds workspace root",
Tags: []string{"Builds"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermBuildWorkspacesManage, h.BrowseDirectory)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -41,7 +40,7 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorks
Summary: "Get build workspace file content",
Description: "Read file content under the builds workspace root",
Tags: []string{"Builds"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermBuildWorkspacesManage, h.GetFileContent)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -51,7 +50,7 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorks
Summary: "Download build workspace file",
Description: "Download a file from the builds workspace root",
Tags: []string{"Builds"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermBuildWorkspacesManage, h.DownloadFile)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -61,7 +60,7 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorks
Summary: "Upload build workspace file",
Description: "Upload a file into the builds workspace root",
Tags: []string{"Builds"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
RequestBody: &huma.RequestBody{
Content: map[string]*huma.MediaType{
"multipart/form-data": {
@@ -88,7 +87,7 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorks
Summary: "Create build workspace directory",
Description: "Create a directory under the builds workspace root",
Tags: []string{"Builds"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermBuildWorkspacesManage, h.CreateDirectory)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -98,7 +97,7 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *services.BuildWorks
Summary: "Delete build workspace file",
Description: "Delete a file or directory under the builds workspace root",
Tags: []string{"Builds"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermBuildWorkspacesManage, h.DeleteFile)
}
@@ -155,9 +154,6 @@ type DeleteBuildFileInput struct {
}
func (h *BuildWorkspaceHandler) BrowseDirectory(ctx context.Context, input *BrowseBuildsInput) (*BrowseBuildsOutput, error) {
- if h.service == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
entries, err := h.service.ListDirectory(ctx, input.Path)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -166,9 +162,6 @@ func (h *BuildWorkspaceHandler) BrowseDirectory(ctx context.Context, input *Brow
}
func (h *BuildWorkspaceHandler) GetFileContent(ctx context.Context, input *GetBuildFileContentInput) (*GetBuildFileContentOutput, error) {
- if h.service == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
content, mimeType, err := h.service.GetFileContent(ctx, input.Path, input.MaxBytes)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -180,9 +173,6 @@ func (h *BuildWorkspaceHandler) GetFileContent(ctx context.Context, input *GetBu
}
func (h *BuildWorkspaceHandler) DownloadFile(ctx context.Context, input *DownloadBuildFileInput) (*DownloadBuildFileOutput, error) {
- if h.service == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
reader, size, err := h.service.DownloadFile(ctx, input.Path)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -196,19 +186,9 @@ func (h *BuildWorkspaceHandler) DownloadFile(ctx context.Context, input *Downloa
}
func (h *BuildWorkspaceHandler) UploadFile(ctx context.Context, input *UploadBuildFileInput) (*base.ApiResponse[base.MessageResponse], error) {
- if h.service == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
- files := input.RawBody.File["file"]
- if len(files) == 0 {
- return nil, huma.Error400BadRequest((&common.NoFileUploadedError{}).Error())
- }
-
- fileHeader := files[0]
- file, err := fileHeader.Open()
+ file, fileHeader, err := openUploadedFileInternal(input.RawBody)
if err != nil {
- return nil, huma.Error500InternalServerError((&common.FileUploadReadError{Err: err}).Error())
+ return nil, err
}
defer func() { _ = file.Close() }()
@@ -222,9 +202,6 @@ func (h *BuildWorkspaceHandler) UploadFile(ctx context.Context, input *UploadBui
}
func (h *BuildWorkspaceHandler) CreateDirectory(ctx context.Context, input *CreateBuildDirectoryInput) (*base.ApiResponse[base.MessageResponse], error) {
- if h.service == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.service.CreateDirectory(ctx, input.Path); err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
@@ -235,9 +212,6 @@ func (h *BuildWorkspaceHandler) CreateDirectory(ctx context.Context, input *Crea
}
func (h *BuildWorkspaceHandler) DeleteFile(ctx context.Context, input *DeleteBuildFileInput) (*base.ApiResponse[base.MessageResponse], error) {
- if h.service == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.service.DeleteFile(ctx, input.Path); err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
diff --git a/backend/api/handlers/container_registries.go b/backend/api/handlers/container_registries.go
index 6a6c31a49..7cd111a94 100644
--- a/backend/api/handlers/container_registries.go
+++ b/backend/api/handlers/container_registries.go
@@ -27,13 +27,6 @@ type ContainerRegistryHandler struct {
// Input/Output Types
// ============================================================================
-// ContainerRegistryPaginatedResponse is the paginated response for container registries.
-type ContainerRegistryPaginatedResponse struct {
- Success bool `json:"success"`
- Data []containerregistry.ContainerRegistry `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListContainerRegistriesInput struct {
Search string `query:"search" doc:"Search query"`
Sort string `query:"sort" doc:"Column to sort by"`
@@ -43,7 +36,7 @@ type ListContainerRegistriesInput struct {
}
type ListContainerRegistriesOutput struct {
- Body ContainerRegistryPaginatedResponse
+ Body base.Paginated[containerregistry.ContainerRegistry]
}
type CreateContainerRegistryInput struct {
@@ -117,10 +110,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
Summary: "List container registries",
Description: "Get a paginated list of container registries",
Tags: []string{"Container Registries"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermRegistriesList),
}, h.ListRegistries)
@@ -131,10 +121,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
Summary: "Create a container registry",
Description: "Create a new container registry",
Tags: []string{"Container Registries"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermRegistriesCreate),
}, h.CreateRegistry)
@@ -145,10 +132,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
Summary: "Sync container registries",
Description: "Sync container registries from a remote source",
Tags: []string{"Container Registries"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermRegistriesUpdate),
}, h.SyncRegistries)
@@ -159,10 +143,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
Summary: "Get container registry pull usage",
Description: "Get configured registry pull usage and rate limit visibility",
Tags: []string{"Container Registries"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermRegistriesRead),
}, h.GetPullUsage)
@@ -173,10 +154,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
Summary: "Get a container registry",
Description: "Get a container registry by ID",
Tags: []string{"Container Registries"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermRegistriesRead),
}, h.GetRegistry)
@@ -187,10 +165,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
Summary: "Update a container registry",
Description: "Update an existing container registry",
Tags: []string{"Container Registries"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermRegistriesUpdate),
}, h.UpdateRegistry)
@@ -201,10 +176,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
Summary: "Delete a container registry",
Description: "Delete a container registry by ID",
Tags: []string{"Container Registries"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermRegistriesDelete),
}, h.DeleteRegistry)
@@ -215,10 +187,7 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
Summary: "Test a container registry",
Description: "Test connectivity and authentication to a container registry",
Tags: []string{"Container Registries"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermRegistriesTest),
}, h.TestRegistry)
}
@@ -229,10 +198,6 @@ func RegisterContainerRegistries(api huma.API, registryService *services.Contain
// ListRegistries returns a paginated list of container registries.
func (h *ContainerRegistryHandler) ListRegistries(ctx context.Context, input *ListContainerRegistriesInput) (*ListContainerRegistriesOutput, error) {
- if h.registryService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
registries, paginationResp, err := h.registryService.GetRegistriesPaginated(ctx, params)
@@ -241,7 +206,7 @@ func (h *ContainerRegistryHandler) ListRegistries(ctx context.Context, input *Li
}
return &ListContainerRegistriesOutput{
- Body: ContainerRegistryPaginatedResponse{
+ Body: base.Paginated[containerregistry.ContainerRegistry]{
Success: true,
Data: registries,
Pagination: toPaginationResponseInternal(paginationResp),
@@ -251,10 +216,6 @@ func (h *ContainerRegistryHandler) ListRegistries(ctx context.Context, input *Li
// GetPullUsage returns pull usage visibility for configured registries.
func (h *ContainerRegistryHandler) GetPullUsage(ctx context.Context, input *struct{}) (*GetContainerRegistryPullUsageOutput, error) {
- if h.registryService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
usage, err := h.registryService.GetRegistryPullUsage(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.RegistryRetrievalError{Err: err}).Error())
@@ -270,10 +231,6 @@ func (h *ContainerRegistryHandler) GetPullUsage(ctx context.Context, input *stru
// CreateRegistry creates a new container registry.
func (h *ContainerRegistryHandler) CreateRegistry(ctx context.Context, input *CreateContainerRegistryInput) (*CreateContainerRegistryOutput, error) {
- if h.registryService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
reg, err := h.registryService.CreateRegistry(ctx, input.Body)
if err != nil {
apiErr := models.ToAPIError(err)
@@ -297,10 +254,6 @@ func (h *ContainerRegistryHandler) CreateRegistry(ctx context.Context, input *Cr
// GetRegistry returns a container registry by ID.
func (h *ContainerRegistryHandler) GetRegistry(ctx context.Context, input *GetContainerRegistryInput) (*GetContainerRegistryOutput, error) {
- if h.registryService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
reg, err := h.registryService.GetRegistryByID(ctx, input.ID)
if err != nil {
apiErr := models.ToAPIError(err)
@@ -322,10 +275,6 @@ func (h *ContainerRegistryHandler) GetRegistry(ctx context.Context, input *GetCo
// UpdateRegistry updates a container registry.
func (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *UpdateContainerRegistryInput) (*UpdateContainerRegistryOutput, error) {
- if h.registryService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
reg, err := h.registryService.UpdateRegistry(ctx, input.ID, input.Body)
if err != nil {
apiErr := models.ToAPIError(err)
@@ -349,10 +298,6 @@ func (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *Up
// DeleteRegistry deletes a container registry.
func (h *ContainerRegistryHandler) DeleteRegistry(ctx context.Context, input *DeleteContainerRegistryInput) (*DeleteContainerRegistryOutput, error) {
- if h.registryService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if err := h.registryService.DeleteRegistry(ctx, input.ID); err != nil {
apiErr := models.ToAPIError(err)
return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryDeletionError{Err: err}).Error())
@@ -372,10 +317,6 @@ func (h *ContainerRegistryHandler) DeleteRegistry(ctx context.Context, input *De
// TestRegistry tests connectivity to a container registry.
func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *TestContainerRegistryInput) (*TestContainerRegistryOutput, error) {
- if h.registryService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
reg, err := h.registryService.GetRegistryByID(ctx, input.ID)
if err != nil {
apiErr := models.ToAPIError(err)
@@ -423,10 +364,6 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Test
// SyncRegistries syncs container registries from a remote source.
func (h *ContainerRegistryHandler) SyncRegistries(ctx context.Context, input *SyncContainerRegistriesInput) (*SyncContainerRegistriesOutput, error) {
- if h.registryService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if err := h.registryService.SyncRegistries(ctx, input.Body.Registries); err != nil {
apiErr := models.ToAPIError(err)
return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistrySyncError{Err: err}).Error())
diff --git a/backend/api/handlers/containers.go b/backend/api/handlers/containers.go
index e66fb4fb9..5311733b7 100644
--- a/backend/api/handlers/containers.go
+++ b/backend/api/handlers/containers.go
@@ -64,14 +64,8 @@ type GetContainerStatusCountsInput struct {
IncludeInternal bool `query:"includeInternal" default:"false" doc:"Include internal containers"`
}
-// ContainerStatusCountsResponse is a dedicated response type to avoid schema name collision
-type ContainerStatusCountsResponse struct {
- Success bool `json:"success"`
- Data containertypes.StatusCounts `json:"data"`
-}
-
type GetContainerStatusCountsOutput struct {
- Body ContainerStatusCountsResponse
+ Body base.ApiResponse[containertypes.StatusCounts]
}
type CreateContainerInput struct {
@@ -79,14 +73,8 @@ type CreateContainerInput struct {
Body containertypes.Create
}
-// ContainerCreatedResponse is a dedicated response type
-type ContainerCreatedResponse struct {
- Success bool `json:"success"`
- Data containertypes.Created `json:"data"`
-}
-
type CreateContainerOutput struct {
- Body ContainerCreatedResponse
+ Body base.ApiResponse[containertypes.Created]
}
type GetContainerInput struct {
@@ -94,14 +82,8 @@ type GetContainerInput struct {
ContainerID string `path:"containerId" doc:"Container ID"`
}
-// ContainerDetailsResponse is a dedicated response type
-type ContainerDetailsResponse struct {
- Success bool `json:"success"`
- Data containertypes.Details `json:"data"`
-}
-
type GetContainerOutput struct {
- Body ContainerDetailsResponse
+ Body base.ApiResponse[containertypes.Details]
}
type ContainerActionInput struct {
@@ -109,14 +91,8 @@ type ContainerActionInput struct {
ContainerID string `path:"containerId" doc:"Container ID"`
}
-// ContainerActionResponse is a dedicated response type
-type ContainerActionResponse struct {
- Success bool `json:"success"`
- Data base.MessageResponse `json:"data"`
-}
-
type ContainerActionOutput struct {
- Body ContainerActionResponse
+ Body base.ApiResponse[base.MessageResponse]
}
type DeleteContainerInput struct {
@@ -127,7 +103,7 @@ type DeleteContainerInput struct {
}
type DeleteContainerOutput struct {
- Body ContainerActionResponse
+ Body base.ApiResponse[base.MessageResponse]
}
// SetAutoUpdateInput is the request input for toggling container auto-update.
@@ -140,7 +116,7 @@ type SetAutoUpdateInput struct {
}
type SetAutoUpdateOutput struct {
- Body ContainerActionResponse
+ Body base.ApiResponse[base.MessageResponse]
}
// KillContainerInput carries the optional signal for a container kill.
@@ -176,7 +152,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Summary: "List containers",
Description: "Paginated list of containers",
Tags: []string{"Containers"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersList, h.ListContainers)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -185,7 +161,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Path: "/environments/{id}/containers/counts",
Summary: "Container status counts",
Tags: []string{"Containers"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersList, h.GetContainerStatusCounts)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -194,7 +170,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Path: "/environments/{id}/containers",
Summary: "Create container",
Tags: []string{"Containers"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersCreate, h.CreateContainer)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -203,7 +179,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Path: "/environments/{id}/containers/{containerId}",
Summary: "Get container",
Tags: []string{"Containers"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersRead, h.GetContainer)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -212,7 +188,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Path: "/environments/{id}/containers/{containerId}/start",
Summary: "Start container",
Tags: []string{"Containers"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersStart, h.StartContainer)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -221,7 +197,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Path: "/environments/{id}/containers/{containerId}/stop",
Summary: "Stop container",
Tags: []string{"Containers"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersStop, h.StopContainer)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -230,7 +206,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Path: "/environments/{id}/containers/{containerId}/restart",
Summary: "Restart container",
Tags: []string{"Containers"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersRestart, h.RestartContainer)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -240,7 +216,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Summary: "Kill container",
Description: "Send a signal to the container's main process (default SIGKILL)",
Tags: []string{"Containers"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersKill, h.KillContainer)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -249,7 +225,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Path: "/environments/{id}/containers/{containerId}/pause",
Summary: "Pause container",
Tags: []string{"Containers"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersPause, h.PauseContainer)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -258,7 +234,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Path: "/environments/{id}/containers/{containerId}/unpause",
Summary: "Unpause container",
Tags: []string{"Containers"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersPause, h.UnpauseContainer)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -268,7 +244,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Summary: "Commit container",
Description: "Create an image from a container",
Tags: []string{"Containers", "Images"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesCommit, h.CommitContainer)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -278,7 +254,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Summary: "Redeploy container",
Description: "Pull latest image and recreate container",
Tags: []string{"Containers"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersRedeploy, h.RedeployContainer)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -287,7 +263,7 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Path: "/environments/{id}/containers/{containerId}",
Summary: "Delete container",
Tags: []string{"Containers"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersDelete, h.DeleteContainer)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -297,15 +273,11 @@ func RegisterContainers(api huma.API, containerSvc *services.ContainerService, d
Summary: "Set container auto-update",
Description: "Enable or disable auto-update for a specific container",
Tags: []string{"Containers", "Updater"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersAutoUpdate, h.SetAutoUpdate)
}
func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContainersInput) (*ListContainersOutput, error) {
- if h.containerService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.Updates != "" {
params.Filters["updates"] = input.Updates
@@ -331,10 +303,6 @@ func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContai
}
func (h *ContainerHandler) GetContainerStatusCounts(ctx context.Context, input *GetContainerStatusCountsInput) (*GetContainerStatusCountsOutput, error) {
- if h.dockerService == nil {
- return nil, huma.Error500InternalServerError("docker service not available")
- }
-
containers, _, _, _, err := h.dockerService.GetAllContainers(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ContainerStatusCountsError{Err: err}).Error())
@@ -362,7 +330,7 @@ func (h *ContainerHandler) GetContainerStatusCounts(ctx context.Context, input *
total := len(containers)
return &GetContainerStatusCountsOutput{
- Body: ContainerStatusCountsResponse{
+ Body: base.ApiResponse[containertypes.StatusCounts]{
Success: true,
Data: containertypes.StatusCounts{
RunningContainers: running,
@@ -575,10 +543,6 @@ func buildNetworkingConfig(body containertypes.Create) *network.NetworkingConfig
}
func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateContainerInput) (*CreateContainerOutput, error) {
- if h.containerService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -615,7 +579,7 @@ func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateCon
}
return &CreateContainerOutput{
- Body: ContainerCreatedResponse{
+ Body: base.ApiResponse[containertypes.Created]{
Success: true,
Data: out,
},
@@ -623,17 +587,13 @@ func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateCon
}
func (h *ContainerHandler) GetContainer(ctx context.Context, input *GetContainerInput) (*GetContainerOutput, error) {
- if h.containerService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
details, err := h.containerService.GetContainerDetails(ctx, input.ContainerID)
if err != nil {
return nil, huma.Error404NotFound((&common.ContainerRetrievalError{Err: err}).Error())
}
return &GetContainerOutput{
- Body: ContainerDetailsResponse{
+ Body: base.ApiResponse[containertypes.Details]{
Success: true,
Data: details,
},
@@ -748,10 +708,6 @@ type containerActionConfigInternal struct {
}
func (h *ContainerHandler) runContainerActionInternal(ctx context.Context, input *ContainerActionInput, cfg containerActionConfigInternal) (*ContainerActionOutput, error) {
- if h.containerService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -766,7 +722,7 @@ func (h *ContainerHandler) runContainerActionInternal(ctx context.Context, input
activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, cfg.CompleteMessage, nil)
return &ContainerActionOutput{
- Body: ContainerActionResponse{
+ Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: cfg.SuccessMessage, ActivityID: utils.StringPtrFromTrimmed(activityID)},
},
@@ -774,10 +730,6 @@ func (h *ContainerHandler) runContainerActionInternal(ctx context.Context, input
}
func (h *ContainerHandler) CommitContainer(ctx context.Context, input *CommitContainerInput) (*CommitContainerOutput, error) {
- if h.containerService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if strings.TrimSpace(input.ContainerID) == "" {
return nil, huma.Error400BadRequest("container ID is required")
}
@@ -801,10 +753,6 @@ func (h *ContainerHandler) CommitContainer(ctx context.Context, input *CommitCon
}
func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *ContainerActionInput) (*GetContainerOutput, error) {
- if h.containerService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -830,7 +778,7 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Contain
details.ActivityID = utils.StringPtrFromTrimmed(activityID)
return &GetContainerOutput{
- Body: ContainerDetailsResponse{
+ Body: base.ApiResponse[containertypes.Details]{
Success: true,
Data: details,
},
@@ -840,7 +788,7 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Contain
// Container was redeployed successfully, but we couldn't fetch full details.
// Return minimal response with just the ID so frontend can still navigate.
return &GetContainerOutput{
- Body: ContainerDetailsResponse{
+ Body: base.ApiResponse[containertypes.Details]{
Success: true,
Data: containertypes.Details{
ID: newContainerID,
@@ -851,10 +799,6 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Contain
}
func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteContainerInput) (*DeleteContainerOutput, error) {
- if h.containerService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -869,7 +813,7 @@ func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteCon
activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container deleted", nil)
return &DeleteContainerOutput{
- Body: ContainerActionResponse{
+ Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Container deleted successfully", ActivityID: utils.StringPtrFromTrimmed(activityID)},
},
@@ -877,10 +821,6 @@ func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteCon
}
func (h *ContainerHandler) SetAutoUpdate(ctx context.Context, input *SetAutoUpdateInput) (*SetAutoUpdateOutput, error) {
- if h.settingsService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
// Resolve container name from ID
containerName, err := h.containerService.GetContainerNameByID(ctx, input.ContainerID)
if err != nil {
@@ -898,7 +838,7 @@ func (h *ContainerHandler) SetAutoUpdate(ctx context.Context, input *SetAutoUpda
}
return &SetAutoUpdateOutput{
- Body: ContainerActionResponse{
+ Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: msg},
},
diff --git a/backend/api/handlers/customize.go b/backend/api/handlers/customize.go
index f62866196..6be5c78cb 100644
--- a/backend/api/handlers/customize.go
+++ b/backend/api/handlers/customize.go
@@ -48,10 +48,7 @@ func RegisterCustomize(api huma.API, customizeSearchService *services.CustomizeS
Summary: "Search customization options",
Description: "Search customization categories and options by query",
Tags: []string{"Customize"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, h.Search)
huma.Register(api, huma.Operation{
@@ -61,10 +58,7 @@ func RegisterCustomize(api huma.API, customizeSearchService *services.CustomizeS
Summary: "Get customization categories",
Description: "Get all available customization categories with metadata",
Tags: []string{"Customize"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, h.GetCategories)
}
@@ -83,10 +77,6 @@ func filterCustomizeCategoriesInternal(ps *authz.PermissionSet, categories []cat
// Search searches customization options by query.
func (h *CustomizeHandler) Search(ctx context.Context, input *SearchCustomizeInput) (*SearchCustomizeOutput, error) {
- if h.customizeSearchService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if strings.TrimSpace(input.Body.Query) == "" {
return nil, huma.Error400BadRequest((&common.QueryParameterRequiredError{}).Error())
}
@@ -103,10 +93,6 @@ func (h *CustomizeHandler) Search(ctx context.Context, input *SearchCustomizeInp
// GetCategories returns all available customization categories.
func (h *CustomizeHandler) GetCategories(ctx context.Context, input *GetCustomizeCategoriesInput) (*GetCustomizeCategoriesOutput, error) {
- if h.customizeSearchService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
ps, _ := humamw.PermissionsFromContext(ctx)
categories := filterCustomizeCategoriesInternal(ps, h.customizeSearchService.GetCustomizeCategories())
diff --git a/backend/api/handlers/dashboard.go b/backend/api/handlers/dashboard.go
index d14f165e2..974b9a531 100644
--- a/backend/api/handlers/dashboard.go
+++ b/backend/api/handlers/dashboard.go
@@ -63,10 +63,7 @@ func RegisterDashboard(api huma.API, dashboardService *services.DashboardService
Summary: "Get dashboard snapshot",
Description: "Returns the dashboard first-paint snapshot in a single response",
Tags: []string{"Dashboard"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermDashboardRead, h.GetDashboard)
huma.Register(api, huma.Operation{
@@ -76,19 +73,12 @@ func RegisterDashboard(api huma.API, dashboardService *services.DashboardService
Summary: "Stream dashboard snapshots across all environments",
Description: "Stream dashboard snapshot updates for the local environment and all enabled remote environments as JSON lines",
Tags: []string{"Dashboard"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireAnyEnvironmentPermission(api, authz.PermDashboardRead),
}, h.StreamAllDashboards)
}
func (h *DashboardHandler) GetDashboard(ctx context.Context, input *GetDashboardInput) (*GetDashboardOutput, error) {
- if h.dashboardService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
// EnvironmentID is consumed by env proxy/auth middleware for routing/validation.
_ = input.EnvironmentID
@@ -112,10 +102,6 @@ func (h *DashboardHandler) GetDashboard(ctx context.Context, input *GetDashboard
}
func (h *DashboardHandler) StreamAllDashboards(ctx context.Context, input *StreamAllDashboardsInput) (*huma.StreamResponse, error) {
- if h.dashboardService == nil || h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
return &huma.StreamResponse{
Body: func(humaCtx huma.Context) { //nolint:contextcheck // streaming work must use humaCtx.Context()
httpx.SetJSONStreamHeaders(humaCtx)
diff --git a/backend/api/handlers/diagnostics.go b/backend/api/handlers/diagnostics.go
index b481c56c7..faf211495 100644
--- a/backend/api/handlers/diagnostics.go
+++ b/backend/api/handlers/diagnostics.go
@@ -42,10 +42,7 @@ func RegisterDiagnostics(api huma.API, diag *services.DiagnosticsService) {
Summary: "Get runtime diagnostics",
Description: "Returns Go runtime, memory, garbage-collector, and WebSocket connection statistics.",
Tags: []string{"Diagnostics"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermDiagnosticsRead),
}, h.GetDiagnostics)
@@ -56,10 +53,7 @@ func RegisterDiagnostics(api huma.API, diag *services.DiagnosticsService) {
Summary: "Get recent backend logs",
Description: "Returns the most recent buffered backend log entries (oldest first).",
Tags: []string{"Diagnostics"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermDiagnosticsRead),
}, h.GetRecentLogs)
}
diff --git a/backend/api/handlers/environments.go b/backend/api/handlers/environments.go
index cd0c93c05..6fbfbca83 100644
--- a/backend/api/handlers/environments.go
+++ b/backend/api/handlers/environments.go
@@ -46,13 +46,6 @@ type EnvironmentHandler struct {
// Input/Output Types
// ============================================================================
-// EnvironmentPaginatedResponse is the paginated response for environments.
-type EnvironmentPaginatedResponse struct {
- Success bool `json:"success"`
- Data []environment.Environment `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListEnvironmentsInput struct {
Search string `query:"search" doc:"Search query for filtering by name or API URL"`
Sort string `query:"sort" doc:"Column to sort by"`
@@ -63,7 +56,7 @@ type ListEnvironmentsInput struct {
}
type ListEnvironmentsOutput struct {
- Body EnvironmentPaginatedResponse
+ Body base.Paginated[environment.Environment]
}
type CreateEnvironmentInput struct {
@@ -217,10 +210,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "List environments",
Description: "Get a paginated list of Docker environments",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
// No global PermEnvironmentsList gate: this endpoint also backs the
// environment switcher, so any authenticated caller may list. The handler
// filters the result to the environments the caller can actually access.
@@ -234,10 +224,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "Create an environment",
Description: "Create a new Docker environment",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsCreate),
}, h.CreateEnvironment)
@@ -248,10 +235,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "Get an environment",
Description: "Get a Docker environment by ID",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsRead),
}, h.GetEnvironment)
@@ -262,10 +246,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "Update an environment",
Description: "Update a Docker environment",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsUpdate),
}, h.UpdateEnvironment)
@@ -276,10 +257,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "Delete an environment",
Description: "Delete a Arcane environment",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsDelete),
}, h.DeleteEnvironment)
@@ -290,10 +268,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "Test environment connection",
Description: "Test connectivity to a Arcane environment",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermEnvironmentsRead, h.TestConnection)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -303,10 +278,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "Update environment heartbeat",
Description: "Update the heartbeat timestamp for an environment",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermEnvironmentsSync, h.UpdateHeartbeat)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -316,10 +288,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "Pair with local agent",
Description: "Generate or rotate the local agent pairing token",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermEnvironmentsPair, h.PairAgent)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -329,10 +298,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "Sync environment",
Description: "Sync container registries and git repositories to a remote environment",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermEnvironmentsSync, h.SyncEnvironment)
huma.Register(api, huma.Operation{
@@ -353,10 +319,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "Get deployment snippets",
Description: "Get Docker run and compose snippets for environment deployment",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermEnvironmentsPair, h.GetDeploymentSnippets)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -366,10 +329,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "Download environment mTLS bundle",
Description: "Download the generated mTLS client certificate bundle for an edge environment",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermEnvironmentsPair, h.DownloadEnvironmentMTLSBundle)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -379,10 +339,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "Download environment mTLS asset",
Description: "Download an individual generated mTLS client certificate asset for an edge environment",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermEnvironmentsPair, h.DownloadEnvironmentMTLSFile)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -392,10 +349,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "Get environment version",
Description: "Get the version of a remote environment",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermEnvironmentsRead, h.GetEnvironmentVersion)
huma.Register(api, huma.Operation{
@@ -405,10 +359,7 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
Summary: "Download Arcane-generated edge mTLS CA",
Description: "Download the Arcane-managed certificate authority used for generated edge mTLS client certificates",
Tags: []string{"Environments"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermEnvironmentsPair),
}, h.DownloadEdgeMTLSCA)
}
@@ -419,10 +370,6 @@ func RegisterEnvironments(api huma.API, environmentService *services.Environment
// ListEnvironments returns a paginated list of environments.
func (h *EnvironmentHandler) ListEnvironments(ctx context.Context, input *ListEnvironmentsInput) (*ListEnvironmentsOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
// The list endpoint backs both the environments management page and the
// environment switcher, so any authenticated caller may reach it. Global
// listers (sudo, global admins, or holders of the org-level
@@ -451,7 +398,7 @@ func (h *EnvironmentHandler) ListEnvironments(ctx context.Context, input *ListEn
}
return &ListEnvironmentsOutput{
- Body: EnvironmentPaginatedResponse{
+ Body: base.Paginated[environment.Environment]{
Success: true,
Data: envs,
Pagination: toPaginationResponseInternal(paginationResp),
@@ -485,10 +432,6 @@ func accessibleEnvironmentIDsInternal(ps *authz.PermissionSet) []string {
// CreateEnvironment creates a new environment.
func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *CreateEnvironmentInput) (*CreateEnvironmentOutput, error) {
- if h.environmentService == nil || h.apiKeyService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -598,10 +541,6 @@ func (h *EnvironmentHandler) createEnvironmentLegacyInternal(ctx context.Context
// GetEnvironment returns an environment by ID.
func (h *EnvironmentHandler) GetEnvironment(ctx context.Context, input *GetEnvironmentInput) (*GetEnvironmentOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
env, err := h.environmentService.GetEnvironmentByID(ctx, input.ID)
if err != nil {
return nil, huma.Error404NotFound((&common.EnvironmentNotFoundError{}).Error())
@@ -628,10 +567,6 @@ func (h *EnvironmentHandler) GetEnvironment(ctx context.Context, input *GetEnvir
// UpdateEnvironment updates an environment.
func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *UpdateEnvironmentInput) (*UpdateEnvironmentOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
isLocalEnv := input.ID == localDockerEnvironmentID
updates := h.buildUpdateMapInternal(&input.Body, isLocalEnv)
@@ -718,10 +653,6 @@ func (h *EnvironmentHandler) applyEdgeRuntimeStateInternal(env *environment.Envi
// DeleteEnvironment deletes an environment.
func (h *EnvironmentHandler) DeleteEnvironment(ctx context.Context, input *DeleteEnvironmentInput) (*DeleteEnvironmentOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ID == localDockerEnvironmentID {
return nil, huma.Error400BadRequest((&common.LocalEnvironmentDeletionError{}).Error())
}
@@ -748,10 +679,6 @@ func (h *EnvironmentHandler) DeleteEnvironment(ctx context.Context, input *Delet
// TestConnection tests connectivity to an environment.
func (h *EnvironmentHandler) TestConnection(ctx context.Context, input *TestConnectionInput) (*TestConnectionOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
var apiUrl *string
if input.Body != nil {
apiUrl = input.Body.ApiUrl
@@ -779,10 +706,6 @@ func (h *EnvironmentHandler) TestConnection(ctx context.Context, input *TestConn
// UpdateHeartbeat updates the heartbeat for an environment.
func (h *EnvironmentHandler) UpdateHeartbeat(ctx context.Context, input *UpdateHeartbeatInput) (*UpdateHeartbeatOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if err := h.environmentService.UpdateEnvironmentHeartbeat(ctx, input.ID); err != nil {
return nil, huma.Error500InternalServerError((&common.HeartbeatUpdateError{Err: err}).Error())
}
@@ -799,10 +722,6 @@ func (h *EnvironmentHandler) UpdateHeartbeat(ctx context.Context, input *UpdateH
// PairAgent generates or rotates the local agent pairing token.
func (h *EnvironmentHandler) PairAgent(ctx context.Context, input *PairAgentInput) (*PairAgentOutput, error) {
- if h.environmentService == nil || h.settingsService == nil || h.cfg == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ID != localDockerEnvironmentID {
return nil, huma.Error404NotFound("Not found")
}
@@ -828,10 +747,6 @@ func (h *EnvironmentHandler) PairAgent(ctx context.Context, input *PairAgentInpu
// SyncEnvironment syncs container registries and git repositories to an environment.
func (h *EnvironmentHandler) SyncEnvironment(ctx context.Context, input *SyncEnvironmentInput) (*SyncEnvironmentOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
// Sync registries
if err := h.environmentService.SyncRegistriesToEnvironment(ctx, input.ID); err != nil {
slog.WarnContext(ctx, "Failed to sync registries", "environmentID", input.ID, "error", err.Error())
@@ -930,10 +845,6 @@ func (h *EnvironmentHandler) triggerEnvironmentResourceSyncInternal(ctx context.
// PairEnvironment handles agent pairing callback with API key.
func (h *EnvironmentHandler) PairEnvironment(ctx context.Context, input *PairEnvironmentInput) (*PairEnvironmentOutput, error) {
- if h.environmentService == nil || h.apiKeyService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.XAPIKey == "" {
return nil, huma.Error400BadRequest("X-API-Key header is required")
}
@@ -982,10 +893,6 @@ func (h *EnvironmentHandler) PairEnvironment(ctx context.Context, input *PairEnv
// GetDeploymentSnippets returns deployment snippets for an environment.
func (h *EnvironmentHandler) GetDeploymentSnippets(ctx context.Context, input *GetDeploymentSnippetsInput) (*GetDeploymentSnippetsOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
env, err := h.environmentService.GetEnvironmentByID(ctx, input.ID)
if err != nil {
return nil, huma.Error404NotFound("Environment not found")
@@ -1057,10 +964,6 @@ func (h *EnvironmentHandler) GetDeploymentSnippets(ctx context.Context, input *G
// GetEnvironmentVersion returns the version of a remote environment.
func (h *EnvironmentHandler) GetEnvironmentVersion(ctx context.Context, input *GetEnvironmentVersionInput) (*GetEnvironmentVersionOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
env, err := h.environmentService.GetEnvironmentByID(ctx, input.ID)
if err != nil {
return nil, huma.Error404NotFound("Environment not found")
@@ -1264,10 +1167,6 @@ func (h *EnvironmentHandler) DownloadEnvironmentMTLSFile(ctx context.Context, in
}
func (h *EnvironmentHandler) loadEnvironmentMTLSEnvironmentInternal(ctx context.Context, environmentID string) (*models.Environment, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
env, err := h.environmentService.GetEnvironmentByID(ctx, environmentID)
if err != nil {
return nil, huma.Error404NotFound("Environment not found")
diff --git a/backend/api/handlers/environments_test.go b/backend/api/handlers/environments_test.go
index a1d04b5f7..1873e5081 100644
--- a/backend/api/handlers/environments_test.go
+++ b/backend/api/handlers/environments_test.go
@@ -42,18 +42,6 @@ func TestEnvironmentSecretDeploymentRoutesRequirePairPermission(t *testing.T) {
require.Contains(t, rec.Body.String(), authz.PermEnvironmentsPair)
})
- t.Run(testCase.name+" pair allowed", func(t *testing.T) {
- ps := authz.NewPermissionSet()
- ps.AddGlobal(authz.PermEnvironmentsPair)
- router, api := newPermissionGatingRouterInternal(t, ps)
- RegisterEnvironments(api, nil, nil, nil, nil, nil)
-
- req := httptest.NewRequest(http.MethodGet, testCase.path, nil)
- rec := httptest.NewRecorder()
- router.ServeHTTP(rec, req)
-
- require.NotEqual(t, http.StatusForbidden, rec.Code)
- })
}
}
diff --git a/backend/api/handlers/events.go b/backend/api/handlers/events.go
index a55fa1ea0..8a88c965e 100644
--- a/backend/api/handlers/events.go
+++ b/backend/api/handlers/events.go
@@ -28,13 +28,6 @@ type EventHandler struct {
// Input/Output Types
// ============================================================================
-// EventPaginatedResponse is the paginated response for events.
-type EventPaginatedResponse struct {
- Success bool `json:"success"`
- Data []event.Event `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListEventsInput struct {
Search string `query:"search" doc:"Search query"`
Sort string `query:"sort" doc:"Column to sort by"`
@@ -46,19 +39,13 @@ type ListEventsInput struct {
}
type ListEventsOutput struct {
- Body EventPaginatedResponse
+ Body base.Paginated[event.Event]
}
type GetEventStatsInput struct{}
-// EventStatsResponse is a dedicated response type to avoid schema name collision.
-type EventStatsResponse struct {
- Success bool `json:"success"`
- Data services.EventSeverityCounts `json:"data"`
-}
-
type GetEventStatsOutput struct {
- Body EventStatsResponse
+ Body base.ApiResponse[services.EventSeverityCounts]
}
type GetEventsByEnvironmentInput struct {
@@ -73,7 +60,7 @@ type GetEventsByEnvironmentInput struct {
}
type GetEventsByEnvironmentOutput struct {
- Body EventPaginatedResponse
+ Body base.Paginated[event.Event]
}
type DeleteEventInput struct {
@@ -162,10 +149,7 @@ func RegisterEvents(api huma.API, eventService *services.EventService) {
Summary: "List events",
Description: "Get a paginated list of system events",
Tags: []string{"Events"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermEventsRead),
}, h.ListEvents)
@@ -176,10 +160,7 @@ func RegisterEvents(api huma.API, eventService *services.EventService) {
Summary: "Event severity counts",
Description: "Get global event counts grouped by severity",
Tags: []string{"Events"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermEventsRead),
}, h.GetEventStats)
@@ -190,10 +171,7 @@ func RegisterEvents(api huma.API, eventService *services.EventService) {
Summary: "Delete an event",
Description: "Delete a system event by ID",
Tags: []string{"Events"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermEventsDelete),
}, h.DeleteEvent)
@@ -204,10 +182,7 @@ func RegisterEvents(api huma.API, eventService *services.EventService) {
Summary: "Get events by environment",
Description: "Get a paginated list of events for a specific environment",
Tags: []string{"Events"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermEventsRead),
}, h.GetEventsByEnvironment)
}
@@ -218,10 +193,6 @@ func RegisterEvents(api huma.API, eventService *services.EventService) {
// ListEvents returns a paginated list of events.
func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (*ListEventsOutput, error) {
- if h.eventService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.Severity != "" {
@@ -237,7 +208,7 @@ func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (
}
return &ListEventsOutput{
- Body: EventPaginatedResponse{
+ Body: base.Paginated[event.Event]{
Success: true,
Data: events,
Pagination: toPaginationResponseInternal(paginationResp),
@@ -247,17 +218,13 @@ func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (
// GetEventStats returns global event counts grouped by severity.
func (h *EventHandler) GetEventStats(ctx context.Context, _ *GetEventStatsInput) (*GetEventStatsOutput, error) {
- if h.eventService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
counts, err := h.eventService.GetEventSeverityCounts(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.EventStatsError{Err: err}).Error())
}
return &GetEventStatsOutput{
- Body: EventStatsResponse{
+ Body: base.ApiResponse[services.EventSeverityCounts]{
Success: true,
Data: counts,
},
@@ -266,10 +233,6 @@ func (h *EventHandler) GetEventStats(ctx context.Context, _ *GetEventStatsInput)
// GetEventsByEnvironment returns events for a specific environment.
func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEventsByEnvironmentInput) (*GetEventsByEnvironmentOutput, error) {
- if h.eventService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.EnvironmentID == "" {
return nil, huma.Error400BadRequest((&common.EnvironmentIDRequiredError{}).Error())
}
@@ -289,7 +252,7 @@ func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEve
}
return &GetEventsByEnvironmentOutput{
- Body: EventPaginatedResponse{
+ Body: base.Paginated[event.Event]{
Success: true,
Data: events,
Pagination: toPaginationResponseInternal(paginationResp),
@@ -299,10 +262,6 @@ func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEve
// DeleteEvent deletes an event.
func (h *EventHandler) DeleteEvent(ctx context.Context, input *DeleteEventInput) (*DeleteEventOutput, error) {
- if h.eventService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.EventID == "" {
return nil, huma.Error400BadRequest((&common.EventIDRequiredError{}).Error())
}
diff --git a/backend/api/handlers/events_test.go b/backend/api/handlers/events_test.go
index e3e8b6afd..4bc0649fb 100644
--- a/backend/api/handlers/events_test.go
+++ b/backend/api/handlers/events_test.go
@@ -24,17 +24,10 @@ func TestEventDeleteRequiresEventsDeletePermission(t *testing.T) {
testCases := []struct {
name string
permission string
- wantStatus int
}{
{
name: "events read cannot delete",
permission: authz.PermEventsRead,
- wantStatus: http.StatusForbidden,
- },
- {
- name: "events delete reaches handler",
- permission: authz.PermEventsDelete,
- wantStatus: http.StatusInternalServerError,
},
}
@@ -49,10 +42,8 @@ func TestEventDeleteRequiresEventsDeletePermission(t *testing.T) {
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
- require.Equal(t, testCase.wantStatus, rec.Code)
- if testCase.wantStatus == http.StatusForbidden {
- require.Contains(t, rec.Body.String(), authz.PermEventsDelete)
- }
+ require.Equal(t, http.StatusForbidden, rec.Code)
+ require.Contains(t, rec.Body.String(), authz.PermEventsDelete)
})
}
}
diff --git a/backend/api/handlers/federated.go b/backend/api/handlers/federated.go
index e43a8c929..d521db4cb 100644
--- a/backend/api/handlers/federated.go
+++ b/backend/api/handlers/federated.go
@@ -117,10 +117,7 @@ func RegisterFederatedCredentials(api huma.API, federatedCredentialService *serv
Summary: "List federated credentials",
Description: "Get a paginated list of workload identity federation trust rules",
Tags: []string{"Federated Credentials"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermFederatedList),
}, h.ListFederatedCredentials)
@@ -131,10 +128,7 @@ func RegisterFederatedCredentials(api huma.API, federatedCredentialService *serv
Summary: "Create a federated credential",
Description: "Create a workload identity federation trust rule",
Tags: []string{"Federated Credentials"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireGlobalAdmin(api),
}, h.CreateFederatedCredential)
@@ -145,10 +139,7 @@ func RegisterFederatedCredentials(api huma.API, federatedCredentialService *serv
Summary: "Get a federated credential",
Description: "Get details of a workload identity federation trust rule",
Tags: []string{"Federated Credentials"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermFederatedRead),
}, h.GetFederatedCredential)
@@ -159,10 +150,7 @@ func RegisterFederatedCredentials(api huma.API, federatedCredentialService *serv
Summary: "Update a federated credential",
Description: "Update a workload identity federation trust rule",
Tags: []string{"Federated Credentials"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireGlobalAdmin(api),
}, h.UpdateFederatedCredential)
@@ -173,19 +161,12 @@ func RegisterFederatedCredentials(api huma.API, federatedCredentialService *serv
Summary: "Delete a federated credential",
Description: "Delete a workload identity federation trust rule and its service user",
Tags: []string{"Federated Credentials"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireGlobalAdmin(api),
}, h.DeleteFederatedCredential)
}
func (h *FederatedCredentialHandler) ListFederatedCredentials(ctx context.Context, input *ListFederatedCredentialsInput) (*ListFederatedCredentialsOutput, error) {
- if h.federatedCredentialService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
credentials, paginationResp, err := h.federatedCredentialService.List(ctx, buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search))
if err != nil {
return nil, huma.Error500InternalServerError("failed to list federated credentials")
@@ -201,9 +182,6 @@ func (h *FederatedCredentialHandler) ListFederatedCredentials(ctx context.Contex
}
func (h *FederatedCredentialHandler) CreateFederatedCredential(ctx context.Context, input *CreateFederatedCredentialInput) (*CreateFederatedCredentialOutput, error) {
- if h.federatedCredentialService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -223,9 +201,6 @@ func (h *FederatedCredentialHandler) CreateFederatedCredential(ctx context.Conte
}
func (h *FederatedCredentialHandler) GetFederatedCredential(ctx context.Context, input *GetFederatedCredentialInput) (*GetFederatedCredentialOutput, error) {
- if h.federatedCredentialService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
credential, err := h.federatedCredentialService.Get(ctx, input.ID)
if err != nil {
return nil, federatedCredentialManagementErrorInternal(err)
@@ -240,9 +215,6 @@ func (h *FederatedCredentialHandler) GetFederatedCredential(ctx context.Context,
}
func (h *FederatedCredentialHandler) UpdateFederatedCredential(ctx context.Context, input *UpdateFederatedCredentialInput) (*UpdateFederatedCredentialOutput, error) {
- if h.federatedCredentialService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -262,9 +234,6 @@ func (h *FederatedCredentialHandler) UpdateFederatedCredential(ctx context.Conte
}
func (h *FederatedCredentialHandler) DeleteFederatedCredential(ctx context.Context, input *DeleteFederatedCredentialInput) (*DeleteFederatedCredentialOutput, error) {
- if h.federatedCredentialService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.federatedCredentialService.Delete(ctx, input.ID); err != nil {
return nil, federatedCredentialManagementErrorInternal(err)
}
diff --git a/backend/api/handlers/git_repositories.go b/backend/api/handlers/git_repositories.go
index 1ef123961..dea1f94ae 100644
--- a/backend/api/handlers/git_repositories.go
+++ b/backend/api/handlers/git_repositories.go
@@ -21,13 +21,6 @@ type GitRepositoryHandler struct {
// Input/Output Types
// ============================================================================
-// GitRepositoryPaginatedResponse is the paginated response for git repositories.
-type GitRepositoryPaginatedResponse struct {
- Success bool `json:"success"`
- Data []gitops.GitRepository `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListGitRepositoriesInput struct {
Search string `query:"search" doc:"Search query"`
Sort string `query:"sort" doc:"Column to sort by"`
@@ -37,7 +30,7 @@ type ListGitRepositoriesInput struct {
}
type ListGitRepositoriesOutput struct {
- Body GitRepositoryPaginatedResponse
+ Body base.Paginated[gitops.GitRepository]
}
type CreateGitRepositoryInput struct {
@@ -133,10 +126,6 @@ func RegisterGitRepositories(api huma.API, repoService *services.GitRepositorySe
// ListRepositories returns a paginated list of git repositories.
func (h *GitRepositoryHandler) ListRepositories(ctx context.Context, input *ListGitRepositoriesInput) (*ListGitRepositoriesOutput, error) {
- if h.repoService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
repositories, paginationResp, err := h.repoService.GetRepositoriesPaginated(ctx, params)
@@ -145,7 +134,7 @@ func (h *GitRepositoryHandler) ListRepositories(ctx context.Context, input *List
}
return &ListGitRepositoriesOutput{
- Body: GitRepositoryPaginatedResponse{
+ Body: base.Paginated[gitops.GitRepository]{
Success: true,
Data: repositories,
Pagination: toPaginationResponseInternal(paginationResp),
@@ -155,10 +144,6 @@ func (h *GitRepositoryHandler) ListRepositories(ctx context.Context, input *List
// CreateRepository creates a new git repository.
func (h *GitRepositoryHandler) CreateRepository(ctx context.Context, input *CreateGitRepositoryInput) (*CreateGitRepositoryOutput, error) {
- if h.repoService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
actor := currentActorInternal(ctx)
repo, err := h.repoService.CreateRepository(ctx, input.Body, actor)
@@ -181,10 +166,6 @@ func (h *GitRepositoryHandler) CreateRepository(ctx context.Context, input *Crea
// GetRepository returns a git repository by ID.
func (h *GitRepositoryHandler) GetRepository(ctx context.Context, input *GetGitRepositoryInput) (*GetGitRepositoryOutput, error) {
- if h.repoService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
repo, err := h.repoService.GetRepositoryByID(ctx, input.ID)
if err != nil {
apiErr := models.ToAPIError(err)
@@ -205,10 +186,6 @@ func (h *GitRepositoryHandler) GetRepository(ctx context.Context, input *GetGitR
// UpdateRepository updates an existing git repository.
func (h *GitRepositoryHandler) UpdateRepository(ctx context.Context, input *UpdateGitRepositoryInput) (*UpdateGitRepositoryOutput, error) {
- if h.repoService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
actor := currentActorInternal(ctx)
repo, err := h.repoService.UpdateRepository(ctx, input.ID, input.Body, actor)
@@ -231,10 +208,6 @@ func (h *GitRepositoryHandler) UpdateRepository(ctx context.Context, input *Upda
// DeleteRepository deletes a git repository by ID.
func (h *GitRepositoryHandler) DeleteRepository(ctx context.Context, input *DeleteGitRepositoryInput) (*DeleteGitRepositoryOutput, error) {
- if h.repoService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
actor := currentActorInternal(ctx)
if err := h.repoService.DeleteRepository(ctx, input.ID, actor); err != nil {
@@ -254,10 +227,6 @@ func (h *GitRepositoryHandler) DeleteRepository(ctx context.Context, input *Dele
// TestRepository tests connectivity and authentication to a git repository.
func (h *GitRepositoryHandler) TestRepository(ctx context.Context, input *TestGitRepositoryInput) (*TestGitRepositoryOutput, error) {
- if h.repoService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
actor := currentActorInternal(ctx)
if err := h.repoService.TestConnection(ctx, input.ID, input.Branch, actor); err != nil {
@@ -276,10 +245,6 @@ func (h *GitRepositoryHandler) TestRepository(ctx context.Context, input *TestGi
// ListBranches returns all branches from a git repository.
func (h *GitRepositoryHandler) ListBranches(ctx context.Context, input *ListBranchesInput) (*ListBranchesOutput, error) {
- if h.repoService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
branches, err := h.repoService.ListBranches(ctx, input.ID)
if err != nil {
return nil, huma.Error400BadRequest((&common.GitRepositoryTestError{Err: err}).Error())
@@ -297,10 +262,6 @@ func (h *GitRepositoryHandler) ListBranches(ctx context.Context, input *ListBran
// BrowseFiles returns files and directories from a git repository.
func (h *GitRepositoryHandler) BrowseFiles(ctx context.Context, input *BrowseFilesInput) (*BrowseFilesOutput, error) {
- if h.repoService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.Branch == "" {
return nil, huma.Error400BadRequest("branch parameter is required")
}
@@ -320,10 +281,6 @@ func (h *GitRepositoryHandler) BrowseFiles(ctx context.Context, input *BrowseFil
// SyncRepositories syncs git repositories from a manager to this agent instance.
func (h *GitRepositoryHandler) SyncRepositories(ctx context.Context, input *SyncGitRepositoriesInput) (*SyncGitRepositoriesOutput, error) {
- if h.repoService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if err := h.repoService.SyncRepositories(ctx, input.Body.Repositories); err != nil {
apiErr := models.ToAPIError(err)
return nil, huma.NewError(apiErr.HTTPStatus(), (&common.GitRepositorySyncError{Err: err}).Error())
diff --git a/backend/api/handlers/gitops_syncs.go b/backend/api/handlers/gitops_syncs.go
index 2fbafd6bb..ebdc2ae6e 100644
--- a/backend/api/handlers/gitops_syncs.go
+++ b/backend/api/handlers/gitops_syncs.go
@@ -22,14 +22,6 @@ type GitOpsSyncHandler struct {
// Input/Output Types
// ============================================================================
-// GitOpsSyncPaginatedResponse is the paginated response for GitOps syncs.
-type GitOpsSyncPaginatedResponse struct {
- Success bool `json:"success"`
- Data []gitops.GitOpsSync `json:"data"`
- Counts gitops.SyncCounts `json:"counts"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListGitOpsSyncsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -40,7 +32,7 @@ type ListGitOpsSyncsInput struct {
}
type ListGitOpsSyncsOutput struct {
- Body GitOpsSyncPaginatedResponse
+ Body base.PaginatedWithCounts[gitops.GitOpsSync, gitops.SyncCounts]
}
type CreateGitOpsSyncInput struct {
@@ -161,10 +153,6 @@ func requireLifecyclePermissionInternal(ctx context.Context, environmentID strin
// ListSyncs returns a paginated list of GitOps syncs.
func (h *GitOpsSyncHandler) ListSyncs(ctx context.Context, input *ListGitOpsSyncsInput) (*ListGitOpsSyncsOutput, error) {
- if h.syncService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
syncs, paginationResp, counts, err := h.syncService.GetSyncsPaginated(ctx, input.EnvironmentID, params)
@@ -173,7 +161,7 @@ func (h *GitOpsSyncHandler) ListSyncs(ctx context.Context, input *ListGitOpsSync
}
return &ListGitOpsSyncsOutput{
- Body: GitOpsSyncPaginatedResponse{
+ Body: base.PaginatedWithCounts[gitops.GitOpsSync, gitops.SyncCounts]{
Success: true,
Data: syncs,
Counts: counts,
@@ -184,10 +172,6 @@ func (h *GitOpsSyncHandler) ListSyncs(ctx context.Context, input *ListGitOpsSync
// CreateSync creates a new GitOps sync.
func (h *GitOpsSyncHandler) CreateSync(ctx context.Context, input *CreateGitOpsSyncInput) (*CreateGitOpsSyncOutput, error) {
- if h.syncService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if err := requireLifecyclePermissionInternal(ctx, input.EnvironmentID, input.Body.HasPreDeployConfig()); err != nil {
return nil, err
}
@@ -214,10 +198,6 @@ func (h *GitOpsSyncHandler) CreateSync(ctx context.Context, input *CreateGitOpsS
// ImportSyncs imports multiple GitOps syncs.
func (h *GitOpsSyncHandler) ImportSyncs(ctx context.Context, input *ImportGitOpsSyncsInput) (*ImportGitOpsSyncsOutput, error) {
- if h.syncService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
actor := currentActorInternal(ctx)
response, err := h.syncService.ImportSyncs(ctx, input.EnvironmentID, input.Body, actor)
@@ -235,10 +215,6 @@ func (h *GitOpsSyncHandler) ImportSyncs(ctx context.Context, input *ImportGitOps
// GetSync returns a GitOps sync by ID.
func (h *GitOpsSyncHandler) GetSync(ctx context.Context, input *GetGitOpsSyncInput) (*GetGitOpsSyncOutput, error) {
- if h.syncService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
sync, err := h.syncService.GetSyncByID(ctx, input.EnvironmentID, input.SyncID)
if err != nil {
apiErr := models.ToAPIError(err)
@@ -259,10 +235,6 @@ func (h *GitOpsSyncHandler) GetSync(ctx context.Context, input *GetGitOpsSyncInp
// UpdateSync updates an existing GitOps sync.
func (h *GitOpsSyncHandler) UpdateSync(ctx context.Context, input *UpdateGitOpsSyncInput) (*UpdateGitOpsSyncOutput, error) {
- if h.syncService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if err := requireLifecyclePermissionInternal(ctx, input.EnvironmentID, input.Body.HasPreDeployConfig()); err != nil {
return nil, err
}
@@ -289,10 +261,6 @@ func (h *GitOpsSyncHandler) UpdateSync(ctx context.Context, input *UpdateGitOpsS
// DeleteSync deletes a GitOps sync by ID.
func (h *GitOpsSyncHandler) DeleteSync(ctx context.Context, input *DeleteGitOpsSyncInput) (*DeleteGitOpsSyncOutput, error) {
- if h.syncService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
actor := currentActorInternal(ctx)
if err := h.syncService.DeleteSync(ctx, input.EnvironmentID, input.SyncID, actor); err != nil {
@@ -312,10 +280,6 @@ func (h *GitOpsSyncHandler) DeleteSync(ctx context.Context, input *DeleteGitOpsS
// PerformSync manually triggers a sync operation.
func (h *GitOpsSyncHandler) PerformSync(ctx context.Context, input *PerformSyncInput) (*PerformSyncOutput, error) {
- if h.syncService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
actor := currentActorInternal(ctx)
result, err := h.syncService.PerformSync(ctx, input.EnvironmentID, input.SyncID, actor)
@@ -334,10 +298,6 @@ func (h *GitOpsSyncHandler) PerformSync(ctx context.Context, input *PerformSyncI
// GetStatus returns the current status of a GitOps sync.
func (h *GitOpsSyncHandler) GetStatus(ctx context.Context, input *GetSyncStatusInput) (*GetSyncStatusOutput, error) {
- if h.syncService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
status, err := h.syncService.GetSyncStatus(ctx, input.EnvironmentID, input.SyncID)
if err != nil {
apiErr := models.ToAPIError(err)
@@ -354,10 +314,6 @@ func (h *GitOpsSyncHandler) GetStatus(ctx context.Context, input *GetSyncStatusI
// BrowseFiles returns the file tree at the specified path in the repository.
func (h *GitOpsSyncHandler) BrowseFiles(ctx context.Context, input *BrowseSyncFilesInput) (*BrowseSyncFilesOutput, error) {
- if h.syncService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
response, err := h.syncService.BrowseFiles(ctx, input.EnvironmentID, input.SyncID, input.Path)
if err != nil {
apiErr := models.ToAPIError(err)
diff --git a/backend/api/handlers/helpers.go b/backend/api/handlers/helpers.go
index a45e83052..5f1ad3e25 100644
--- a/backend/api/handlers/helpers.go
+++ b/backend/api/handlers/helpers.go
@@ -4,6 +4,7 @@ import (
"context"
json "encoding/json/v2"
"errors"
+ "mime/multipart"
"strings"
"github.com/danielgtaylor/huma/v2"
@@ -80,6 +81,21 @@ func requireUserInternal(ctx context.Context) (*models.User, error) {
return user, nil
}
+func openUploadedFileInternal(form multipart.Form) (multipart.File, *multipart.FileHeader, error) {
+ files := form.File["file"]
+ if len(files) == 0 {
+ return nil, nil, huma.Error400BadRequest((&common.NoFileUploadedError{}).Error())
+ }
+
+ fileHeader := files[0]
+ file, err := fileHeader.Open()
+ if err != nil {
+ return nil, nil, huma.Error500InternalServerError((&common.FileUploadReadError{Err: err}).Error())
+ }
+
+ return file, fileHeader, nil
+}
+
func registerSecuredInternal[I, O any](
api huma.API,
op huma.Operation,
diff --git a/backend/api/handlers/image_updates.go b/backend/api/handlers/image_updates.go
index 02431c36f..cd359151f 100644
--- a/backend/api/handlers/image_updates.go
+++ b/backend/api/handlers/image_updates.go
@@ -89,7 +89,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Path: "/environments/{id}/image-updates/check",
Summary: "Check image update by reference",
Tags: []string{"Image Updates"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImageUpdatesCheck, h.CheckImageUpdate)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -98,7 +98,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Path: "/environments/{id}/image-updates/check/{imageId}",
Summary: "Check image update by ID",
Tags: []string{"Image Updates"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImageUpdatesCheck, h.CheckImageUpdateByID)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -107,7 +107,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Path: "/environments/{id}/image-updates/check/{imageId}",
Summary: "Check image update by ID (POST)",
Tags: []string{"Image Updates"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImageUpdatesCheck, h.CheckImageUpdateByID)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -116,7 +116,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Path: "/environments/{id}/image-updates/check-batch",
Summary: "Check multiple images",
Tags: []string{"Image Updates"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImageUpdatesCheck, h.CheckMultipleImages)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -125,7 +125,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Path: "/environments/{id}/image-updates/check-all",
Summary: "Check all images",
Tags: []string{"Image Updates"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImageUpdatesCheck, h.CheckAllImages)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -134,7 +134,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
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": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImageUpdatesRead, h.GetUpdateInfoByRefs)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -143,7 +143,7 @@ func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateServ
Path: "/environments/{id}/image-updates/summary",
Summary: "Get update summary",
Tags: []string{"Image Updates"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImageUpdatesRead, h.GetUpdateSummary)
}
diff --git a/backend/api/handlers/images.go b/backend/api/handlers/images.go
index 5e63960d9..5324c161d 100644
--- a/backend/api/handlers/images.go
+++ b/backend/api/handlers/images.go
@@ -40,13 +40,6 @@ type ImageHandler struct {
// --- Huma Input/Output Wrappers ---
-// ImagePaginatedResponse is the paginated response for images.
-type ImagePaginatedResponse struct {
- Success bool `json:"success"`
- Data []image.Summary `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListImagesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -59,7 +52,7 @@ type ListImagesInput struct {
}
type ListImagesOutput struct {
- Body ImagePaginatedResponse
+ Body base.Paginated[image.Summary]
}
type GetImageInput struct {
@@ -136,12 +129,6 @@ type BuildImageInput struct {
Body buildtypes.BuildRequest
}
-type ImageBuildPaginatedResponse struct {
- Success bool `json:"success"`
- Data []image.BuildRecord `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListImageBuildsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -154,7 +141,7 @@ type ListImageBuildsInput struct {
}
type ListImageBuildsOutput struct {
- Body ImageBuildPaginatedResponse
+ Body base.Paginated[image.BuildRecord]
}
type GetImageBuildInput struct {
@@ -185,13 +172,8 @@ type GetImageUsageCountsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type ImageUsageCountsResponse struct {
- Success bool `json:"success"`
- Data image.UsageCounts `json:"data"`
-}
-
type GetImageUsageCountsOutput struct {
- Body ImageUsageCountsResponse
+ Body base.ApiResponse[image.UsageCounts]
}
type UploadImageInput struct {
@@ -222,10 +204,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "List images",
Description: "Get a paginated list of Docker images",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesList, h.ListImages)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -235,10 +214,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "Get image usage counts",
Description: "Get counts of images in use, unused, total, and total size",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesList, h.GetImageUsageCounts)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -248,10 +224,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "Get image attestations",
Description: "Get in-toto attestation statements attached to a Docker image",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesRead, h.GetImageAttestations)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -261,10 +234,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "Search images",
Description: "Search Docker Hub images",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesRead, h.SearchImages)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -274,10 +244,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "Tag image",
Description: "Add a repository tag to an image",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesTag, h.TagImage)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -287,10 +254,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "Get image history",
Description: "Get Docker image layer history",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesRead, h.GetImageHistory)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -300,10 +264,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "Export image",
Description: "Download a Docker image as a tar archive",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesRead, h.ExportImage)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -313,10 +274,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "Get image by ID",
Description: "Get a Docker image by its ID",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesRead, h.GetImage)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -326,10 +284,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "Remove an image",
Description: "Remove a Docker image by ID",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesDelete, h.RemoveImage)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -339,10 +294,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "Pull an image",
Description: "Pull a Docker image from a registry with streaming progress output",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesPull, h.PullImage)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -352,10 +304,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "Build an image",
Description: "Build a Docker image using BuildKit with streaming progress output",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesBuild, h.BuildImage)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -365,10 +314,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "List image builds",
Description: "Get a paginated list of image build history for an environment",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesList, h.ListImageBuilds)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -378,10 +324,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "Get image build",
Description: "Get a single image build history entry with output",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesRead, h.GetImageBuild)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -391,10 +334,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "Prune unused images",
Description: "Remove unused Docker images",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImagesPrune, h.PruneImages)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -404,10 +344,7 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
Summary: "Upload an image",
Description: "Upload a Docker image from a tar archive",
Tags: []string{"Images"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
RequestBody: &huma.RequestBody{
Content: map[string]*huma.MediaType{
"multipart/form-data": {
@@ -430,10 +367,6 @@ func RegisterImages(api huma.API, dockerService *services.DockerClientService, i
// ListImages returns a paginated list of images.
func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (*ListImagesOutput, error) {
- if h.imageService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.InUse != "" {
params.Filters["inUse"] = input.InUse
@@ -456,7 +389,7 @@ func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (
}
return &ListImagesOutput{
- Body: ImagePaginatedResponse{
+ Body: base.Paginated[image.Summary]{
Success: true,
Data: images,
Pagination: toPaginationResponseInternal(paginationResp),
@@ -466,10 +399,6 @@ func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (
// GetImage returns an image by ID.
func (h *ImageHandler) GetImage(ctx context.Context, input *GetImageInput) (*GetImageOutput, error) {
- if h.imageService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
out, err := h.imageService.GetImageDetail(ctx, input.ImageID)
if err != nil {
return nil, huma.Error404NotFound((&common.ImageNotFoundError{Err: err}).Error())
@@ -485,10 +414,6 @@ func (h *ImageHandler) GetImage(ctx context.Context, input *GetImageInput) (*Get
// GetImageAttestations returns in-toto attestation statements attached to an image.
func (h *ImageHandler) GetImageAttestations(ctx context.Context, input *GetImageAttestationsInput) (*GetImageAttestationsOutput, error) {
- if h.imageService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
imageName, err := url.PathUnescape(input.ImageName)
if err != nil {
return nil, huma.Error400BadRequest(fmt.Sprintf("invalid image name %q", input.ImageName))
@@ -523,10 +448,6 @@ func (h *ImageHandler) GetImageAttestations(ctx context.Context, input *GetImage
// TagImage adds a repository tag to an image.
func (h *ImageHandler) TagImage(ctx context.Context, input *TagImageInput) (*TagImageOutput, error) {
- if h.imageService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
imageName, err := decodeImageNameInternal(input.ImageName)
if err != nil {
return nil, err
@@ -554,10 +475,6 @@ func (h *ImageHandler) TagImage(ctx context.Context, input *TagImageInput) (*Tag
// GetImageHistory returns Docker image layer history.
func (h *ImageHandler) GetImageHistory(ctx context.Context, input *GetImageHistoryInput) (*GetImageHistoryOutput, error) {
- if h.imageService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
imageName, err := decodeImageNameInternal(input.ImageName)
if err != nil {
return nil, err
@@ -581,10 +498,6 @@ func (h *ImageHandler) GetImageHistory(ctx context.Context, input *GetImageHisto
// SearchImages searches Docker Hub images.
func (h *ImageHandler) SearchImages(ctx context.Context, input *SearchImagesInput) (*SearchImagesOutput, error) {
- if h.imageService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
results, err := h.imageService.SearchImages(ctx, input.Term)
if err != nil {
if strings.Contains(err.Error(), "term is required") {
@@ -606,10 +519,6 @@ func (h *ImageHandler) SearchImages(ctx context.Context, input *SearchImagesInpu
// ExportImage streams a Docker image tar archive.
func (h *ImageHandler) ExportImage(ctx context.Context, input *ExportImageInput) (*huma.StreamResponse, error) {
- if h.imageService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
imageName, err := decodeImageNameInternal(input.ImageName)
if err != nil {
return nil, err
@@ -655,10 +564,6 @@ func imageExportFileNameInternal(imageName string) string {
// RemoveImage removes a Docker image.
func (h *ImageHandler) RemoveImage(ctx context.Context, input *RemoveImageInput) (*RemoveImageOutput, error) {
- if h.imageService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -680,10 +585,6 @@ func (h *ImageHandler) RemoveImage(ctx context.Context, input *RemoveImageInput)
// PullImage pulls a Docker image with streaming progress.
func (h *ImageHandler) PullImage(ctx context.Context, input *PullImageInput) (*huma.StreamResponse, error) {
- if h.imageService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.Body.ImageName == "" {
return nil, huma.Error400BadRequest("image name is required")
}
@@ -737,10 +638,6 @@ func (h *ImageHandler) PullImage(ctx context.Context, input *PullImageInput) (*h
// BuildImage builds a Docker image with streaming progress.
func (h *ImageHandler) BuildImage(ctx context.Context, input *BuildImageInput) (*huma.StreamResponse, error) {
- if h.buildService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if strings.TrimSpace(input.Body.ContextDir) == "" {
return nil, huma.Error400BadRequest("contextDir is required")
}
@@ -794,10 +691,6 @@ func (h *ImageHandler) BuildImage(ctx context.Context, input *BuildImageInput) (
// ListImageBuilds returns a paginated list of image build history entries.
func (h *ImageHandler) ListImageBuilds(ctx context.Context, input *ListImageBuildsInput) (*ListImageBuildsOutput, error) {
- if h.buildService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.EnvironmentID == "" {
return nil, huma.Error400BadRequest((&common.EnvironmentIDRequiredError{}).Error())
}
@@ -820,7 +713,7 @@ func (h *ImageHandler) ListImageBuilds(ctx context.Context, input *ListImageBuil
}
return &ListImageBuildsOutput{
- Body: ImageBuildPaginatedResponse{
+ Body: base.Paginated[image.BuildRecord]{
Success: true,
Data: builds,
Pagination: toPaginationResponseInternal(paginationResp),
@@ -830,10 +723,6 @@ func (h *ImageHandler) ListImageBuilds(ctx context.Context, input *ListImageBuil
// GetImageBuild returns a single build history entry.
func (h *ImageHandler) GetImageBuild(ctx context.Context, input *GetImageBuildInput) (*GetImageBuildOutput, error) {
- if h.buildService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.EnvironmentID == "" {
return nil, huma.Error400BadRequest((&common.EnvironmentIDRequiredError{}).Error())
}
@@ -860,10 +749,6 @@ func (h *ImageHandler) GetImageBuild(ctx context.Context, input *GetImageBuildIn
// PruneImages removes unused Docker images.
func (h *ImageHandler) PruneImages(ctx context.Context, input *PruneImagesInput) (*PruneImagesOutput, error) {
- if h.imageService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
mode := resolvePruneImageModeInternal(input)
until := resolvePruneImageUntilInternal(input)
@@ -939,10 +824,6 @@ func resolveLegacyPruneImageModeInternal(dangling bool) string {
// GetImageUsageCounts returns counts of images by usage status.
func (h *ImageHandler) GetImageUsageCounts(ctx context.Context, input *GetImageUsageCountsInput) (*GetImageUsageCountsOutput, error) {
- if h.dockerService == nil || h.imageService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
var (
inuse, unused, total int
totalSize int64
@@ -968,7 +849,7 @@ func (h *ImageHandler) GetImageUsageCounts(ctx context.Context, input *GetImageU
}
return &GetImageUsageCountsOutput{
- Body: ImageUsageCountsResponse{
+ Body: base.ApiResponse[image.UsageCounts]{
Success: true,
Data: image.UsageCounts{
Inuse: inuse,
@@ -982,10 +863,6 @@ func (h *ImageHandler) GetImageUsageCounts(ctx context.Context, input *GetImageU
// UploadImage uploads a Docker image from a tar archive.
func (h *ImageHandler) UploadImage(ctx context.Context, input *UploadImageInput) (*UploadImageOutput, error) {
- if h.imageService == nil || h.settingsService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
diff --git a/backend/api/handlers/job_schedules.go b/backend/api/handlers/job_schedules.go
index 60a0180ef..97ce19b53 100644
--- a/backend/api/handlers/job_schedules.go
+++ b/backend/api/handlers/job_schedules.go
@@ -59,10 +59,7 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *ser
Summary: "Get job schedules",
Description: "Get configured cron schedules for background jobs",
Tags: []string{"JobSchedules"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermJobsManage, h.Get)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -72,10 +69,7 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *ser
Summary: "Update job schedules",
Description: "Update background job cron schedules and reschedule running jobs",
Tags: []string{"JobSchedules"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermJobsManage, h.Update)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -85,10 +79,7 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *ser
Summary: "List all background jobs",
Description: "Get status, schedule, and metadata for all background jobs",
Tags: []string{"JobSchedules"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermJobsManage, h.ListJobs)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -98,10 +89,7 @@ func RegisterJobSchedules(api huma.API, jobSvc *services.JobService, envSvc *ser
Summary: "Run a job now",
Description: "Manually trigger a background job to run immediately",
Tags: []string{"JobSchedules"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermJobsManage, h.RunJob)
}
@@ -111,14 +99,7 @@ type JobSchedulesHandler struct {
}
func (h *JobSchedulesHandler) ListJobs(ctx context.Context, input *ListJobsInput) (*GetJobsOutput, error) {
- if h.jobService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ID != "0" {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
jobs, err := proxyRemoteJSONInternal[jobschedule.JobListResponse](ctx, h.environmentService, input.ID, http.MethodGet, "/api/environments/0/jobs", nil)
if err != nil {
return nil, err
@@ -135,14 +116,7 @@ func (h *JobSchedulesHandler) ListJobs(ctx context.Context, input *ListJobsInput
}
func (h *JobSchedulesHandler) RunJob(ctx context.Context, input *RunJobInput) (*RunJobOutput, error) {
- if h.jobService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ID != "0" {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
runResp, err := proxyRemoteJSONInternal[jobschedule.JobRunResponse](ctx, h.environmentService, input.ID, http.MethodPost, "/api/environments/0/jobs/"+input.JobID+"/run", nil)
if err != nil {
return nil, err
@@ -164,14 +138,7 @@ func (h *JobSchedulesHandler) RunJob(ctx context.Context, input *RunJobInput) (*
}
func (h *JobSchedulesHandler) Get(ctx context.Context, input *GetJobSchedulesInput) (*GetJobSchedulesOutput, error) {
- if h.jobService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ID != "0" {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
cfg, err := proxyRemoteJSONInternal[jobschedule.Config](ctx, h.environmentService, input.ID, http.MethodGet, "/api/environments/0/job-schedules", nil)
if err != nil {
return nil, err
@@ -184,15 +151,7 @@ func (h *JobSchedulesHandler) Get(ctx context.Context, input *GetJobSchedulesInp
}
func (h *JobSchedulesHandler) Update(ctx context.Context, input *UpdateJobSchedulesInput) (*UpdateJobSchedulesOutput, error) {
- if h.jobService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ID != "0" {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
-
apiResp, err := proxyRemoteJSONInternal[base.ApiResponse[jobschedule.Config]](ctx, h.environmentService, input.ID, http.MethodPut, "/api/environments/0/job-schedules", input.Body)
if err != nil {
return nil, err
diff --git a/backend/api/handlers/networks.go b/backend/api/handlers/networks.go
index 935734fe3..fd69a7a53 100644
--- a/backend/api/handlers/networks.go
+++ b/backend/api/handlers/networks.go
@@ -29,13 +29,6 @@ type NetworkHandler struct {
appCtx context.Context
}
-type NetworkPaginatedResponse struct {
- Success bool `json:"success"`
- Data []networktypes.Summary `json:"data"`
- Counts networktypes.UsageCounts `json:"counts"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListNetworksInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -47,25 +40,15 @@ type ListNetworksInput struct {
}
type ListNetworksOutput struct {
- Body NetworkPaginatedResponse
+ Body base.PaginatedWithCounts[networktypes.Summary, networktypes.UsageCounts]
}
type GetNetworkCountsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-type NetworkCountsApiResponse struct {
- Success bool `json:"success"`
- Data networktypes.UsageCounts `json:"data"`
-}
-
type GetNetworkCountsOutput struct {
- Body NetworkCountsApiResponse
-}
-
-type NetworkCreatedApiResponse struct {
- Success bool `json:"success"`
- Data networktypes.CreateResponse `json:"data"`
+ Body base.ApiResponse[networktypes.UsageCounts]
}
type CreateNetworkInput struct {
@@ -74,13 +57,7 @@ type CreateNetworkInput struct {
}
type CreateNetworkOutput struct {
- Body NetworkCreatedApiResponse
-}
-
-// NetworkInspectApiResponse is a dedicated response type
-type NetworkInspectApiResponse struct {
- Success bool `json:"success"`
- Data networktypes.Inspect `json:"data"`
+ Body base.ApiResponse[networktypes.CreateResponse]
}
type GetNetworkInput struct {
@@ -91,12 +68,7 @@ type GetNetworkInput struct {
}
type GetNetworkOutput struct {
- Body NetworkInspectApiResponse
-}
-
-type NetworkTopologyApiResponse struct {
- Success bool `json:"success"`
- Data networktypes.Topology `json:"data"`
+ Body base.ApiResponse[networktypes.Inspect]
}
type GetNetworkTopologyInput struct {
@@ -104,13 +76,7 @@ type GetNetworkTopologyInput struct {
}
type GetNetworkTopologyOutput struct {
- Body NetworkTopologyApiResponse
-}
-
-// NetworkMessageApiResponse is a dedicated response type
-type NetworkMessageApiResponse struct {
- Success bool `json:"success"`
- Data base.MessageResponse `json:"data"`
+ Body base.ApiResponse[networktypes.Topology]
}
type DeleteNetworkInput struct {
@@ -119,21 +85,15 @@ type DeleteNetworkInput struct {
}
type DeleteNetworkOutput struct {
- Body NetworkMessageApiResponse
+ Body base.ApiResponse[base.MessageResponse]
}
type PruneNetworksInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
-// NetworkPruneResponse is a dedicated response type
-type NetworkPruneResponse struct {
- Success bool `json:"success"`
- Data networktypes.PruneReport `json:"data"`
-}
-
type PruneNetworksOutput struct {
- Body NetworkPruneResponse
+ Body base.ApiResponse[networktypes.PruneReport]
}
// RegisterNetworks registers network endpoints.
@@ -151,7 +111,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Path: "/environments/{id}/networks",
Summary: "List networks",
Tags: []string{"Networks"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermNetworksList, h.ListNetworks)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -160,7 +120,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Path: "/environments/{id}/networks/counts",
Summary: "Network counts",
Tags: []string{"Networks"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermNetworksList, h.GetNetworkCounts)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -169,7 +129,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Path: "/environments/{id}/networks",
Summary: "Create network",
Tags: []string{"Networks"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermNetworksCreate, h.CreateNetwork)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -178,7 +138,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Path: "/environments/{id}/networks/topology",
Summary: "Get network topology",
Tags: []string{"Networks"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermNetworksRead, h.GetNetworkTopology)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -187,7 +147,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Path: "/environments/{id}/networks/{networkId}",
Summary: "Get network",
Tags: []string{"Networks"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermNetworksRead, h.GetNetwork)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -196,7 +156,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Path: "/environments/{id}/networks/{networkId}",
Summary: "Delete network",
Tags: []string{"Networks"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermNetworksDelete, h.DeleteNetwork)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -205,7 +165,7 @@ func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerS
Path: "/environments/{id}/networks/prune",
Summary: "Prune networks",
Tags: []string{"Networks"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermNetworksPrune, h.PruneNetworks)
}
@@ -221,7 +181,7 @@ func (h *NetworkHandler) ListNetworks(ctx context.Context, input *ListNetworksIn
}
return &ListNetworksOutput{
- Body: NetworkPaginatedResponse{
+ Body: base.PaginatedWithCounts[networktypes.Summary, networktypes.UsageCounts]{
Success: true,
Data: networks,
Counts: counts,
@@ -237,7 +197,7 @@ func (h *NetworkHandler) GetNetworkCounts(ctx context.Context, input *GetNetwork
}
return &GetNetworkCountsOutput{
- Body: NetworkCountsApiResponse{
+ Body: base.ApiResponse[networktypes.UsageCounts]{
Success: true,
Data: networktypes.UsageCounts{
Inuse: inuse,
@@ -289,7 +249,7 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetwork
out.ActivityID = utils.StringPtrFromTrimmed(activityID)
return &CreateNetworkOutput{
- Body: NetworkCreatedApiResponse{
+ Body: base.ApiResponse[networktypes.CreateResponse]{
Success: true,
Data: out,
},
@@ -377,7 +337,7 @@ func (h *NetworkHandler) GetNetwork(ctx context.Context, input *GetNetworkInput)
})
return &GetNetworkOutput{
- Body: NetworkInspectApiResponse{
+ Body: base.ApiResponse[networktypes.Inspect]{
Success: true,
Data: out,
},
@@ -391,7 +351,7 @@ func (h *NetworkHandler) GetNetworkTopology(ctx context.Context, input *GetNetwo
}
return &GetNetworkTopologyOutput{
- Body: NetworkTopologyApiResponse{
+ Body: base.ApiResponse[networktypes.Topology]{
Success: true,
Data: *topology,
},
@@ -426,7 +386,7 @@ func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetwork
}
return &DeleteNetworkOutput{
- Body: NetworkMessageApiResponse{
+ Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{Message: "Network removed successfully", ActivityID: utils.StringPtrFromTrimmed(activityID)},
},
@@ -460,7 +420,7 @@ func (h *NetworkHandler) PruneNetworks(ctx context.Context, input *PruneNetworks
out.ActivityID = utils.StringPtrFromTrimmed(activityID)
return &PruneNetworksOutput{
- Body: NetworkPruneResponse{
+ Body: base.ApiResponse[networktypes.PruneReport]{
Success: true,
Data: out,
},
diff --git a/backend/api/handlers/notifications.go b/backend/api/handlers/notifications.go
index fb7bcb30e..1ce903ae3 100644
--- a/backend/api/handlers/notifications.go
+++ b/backend/api/handlers/notifications.go
@@ -111,7 +111,7 @@ func RegisterNotifications(api huma.API, notificationSvc *services.NotificationS
Path: "/environments/{id}/notifications/settings",
Summary: "Get all notification settings",
Tags: []string{"Notifications"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermNotificationsManage, h.GetAllNotificationSettings)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -120,7 +120,7 @@ func RegisterNotifications(api huma.API, notificationSvc *services.NotificationS
Path: "/environments/{id}/notifications/settings/{provider}",
Summary: "Get notification settings by provider",
Tags: []string{"Notifications"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermNotificationsManage, h.GetNotificationSettings)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -129,7 +129,7 @@ func RegisterNotifications(api huma.API, notificationSvc *services.NotificationS
Path: "/environments/{id}/notifications/settings",
Summary: "Create or update notification settings",
Tags: []string{"Notifications"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermNotificationsManage, h.CreateOrUpdateNotificationSettings)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -138,7 +138,7 @@ func RegisterNotifications(api huma.API, notificationSvc *services.NotificationS
Path: "/environments/{id}/notifications/settings/{provider}",
Summary: "Delete notification settings",
Tags: []string{"Notifications"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermNotificationsManage, h.DeleteNotificationSettings)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -147,7 +147,7 @@ func RegisterNotifications(api huma.API, notificationSvc *services.NotificationS
Path: "/environments/{id}/notifications/test/{provider}",
Summary: "Test notification",
Tags: []string{"Notifications"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermNotificationsManage, h.TestNotification)
// Environment tokens are authenticated by ApiKeyAuth and revalidated by the
diff --git a/backend/api/handlers/oidc.go b/backend/api/handlers/oidc.go
index 4c91bb256..767c29961 100644
--- a/backend/api/handlers/oidc.go
+++ b/backend/api/handlers/oidc.go
@@ -16,6 +16,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie"
httputils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"
"github.com/getarcaneapp/arcane/types/v2/auth"
+ "github.com/getarcaneapp/arcane/types/v2/base"
roletypes "github.com/getarcaneapp/arcane/types/v2/role"
)
@@ -99,10 +100,7 @@ type ExchangeDeviceTokenOutput struct {
type ListOidcRoleMappingsInput struct{}
type ListOidcRoleMappingsOutput struct {
- Body struct {
- Success bool `json:"success"`
- Data []roletypes.OidcRoleMapping `json:"data"`
- }
+ Body base.ApiResponse[[]roletypes.OidcRoleMapping]
}
type CreateOidcRoleMappingInput struct {
@@ -110,10 +108,7 @@ type CreateOidcRoleMappingInput struct {
}
type CreateOidcRoleMappingOutput struct {
- Body struct {
- Success bool `json:"success"`
- Data roletypes.OidcRoleMapping `json:"data"`
- }
+ Body base.ApiResponse[roletypes.OidcRoleMapping]
}
type UpdateOidcRoleMappingInput struct {
@@ -122,10 +117,7 @@ type UpdateOidcRoleMappingInput struct {
}
type UpdateOidcRoleMappingOutput struct {
- Body struct {
- Success bool `json:"success"`
- Data roletypes.OidcRoleMapping `json:"data"`
- }
+ Body base.ApiResponse[roletypes.OidcRoleMapping]
}
type DeleteOidcRoleMappingInput struct {
@@ -217,7 +209,7 @@ func RegisterOidc(api huma.API, authService *services.AuthService, oidcService *
Summary: "List OIDC group → role mappings",
Description: "Returns every mapping. On each OIDC login the user's group claim is matched against ClaimValue and matching rows become source='oidc' role assignments.",
Tags: []string{"OIDC"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireGlobalAdmin(api),
}, h.ListOidcRoleMappings)
@@ -227,7 +219,7 @@ func RegisterOidc(api huma.API, authService *services.AuthService, oidcService *
Path: "/oidc/role-mappings",
Summary: "Create an OIDC role mapping",
Tags: []string{"OIDC"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireGlobalAdmin(api),
}, h.CreateOidcRoleMapping)
@@ -237,7 +229,7 @@ func RegisterOidc(api huma.API, authService *services.AuthService, oidcService *
Path: "/oidc/role-mappings/{id}",
Summary: "Update an OIDC role mapping",
Tags: []string{"OIDC"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireGlobalAdmin(api),
}, h.UpdateOidcRoleMapping)
@@ -247,7 +239,7 @@ func RegisterOidc(api huma.API, authService *services.AuthService, oidcService *
Path: "/oidc/role-mappings/{id}",
Summary: "Delete an OIDC role mapping",
Tags: []string{"OIDC"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireGlobalAdmin(api),
}, h.DeleteOidcRoleMapping)
}
@@ -258,10 +250,6 @@ func RegisterOidc(api huma.API, authService *services.AuthService, oidcService *
// GetOidcStatus returns the OIDC configuration status.
func (h *OidcHandler) GetOidcStatus(ctx context.Context, _ *GetOidcStatusInput) (*GetOidcStatusOutput, error) {
- if h.authService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
status, err := h.authService.GetOidcConfigurationStatus(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.OidcStatusError{Err: err}).Error())
@@ -274,10 +262,6 @@ func (h *OidcHandler) GetOidcStatus(ctx context.Context, _ *GetOidcStatusInput)
// GetOidcConfig returns the OIDC client configuration.
func (h *OidcHandler) GetOidcConfig(ctx context.Context, input *GetOidcConfigInput) (*GetOidcConfigOutput, error) {
- if h.authService == nil || h.oidcService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
config, err := h.authService.GetOidcConfig(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.OidcConfigError{}).Error())
@@ -305,10 +289,6 @@ func (h *OidcHandler) GetOidcConfig(ctx context.Context, input *GetOidcConfigInp
// GetOidcAuthUrl generates an OIDC authorization URL and sets the state cookie.
func (h *OidcHandler) GetOidcAuthUrl(ctx context.Context, input *GetOidcAuthUrlInput) (*GetOidcAuthUrlOutput, error) {
- if h.authService == nil || h.oidcService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
enabled, err := h.authService.IsOidcEnabled(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.OidcStatusCheckError{}).Error())
@@ -349,10 +329,6 @@ func (h *OidcHandler) GetOidcAuthUrl(ctx context.Context, input *GetOidcAuthUrlI
// HandleOidcCallback processes the OIDC callback and completes authentication.
func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcCallbackInput) (*HandleOidcCallbackOutput, error) {
- if h.authService == nil || h.oidcService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
// Validate state cookie
if input.OidcStateCookie == "" {
return nil, huma.Error400BadRequest((&common.OidcStateCookieError{}).Error())
@@ -415,10 +391,6 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcC
// InitiateDeviceAuth initiates the OIDC device authorization flow.
func (h *OidcHandler) InitiateDeviceAuth(ctx context.Context, _ *InitiateDeviceAuthInput) (*InitiateDeviceAuthOutput, error) {
- if h.authService == nil || h.oidcService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
enabled, err := h.authService.IsOidcEnabled(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.OidcStatusCheckError{}).Error())
@@ -440,10 +412,6 @@ func (h *OidcHandler) InitiateDeviceAuth(ctx context.Context, _ *InitiateDeviceA
// ExchangeDeviceToken exchanges a device code for authentication tokens.
func (h *OidcHandler) ExchangeDeviceToken(ctx context.Context, input *ExchangeDeviceTokenInput) (*ExchangeDeviceTokenOutput, error) {
- if h.authService == nil || h.oidcService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.Body.DeviceCode == "" {
return nil, huma.Error400BadRequest("device code is required")
}
@@ -498,9 +466,6 @@ func (h *OidcHandler) ExchangeDeviceToken(ctx context.Context, input *ExchangeDe
// ============================================================================
func (h *OidcHandler) ListOidcRoleMappings(ctx context.Context, _ *ListOidcRoleMappingsInput) (*ListOidcRoleMappingsOutput, error) {
- if h.roleService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
rows, err := h.roleService.ListOidcMappings(ctx)
if err != nil {
return nil, huma.Error500InternalServerError("failed to list mappings: " + err.Error())
@@ -515,9 +480,6 @@ func (h *OidcHandler) ListOidcRoleMappings(ctx context.Context, _ *ListOidcRoleM
}
func (h *OidcHandler) CreateOidcRoleMapping(ctx context.Context, input *CreateOidcRoleMappingInput) (*CreateOidcRoleMappingOutput, error) {
- if h.roleService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
claimValue := strings.TrimSpace(input.Body.ClaimValue)
roleID := strings.TrimSpace(input.Body.RoleID)
if claimValue == "" {
@@ -540,9 +502,6 @@ func (h *OidcHandler) CreateOidcRoleMapping(ctx context.Context, input *CreateOi
}
func (h *OidcHandler) UpdateOidcRoleMapping(ctx context.Context, input *UpdateOidcRoleMappingInput) (*UpdateOidcRoleMappingOutput, error) {
- if h.roleService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
claimValue := strings.TrimSpace(input.Body.ClaimValue)
roleID := strings.TrimSpace(input.Body.RoleID)
if claimValue == "" {
@@ -571,9 +530,6 @@ func (h *OidcHandler) UpdateOidcRoleMapping(ctx context.Context, input *UpdateOi
}
func (h *OidcHandler) DeleteOidcRoleMapping(ctx context.Context, input *DeleteOidcRoleMappingInput) (*DeleteOidcRoleMappingOutput, error) {
- if h.roleService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.roleService.DeleteOidcMapping(ctx, input.ID); err != nil {
if common.IsOidcMappingNotFoundError(err) {
return nil, huma.Error404NotFound("mapping not found")
diff --git a/backend/api/handlers/ports.go b/backend/api/handlers/ports.go
index 2737c2e7d..4f4f2291e 100644
--- a/backend/api/handlers/ports.go
+++ b/backend/api/handlers/ports.go
@@ -16,12 +16,6 @@ type PortHandler struct {
portService *services.PortService
}
-type PortPaginatedResponse struct {
- Success bool `json:"success"`
- Data []porttypes.PortMapping `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListPortsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -32,7 +26,7 @@ type ListPortsInput struct {
}
type ListPortsOutput struct {
- Body PortPaginatedResponse
+ Body base.Paginated[porttypes.PortMapping]
}
func RegisterPorts(api huma.API, portSvc *services.PortService) {
@@ -44,15 +38,11 @@ func RegisterPorts(api huma.API, portSvc *services.PortService) {
Path: "/environments/{id}/ports",
Summary: "List port mappings",
Tags: []string{"Ports"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersList, h.ListPorts)
}
func (h *PortHandler) ListPorts(ctx context.Context, input *ListPortsInput) (*ListPortsOutput, error) {
- if h.portService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.portService.ListPortsPaginated(ctx, params)
@@ -61,7 +51,7 @@ func (h *PortHandler) ListPorts(ctx context.Context, input *ListPortsInput) (*Li
}
return &ListPortsOutput{
- Body: PortPaginatedResponse{
+ Body: base.Paginated[porttypes.PortMapping]{
Success: true,
Data: items,
Pagination: toPaginationResponseInternal(paginationResp),
diff --git a/backend/api/handlers/projects.go b/backend/api/handlers/projects.go
index b9e3a863a..00e07da3f 100644
--- a/backend/api/handlers/projects.go
+++ b/backend/api/handlers/projects.go
@@ -34,13 +34,6 @@ type ProjectHandler struct {
// --- Huma Input/Output Wrappers ---
-// ProjectPaginatedResponse is the paginated response for projects.
-type ProjectPaginatedResponse struct {
- Success bool `json:"success"`
- Data []project.Details `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListProjectsInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -54,7 +47,7 @@ type ListProjectsInput struct {
}
type ListProjectsOutput struct {
- Body ProjectPaginatedResponse
+ Body base.Paginated[project.Details]
}
type GetProjectStatusCountsInput struct {
@@ -222,8 +215,6 @@ type PullProgressEvent struct {
// RegisterProjects registers project management routes using Huma.
// Note: WebSocket and streaming endpoints remain as Gin handlers.
-//
-//nolint:maintidx // long but flat Huma route-registration function; complexity is sequential, not branching
func RegisterProjects(api huma.API, projectService *services.ProjectService, activityService *services.ActivityService, appCtx ActivityAppContext) {
h := &ProjectHandler{
projectService: projectService,
@@ -238,10 +229,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "List projects",
Description: "Get a paginated list of Docker Compose projects",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsList, h.ListProjects)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -251,10 +239,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Get project status counts",
Description: "Get counts of running, stopped, and total projects",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsList, h.GetProjectStatusCounts)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -264,10 +249,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Deploy a project",
Description: "Deploy a Docker Compose project (docker-compose up)",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsDeploy, h.DeployProject)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -277,10 +259,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Bring down a project",
Description: "Bring down a Docker Compose project (docker-compose down)",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsDown, h.DownProject)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -290,10 +269,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Create a project",
Description: "Create a new Docker Compose project",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsCreate, h.CreateProject)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -303,10 +279,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Get a project",
Description: "Get a Docker Compose project by ID",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsRead, h.GetProject)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -316,10 +289,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Get project compose details",
Description: "Get compose content, includes, and service configs for a project",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsRead, h.GetProjectCompose)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -329,10 +299,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Get project files",
Description: "Get directory files for a project",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsRead, h.GetProjectFiles)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -342,10 +309,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Get project runtime",
Description: "Get runtime service state for a project",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsRead, h.GetProjectRuntime)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -355,10 +319,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Get project updates",
Description: "Get image update summary for a project",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsRead, h.GetProjectUpdates)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -368,10 +329,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Get a project file",
Description: "Get the contents of a single project-related file by relative path",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsRead, h.GetProjectFile)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -381,10 +339,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Redeploy a project",
Description: "Redeploy a Docker Compose project (down + up)",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsDeploy, h.RedeployProject)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -394,10 +349,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Destroy a project",
Description: "Destroy a Docker Compose project and optionally remove files/volumes",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsDelete, h.DestroyProject)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -407,10 +359,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Update a project",
Description: "Update a Docker Compose project configuration",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsUpdate, h.UpdateProject)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -420,10 +369,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Update project include file",
Description: "Update an include file within a Docker Compose project",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsUpdate, h.UpdateProjectInclude)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -433,10 +379,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Restart a project",
Description: "Restart all containers in a Docker Compose project",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsRestart, h.RestartProject)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -446,10 +389,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Update project services",
Description: "Pull latest images and recreate the given services (all services when none are specified)",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsUpdate, h.UpdateProjectServices)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -459,10 +399,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Archive a project",
Description: "Archive a stopped Docker Compose project",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsArchive, h.ArchiveProject)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -472,10 +409,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Unarchive a project",
Description: "Unarchive a Docker Compose project",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsArchive, h.UnarchiveProject)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -485,10 +419,7 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Pull project images",
Description: "Pull all images for a Docker Compose project with streaming progress output",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsDeploy, h.PullProjectImages)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -498,19 +429,12 @@ func RegisterProjects(api huma.API, projectService *services.ProjectService, act
Summary: "Build project images",
Description: "Build Docker Compose services with build directives using BuildKit",
Tags: []string{"Projects"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermProjectsDeploy, h.BuildProjectImages)
}
// ListProjects returns a paginated list of projects.
func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsInput) (*ListProjectsOutput, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.Status != "" {
params.Filters["status"] = input.Status
@@ -535,7 +459,7 @@ func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsIn
}
return &ListProjectsOutput{
- Body: ProjectPaginatedResponse{
+ Body: base.Paginated[project.Details]{
Success: true,
Data: projects,
Pagination: toPaginationResponseInternal(paginationResp),
@@ -545,10 +469,6 @@ func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsIn
// GetProjectStatusCounts returns counts of projects by status.
func (h *ProjectHandler) GetProjectStatusCounts(ctx context.Context, input *GetProjectStatusCountsInput) (*GetProjectStatusCountsOutput, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
_, running, stopped, total, archived, err := h.projectService.GetProjectStatusCounts(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ProjectStatusCountsError{Err: err}).Error())
@@ -569,10 +489,6 @@ func (h *ProjectHandler) GetProjectStatusCounts(ctx context.Context, input *GetP
// DeployProject deploys a Docker Compose project.
func (h *ProjectHandler) DeployProject(ctx context.Context, input *DeployProjectInput) (*huma.StreamResponse, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ProjectID == "" {
return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
}
@@ -635,10 +551,6 @@ func (h *ProjectHandler) DeployProject(ctx context.Context, input *DeployProject
// DownProject brings down a Docker Compose project.
func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInput) (*DownProjectOutput, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -700,10 +612,6 @@ func projectFileHTTPError(err error) error {
// CreateProject creates a new Docker Compose project.
func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectInput) (*CreateProjectOutput, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -759,10 +667,6 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProject
// GetProject returns a project by ID.
func (h *ProjectHandler) GetProject(ctx context.Context, input *GetProjectInput) (*GetProjectOutput, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ProjectID == "" {
return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
}
@@ -781,9 +685,6 @@ func (h *ProjectHandler) GetProject(ctx context.Context, input *GetProjectInput)
}
func (h *ProjectHandler) getProjectDetailsWithOptionsInternal(ctx context.Context, input *GetProjectInput, opts project.DetailsOptions) (*GetProjectOutput, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if input.ProjectID == "" {
return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
}
@@ -831,9 +732,6 @@ func (h *ProjectHandler) GetProjectUpdates(ctx context.Context, input *GetProjec
}
func (h *ProjectHandler) GetProjectFile(ctx context.Context, input *GetProjectFileInput) (*GetProjectFileOutput, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if input.ProjectID == "" {
return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
}
@@ -881,10 +779,6 @@ func (h *ProjectHandler) RedeployProject(ctx context.Context, input *RedeployPro
// DestroyProject destroys a Docker Compose project.
func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProjectInput) (*DestroyProjectOutput, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -931,10 +825,6 @@ func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProje
// UpdateProject updates a Docker Compose project.
func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectInput) (*UpdateProjectOutput, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ProjectID == "" {
return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
}
@@ -994,10 +884,6 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProject
// UpdateProjectInclude updates an include file within a project.
func (h *ProjectHandler) UpdateProjectInclude(ctx context.Context, input *UpdateProjectIncludeInput) (*UpdateProjectIncludeOutput, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ProjectID == "" {
return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
}
@@ -1179,10 +1065,6 @@ func (h *ProjectHandler) runProjectActivityActionResponseInternal(
}
func (h *ProjectHandler) runProjectActivityActionInternal(ctx context.Context, environmentID, projectID string, cfg projectActivityActionConfigInternal) (base.MessageResponse, error) {
- if h.projectService == nil {
- return base.MessageResponse{}, huma.Error500InternalServerError("service not available")
- }
-
if projectID == "" {
return base.MessageResponse{}, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
}
@@ -1217,10 +1099,6 @@ func (h *ProjectHandler) runProjectActivityActionInternal(ctx context.Context, e
}
func (h *ProjectHandler) ArchiveProject(ctx context.Context, input *ArchiveProjectInput) (*ArchiveProjectOutput, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ProjectID == "" {
return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
}
@@ -1246,10 +1124,6 @@ func (h *ProjectHandler) ArchiveProject(ctx context.Context, input *ArchiveProje
}
func (h *ProjectHandler) UnarchiveProject(ctx context.Context, input *UnarchiveProjectInput) (*UnarchiveProjectOutput, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ProjectID == "" {
return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
}
@@ -1273,10 +1147,6 @@ func (h *ProjectHandler) UnarchiveProject(ctx context.Context, input *UnarchiveP
// PullProjectImages pulls all images for a project with streaming progress.
func (h *ProjectHandler) PullProjectImages(ctx context.Context, input *PullProjectImagesInput) (*huma.StreamResponse, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ProjectID == "" {
return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
}
@@ -1335,10 +1205,6 @@ func (h *ProjectHandler) PullProjectImages(ctx context.Context, input *PullProje
// BuildProjectImages builds compose services with build directives.
func (h *ProjectHandler) BuildProjectImages(ctx context.Context, input *BuildProjectInput) (*huma.StreamResponse, error) {
- if h.projectService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ProjectID == "" {
return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
}
diff --git a/backend/api/handlers/roles.go b/backend/api/handlers/roles.go
index 9e9f8aa81..50e50bc61 100644
--- a/backend/api/handlers/roles.go
+++ b/backend/api/handlers/roles.go
@@ -20,12 +20,6 @@ type RoleHandler struct {
// ---------- I/O wrappers ----------
-type RolePaginatedResponse struct {
- Success bool `json:"success"`
- Data []roletypes.Role `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListRolesInput struct {
Search string `query:"search" doc:"Search by role name or description"`
Sort string `query:"sort" doc:"Column to sort by"`
@@ -35,7 +29,7 @@ type ListRolesInput struct {
}
type ListRolesOutput struct {
- Body RolePaginatedResponse
+ Body base.Paginated[roletypes.Role]
}
type GetRoleInput struct {
@@ -104,7 +98,7 @@ func RegisterRoles(api huma.API, roleService *services.RoleService) {
Summary: "List roles",
Description: "Get a paginated list of roles (built-in + custom)",
Tags: []string{"Roles"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermRolesList),
}, h.ListRoles)
@@ -114,7 +108,7 @@ func RegisterRoles(api huma.API, roleService *services.RoleService) {
Path: "/roles/{id}",
Summary: "Get a role",
Tags: []string{"Roles"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermRolesRead),
}, h.GetRole)
@@ -125,7 +119,7 @@ func RegisterRoles(api huma.API, roleService *services.RoleService) {
Summary: "Create a custom role",
Description: "Built-in roles cannot be created via this endpoint; only custom roles are accepted. Reserved for global admins.",
Tags: []string{"Roles"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireGlobalAdmin(api),
}, h.CreateRole)
@@ -136,7 +130,7 @@ func RegisterRoles(api huma.API, roleService *services.RoleService) {
Summary: "Update a custom role",
Description: "Built-in roles are read-only and return 403 on update. Reserved for global admins.",
Tags: []string{"Roles"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireGlobalAdmin(api),
}, h.UpdateRole)
@@ -147,7 +141,7 @@ func RegisterRoles(api huma.API, roleService *services.RoleService) {
Summary: "Delete a custom role",
Description: "Built-in roles are protected; deleting cascades all user assignments. Reserved for global admins.",
Tags: []string{"Roles"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireGlobalAdmin(api),
}, h.DeleteRole)
@@ -158,7 +152,7 @@ func RegisterRoles(api huma.API, roleService *services.RoleService) {
Summary: "Get the permission manifest",
Description: "Returns every permission the server recognizes, grouped by resource. Used by permission-picking UIs.",
Tags: []string{"Roles"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
}, h.GetPermissionsManifest)
huma.Register(api, huma.Operation{
@@ -168,7 +162,7 @@ func RegisterRoles(api huma.API, roleService *services.RoleService) {
Summary: "List a user's role assignments",
Description: "Reserved for global admins.",
Tags: []string{"Roles"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireGlobalAdmin(api),
}, h.ListUserRoleAssignments)
@@ -179,7 +173,7 @@ func RegisterRoles(api huma.API, roleService *services.RoleService) {
Summary: "Replace a user's manual role assignments",
Description: "Replaces every source='manual' assignment for the user. source='oidc' assignments are not touched. Reserved for global admins; enforces the last-admin guard.",
Tags: []string{"Roles"},
- Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequireGlobalAdmin(api),
}, h.SetUserRoleAssignments)
}
@@ -187,9 +181,6 @@ func RegisterRoles(api huma.API, roleService *services.RoleService) {
// ---------- Handler implementations ----------
func (h *RoleHandler) ListRoles(ctx context.Context, input *ListRolesInput) (*ListRolesOutput, error) {
- if h.roleService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
roles, paginationResp, err := h.roleService.ListRoles(ctx, params)
if err != nil {
@@ -200,7 +191,7 @@ func (h *RoleHandler) ListRoles(ctx context.Context, input *ListRolesInput) (*Li
dtos[i] = h.toRoleDTO(ctx, &roles[i])
}
return &ListRolesOutput{
- Body: RolePaginatedResponse{
+ Body: base.Paginated[roletypes.Role]{
Success: true,
Data: dtos,
Pagination: toPaginationResponseInternal(paginationResp),
@@ -209,9 +200,6 @@ func (h *RoleHandler) ListRoles(ctx context.Context, input *ListRolesInput) (*Li
}
func (h *RoleHandler) GetRole(ctx context.Context, input *GetRoleInput) (*GetRoleOutput, error) {
- if h.roleService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
role, err := h.roleService.GetRole(ctx, input.ID)
if err != nil {
if common.IsRoleNotFoundError(err) {
@@ -225,9 +213,6 @@ func (h *RoleHandler) GetRole(ctx context.Context, input *GetRoleInput) (*GetRol
}
func (h *RoleHandler) CreateRole(ctx context.Context, input *CreateRoleInput) (*CreateRoleOutput, error) {
- if h.roleService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
callerPS, _ := humamw.PermissionsFromContext(ctx)
if err := h.roleService.ValidatePermissionsAgainstCaller(callerPS, input.Body.Permissions); err != nil {
switch {
@@ -254,9 +239,6 @@ func (h *RoleHandler) CreateRole(ctx context.Context, input *CreateRoleInput) (*
}
func (h *RoleHandler) UpdateRole(ctx context.Context, input *UpdateRoleInput) (*UpdateRoleOutput, error) {
- if h.roleService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
callerPS, _ := humamw.PermissionsFromContext(ctx)
if err := h.roleService.ValidatePermissionsAgainstCaller(callerPS, input.Body.Permissions); err != nil {
switch {
@@ -287,9 +269,6 @@ func (h *RoleHandler) UpdateRole(ctx context.Context, input *UpdateRoleInput) (*
}
func (h *RoleHandler) DeleteRole(ctx context.Context, input *DeleteRoleInput) (*DeleteRoleOutput, error) {
- if h.roleService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.roleService.DeleteRole(ctx, input.ID); err != nil {
switch {
case common.IsRoleNotFoundError(err):
@@ -313,9 +292,6 @@ func (h *RoleHandler) GetPermissionsManifest(_ context.Context, _ *struct{}) (*P
}
func (h *RoleHandler) ListUserRoleAssignments(ctx context.Context, input *ListUserRoleAssignmentsInput) (*ListUserRoleAssignmentsOutput, error) {
- if h.roleService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
rows, err := h.roleService.ListUserAssignments(ctx, input.UserID)
if err != nil {
return nil, huma.Error500InternalServerError("failed to list assignments: " + err.Error())
@@ -330,9 +306,6 @@ func (h *RoleHandler) ListUserRoleAssignments(ctx context.Context, input *ListUs
}
func (h *RoleHandler) SetUserRoleAssignments(ctx context.Context, input *SetUserRoleAssignmentsInput) (*SetUserRoleAssignmentsOutput, error) {
- if h.roleService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
desired := make([]models.UserRoleAssignment, len(input.Body.Assignments))
for i, a := range input.Body.Assignments {
desired[i] = models.UserRoleAssignment{RoleID: a.RoleID, EnvironmentID: a.EnvironmentID}
diff --git a/backend/api/handlers/roles_access_policy_test.go b/backend/api/handlers/roles_access_policy_test.go
index e607125ed..91913d3c4 100644
--- a/backend/api/handlers/roles_access_policy_test.go
+++ b/backend/api/handlers/roles_access_policy_test.go
@@ -50,3 +50,35 @@ func TestBuildPermissionsManifestIncludesEventsDelete(t *testing.T) {
t.Fatal("events resource not found")
}
+
+func TestBuildPermissionsManifestKeepsVariablesSeparateFromTemplates(t *testing.T) {
+ manifest := buildPermissionsManifestInternal()
+
+ var variablePermissions []string
+ for _, resource := range manifest.Resources {
+ if resource.Key != "variables" {
+ continue
+ }
+ for _, action := range resource.Actions {
+ variablePermissions = append(variablePermissions, action.Permission)
+ }
+ }
+ require.ElementsMatch(t, []string{
+ authz.PermVariablesRead,
+ authz.PermVariablesCreate,
+ authz.PermVariablesUpdate,
+ authz.PermVariablesDelete,
+ authz.PermVariablesSync,
+ }, variablePermissions)
+ for _, permission := range variablePermissions {
+ require.NotEqual(t, authz.PermTemplatesRead, permission)
+ }
+
+ surfaces := make(map[string][]string, len(manifest.AccessSurfaces))
+ for _, surface := range manifest.AccessSurfaces {
+ surfaces[surface.ID] = surface.Permissions
+ }
+ require.Equal(t, []string{authz.PermVariablesRead}, surfaces["customize.category.variables"])
+ require.Equal(t, []string{authz.PermActivitiesRead}, surfaces["route.activities"])
+ require.ElementsMatch(t, authz.AllPermissions(), surfaces["route.oidc-role-mappings"])
+}
diff --git a/backend/api/handlers/settings.go b/backend/api/handlers/settings.go
index 8871bea25..b1dcc3628 100644
--- a/backend/api/handlers/settings.go
+++ b/backend/api/handlers/settings.go
@@ -138,10 +138,7 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s
Summary: "Get settings",
Description: "Get all settings for an environment",
Tags: []string{"Settings"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermSettingsRead, h.GetSettings)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -151,10 +148,7 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s
Summary: "Update settings",
Description: "Update settings for an environment",
Tags: []string{"Settings"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermSettingsWrite, h.UpdateSettings)
// Top-level settings endpoints (not environment-scoped)
@@ -165,10 +159,7 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s
Summary: "Search settings",
Description: "Search settings categories and individual settings by query",
Tags: []string{"Settings"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, h.Search)
huma.Register(api, huma.Operation{
@@ -178,10 +169,7 @@ func RegisterSettings(api huma.API, settingsService *services.SettingsService, s
Summary: "Get settings categories",
Description: "Get all available settings categories with metadata",
Tags: []string{"Settings"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, h.GetCategories)
}
@@ -259,14 +247,7 @@ func (h *SettingsHandler) appendRuntimeSettingsInternal(settingsDto []settings.P
// GetPublicSettings returns public settings for an environment.
func (h *SettingsHandler) GetPublicSettings(ctx context.Context, input *GetPublicSettingsInput) (*GetPublicSettingsOutput, error) {
- if h.settingsService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.EnvironmentID != "0" {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
settingsDto, err := proxyRemoteJSONInternal[[]settings.PublicSetting](ctx, h.environmentService, input.EnvironmentID, http.MethodGet, "/api/environments/0/settings/public", nil)
if err != nil {
return nil, err
@@ -286,10 +267,6 @@ func (h *SettingsHandler) GetPublicSettings(ctx context.Context, input *GetPubli
// GetSettings returns all settings for an environment.
func (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInput) (*GetSettingsOutput, error) {
- if h.settingsService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
ps, _ := humamw.PermissionsFromContext(ctx)
isAdmin := ps.IsGlobalAdmin()
visibility := models.SettingVisibilityNonAdmin
@@ -298,9 +275,6 @@ func (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInp
}
if input.EnvironmentID != "0" {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
settingsDto, err := proxyRemoteJSONInternal[[]settings.PublicSetting](ctx, h.environmentService, input.EnvironmentID, http.MethodGet, "/api/environments/0/settings", nil)
if err != nil {
return nil, err
@@ -333,10 +307,6 @@ func (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInp
// UpdateSettings updates settings for an environment.
func (h *SettingsHandler) UpdateSettings(ctx context.Context, input *UpdateSettingsInput) (*UpdateSettingsOutput, error) {
- if h.settingsService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if err := h.validateSettingsUpdateInput(input.Body); err != nil {
return nil, err
}
@@ -381,10 +351,6 @@ func (h *SettingsHandler) validateSettingsUpdateInput(input settings.Update) err
}
func (h *SettingsHandler) updateSettingsForRemoteEnvironment(ctx context.Context, input *UpdateSettingsInput) (*UpdateSettingsOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
-
// Check if trying to update auth settings on non-local environment.
if hasAuthSettingsUpdateInternal(input.Body) {
return nil, huma.Error403Forbidden((&common.AuthSettingsUpdateError{}).Error())
@@ -454,10 +420,6 @@ func hasAuthSettingsUpdateInternal(req settings.Update) bool {
// Search searches settings by query.
func (h *SettingsHandler) Search(ctx context.Context, input *SearchSettingsInput) (*SearchSettingsOutput, error) {
- if h.settingsSearchService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if strings.TrimSpace(input.Body.Query) == "" {
return nil, huma.Error400BadRequest((&common.QueryParameterRequiredError{}).Error())
}
@@ -471,10 +433,6 @@ func (h *SettingsHandler) Search(ctx context.Context, input *SearchSettingsInput
// GetCategories returns all available settings categories.
func (h *SettingsHandler) GetCategories(ctx context.Context, input *struct{}) (*GetCategoriesOutput, error) {
- if h.settingsSearchService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
ps, _ := humamw.PermissionsFromContext(ctx)
categories := filterSettingsCategoriesInternal(ps, h.settingsSearchService.GetSettingsCategories())
return &GetCategoriesOutput{Body: categories}, nil
diff --git a/backend/api/handlers/swarm.go b/backend/api/handlers/swarm.go
index 0bacf15b6..3d25d7fbd 100644
--- a/backend/api/handlers/swarm.go
+++ b/backend/api/handlers/swarm.go
@@ -28,12 +28,6 @@ type SwarmHandler struct {
cfg *config.Config
}
-type SwarmPaginatedResponse[T any] struct {
- Success bool `json:"success"`
- Data []T `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListSwarmServicesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -44,7 +38,7 @@ type ListSwarmServicesInput struct {
}
type ListSwarmServicesOutput struct {
- Body SwarmPaginatedResponse[swarmtypes.ServiceSummary]
+ Body base.Paginated[swarmtypes.ServiceSummary]
}
type GetSwarmServiceInput struct {
@@ -95,7 +89,7 @@ type ListSwarmServiceTasksInput struct {
}
type ListSwarmServiceTasksOutput struct {
- Body SwarmPaginatedResponse[swarmtypes.TaskSummary]
+ Body base.Paginated[swarmtypes.TaskSummary]
}
type RollbackSwarmServiceInput struct {
@@ -127,7 +121,7 @@ type ListSwarmNodesInput struct {
}
type ListSwarmNodesOutput struct {
- Body SwarmPaginatedResponse[swarmtypes.NodeSummary]
+ Body base.Paginated[swarmtypes.NodeSummary]
}
type GetSwarmNodeInput struct {
@@ -250,7 +244,7 @@ type ListSwarmNodeTasksInput struct {
}
type ListSwarmNodeTasksOutput struct {
- Body SwarmPaginatedResponse[swarmtypes.TaskSummary]
+ Body base.Paginated[swarmtypes.TaskSummary]
}
type ListSwarmTasksInput struct {
@@ -263,7 +257,7 @@ type ListSwarmTasksInput struct {
}
type ListSwarmTasksOutput struct {
- Body SwarmPaginatedResponse[swarmtypes.TaskSummary]
+ Body base.Paginated[swarmtypes.TaskSummary]
}
type ListSwarmStacksInput struct {
@@ -276,7 +270,7 @@ type ListSwarmStacksInput struct {
}
type ListSwarmStacksOutput struct {
- Body SwarmPaginatedResponse[swarmtypes.StackSummary]
+ Body base.Paginated[swarmtypes.StackSummary]
}
type DeploySwarmStackInput struct {
@@ -336,7 +330,7 @@ type ListSwarmStackServicesInput struct {
}
type ListSwarmStackServicesOutput struct {
- Body SwarmPaginatedResponse[swarmtypes.ServiceSummary]
+ Body base.Paginated[swarmtypes.ServiceSummary]
}
type ListSwarmStackTasksInput struct {
@@ -350,7 +344,7 @@ type ListSwarmStackTasksInput struct {
}
type ListSwarmStackTasksOutput struct {
- Body SwarmPaginatedResponse[swarmtypes.TaskSummary]
+ Body base.Paginated[swarmtypes.TaskSummary]
}
type RenderSwarmStackConfigInput struct {
@@ -574,65 +568,65 @@ func RegisterSwarm(api huma.API, swarmSvc *services.SwarmService, environmentSvc
cfg: cfg,
}
- 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: "reconcile-swarm-node-agents", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/agents/reconcile", Summary: "Reconcile swarm node agent bindings", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, authz.PermSwarmNodes, h.ReconcileNodeAgents)
- humamw.RegisterWithPermission(api, huma.Operation{OperationID: "put-swarm-node-agent-binding", Method: http.MethodPut, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/binding", Summary: "Attach a visible environment to a swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, authz.PermSwarmNodes, h.PutNodeAgentBinding)
- humamw.RegisterWithPermission(api, huma.Operation{OperationID: "delete-swarm-node-agent-binding", Method: http.MethodDelete, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/binding", Summary: "Detach a visible environment from a swarm node", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, authz.PermSwarmNodes, h.DeleteNodeAgentBinding)
- humamw.RegisterWithPermission(api, huma.Operation{OperationID: "delete-swarm-node-agent-deployment", Method: http.MethodDelete, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/deployment", Summary: "Remove a dedicated swarm node agent registration", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, authz.PermSwarmNodes, h.DeleteNodeAgentDeployment)
- 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)
-
- 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: "get-swarm-join-candidates", Method: http.MethodGet, Path: "/environments/{id}/swarm/join-candidates", Summary: "List environments available for Easy Join", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, authz.PermSwarmNodes, h.GetJoinCandidates)
- humamw.RegisterWithPermission(api, huma.Operation{OperationID: "join-swarm-environments", Method: http.MethodPost, Path: "/environments/{id}/swarm/join-environments", Summary: "Join environments to a swarm", Tags: []string{"Swarm"}, Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}}}, authz.PermSwarmNodes, h.JoinEnvironments)
- 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)
+ 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, authz.PermSwarmNodes, h.GetNodeAgentDeployment)
+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "reconcile-swarm-node-agents", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/agents/reconcile", Summary: "Reconcile swarm node agent bindings", Tags: []string{"Swarm"}, Security: defaultOperationSecurityInternal()}, authz.PermSwarmNodes, h.ReconcileNodeAgents)
+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "put-swarm-node-agent-binding", Method: http.MethodPut, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/binding", Summary: "Attach a visible environment to a swarm node", Tags: []string{"Swarm"}, Security: defaultOperationSecurityInternal()}, authz.PermSwarmNodes, h.PutNodeAgentBinding)
+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "delete-swarm-node-agent-binding", Method: http.MethodDelete, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/binding", Summary: "Detach a visible environment from a swarm node", Tags: []string{"Swarm"}, Security: defaultOperationSecurityInternal()}, authz.PermSwarmNodes, h.DeleteNodeAgentBinding)
+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "delete-swarm-node-agent-deployment", Method: http.MethodDelete, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/deployment", Summary: "Remove a dedicated swarm node agent registration", Tags: []string{"Swarm"}, Security: defaultOperationSecurityInternal()}, authz.PermSwarmNodes, h.DeleteNodeAgentDeployment)
+ 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal(), Middlewares: humamw.RequirePermission(api, authz.PermSwarmRead)}, h.GetNodeIdentity)
+
+ 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, authz.PermSwarmJoin, h.JoinSwarm)
+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-join-candidates", Method: http.MethodGet, Path: "/environments/{id}/swarm/join-candidates", Summary: "List environments available for Easy Join", Tags: []string{"Swarm"}, Security: defaultOperationSecurityInternal()}, authz.PermSwarmJoin, h.GetJoinCandidates)
+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "join-swarm-environments", Method: http.MethodPost, Path: "/environments/{id}/swarm/join-environments", Summary: "Join environments to a swarm", Tags: []string{"Swarm"}, Security: defaultOperationSecurityInternal()}, authz.PermSwarmJoin, h.JoinEnvironments)
+ humamw.RegisterWithPermission(api, huma.Operation{OperationID: "leave-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/leave", Summary: "Leave swarm", Tags: []string{"Swarm"}, Security: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, 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: defaultOperationSecurityInternal()}, authz.PermSwarmSecrets, h.DeleteSecret)
}
// ListServices lists swarm services for an environment and returns a paginated response.
@@ -648,11 +642,7 @@ func RegisterSwarm(api huma.API, swarmSvc *services.SwarmService, environmentSvc
// Returns an HTTP-shaped error if the swarm service is unavailable or if the
// underlying swarm lookup fails.
func (h *SwarmHandler) ListServices(ctx context.Context, input *ListSwarmServicesInput) (*ListSwarmServicesOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
- params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)
+ params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListServicesPaginated(ctx, params)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmServiceListError{Err: err}).Error())
@@ -661,7 +651,7 @@ func (h *SwarmHandler) ListServices(ctx context.Context, input *ListSwarmService
items = []swarmtypes.ServiceSummary{}
}
- return &ListSwarmServicesOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil
+ return &ListSwarmServicesOutput{Body: base.Paginated[swarmtypes.ServiceSummary]{Success: true, Data: items, Pagination: toPaginationResponseInternal(paginationResp)}}, nil
}
// GetService returns detailed information for a single swarm service.
@@ -676,10 +666,6 @@ func (h *SwarmHandler) ListServices(ctx context.Context, input *ListSwarmService
// Returns `404 Not Found` when the service does not exist and other mapped HTTP
// errors when the inspection fails.
func (h *SwarmHandler) GetService(ctx context.Context, input *GetSwarmServiceInput) (*GetSwarmServiceOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
service, err := h.swarmService.GetService(ctx, input.ServiceID)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -703,9 +689,6 @@ func (h *SwarmHandler) GetService(ctx context.Context, input *GetSwarmServiceInp
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when validation or creation fails.
func (h *SwarmHandler) CreateService(ctx context.Context, input *CreateSwarmServiceInput) (*CreateSwarmServiceOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
resp, err := h.swarmService.CreateService(ctx, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmServiceCreateError{Err: err}).Error())
@@ -728,9 +711,6 @@ func (h *SwarmHandler) CreateService(ctx context.Context, input *CreateSwarmServ
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the update request is invalid or the underlying update fails.
func (h *SwarmHandler) UpdateService(ctx context.Context, input *UpdateSwarmServiceInput) (*UpdateSwarmServiceOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
resp, err := h.swarmService.UpdateService(ctx, input.ServiceID, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmServiceUpdateError{Err: err}).Error())
@@ -754,9 +734,6 @@ func (h *SwarmHandler) UpdateService(ctx context.Context, input *UpdateSwarmServ
// Returns an authorization error for non-admin callers, `404 Not Found` when
// the service does not exist, or another mapped HTTP error when removal fails.
func (h *SwarmHandler) DeleteService(ctx context.Context, input *DeleteSwarmServiceInput) (*DeleteSwarmServiceOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.RemoveService(ctx, input.ServiceID); err != nil {
if errdefs.IsNotFound(err) {
return nil, huma.Error404NotFound((&common.SwarmServiceNotFoundError{Err: err}).Error())
@@ -780,11 +757,7 @@ func (h *SwarmHandler) DeleteService(ctx context.Context, input *DeleteSwarmServ
// Returns a paginated list of task summaries for the service.
// Returns a mapped HTTP error when the swarm task lookup fails.
func (h *SwarmHandler) ListServiceTasks(ctx context.Context, input *ListSwarmServiceTasksInput) (*ListSwarmServiceTasksOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
- params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)
+ params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListServiceTasksPaginated(ctx, input.ServiceID, params)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmTaskListError{Err: err}).Error())
@@ -793,7 +766,7 @@ func (h *SwarmHandler) ListServiceTasks(ctx context.Context, input *ListSwarmSer
items = []swarmtypes.TaskSummary{}
}
- return &ListSwarmServiceTasksOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil
+ return &ListSwarmServiceTasksOutput{Body: base.Paginated[swarmtypes.TaskSummary]{Success: true, Data: items, Pagination: toPaginationResponseInternal(paginationResp)}}, nil
}
// RollbackService requests a server-side rollback for a swarm service.
@@ -808,9 +781,6 @@ func (h *SwarmHandler) ListServiceTasks(ctx context.Context, input *ListSwarmSer
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the rollback cannot be performed.
func (h *SwarmHandler) RollbackService(ctx context.Context, input *RollbackSwarmServiceInput) (*RollbackSwarmServiceOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
resp, err := h.swarmService.RollbackService(ctx, input.ServiceID)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmServiceUpdateError{Err: err}).Error())
@@ -833,9 +803,6 @@ func (h *SwarmHandler) RollbackService(ctx context.Context, input *RollbackSwarm
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when scaling is invalid or the update fails.
func (h *SwarmHandler) ScaleService(ctx context.Context, input *ScaleSwarmServiceInput) (*ScaleSwarmServiceOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
resp, err := h.swarmService.ScaleService(ctx, input.ServiceID, input.Body.Replicas)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmServiceUpdateError{Err: err}).Error())
@@ -857,11 +824,7 @@ func (h *SwarmHandler) ScaleService(ctx context.Context, input *ScaleSwarmServic
// Returns a paginated list of node summaries.
// Returns a mapped HTTP error when node enumeration fails.
func (h *SwarmHandler) ListNodes(ctx context.Context, input *ListSwarmNodesInput) (*ListSwarmNodesOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
- params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)
+ params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListNodesPaginated(ctx, input.EnvironmentID, params)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmNodeListError{Err: err}).Error())
@@ -870,7 +833,7 @@ func (h *SwarmHandler) ListNodes(ctx context.Context, input *ListSwarmNodesInput
items = []swarmtypes.NodeSummary{}
}
- return &ListSwarmNodesOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil
+ return &ListSwarmNodesOutput{Body: base.Paginated[swarmtypes.NodeSummary]{Success: true, Data: items, Pagination: toPaginationResponseInternal(paginationResp)}}, nil
}
// GetNode returns detailed information for a single swarm node.
@@ -885,10 +848,6 @@ func (h *SwarmHandler) ListNodes(ctx context.Context, input *ListSwarmNodesInput
// Returns `404 Not Found` when the node does not exist or another mapped HTTP
// error when the inspection fails.
func (h *SwarmHandler) GetNode(ctx context.Context, input *GetSwarmNodeInput) (*GetSwarmNodeOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
node, err := h.swarmService.GetNode(ctx, input.EnvironmentID, input.NodeID)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -917,9 +876,6 @@ func (h *SwarmHandler) GetNode(ctx context.Context, input *GetSwarmNodeInput) (*
// not exist, or `500 Internal Server Error` when environment provisioning or
// snippet generation fails.
func (h *SwarmHandler) GetNodeAgentDeployment(ctx context.Context, input *GetSwarmNodeAgentDeploymentInput) (*GetSwarmNodeAgentDeploymentOutput, error) {
- if h.swarmService == nil || h.environmentService == nil || h.cfg == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
node, err := h.swarmService.GetNode(ctx, input.EnvironmentID, input.NodeID)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -983,10 +939,6 @@ func (h *SwarmHandler) GetNodeAgentDeployment(ctx context.Context, input *GetSwa
// ReconcileNodeAgents verifies and persists unique visible-environment node bindings.
func (h *SwarmHandler) ReconcileNodeAgents(ctx context.Context, input *ReconcileSwarmNodeAgentsInput) (*ReconcileSwarmNodeAgentsOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
result, err := h.swarmService.ReconcileNodeAgents(ctx, input.EnvironmentID)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to reconcile swarm node agents")
@@ -996,10 +948,6 @@ func (h *SwarmHandler) ReconcileNodeAgents(ctx context.Context, input *Reconcile
// PutNodeAgentBinding verifies and attaches an existing visible environment.
func (h *SwarmHandler) PutNodeAgentBinding(ctx context.Context, input *PutSwarmNodeAgentBindingInput) (*PutSwarmNodeAgentBindingOutput, error) {
- if h.swarmService == nil || h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if _, err := h.swarmService.BindNodeAgent(ctx, input.EnvironmentID, input.NodeID, input.Body); err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
@@ -1022,9 +970,6 @@ func (h *SwarmHandler) PutNodeAgentBinding(ctx context.Context, input *PutSwarmN
// DeleteNodeAgentBinding detaches the visible environment currently bound to a node.
func (h *SwarmHandler) DeleteNodeAgentBinding(ctx context.Context, input *DeleteSwarmNodeAgentBindingInput) (*DeleteSwarmNodeAgentBindingOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.environmentService.DetachSwarmNodeEnvironment(ctx, input.EnvironmentID, input.NodeID); err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
@@ -1033,9 +978,6 @@ func (h *SwarmHandler) DeleteNodeAgentBinding(ctx context.Context, input *Delete
// DeleteNodeAgentDeployment removes a dedicated hidden node-agent registration.
func (h *SwarmHandler) DeleteNodeAgentDeployment(ctx context.Context, input *DeleteSwarmNodeAgentDeploymentInput) (*DeleteSwarmNodeAgentDeploymentOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -1058,10 +1000,6 @@ func (h *SwarmHandler) DeleteNodeAgentDeployment(ctx context.Context, input *Del
// Returns `500 Internal Server Error` when the swarm service is unavailable or
// identity discovery fails.
func (h *SwarmHandler) GetNodeIdentity(ctx context.Context, _ *GetSwarmNodeIdentityInput) (*GetSwarmNodeIdentityOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
identity, err := h.swarmService.GetLocalNodeIdentity(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -1087,9 +1025,6 @@ func (h *SwarmHandler) GetNodeIdentity(ctx context.Context, _ *GetSwarmNodeIdent
// Returns an authorization error for non-admin callers or a mapped HTTP error
// when the node update fails.
func (h *SwarmHandler) UpdateNode(ctx context.Context, input *UpdateSwarmNodeInput) (*UpdateSwarmNodeOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.UpdateNode(ctx, input.NodeID, input.Body); err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())
}
@@ -1111,9 +1046,6 @@ func (h *SwarmHandler) UpdateNode(ctx context.Context, input *UpdateSwarmNodeInp
// Returns an authorization error for non-admin callers or a mapped HTTP error
// when the node cannot be removed.
func (h *SwarmHandler) DeleteNode(ctx context.Context, input *DeleteSwarmNodeInput) (*DeleteSwarmNodeOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.RemoveNode(ctx, input.NodeID, input.Force); err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())
}
@@ -1135,9 +1067,6 @@ func (h *SwarmHandler) DeleteNode(ctx context.Context, input *DeleteSwarmNodeInp
// Returns an authorization error for non-admin callers or a mapped HTTP error
// when the promotion fails.
func (h *SwarmHandler) PromoteNode(ctx context.Context, input *PromoteSwarmNodeInput) (*PromoteSwarmNodeOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.PromoteNode(ctx, input.NodeID); err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())
}
@@ -1159,9 +1088,6 @@ func (h *SwarmHandler) PromoteNode(ctx context.Context, input *PromoteSwarmNodeI
// Returns an authorization error for non-admin callers or a mapped HTTP error
// when the demotion fails.
func (h *SwarmHandler) DemoteNode(ctx context.Context, input *DemoteSwarmNodeInput) (*DemoteSwarmNodeOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.DemoteNode(ctx, input.NodeID); err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmNodeNotFoundError{Err: err}).Error())
}
@@ -1182,11 +1108,7 @@ func (h *SwarmHandler) DemoteNode(ctx context.Context, input *DemoteSwarmNodeInp
// Returns a paginated list of node task summaries.
// Returns a mapped HTTP error when the underlying lookup fails.
func (h *SwarmHandler) ListNodeTasks(ctx context.Context, input *ListSwarmNodeTasksInput) (*ListSwarmNodeTasksOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
- params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)
+ params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListNodeTasksPaginated(ctx, input.NodeID, params)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmTaskListError{Err: err}).Error())
@@ -1195,7 +1117,7 @@ func (h *SwarmHandler) ListNodeTasks(ctx context.Context, input *ListSwarmNodeTa
items = []swarmtypes.TaskSummary{}
}
- return &ListSwarmNodeTasksOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil
+ return &ListSwarmNodeTasksOutput{Body: base.Paginated[swarmtypes.TaskSummary]{Success: true, Data: items, Pagination: toPaginationResponseInternal(paginationResp)}}, nil
}
// ListTasks lists swarm tasks across the current environment.
@@ -1209,11 +1131,7 @@ func (h *SwarmHandler) ListNodeTasks(ctx context.Context, input *ListSwarmNodeTa
// Returns a paginated task listing for the environment.
// Returns a mapped HTTP error when task enumeration fails.
func (h *SwarmHandler) ListTasks(ctx context.Context, input *ListSwarmTasksInput) (*ListSwarmTasksOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
- params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)
+ params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListTasksPaginated(ctx, params)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmTaskListError{Err: err}).Error())
@@ -1222,7 +1140,7 @@ func (h *SwarmHandler) ListTasks(ctx context.Context, input *ListSwarmTasksInput
items = []swarmtypes.TaskSummary{}
}
- return &ListSwarmTasksOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil
+ return &ListSwarmTasksOutput{Body: base.Paginated[swarmtypes.TaskSummary]{Success: true, Data: items, Pagination: toPaginationResponseInternal(paginationResp)}}, nil
}
// ListStacks lists swarm stacks for the current environment.
@@ -1236,11 +1154,7 @@ func (h *SwarmHandler) ListTasks(ctx context.Context, input *ListSwarmTasksInput
// Returns a paginated list of stack summaries.
// Returns a mapped HTTP error when stack enumeration fails.
func (h *SwarmHandler) ListStacks(ctx context.Context, input *ListSwarmStacksInput) (*ListSwarmStacksOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
- params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)
+ params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListStacksPaginated(ctx, input.EnvironmentID, params)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmStackListError{Err: err}).Error())
@@ -1249,7 +1163,7 @@ func (h *SwarmHandler) ListStacks(ctx context.Context, input *ListSwarmStacksInp
items = []swarmtypes.StackSummary{}
}
- return &ListSwarmStacksOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil
+ return &ListSwarmStacksOutput{Body: base.Paginated[swarmtypes.StackSummary]{Success: true, Data: items, Pagination: toPaginationResponseInternal(paginationResp)}}, nil
}
// DeployStack deploys or updates a swarm stack.
@@ -1265,9 +1179,6 @@ func (h *SwarmHandler) ListStacks(ctx context.Context, input *ListSwarmStacksInp
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when rendering, validation, or deployment fails.
func (h *SwarmHandler) DeployStack(ctx context.Context, input *DeploySwarmStackInput) (*DeploySwarmStackOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
resp, err := h.swarmService.DeployStack(ctx, input.EnvironmentID, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmStackDeployError{Err: err}).Error())
@@ -1290,10 +1201,6 @@ func (h *SwarmHandler) DeployStack(ctx context.Context, input *DeploySwarmStackI
// Returns `404 Not Found` when the stack does not exist or another mapped HTTP
// error when inspection fails.
func (h *SwarmHandler) GetStack(ctx context.Context, input *GetSwarmStackInput) (*GetSwarmStackOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
stack, err := h.swarmService.GetStack(ctx, input.EnvironmentID, input.Name)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -1317,9 +1224,6 @@ func (h *SwarmHandler) GetStack(ctx context.Context, input *GetSwarmStackInput)
// Returns an authorization error for non-admin callers, `404 Not Found` when
// no saved source exists, or another mapped HTTP error when loading fails.
func (h *SwarmHandler) GetStackSource(ctx context.Context, input *GetSwarmStackSourceInput) (*GetSwarmStackSourceOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
source, err := h.swarmService.GetStackSource(ctx, input.EnvironmentID, input.Name)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -1337,9 +1241,6 @@ func (h *SwarmHandler) GetStackSource(ctx context.Context, input *GetSwarmStackS
// sensitive configuration. The stack name comes from the route, and the body
// contains the replacement source files to save.
func (h *SwarmHandler) UpdateStackSource(ctx context.Context, input *UpdateSwarmStackSourceInput) (*UpdateSwarmStackSourceOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
source, err := h.swarmService.UpdateStackSource(ctx, input.EnvironmentID, input.Name, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to update swarm stack source")
@@ -1363,9 +1264,6 @@ func (h *SwarmHandler) UpdateStackSource(ctx context.Context, input *UpdateSwarm
// Returns an authorization error for non-admin callers, `404 Not Found` when
// the stack does not exist, or another mapped HTTP error when removal fails.
func (h *SwarmHandler) DeleteStack(ctx context.Context, input *DeleteSwarmStackInput) (*DeleteSwarmStackOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.RemoveStack(ctx, input.EnvironmentID, input.Name); err != nil {
if errdefs.IsNotFound(err) {
return nil, huma.Error404NotFound("Swarm stack not found")
@@ -1390,11 +1288,7 @@ func (h *SwarmHandler) DeleteStack(ctx context.Context, input *DeleteSwarmStackI
// Returns `404 Not Found` when the stack does not exist or another mapped HTTP
// error when the lookup fails.
func (h *SwarmHandler) ListStackServices(ctx context.Context, input *ListSwarmStackServicesInput) (*ListSwarmStackServicesOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
- params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)
+ params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListStackServicesPaginated(ctx, input.Name, params)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -1406,7 +1300,7 @@ func (h *SwarmHandler) ListStackServices(ctx context.Context, input *ListSwarmSt
items = []swarmtypes.ServiceSummary{}
}
- return &ListSwarmStackServicesOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil
+ return &ListSwarmStackServicesOutput{Body: base.Paginated[swarmtypes.ServiceSummary]{Success: true, Data: items, Pagination: toPaginationResponseInternal(paginationResp)}}, nil
}
// ListStackTasks lists tasks belonging to a swarm stack.
@@ -1421,11 +1315,7 @@ func (h *SwarmHandler) ListStackServices(ctx context.Context, input *ListSwarmSt
// Returns `404 Not Found` when the stack does not exist or another mapped HTTP
// error when the lookup fails.
func (h *SwarmHandler) ListStackTasks(ctx context.Context, input *ListSwarmStackTasksInput) (*ListSwarmStackTasksOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
- params := buildSwarmQueryParams(input.Search, input.Sort, input.Order, input.Start, input.Limit)
+ params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
items, paginationResp, err := h.swarmService.ListStackTasksPaginated(ctx, input.Name, params)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -1437,7 +1327,7 @@ func (h *SwarmHandler) ListStackTasks(ctx context.Context, input *ListSwarmStack
items = []swarmtypes.TaskSummary{}
}
- return &ListSwarmStackTasksOutput{Body: toSwarmPaginatedResponse(items, paginationResp)}, nil
+ return &ListSwarmStackTasksOutput{Body: base.Paginated[swarmtypes.TaskSummary]{Success: true, Data: items, Pagination: toPaginationResponseInternal(paginationResp)}}, nil
}
// RenderStackConfig renders and validates a swarm stack configuration without deploying it.
@@ -1451,10 +1341,6 @@ func (h *SwarmHandler) ListStackTasks(ctx context.Context, input *ListSwarmStack
// Returns the rendered compose content together with discovered resource names.
// Returns a mapped HTTP error when parsing, interpolation, or rendering fails.
func (h *SwarmHandler) RenderStackConfig(ctx context.Context, input *RenderSwarmStackConfigInput) (*RenderSwarmStackConfigOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
resp, err := h.swarmService.RenderStackConfig(ctx, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to render swarm stack config")
@@ -1474,10 +1360,6 @@ func (h *SwarmHandler) RenderStackConfig(ctx context.Context, input *RenderSwarm
// Returns the current swarm information when swarm mode is available.
// Returns a mapped HTTP error when swarm inspection fails.
func (h *SwarmHandler) GetSwarmStatus(ctx context.Context, input *GetSwarmStatusInput) (*GetSwarmStatusOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
enabled, err := h.swarmService.IsEnabled(ctx)
if err != nil {
return nil, huma.Error500InternalServerError("failed to read swarm status")
@@ -1502,10 +1384,6 @@ func (h *SwarmHandler) GetSwarmStatus(ctx context.Context, input *GetSwarmStatus
// Returns the current swarm information when swarm mode is available.
// Returns a mapped HTTP error when swarm inspection fails.
func (h *SwarmHandler) GetSwarmInfo(ctx context.Context, input *GetSwarmInfoInput) (*GetSwarmInfoOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
info, err := h.swarmService.GetSwarmInfo(ctx)
if err != nil {
return nil, mapSwarmServiceError(err, (&common.SwarmInspectError{Err: err}).Error())
@@ -1526,9 +1404,6 @@ func (h *SwarmHandler) GetSwarmInfo(ctx context.Context, input *GetSwarmInfoInpu
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when initialization fails.
func (h *SwarmHandler) InitSwarm(ctx context.Context, input *InitSwarmInput) (*InitSwarmOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
resp, err := h.swarmService.InitSwarm(ctx, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to initialize swarm")
@@ -1551,9 +1426,6 @@ func (h *SwarmHandler) InitSwarm(ctx context.Context, input *InitSwarmInput) (*I
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the join operation fails.
func (h *SwarmHandler) JoinSwarm(ctx context.Context, input *JoinSwarmInput) (*JoinSwarmOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.JoinSwarm(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to join swarm")
}
@@ -1565,9 +1437,6 @@ func (h *SwarmHandler) JoinSwarm(ctx context.Context, input *JoinSwarmInput) (*J
// GetJoinCandidates lists enabled visible environments the caller can join.
func (h *SwarmHandler) GetJoinCandidates(ctx context.Context, input *GetSwarmJoinCandidatesInput) (*GetSwarmJoinCandidatesOutput, error) {
- if h.environmentService == nil || h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := requireEasyJoinManagerPermissionsInternal(ctx, input.EnvironmentID); err != nil {
return nil, err
}
@@ -1612,9 +1481,6 @@ func (h *SwarmHandler) GetJoinCandidates(ctx context.Context, input *GetSwarmJoi
// JoinEnvironments performs Easy Join without returning manager join tokens.
func (h *SwarmHandler) JoinEnvironments(ctx context.Context, input *JoinSwarmEnvironmentsInput) (*JoinSwarmEnvironmentsOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := requireEasyJoinManagerPermissionsInternal(ctx, input.EnvironmentID); err != nil {
return nil, err
}
@@ -1653,8 +1519,8 @@ func (h *SwarmHandler) JoinEnvironments(ctx context.Context, input *JoinSwarmEnv
func requireEasyJoinManagerPermissionsInternal(ctx context.Context, environmentID string) error {
permissions, _ := humamw.PermissionsFromContext(ctx)
- if permissions == nil || !permissions.Allows(authz.PermSwarmNodes, environmentID) || !permissions.Allows(authz.PermSwarmUnlock, environmentID) {
- return huma.Error403Forbidden("swarm:nodes and swarm:unlock permissions are required on the manager environment")
+ if permissions == nil || !permissions.Allows(authz.PermSwarmJoin, environmentID) {
+ return huma.Error403Forbidden("swarm:join permission is required on the manager environment")
}
return nil
}
@@ -1671,9 +1537,6 @@ func requireEasyJoinManagerPermissionsInternal(ctx context.Context, environmentI
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the leave operation fails.
func (h *SwarmHandler) LeaveSwarm(ctx context.Context, input *LeaveSwarmInput) (*LeaveSwarmOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.LeaveSwarm(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to leave swarm")
}
@@ -1695,9 +1558,6 @@ func (h *SwarmHandler) LeaveSwarm(ctx context.Context, input *LeaveSwarmInput) (
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the unlock operation fails.
func (h *SwarmHandler) UnlockSwarm(ctx context.Context, input *UnlockSwarmInput) (*UnlockSwarmOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.UnlockSwarm(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to unlock swarm")
}
@@ -1718,9 +1578,6 @@ func (h *SwarmHandler) UnlockSwarm(ctx context.Context, input *UnlockSwarmInput)
// Returns the current manager unlock key.
// Returns a mapped HTTP error when the unlock key cannot be retrieved.
func (h *SwarmHandler) GetUnlockKey(ctx context.Context, input *GetSwarmUnlockKeyInput) (*GetSwarmUnlockKeyOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
resp, err := h.swarmService.GetSwarmUnlockKey(ctx)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to get swarm unlock key")
@@ -1740,9 +1597,6 @@ func (h *SwarmHandler) GetUnlockKey(ctx context.Context, input *GetSwarmUnlockKe
// Returns the current worker and manager join tokens.
// Returns a mapped HTTP error when token lookup fails.
func (h *SwarmHandler) GetJoinTokens(ctx context.Context, input *GetSwarmJoinTokensInput) (*GetSwarmJoinTokensOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
resp, err := h.swarmService.GetSwarmJoinTokens(ctx)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to get swarm join tokens")
@@ -1763,9 +1617,6 @@ func (h *SwarmHandler) GetJoinTokens(ctx context.Context, input *GetSwarmJoinTok
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when token rotation fails.
func (h *SwarmHandler) RotateJoinTokens(ctx context.Context, input *RotateSwarmJoinTokensInput) (*RotateSwarmJoinTokensOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.RotateSwarmJoinTokens(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to rotate swarm join tokens")
}
@@ -1787,9 +1638,6 @@ func (h *SwarmHandler) RotateJoinTokens(ctx context.Context, input *RotateSwarmJ
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the spec update fails.
func (h *SwarmHandler) UpdateSwarmSpec(ctx context.Context, input *UpdateSwarmSpecInput) (*UpdateSwarmSpecOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.UpdateSwarmSpec(ctx, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to update swarm spec")
}
@@ -1810,10 +1658,6 @@ func (h *SwarmHandler) UpdateSwarmSpec(ctx context.Context, input *UpdateSwarmSp
// Returns the current swarm configs.
// Returns a mapped HTTP error when config enumeration fails.
func (h *SwarmHandler) ListConfigs(ctx context.Context, input *ListSwarmConfigsInput) (*ListSwarmConfigsOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
items, err := h.swarmService.ListConfigs(ctx)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to list swarm configs")
@@ -1837,10 +1681,6 @@ func (h *SwarmHandler) ListConfigs(ctx context.Context, input *ListSwarmConfigsI
// Returns `404 Not Found` when the config does not exist or another mapped HTTP
// error when inspection fails.
func (h *SwarmHandler) GetConfig(ctx context.Context, input *GetSwarmConfigInput) (*GetSwarmConfigOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
cfg, err := h.swarmService.GetConfig(ctx, input.ConfigID)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -1864,9 +1704,6 @@ func (h *SwarmHandler) GetConfig(ctx context.Context, input *GetSwarmConfigInput
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when validation or creation fails.
func (h *SwarmHandler) CreateConfig(ctx context.Context, input *CreateSwarmConfigInput) (*CreateSwarmConfigOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
cfg, err := h.swarmService.CreateConfig(ctx, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to create swarm config")
@@ -1890,9 +1727,6 @@ func (h *SwarmHandler) CreateConfig(ctx context.Context, input *CreateSwarmConfi
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the update fails.
func (h *SwarmHandler) UpdateConfig(ctx context.Context, input *UpdateSwarmConfigInput) (*UpdateSwarmConfigOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.UpdateConfig(ctx, input.ConfigID, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to update swarm config")
}
@@ -1911,9 +1745,6 @@ func (h *SwarmHandler) UpdateConfig(ctx context.Context, input *UpdateSwarmConfi
// Returns an authorization error for non-admin callers, `404 Not Found` when
// the config does not exist, or another mapped HTTP error when removal fails.
func (h *SwarmHandler) DeleteConfig(ctx context.Context, input *DeleteSwarmConfigInput) (*DeleteSwarmConfigOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.RemoveConfig(ctx, input.ConfigID); err != nil {
if errdefs.IsNotFound(err) {
return nil, huma.Error404NotFound("Swarm config not found")
@@ -1937,10 +1768,6 @@ func (h *SwarmHandler) DeleteConfig(ctx context.Context, input *DeleteSwarmConfi
// Returns the current swarm secrets.
// Returns a mapped HTTP error when secret enumeration fails.
func (h *SwarmHandler) ListSecrets(ctx context.Context, input *ListSwarmSecretsInput) (*ListSwarmSecretsOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
items, err := h.swarmService.ListSecrets(ctx)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to list swarm secrets")
@@ -1964,10 +1791,6 @@ func (h *SwarmHandler) ListSecrets(ctx context.Context, input *ListSwarmSecretsI
// Returns `404 Not Found` when the secret does not exist or another mapped HTTP
// error when inspection fails.
func (h *SwarmHandler) GetSecret(ctx context.Context, input *GetSwarmSecretInput) (*GetSwarmSecretOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
secret, err := h.swarmService.GetSecret(ctx, input.SecretID)
if err != nil {
if errdefs.IsNotFound(err) {
@@ -1991,9 +1814,6 @@ func (h *SwarmHandler) GetSecret(ctx context.Context, input *GetSwarmSecretInput
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when validation or creation fails.
func (h *SwarmHandler) CreateSecret(ctx context.Context, input *CreateSwarmSecretInput) (*CreateSwarmSecretOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
secret, err := h.swarmService.CreateSecret(ctx, input.Body)
if err != nil {
return nil, mapSwarmServiceError(err, "Failed to create swarm secret")
@@ -2017,9 +1837,6 @@ func (h *SwarmHandler) CreateSecret(ctx context.Context, input *CreateSwarmSecre
// Returns an authorization error for non-admin callers or mapped HTTP errors
// when the update fails.
func (h *SwarmHandler) UpdateSecret(ctx context.Context, input *UpdateSwarmSecretInput) (*UpdateSwarmSecretOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.UpdateSecret(ctx, input.SecretID, input.Body); err != nil {
return nil, mapSwarmServiceError(err, "Failed to update swarm secret")
}
@@ -2038,9 +1855,6 @@ func (h *SwarmHandler) UpdateSecret(ctx context.Context, input *UpdateSwarmSecre
// Returns an authorization error for non-admin callers, `404 Not Found` when
// the secret does not exist, or another mapped HTTP error when removal fails.
func (h *SwarmHandler) DeleteSecret(ctx context.Context, input *DeleteSwarmSecretInput) (*DeleteSwarmSecretOutput, error) {
- if h.swarmService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.swarmService.RemoveSecret(ctx, input.SecretID); err != nil {
if errdefs.IsNotFound(err) {
return nil, huma.Error404NotFound("Swarm secret not found")
@@ -2053,20 +1867,6 @@ func (h *SwarmHandler) DeleteSecret(ctx context.Context, input *DeleteSwarmSecre
return &DeleteSwarmSecretOutput{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm secret removed successfully"}}}, nil
}
-// toSwarmPaginatedResponse wraps items and pagination metadata in the standard swarm list envelope.
-//
-// items is the collection to include in the response body.
-// p provides the pagination metadata produced by the pagination package.
-//
-// Returns a SwarmPaginatedResponse with `Success` set to true.
-func toSwarmPaginatedResponse[T any](items []T, p pagination.Response) SwarmPaginatedResponse[T] {
- return SwarmPaginatedResponse[T]{
- Success: true,
- Data: items,
- Pagination: toPaginationResponseInternal(p),
- }
-}
-
// auditSwarmMutation writes an informational event for a completed swarm mutation.
//
// It enriches the event with the current user when available, normalizes blank
@@ -2132,38 +1932,6 @@ func (h *SwarmHandler) auditSwarmMutation(ctx context.Context, environmentID, ac
}
}
-// buildSwarmQueryParams converts raw request values into pagination query parameters.
-//
-// It trims string inputs, applies the default limit used by the swarm API, and
-// preserves the requested start offset.
-//
-// search is the free-text search term.
-// sort is the requested sort column.
-// order is the requested sort direction.
-// start is the zero-based pagination offset.
-// limit is the requested page size.
-//
-// Returns normalized pagination.QueryParams for downstream service calls.
-func buildSwarmQueryParams(search, sort, order string, start, limit int) pagination.QueryParams {
- if limit == 0 {
- limit = 20
- }
-
- return pagination.QueryParams{
- SearchQuery: pagination.SearchQuery{
- Search: strings.TrimSpace(search),
- },
- SortParams: pagination.SortParams{
- Sort: strings.TrimSpace(sort),
- Order: pagination.SortOrder(order),
- },
- Params: pagination.Params{
- Start: start,
- Limit: limit,
- },
- }
-}
-
// mapSwarmServiceError converts swarm-service errors into Huma HTTP errors.
//
// It recognizes Arcane's swarm sentinel errors, common Docker error classes,
diff --git a/backend/api/handlers/swarm_easy_join_permissions_test.go b/backend/api/handlers/swarm_easy_join_permissions_test.go
new file mode 100644
index 000000000..fb015e51d
--- /dev/null
+++ b/backend/api/handlers/swarm_easy_join_permissions_test.go
@@ -0,0 +1,44 @@
+package handlers
+
+import (
+ "context"
+ "testing"
+
+ humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/services"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ swarmtypes "github.com/getarcaneapp/arcane/types/v2/swarm"
+ "github.com/stretchr/testify/require"
+)
+
+func TestRequireEasyJoinManagerPermissionsUsesSwarmJoinOnly(t *testing.T) {
+ legacyPermissions := authz.NewPermissionSet()
+ legacyPermissions.AddEnv("manager", authz.PermSwarmNodes, authz.PermSwarmUnlock)
+ legacyContext := context.WithValue(context.Background(), humamw.ContextKeyUserPermissions, legacyPermissions)
+ require.Error(t, requireEasyJoinManagerPermissionsInternal(legacyContext, "manager"))
+
+ joinPermissions := authz.NewPermissionSet()
+ joinPermissions.AddEnv("manager", authz.PermSwarmJoin)
+ joinContext := context.WithValue(context.Background(), humamw.ContextKeyUserPermissions, joinPermissions)
+ require.NoError(t, requireEasyJoinManagerPermissionsInternal(joinContext, "manager"))
+}
+
+func TestJoinEnvironmentsRequiresSwarmJoinOnEveryTarget(t *testing.T) {
+ permissions := authz.NewPermissionSet()
+ permissions.AddEnv("manager", authz.PermSwarmJoin)
+ ctx := context.WithValue(context.Background(), humamw.ContextKeyUserPermissions, permissions)
+ handler := &SwarmHandler{swarmService: &services.SwarmService{}}
+
+ _, err := handler.JoinEnvironments(ctx, &JoinSwarmEnvironmentsInput{
+ EnvironmentID: "manager",
+ Body: swarmtypes.SwarmJoinEnvironmentsRequest{
+ RemoteAddrs: []string{"manager:2377"},
+ Targets: []swarmtypes.SwarmJoinEnvironmentTarget{
+ {EnvironmentID: "target", Role: swarmtypes.SwarmJoinEnvironmentRoleWorker},
+ },
+ },
+ })
+
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "swarm:join permission is required for every target environment")
+}
diff --git a/backend/api/handlers/system.go b/backend/api/handlers/system.go
index 6555383aa..daa34a1a3 100644
--- a/backend/api/handlers/system.go
+++ b/backend/api/handlers/system.go
@@ -159,10 +159,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
Description: "Check if the Docker daemon is responsive",
Tags: []string{"System"},
DefaultStatus: http.StatusOK,
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermSystemRead, h.Health)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -172,10 +169,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
Summary: "Get Docker info",
Description: "Get Docker daemon version and system information",
Tags: []string{"System"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermSystemRead, h.GetDockerInfo)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -185,10 +179,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
Summary: "Prune Docker resources",
Description: "Remove unused Docker resources (containers, images, volumes, networks)",
Tags: []string{"System"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermSystemPrune, h.PruneAll)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -198,10 +189,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
Summary: "Start all containers",
Description: "Start all Docker containers",
Tags: []string{"System"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersStart, h.StartAllContainers)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -211,10 +199,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
Summary: "Start all stopped containers",
Description: "Start all stopped Docker containers",
Tags: []string{"System"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersStart, h.StartAllStoppedContainers)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -224,10 +209,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
Summary: "Stop all containers",
Description: "Stop all running Docker containers",
Tags: []string{"System"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersStop, h.StopAllContainers)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -237,10 +219,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
Summary: "Convert docker run command",
Description: "Convert a docker run command to docker-compose format",
Tags: []string{"System"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermContainersCreate, h.ConvertDockerRun)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -250,10 +229,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
Summary: "Check for system upgrade",
Description: "Check if a system upgrade is available",
Tags: []string{"System"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermSystemRead, h.CheckUpgradeAvailable)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -264,10 +240,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
Description: "Trigger a system upgrade",
DefaultStatus: http.StatusAccepted,
Tags: []string{"System"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermSystemUpgrade, h.TriggerUpgrade)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -278,10 +251,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
Description: "Upgrade every Arcane environment, starting with the manager",
DefaultStatus: http.StatusAccepted,
Tags: []string{"System"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermSystemUpgrade, h.TriggerUpdateAll)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -291,10 +261,7 @@ func RegisterSystem(api huma.API, dockerService *services.DockerClientService, s
Summary: "Get update-all status",
Description: "Get the status of the latest update-all-environments job",
Tags: []string{"System"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermSystemRead, h.GetUpdateAllStatus)
}
@@ -308,10 +275,6 @@ func (h *SystemHandler) rejectIfAgentModeInternal() error {
// Health checks if the Docker daemon is responsive.
func (h *SystemHandler) Health(ctx context.Context, input *SystemHealthInput) (*SystemHealthOutput, error) {
- if h.dockerService == nil {
- return nil, huma.Error503ServiceUnavailable("docker service not available")
- }
-
dockerClient, err := h.dockerService.GetClient(ctx)
if err != nil {
return nil, huma.Error503ServiceUnavailable((&common.DockerConnectionError{Err: err}).Error())
@@ -327,10 +290,6 @@ func (h *SystemHandler) Health(ctx context.Context, input *SystemHealthInput) (*
// GetDockerInfo returns Docker daemon version and system information.
func (h *SystemHandler) GetDockerInfo(ctx context.Context, input *GetDockerInfoInput) (*GetDockerInfoOutput, error) {
- if h.dockerService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
dockerClient, err := h.dockerService.GetClient(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.DockerConnectionError{Err: err}).Error())
@@ -419,10 +378,6 @@ func extractVersionDetailsFromComponents(components []dockersystem.ComponentVers
// PruneAll removes unused Docker resources.
func (h *SystemHandler) PruneAll(ctx context.Context, input *PruneAllInput) (*PruneAllOutput, error) {
- if h.systemService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
slog.InfoContext(ctx, "System prune operation initiated",
"containers", input.Body.Containers,
"images", input.Body.Images,
@@ -445,10 +400,6 @@ func (h *SystemHandler) PruneAll(ctx context.Context, input *PruneAllInput) (*Pr
// StartAllContainers starts all Docker containers.
func (h *SystemHandler) StartAllContainers(ctx context.Context, input *StartAllContainersInput) (*StartAllContainersOutput, error) {
- if h.systemService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
result, err := h.systemService.StartAllContainers(runtimeCtx, input.EnvironmentID)
if err != nil {
@@ -465,10 +416,6 @@ func (h *SystemHandler) StartAllContainers(ctx context.Context, input *StartAllC
// StartAllStoppedContainers starts all stopped Docker containers.
func (h *SystemHandler) StartAllStoppedContainers(ctx context.Context, input *StartAllStoppedContainersInput) (*StartAllStoppedContainersOutput, error) {
- if h.systemService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
result, err := h.systemService.StartAllStoppedContainers(runtimeCtx, input.EnvironmentID)
if err != nil {
@@ -485,10 +432,6 @@ func (h *SystemHandler) StartAllStoppedContainers(ctx context.Context, input *St
// StopAllContainers stops all running Docker containers.
func (h *SystemHandler) StopAllContainers(ctx context.Context, input *StopAllContainersInput) (*StopAllContainersOutput, error) {
- if h.systemService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
result, err := h.systemService.StopAllContainers(runtimeCtx, input.EnvironmentID)
if err != nil {
@@ -505,10 +448,6 @@ func (h *SystemHandler) StopAllContainers(ctx context.Context, input *StopAllCon
// ConvertDockerRun converts a docker run command to docker-compose format.
func (h *SystemHandler) ConvertDockerRun(ctx context.Context, input *ConvertDockerRunInput) (*ConvertDockerRunOutput, error) {
- if h.systemService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
result, err := convert.Convert(input.Body.DockerRunCommand, converttypes.Options{})
if err != nil {
if errors.Is(err, converttypes.ErrParse) {
@@ -534,10 +473,6 @@ func (h *SystemHandler) ConvertDockerRun(ctx context.Context, input *ConvertDock
// CheckUpgradeAvailable checks if a system upgrade is available.
func (h *SystemHandler) CheckUpgradeAvailable(ctx context.Context, input *CheckUpgradeInput) (*CheckUpgradeOutput, error) {
- if h.upgradeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
canUpgrade, err := h.upgradeService.CanUpgrade(ctx)
if err != nil {
slog.Debug("System upgrade check failed", "error", err)
@@ -561,10 +496,6 @@ func (h *SystemHandler) CheckUpgradeAvailable(ctx context.Context, input *CheckU
// TriggerUpgrade triggers a system upgrade.
func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgradeInput) (*TriggerUpgradeOutput, error) {
- if h.upgradeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -596,9 +527,6 @@ func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgrad
// TriggerUpdateAll starts a fleet-wide update, upgrading the manager first and then
// the remote agents (the latter resume after the manager restarts).
func (h *SystemHandler) TriggerUpdateAll(ctx context.Context, input *TriggerUpdateAllInput) (*TriggerUpdateAllOutput, error) {
- if h.upgradeService == nil || h.environmentService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.rejectIfAgentModeInternal(); err != nil {
return nil, err
}
@@ -632,9 +560,6 @@ func (h *SystemHandler) TriggerUpdateAll(ctx context.Context, input *TriggerUpda
// GetUpdateAllStatus returns the latest update-all job for live progress polling.
func (h *SystemHandler) GetUpdateAllStatus(ctx context.Context, input *UpdateAllStatusInput) (*UpdateAllStatusOutput, error) {
- if h.upgradeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if err := h.rejectIfAgentModeInternal(); err != nil {
return nil, err
}
diff --git a/backend/api/handlers/templates.go b/backend/api/handlers/templates.go
index dcba3d975..28f0f4959 100644
--- a/backend/api/handlers/templates.go
+++ b/backend/api/handlers/templates.go
@@ -25,13 +25,6 @@ type TemplateHandler struct {
// Input/Output Types
// ============================================================================
-// TemplatePaginatedResponse is the paginated response for templates.
-type TemplatePaginatedResponse struct {
- Success bool `json:"success"`
- Data []template.Template `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListTemplatesInput struct {
Search string `query:"search" doc:"Search query"`
Sort string `query:"sort" doc:"Column to sort by"`
@@ -42,7 +35,7 @@ type ListTemplatesInput struct {
}
type ListTemplatesOutput struct {
- Body TemplatePaginatedResponse
+ Body base.Paginated[template.Template]
}
type GetAllTemplatesInput struct{}
@@ -169,10 +162,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService)
Summary: "Fetch remote registry",
Description: "Fetch templates from a remote registry URL",
Tags: []string{"Templates"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermTemplatesRead),
}, h.FetchRegistry)
@@ -224,10 +214,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService)
Summary: "Create a template",
Description: "Create a new compose template",
Tags: []string{"Templates"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermTemplatesCreate),
}, h.CreateTemplate)
@@ -238,10 +225,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService)
Summary: "Update a template",
Description: "Update an existing compose template",
Tags: []string{"Templates"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermTemplatesUpdate),
}, h.UpdateTemplate)
@@ -252,10 +236,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService)
Summary: "Delete a template",
Description: "Delete a compose template",
Tags: []string{"Templates"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermTemplatesDelete),
}, h.DeleteTemplate)
@@ -266,10 +247,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService)
Summary: "Download a template",
Description: "Download a remote template to local storage",
Tags: []string{"Templates"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermTemplatesRead),
}, h.DownloadTemplate)
@@ -280,10 +258,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService)
Summary: "Get default templates",
Description: "Get the default compose and env templates",
Tags: []string{"Templates"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermTemplatesRead),
}, h.GetDefaultTemplates)
@@ -294,10 +269,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService)
Summary: "Save default templates",
Description: "Save the default compose and env templates",
Tags: []string{"Templates"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermTemplatesUpdate),
}, h.SaveDefaultTemplates)
@@ -308,10 +280,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService)
Summary: "List template registries",
Description: "Get all template registries",
Tags: []string{"Templates"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermTemplatesList),
}, h.GetRegistries)
@@ -322,10 +291,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService)
Summary: "Create a template registry",
Description: "Create a new template registry",
Tags: []string{"Templates"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermTemplatesCreate),
}, h.CreateRegistry)
@@ -336,10 +302,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService)
Summary: "Update a template registry",
Description: "Update an existing template registry",
Tags: []string{"Templates"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermTemplatesUpdate),
}, h.UpdateRegistry)
@@ -350,10 +313,7 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService)
Summary: "Delete a template registry",
Description: "Delete a template registry",
Tags: []string{"Templates"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermTemplatesDelete),
}, h.DeleteRegistry)
}
@@ -364,10 +324,6 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService)
// ListTemplates returns a paginated list of templates.
func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplatesInput) (*ListTemplatesOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if params.Limit == 0 {
params.Limit = 20
@@ -382,7 +338,7 @@ func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplate
}
return &ListTemplatesOutput{
- Body: TemplatePaginatedResponse{
+ Body: base.Paginated[template.Template]{
Success: true,
Data: templates,
Pagination: toPaginationResponseInternal(paginationResp),
@@ -392,10 +348,6 @@ func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplate
// GetAllTemplates returns all templates without pagination.
func (h *TemplateHandler) GetAllTemplates(ctx context.Context, _ *GetAllTemplatesInput) (*GetAllTemplatesOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
templates, err := h.templateService.GetAllTemplates(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.TemplateListError{Err: err}).Error())
@@ -416,10 +368,6 @@ func (h *TemplateHandler) GetAllTemplates(ctx context.Context, _ *GetAllTemplate
// GetTemplate returns a template by ID.
func (h *TemplateHandler) GetTemplate(ctx context.Context, input *GetTemplateInput) (*GetTemplateOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ID == "" {
return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())
}
@@ -455,10 +403,6 @@ func (h *TemplateHandler) GetTemplate(ctx context.Context, input *GetTemplateInp
// GetTemplateContent returns template content with parsed data.
func (h *TemplateHandler) GetTemplateContent(ctx context.Context, input *GetTemplateContentInput) (*GetTemplateContentOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ID == "" {
return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())
}
@@ -486,10 +430,6 @@ func (h *TemplateHandler) GetTemplateContent(ctx context.Context, input *GetTemp
// CreateTemplate creates a new template.
func (h *TemplateHandler) CreateTemplate(ctx context.Context, input *CreateTemplateInput) (*CreateTemplateOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
tmpl := &models.ComposeTemplate{
Name: input.Body.Name,
Description: input.Body.Description,
@@ -520,10 +460,6 @@ func (h *TemplateHandler) CreateTemplate(ctx context.Context, input *CreateTempl
// UpdateTemplate updates a template.
func (h *TemplateHandler) UpdateTemplate(ctx context.Context, input *UpdateTemplateInput) (*UpdateTemplateOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ID == "" {
return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())
}
@@ -571,10 +507,6 @@ func (h *TemplateHandler) UpdateTemplate(ctx context.Context, input *UpdateTempl
// DeleteTemplate deletes a template.
func (h *TemplateHandler) DeleteTemplate(ctx context.Context, input *DeleteTemplateInput) (*DeleteTemplateOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ID == "" {
return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())
}
@@ -603,10 +535,6 @@ func (h *TemplateHandler) DeleteTemplate(ctx context.Context, input *DeleteTempl
// DownloadTemplate downloads a remote template to local storage.
func (h *TemplateHandler) DownloadTemplate(ctx context.Context, input *DownloadTemplateInput) (*DownloadTemplateOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ID == "" {
return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())
}
@@ -647,10 +575,6 @@ func (h *TemplateHandler) DownloadTemplate(ctx context.Context, input *DownloadT
// GetDefaultTemplates returns the default compose and env templates.
func (h *TemplateHandler) GetDefaultTemplates(ctx context.Context, _ *GetDefaultTemplatesInput) (*GetDefaultTemplatesOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
composeTemplate := h.templateService.GetComposeTemplate()
swarmStackTemplate := h.templateService.GetSwarmStackTemplate()
swarmStackEnvTemplate := h.templateService.GetSwarmStackEnvTemplate()
@@ -671,10 +595,6 @@ func (h *TemplateHandler) GetDefaultTemplates(ctx context.Context, _ *GetDefault
// SaveDefaultTemplates saves the default compose and env templates.
func (h *TemplateHandler) SaveDefaultTemplates(ctx context.Context, input *SaveDefaultTemplatesInput) (*SaveDefaultTemplatesOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if err := h.templateService.SaveComposeTemplate(input.Body.ComposeContent); err != nil {
return nil, huma.Error500InternalServerError((&common.DefaultTemplateSaveError{Err: err}).Error())
}
@@ -695,10 +615,6 @@ func (h *TemplateHandler) SaveDefaultTemplates(ctx context.Context, input *SaveD
// GetRegistries returns all template registries.
func (h *TemplateHandler) GetRegistries(ctx context.Context, _ *GetTemplateRegistriesInput) (*GetTemplateRegistriesOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
registries, err := h.templateService.GetRegistries(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.RegistryFetchError{Err: err}).Error())
@@ -729,10 +645,6 @@ func (h *TemplateHandler) GetRegistries(ctx context.Context, _ *GetTemplateRegis
// CreateRegistry creates a new template registry.
func (h *TemplateHandler) CreateRegistry(ctx context.Context, input *CreateTemplateRegistryInput) (*CreateTemplateRegistryOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
registry := &models.TemplateRegistry{
Name: input.Body.Name,
URL: input.Body.URL,
@@ -758,10 +670,6 @@ func (h *TemplateHandler) CreateRegistry(ctx context.Context, input *CreateTempl
// UpdateRegistry updates a template registry.
func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTemplateRegistryInput) (*UpdateTemplateRegistryOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ID == "" {
return nil, huma.Error400BadRequest((&common.RegistryIDRequiredError{}).Error())
}
@@ -791,10 +699,6 @@ func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTempl
// DeleteRegistry deletes a template registry.
func (h *TemplateHandler) DeleteRegistry(ctx context.Context, input *DeleteTemplateRegistryInput) (*DeleteTemplateRegistryOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.ID == "" {
return nil, huma.Error400BadRequest((&common.RegistryIDRequiredError{}).Error())
}
@@ -818,10 +722,6 @@ func (h *TemplateHandler) DeleteRegistry(ctx context.Context, input *DeleteTempl
// FetchRegistry fetches templates from a remote registry URL.
func (h *TemplateHandler) FetchRegistry(ctx context.Context, input *FetchTemplateRegistryInput) (*FetchTemplateRegistryOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.URL == "" {
return nil, huma.Error400BadRequest((&common.QueryParameterRequiredError{}).Error())
}
diff --git a/backend/api/handlers/updater.go b/backend/api/handlers/updater.go
index a32bf0b25..85d427b7a 100644
--- a/backend/api/handlers/updater.go
+++ b/backend/api/handlers/updater.go
@@ -72,10 +72,7 @@ func RegisterUpdater(api huma.API, updaterService *services.UpdaterService, appC
Summary: "Run updater",
Description: "Apply pending container updates",
Tags: []string{"Updater"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImageUpdatesCheck, h.RunUpdater)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -85,10 +82,7 @@ func RegisterUpdater(api huma.API, updaterService *services.UpdaterService, appC
Summary: "Get updater status",
Description: "Get the current status of the updater",
Tags: []string{"Updater"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImageUpdatesRead, h.GetUpdaterStatus)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -98,10 +92,7 @@ func RegisterUpdater(api huma.API, updaterService *services.UpdaterService, appC
Summary: "Get updater history",
Description: "Get the history of update operations",
Tags: []string{"Updater"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImageUpdatesRead, h.GetUpdaterHistory)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -111,19 +102,12 @@ func RegisterUpdater(api huma.API, updaterService *services.UpdaterService, appC
Summary: "Update a single container",
Description: "Pull the latest image and apply the appropriate update strategy for a specific container",
Tags: []string{"Updater", "Containers"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermImageUpdatesCheck, h.UpdateContainer)
}
// RunUpdater applies pending container updates.
func (h *UpdaterHandler) RunUpdater(ctx context.Context, input *RunUpdaterInput) (*RunUpdaterOutput, error) {
- if h.updaterService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
options := updater.Options{}
if input.Body != nil {
options = *input.Body
@@ -145,10 +129,6 @@ func (h *UpdaterHandler) RunUpdater(ctx context.Context, input *RunUpdaterInput)
// GetUpdaterStatus returns the current status of the updater.
func (h *UpdaterHandler) GetUpdaterStatus(ctx context.Context, input *GetUpdaterStatusInput) (*GetUpdaterStatusOutput, error) {
- if h.updaterService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
status := h.updaterService.GetStatus()
return &GetUpdaterStatusOutput{
@@ -161,10 +141,6 @@ func (h *UpdaterHandler) GetUpdaterStatus(ctx context.Context, input *GetUpdater
// GetUpdaterHistory returns the history of update operations.
func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdaterHistoryInput) (*GetUpdaterHistoryOutput, error) {
- if h.updaterService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
limit := input.Limit
if limit <= 0 {
limit = 50
@@ -185,10 +161,6 @@ func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdate
// UpdateContainer updates a single container by pulling the latest image and applying the appropriate update flow.
func (h *UpdaterHandler) UpdateContainer(ctx context.Context, input *UpdateContainerInput) (*UpdateContainerOutput, error) {
- if h.updaterService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
out, err := h.updaterService.UpdateSingleContainer(runtimeCtx, input.ContainerID)
if err != nil {
diff --git a/backend/api/handlers/users.go b/backend/api/handlers/users.go
index e6c017200..a2f819f5f 100644
--- a/backend/api/handlers/users.go
+++ b/backend/api/handlers/users.go
@@ -27,13 +27,6 @@ type UserHandler struct {
// Input/Output Types
// ============================================================================
-// UserPaginatedResponse is the paginated response for users.
-type UserPaginatedResponse struct {
- Success bool `json:"success"`
- Data []user.User `json:"data"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListUsersInput struct {
Search string `query:"search" doc:"Search query"`
Sort string `query:"sort" doc:"Column to sort by"`
@@ -43,7 +36,7 @@ type ListUsersInput struct {
}
type ListUsersOutput struct {
- Body UserPaginatedResponse
+ Body base.Paginated[user.User]
}
type CreateUserInput struct {
@@ -105,10 +98,7 @@ func RegisterUsers(api huma.API, userService *services.UserService, authService
Summary: "List users",
Description: "Get a paginated list of all users",
Tags: []string{"Users"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermUsersList),
}, h.ListUsers)
@@ -119,10 +109,7 @@ func RegisterUsers(api huma.API, userService *services.UserService, authService
Summary: "Create a user",
Description: "Create a new user account",
Tags: []string{"Users"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermUsersCreate),
}, h.CreateUser)
@@ -133,10 +120,7 @@ func RegisterUsers(api huma.API, userService *services.UserService, authService
Summary: "Get a user",
Description: "Get a user by ID",
Tags: []string{"Users"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermUsersRead),
}, h.GetUser)
@@ -147,10 +131,7 @@ func RegisterUsers(api huma.API, userService *services.UserService, authService
Summary: "Update a user",
Description: "Update an existing user's information",
Tags: []string{"Users"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermUsersUpdate),
}, h.UpdateUser)
@@ -161,10 +142,7 @@ func RegisterUsers(api huma.API, userService *services.UserService, authService
Summary: "Delete a user",
Description: "Delete a user by ID",
Tags: []string{"Users"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
Middlewares: humamw.RequirePermission(api, authz.PermUsersDelete),
}, h.DeleteUser)
@@ -187,10 +165,6 @@ func RegisterUsers(api huma.API, userService *services.UserService, authService
// ListUsers returns a paginated list of users.
func (h *UserHandler) ListUsers(ctx context.Context, input *ListUsersInput) (*ListUsersOutput, error) {
- if h.userService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
users, paginationResp, err := h.userService.ListUsersPaginated(ctx, params)
@@ -199,7 +173,7 @@ func (h *UserHandler) ListUsers(ctx context.Context, input *ListUsersInput) (*Li
}
return &ListUsersOutput{
- Body: UserPaginatedResponse{
+ Body: base.Paginated[user.User]{
Success: true,
Data: users,
Pagination: toPaginationResponseInternal(paginationResp),
@@ -209,10 +183,6 @@ func (h *UserHandler) ListUsers(ctx context.Context, input *ListUsersInput) (*Li
// CreateUser creates a new user.
func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*CreateUserOutput, error) {
- if h.userService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
normalizedEmail, err := normalizeOptionalEmailInternal(input.Body.Email)
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
@@ -259,10 +229,6 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*
// GetUser returns a user by ID.
func (h *UserHandler) GetUser(ctx context.Context, input *GetUserInput) (*GetUserOutput, error) {
- if h.userService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
userModel, err := h.userService.GetUserByID(ctx, input.UserID)
if err != nil {
return nil, huma.Error404NotFound((&common.UserNotFoundError{}).Error())
@@ -283,10 +249,6 @@ func (h *UserHandler) GetUser(ctx context.Context, input *GetUserInput) (*GetUse
// UpdateUser updates a user.
func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*UpdateUserOutput, error) {
- if h.userService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
userModel, err := h.userService.GetUserByID(ctx, input.UserID)
if err != nil {
return nil, huma.Error404NotFound((&common.UserNotFoundError{}).Error())
@@ -354,10 +316,6 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*
// DeleteUser deletes a user.
func (h *UserHandler) DeleteUser(ctx context.Context, input *DeleteUserInput) (*DeleteUserOutput, error) {
- if h.userService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if err := h.userService.DeleteUser(ctx, input.UserID); err != nil {
if errors.Is(err, services.ErrCannotRemoveLastAdmin) {
return nil, huma.Error409Conflict(services.ErrCannotRemoveLastAdmin.Error())
@@ -384,10 +342,6 @@ func (h *UserHandler) DeleteUser(ctx context.Context, input *DeleteUserInput) (*
// GetUserAvatar returns the custom profile picture for a user.
func (h *UserHandler) GetUserAvatar(ctx context.Context, input *GetUserAvatarInput) (*GetUserAvatarOutput, error) {
- if h.userService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
data, mimeType, err := h.userService.GetAvatar(ctx, input.UserID)
if err != nil {
if errors.Is(err, services.ErrUserNotFound) {
diff --git a/backend/api/handlers/variables.go b/backend/api/handlers/variables.go
index 2c0153796..9544617c6 100644
--- a/backend/api/handlers/variables.go
+++ b/backend/api/handlers/variables.go
@@ -13,9 +13,8 @@ import (
"github.com/getarcaneapp/arcane/types/v2/env"
)
-// VariableHandler handles the manager-level global variable endpoints plus the
-// per-environment /environments/{id}/templates/variables routes, which remain
-// the materialization channel the manager pushes through to agents.
+// VariableHandler handles manager-level global variables and the separate
+// agent-only materialization channel used to push effective values.
type VariableHandler struct {
variableService *services.VariableService
environmentService *services.EnvironmentService
@@ -99,11 +98,8 @@ func RegisterVariables(api huma.API, variableService *services.VariableService,
Summary: "List global variables",
Description: "List all global variables with their environment scope (secret values are redacted)",
Tags: []string{"Variables"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
- }, authz.PermTemplatesRead, h.ListVariables)
+ Security: defaultOperationSecurityInternal(),
+ }, authz.PermVariablesRead, h.ListVariables)
humamw.RegisterWithPermission(api, huma.Operation{
OperationID: "createVariable",
@@ -112,11 +108,8 @@ func RegisterVariables(api huma.API, variableService *services.VariableService,
Summary: "Create a global variable",
Description: "Create a global variable scoped to all or specific environments",
Tags: []string{"Variables"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
- }, authz.PermTemplatesUpdate, h.CreateVariable)
+ Security: defaultOperationSecurityInternal(),
+ }, authz.PermVariablesCreate, h.CreateVariable)
humamw.RegisterWithPermission(api, huma.Operation{
OperationID: "updateVariable",
@@ -125,11 +118,8 @@ func RegisterVariables(api huma.API, variableService *services.VariableService,
Summary: "Update a global variable",
Description: "Update a global variable's key, value, secret flag, or environment scope",
Tags: []string{"Variables"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
- }, authz.PermTemplatesUpdate, h.UpdateVariable)
+ Security: defaultOperationSecurityInternal(),
+ }, authz.PermVariablesUpdate, h.UpdateVariable)
humamw.RegisterWithPermission(api, huma.Operation{
OperationID: "deleteVariable",
@@ -138,11 +128,8 @@ func RegisterVariables(api huma.API, variableService *services.VariableService,
Summary: "Delete a global variable",
Description: "Delete a global variable and re-sync affected environments",
Tags: []string{"Variables"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
- }, authz.PermTemplatesUpdate, h.DeleteVariable)
+ Security: defaultOperationSecurityInternal(),
+ }, authz.PermVariablesDelete, h.DeleteVariable)
humamw.RegisterWithPermission(api, huma.Operation{
OperationID: "syncVariables",
@@ -151,11 +138,8 @@ func RegisterVariables(api huma.API, variableService *services.VariableService,
Summary: "Sync global variables",
Description: "Push the effective global variable set to every environment now",
Tags: []string{"Variables"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
- }, authz.PermTemplatesUpdate, h.SyncVariables)
+ Security: defaultOperationSecurityInternal(),
+ }, authz.PermVariablesSync, h.SyncVariables)
humamw.RegisterWithPermission(api, huma.Operation{
OperationID: "getVariableSyncStatus",
@@ -164,39 +148,37 @@ func RegisterVariables(api huma.API, variableService *services.VariableService,
Summary: "Get variable sync status",
Description: "Get the last global-variable sync result per environment",
Tags: []string{"Variables"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
- }, authz.PermTemplatesRead, h.GetSyncStatus)
+ Security: defaultOperationSecurityInternal(),
+ }, authz.PermVariablesRead, h.GetSyncStatus)
+}
- // Per-environment materialized-file routes. Agents serve these locally; the
- // manager pushes each environment's effective set through them.
- humamw.RegisterWithPermission(api, huma.Operation{
+// RegisterMaterializedVariables registers the plaintext synchronization
+// channel on agents. It must never be registered on a manager API because its
+// response intentionally contains decrypted values for .env.global.
+func RegisterMaterializedVariables(api huma.API, variableService *services.VariableService, environmentService *services.EnvironmentService) {
+ h := &VariableHandler{variableService: variableService, environmentService: environmentService}
+
+ huma.Register(api, huma.Operation{
OperationID: "getGlobalVariables",
Method: "GET",
Path: "/environments/{id}/templates/variables",
Summary: "Get materialized variables",
Description: "Get the materialized variable set for an environment. Managed via /variables on the manager.",
Tags: []string{"Variables"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
- }, authz.PermTemplatesRead, h.GetMaterializedVariables)
+ Security: defaultOperationSecurityInternal(),
+ Middlewares: humamw.RequireSudo(api),
+ }, h.GetMaterializedVariables)
- humamw.RegisterWithPermission(api, huma.Operation{
+ huma.Register(api, huma.Operation{
OperationID: "updateGlobalVariables",
Method: "PUT",
Path: "/environments/{id}/templates/variables",
Summary: "Update materialized variables",
Description: "Replace the materialized variable set for an environment. Managed via /variables on the manager.",
Tags: []string{"Variables"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
- }, authz.PermTemplatesUpdate, h.UpdateMaterializedVariables)
+ Security: defaultOperationSecurityInternal(),
+ Middlewares: humamw.RequireSudo(api),
+ }, h.UpdateMaterializedVariables)
}
// ============================================================================
@@ -204,10 +186,6 @@ func RegisterVariables(api huma.API, variableService *services.VariableService,
// ============================================================================
func (h *VariableHandler) ListVariables(ctx context.Context, _ *ListGlobalVariablesInput) (*ListGlobalVariablesOutput, error) {
- if h.variableService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
variables, err := h.variableService.ListVariables(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -222,10 +200,6 @@ func (h *VariableHandler) ListVariables(ctx context.Context, _ *ListGlobalVariab
}
func (h *VariableHandler) CreateVariable(ctx context.Context, input *CreateGlobalVariableInput) (*CreateGlobalVariableOutput, error) {
- if h.variableService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
variable, err := h.variableService.CreateVariable(ctx, input.Body)
if err != nil {
return nil, variableMutationHTTPErrorInternal(err)
@@ -243,10 +217,6 @@ func (h *VariableHandler) CreateVariable(ctx context.Context, input *CreateGloba
}
func (h *VariableHandler) UpdateVariable(ctx context.Context, input *UpdateGlobalVariableInput) (*UpdateGlobalVariableOutput, error) {
- if h.variableService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
variable, err := h.variableService.UpdateVariable(ctx, input.ID, input.Body)
if err != nil {
return nil, variableMutationHTTPErrorInternal(err)
@@ -264,10 +234,6 @@ func (h *VariableHandler) UpdateVariable(ctx context.Context, input *UpdateGloba
}
func (h *VariableHandler) DeleteVariable(ctx context.Context, input *DeleteGlobalVariableInput) (*DeleteGlobalVariableOutput, error) {
- if h.variableService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if err := h.variableService.DeleteVariable(ctx, input.ID); err != nil {
return nil, variableMutationHTTPErrorInternal(err)
}
@@ -283,10 +249,6 @@ func (h *VariableHandler) DeleteVariable(ctx context.Context, input *DeleteGloba
}
func (h *VariableHandler) SyncVariables(ctx context.Context, _ *SyncGlobalVariablesInput) (*SyncGlobalVariablesOutput, error) {
- if h.variableService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
return &SyncGlobalVariablesOutput{
Body: base.ApiResponse[[]env.EnvironmentSyncStatus]{
Success: true,
@@ -296,10 +258,6 @@ func (h *VariableHandler) SyncVariables(ctx context.Context, _ *SyncGlobalVariab
}
func (h *VariableHandler) GetSyncStatus(_ context.Context, _ *GetGlobalVariableSyncStatusInput) (*GetGlobalVariableSyncStatusOutput, error) {
- if h.variableService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
return &GetGlobalVariableSyncStatusOutput{
Body: base.ApiResponse[[]env.EnvironmentSyncStatus]{
Success: true,
@@ -311,14 +269,7 @@ func (h *VariableHandler) GetSyncStatus(_ context.Context, _ *GetGlobalVariableS
// GetMaterializedVariables returns the environment's materialized .env.global
// content (local file for environment "0", proxied to the agent otherwise).
func (h *VariableHandler) GetMaterializedVariables(ctx context.Context, input *GetGlobalVariablesInput) (*GetGlobalVariablesOutput, error) {
- if h.variableService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.EnvironmentID != "0" {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
response, err := proxyRemoteJSONInternal[base.ApiResponse[[]env.Variable]](ctx, h.environmentService, input.EnvironmentID, http.MethodGet, "/api/environments/0/templates/variables", nil)
if err != nil {
return nil, err
@@ -342,14 +293,7 @@ func (h *VariableHandler) GetMaterializedVariables(ctx context.Context, input *G
// UpdateMaterializedVariables replaces the environment's materialized
// .env.global content (local file for environment "0", proxied otherwise).
func (h *VariableHandler) UpdateMaterializedVariables(ctx context.Context, input *UpdateGlobalVariablesInput) (*UpdateGlobalVariablesOutput, error) {
- if h.variableService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.EnvironmentID != "0" {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
response, err := proxyRemoteJSONInternal[base.ApiResponse[base.MessageResponse]](ctx, h.environmentService, input.EnvironmentID, http.MethodPut, "/api/environments/0/templates/variables", input.Body)
if err != nil {
return nil, err
diff --git a/backend/api/handlers/variables_test.go b/backend/api/handlers/variables_test.go
new file mode 100644
index 000000000..a5462ff6b
--- /dev/null
+++ b/backend/api/handlers/variables_test.go
@@ -0,0 +1,146 @@
+package handlers
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/models"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/services"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "github.com/labstack/echo/v4"
+ sqlite "github.com/libtnb/sqlite"
+ "github.com/stretchr/testify/require"
+ "gorm.io/gorm"
+)
+
+func TestVariableRoutesRequireTheirExactPermissions(t *testing.T) {
+ tests := []struct {
+ name string
+ method string
+ path string
+ body string
+ permission string
+ }{
+ {name: "list", method: http.MethodGet, path: "/api/variables", permission: authz.PermVariablesRead},
+ {name: "create", method: http.MethodPost, path: "/api/variables", body: `{"key":"API_URL","value":"https://example.test","allEnvironments":true}`, permission: authz.PermVariablesCreate},
+ {name: "update", method: http.MethodPut, path: "/api/variables/variable-1", body: `{}`, permission: authz.PermVariablesUpdate},
+ {name: "delete", method: http.MethodDelete, path: "/api/variables/variable-1", permission: authz.PermVariablesDelete},
+ {name: "sync", method: http.MethodPost, path: "/api/variables/sync", permission: authz.PermVariablesSync},
+ {name: "sync status", method: http.MethodGet, path: "/api/variables/sync-status", permission: authz.PermVariablesRead},
+ }
+
+ allVariablePermissions := []string{
+ authz.PermVariablesRead,
+ authz.PermVariablesCreate,
+ authz.PermVariablesUpdate,
+ authz.PermVariablesDelete,
+ authz.PermVariablesSync,
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name+" rejects other grants", func(t *testing.T) {
+ permissions := authz.NewPermissionSet()
+ permissions.AddGlobal(authz.PermTemplatesRead, authz.PermTemplatesCreate, authz.PermTemplatesUpdate, authz.PermTemplatesDelete)
+ for _, permission := range allVariablePermissions {
+ if permission != tt.permission {
+ permissions.AddGlobal(permission)
+ }
+ }
+
+ router, api := newPermissionGatingRouterInternal(t, permissions)
+ RegisterVariables(api, nil, nil)
+ response := performVariableRequestInternal(router, tt.method, tt.path, tt.body)
+
+ require.Equal(t, http.StatusForbidden, response.Code)
+ require.Contains(t, response.Body.String(), "permission denied: "+tt.permission)
+ })
+
+ t.Run(tt.name+" allows exact grant", func(t *testing.T) {
+ permissions := authz.NewPermissionSet()
+ permissions.AddGlobal(tt.permission)
+
+ router, api := newPermissionGatingRouterInternal(t, permissions)
+ variableService, environmentService := setupVariableHandlerServicesInternal(t)
+ RegisterVariables(api, variableService, environmentService)
+ response := performVariableRequestInternal(router, tt.method, tt.path, tt.body)
+
+ require.NotEqual(t, http.StatusForbidden, response.Code)
+ require.NotContains(t, response.Body.String(), "permission denied")
+ })
+ }
+}
+
+func TestMaterializedVariableRoutesRequireSudo(t *testing.T) {
+ tests := []struct {
+ name string
+ method string
+ body string
+ }{
+ {name: "get", method: http.MethodGet},
+ {name: "put", method: http.MethodPut, body: `{"variables":[{"key":"TOKEN","value":"plaintext"}]}`},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name+" rejects human admin", func(t *testing.T) {
+ permissions := authz.NewPermissionSet()
+ permissions.AddGlobal(authz.AllPermissions()...)
+ router, api := newPermissionGatingRouterInternal(t, permissions)
+ RegisterMaterializedVariables(api, nil, nil)
+
+ response := performVariableRequestInternal(router, tt.method, "/api/environments/0/templates/variables", tt.body)
+
+ require.Equal(t, http.StatusForbidden, response.Code)
+ require.Contains(t, response.Body.String(), "agent authentication required")
+ })
+
+ t.Run(tt.name+" allows agent", func(t *testing.T) {
+ router, api := newPermissionGatingRouterInternal(t, authz.SudoPermissionSet())
+ variableService, environmentService := setupVariableHandlerServicesInternal(t)
+ RegisterMaterializedVariables(api, variableService, environmentService)
+
+ response := performVariableRequestInternal(router, tt.method, "/api/environments/0/templates/variables", tt.body)
+
+ require.Equal(t, http.StatusOK, response.Code)
+ })
+ }
+}
+
+func setupVariableHandlerServicesInternal(t *testing.T) (*services.VariableService, *services.EnvironmentService) {
+ t.Helper()
+
+ databaseConnection, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "variables.db")), &gorm.Config{})
+ require.NoError(t, err)
+ require.NoError(t, databaseConnection.AutoMigrate(
+ &models.GlobalVariable{},
+ &models.Environment{},
+ &models.KVEntry{},
+ &models.SettingVariable{},
+ ))
+ databaseDB := &database.DB{DB: databaseConnection}
+ settingsService, err := services.NewSettingsService(context.Background(), databaseDB)
+ require.NoError(t, err)
+ require.NoError(t, settingsService.UpdateSetting(context.Background(), "projectsDirectory", t.TempDir()))
+ environmentService := services.NewEnvironmentService(databaseDB, nil, nil, nil, settingsService, nil)
+ variableService := services.NewVariableService(databaseDB, environmentService, settingsService, services.NewKVService(databaseDB))
+ return variableService, environmentService
+}
+
+func performVariableRequestInternal(router *echo.Echo, method, path, body string) *httptest.ResponseRecorder {
+ var reader io.Reader
+ if body != "" {
+ reader = strings.NewReader(body)
+ }
+ request := httptest.NewRequest(method, path, reader)
+ if body != "" {
+ request.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
+ }
+ response := httptest.NewRecorder()
+ router.ServeHTTP(response, request)
+ return response
+}
diff --git a/backend/api/handlers/version.go b/backend/api/handlers/version.go
index f789ab5ae..83e950c05 100644
--- a/backend/api/handlers/version.go
+++ b/backend/api/handlers/version.go
@@ -67,10 +67,6 @@ func RegisterVersion(api huma.API, versionService *services.VersionService) {
// GetVersion returns version information with optional update check.
func (h *VersionHandler) GetVersion(ctx context.Context, input *GetVersionInput) (*GetVersionOutput, error) {
- if h.versionService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
current := strings.TrimSpace(input.Current)
check, _ := h.versionService.GetVersionInformation(ctx, current)
@@ -81,10 +77,6 @@ func (h *VersionHandler) GetVersion(ctx context.Context, input *GetVersionInput)
// GetAppVersion returns the current application version.
func (h *VersionHandler) GetAppVersion(ctx context.Context, _ *GetAppVersionInput) (*GetAppVersionOutput, error) {
- if h.versionService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
info := h.versionService.GetAppVersionInfo(ctx)
return &GetAppVersionOutput{
diff --git a/backend/api/handlers/volumes.go b/backend/api/handlers/volumes.go
index 1244eb43b..12b47b8a0 100644
--- a/backend/api/handlers/volumes.go
+++ b/backend/api/handlers/volumes.go
@@ -40,14 +40,6 @@ type VolumeUsageCountsData struct {
Total int `json:"total"`
}
-// VolumePaginatedResponse is the paginated response for volumes.
-type VolumePaginatedResponse struct {
- Success bool `json:"success"`
- Data []volumetypes.Volume `json:"data"`
- Counts VolumeUsageCountsData `json:"counts"`
- Pagination base.PaginationResponse `json:"pagination"`
-}
-
type ListVolumesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -60,7 +52,7 @@ type ListVolumesInput struct {
}
type ListVolumesOutput struct {
- Body VolumePaginatedResponse
+ Body base.PaginatedWithCounts[volumetypes.Volume, VolumeUsageCountsData]
}
type GetVolumeInput struct {
@@ -300,8 +292,6 @@ type UploadAndRestoreOutput struct {
}
// RegisterVolumes registers volume management routes using Huma.
-//
-//nolint:maintidx // long but flat Huma route-registration function; complexity is sequential, not branching
func RegisterVolumes(api huma.API, dockerService *services.DockerClientService, volumeService *services.VolumeService, activityService *services.ActivityService, appCtx ActivityAppContext) {
h := &VolumeHandler{
volumeService: volumeService,
@@ -317,10 +307,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Summary: "Get volume usage counts",
Description: "Get counts of volumes in use, unused, and total",
Tags: []string{"Volumes"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesList, h.GetVolumeUsageCounts)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -330,10 +317,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Summary: "List volumes",
Description: "Get a paginated list of Docker volumes",
Tags: []string{"Volumes"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesList, h.ListVolumes)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -343,10 +327,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Summary: "Get volume by name",
Description: "Get a Docker volume by its name",
Tags: []string{"Volumes"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesRead, h.GetVolume)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -356,10 +337,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Summary: "Create a volume",
Description: "Create a new Docker volume",
Tags: []string{"Volumes"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesCreate, h.CreateVolume)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -369,10 +347,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Summary: "Remove a volume",
Description: "Remove a Docker volume by name",
Tags: []string{"Volumes"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesDelete, h.RemoveVolume)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -382,10 +357,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Summary: "Prune unused volumes",
Description: "Remove all unused Docker volumes",
Tags: []string{"Volumes"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesPrune, h.PruneVolumes)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -395,10 +367,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Summary: "Get volume usage",
Description: "Get containers using a specific volume",
Tags: []string{"Volumes"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesRead, h.GetVolumeUsage)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -408,10 +377,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Summary: "Get volume sizes",
Description: "Get disk usage sizes for all volumes (slow operation)",
Tags: []string{"Volumes"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesList, h.GetVolumeSizes)
// --- Volume Browsing Endpoints ---
@@ -422,10 +388,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/{volumeName}/browse",
Summary: "List volume directory",
Tags: []string{"Volume Browser"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesBrowse, h.BrowseDirectory)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -434,10 +397,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/{volumeName}/browse/content",
Summary: "Get file content preview",
Tags: []string{"Volume Browser"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesBrowse, h.GetFileContent)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -446,10 +406,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/{volumeName}/browse/download",
Summary: "Download file from volume",
Tags: []string{"Volume Browser"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesBrowse, h.DownloadFile)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -458,10 +415,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/{volumeName}/browse/upload",
Summary: "Upload file to volume",
Tags: []string{"Volume Browser"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
RequestBody: &huma.RequestBody{
Content: map[string]*huma.MediaType{
"multipart/form-data": {
@@ -487,10 +441,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/{volumeName}/browse/mkdir",
Summary: "Create directory in volume",
Tags: []string{"Volume Browser"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesUpload, h.CreateDirectory)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -499,10 +450,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/{volumeName}/browse",
Summary: "Delete file or directory in volume",
Tags: []string{"Volume Browser"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesDelete, h.DeleteFile)
// --- Volume Backup Endpoints ---
@@ -513,10 +461,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/{volumeName}/backups",
Summary: "List volume backups",
Tags: []string{"Volume Backup"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesBrowse, h.ListBackups)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -525,10 +470,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/{volumeName}/backups",
Summary: "Create volume backup",
Tags: []string{"Volume Backup"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesBackup, h.CreateBackup)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -537,10 +479,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/{volumeName}/backups/{backupId}/restore",
Summary: "Restore volume backup",
Tags: []string{"Volume Backup"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesBackup, h.RestoreBackup)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -549,10 +488,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/{volumeName}/backups/{backupId}/restore-files",
Summary: "Restore specific files from a volume backup",
Tags: []string{"Volume Backup"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesBackup, h.RestoreBackupFiles)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -561,10 +497,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/backups/{backupId}",
Summary: "Delete volume backup",
Tags: []string{"Volume Backup"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesBackup, h.DeleteBackup)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -573,10 +506,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/backups/{backupId}/download",
Summary: "Download volume backup",
Tags: []string{"Volume Backup"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesBrowse, h.DownloadBackup)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -585,10 +515,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/backups/{backupId}/has-path",
Summary: "Check if backup contains path",
Tags: []string{"Volume Backup"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesBrowse, h.BackupHasPath)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -597,10 +524,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/backups/{backupId}/files",
Summary: "List files in a volume backup",
Tags: []string{"Volume Backup"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVolumesBrowse, h.ListBackupFiles)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -609,10 +533,7 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
Path: "/environments/{id}/volumes/{volumeName}/backups/upload",
Summary: "Upload and restore volume backup",
Tags: []string{"Volume Backup"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
RequestBody: &huma.RequestBody{
Content: map[string]*huma.MediaType{
"multipart/form-data": {
@@ -635,10 +556,6 @@ func RegisterVolumes(api huma.API, dockerService *services.DockerClientService,
// ListVolumes returns a paginated list of volumes.
func (h *VolumeHandler) ListVolumes(ctx context.Context, input *ListVolumesInput) (*ListVolumesOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.InUse != "" {
params.Filters["inUse"] = input.InUse
@@ -658,7 +575,7 @@ func (h *VolumeHandler) ListVolumes(ctx context.Context, input *ListVolumesInput
}
return &ListVolumesOutput{
- Body: VolumePaginatedResponse{
+ Body: base.PaginatedWithCounts[volumetypes.Volume, VolumeUsageCountsData]{
Success: true,
Data: volumes,
Counts: VolumeUsageCountsData{
@@ -673,10 +590,6 @@ func (h *VolumeHandler) ListVolumes(ctx context.Context, input *ListVolumesInput
// GetVolume returns a volume by name.
func (h *VolumeHandler) GetVolume(ctx context.Context, input *GetVolumeInput) (*GetVolumeOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
vol, err := h.volumeService.GetVolumeByName(ctx, input.VolumeName)
if err != nil {
return nil, huma.Error404NotFound((&common.VolumeNotFoundError{Err: err}).Error())
@@ -692,10 +605,6 @@ func (h *VolumeHandler) GetVolume(ctx context.Context, input *GetVolumeInput) (*
// CreateVolume creates a new Docker volume.
func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInput) (*CreateVolumeOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -744,10 +653,6 @@ func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInp
// RemoveVolume removes a Docker volume.
func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInput) (*RemoveVolumeOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -788,10 +693,6 @@ func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInp
// PruneVolumes removes all unused Docker volumes.
func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInput) (*PruneVolumesOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
var report *volumetypes.PruneReport
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
@@ -825,10 +726,6 @@ func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInp
// GetVolumeUsage returns containers using a specific volume.
func (h *VolumeHandler) GetVolumeUsage(ctx context.Context, input *GetVolumeUsageInput) (*GetVolumeUsageOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
inUse, containers, err := h.volumeService.GetVolumeUsage(ctx, input.VolumeName)
if err != nil {
return nil, huma.Error500InternalServerError((&common.VolumeUsageError{Err: err}).Error())
@@ -847,10 +744,6 @@ func (h *VolumeHandler) GetVolumeUsage(ctx context.Context, input *GetVolumeUsag
// GetVolumeUsageCounts returns counts of volumes by usage status.
func (h *VolumeHandler) GetVolumeUsageCounts(ctx context.Context, input *GetVolumeUsageCountsInput) (*GetVolumeUsageCountsOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
_, _, counts, err := h.volumeService.ListVolumesPaginated(ctx, pagination.QueryParams{}, input.IncludeInternal)
if err != nil {
return nil, huma.Error500InternalServerError((&common.VolumeCountsError{Err: err}).Error())
@@ -871,10 +764,6 @@ func (h *VolumeHandler) GetVolumeUsageCounts(ctx context.Context, input *GetVolu
// GetVolumeSizes returns disk usage sizes for all volumes.
// This is a slow operation as it requires calculating disk usage.
func (h *VolumeHandler) GetVolumeSizes(ctx context.Context, input *GetVolumeSizesInput) (*GetVolumeSizesOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
sizes, err := h.volumeService.GetVolumeSizes(ctx)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -900,9 +789,6 @@ func (h *VolumeHandler) GetVolumeSizes(ctx context.Context, input *GetVolumeSize
// --- Volume Browser Handler Methods ---
func (h *VolumeHandler) BrowseDirectory(ctx context.Context, input *BrowseDirectoryInput) (*BrowseDirectoryOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
entries, err := h.volumeService.ListDirectory(ctx, input.VolumeName, input.Path)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -916,9 +802,6 @@ func (h *VolumeHandler) BrowseDirectory(ctx context.Context, input *BrowseDirect
}
func (h *VolumeHandler) GetFileContent(ctx context.Context, input *GetFileContentInput) (*GetFileContentOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
content, mimeType, err := h.volumeService.GetFileContent(ctx, input.VolumeName, input.Path, input.MaxBytes)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -935,9 +818,6 @@ func (h *VolumeHandler) GetFileContent(ctx context.Context, input *GetFileConten
}
func (h *VolumeHandler) DownloadFile(ctx context.Context, input *DownloadFileInput) (*huma.StreamResponse, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
reader, size, err := h.volumeService.DownloadFile(ctx, input.VolumeName, input.Path)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -958,18 +838,9 @@ func (h *VolumeHandler) DownloadFile(ctx context.Context, input *DownloadFileInp
}
func (h *VolumeHandler) UploadFile(ctx context.Context, input *UploadFileInput) (*base.ApiResponse[base.MessageResponse], error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
- files := input.RawBody.File["file"]
- if len(files) == 0 {
- return nil, huma.Error400BadRequest((&common.NoFileUploadedError{}).Error())
- }
-
- fileHeader := files[0]
- file, err := fileHeader.Open()
+ file, fileHeader, err := openUploadedFileInternal(input.RawBody)
if err != nil {
- return nil, huma.Error500InternalServerError((&common.FileUploadReadError{Err: err}).Error())
+ return nil, err
}
defer func() { _ = file.Close() }()
@@ -1035,9 +906,6 @@ type volumePathActivityConfigInternal struct {
}
func (h *VolumeHandler) runVolumePathActivityInternal(ctx context.Context, environmentID, volumeName, volumePath string, cfg volumePathActivityConfigInternal) (*base.ApiResponse[base.MessageResponse], error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
user, _ := humamw.GetCurrentUserFromContext(ctx)
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
@@ -1069,10 +937,6 @@ func (h *VolumeHandler) runVolumePathActivityInternal(ctx context.Context, envir
// --- Volume Backup Handler Methods ---
func (h *VolumeHandler) ListBackups(ctx context.Context, input *ListBackupsInput) (*ListBackupsOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := pagination.QueryParams{
SearchQuery: pagination.SearchQuery{
Search: input.Search,
@@ -1114,9 +978,6 @@ func (h *VolumeHandler) ListBackups(ctx context.Context, input *ListBackupsInput
}
func (h *VolumeHandler) CreateBackup(ctx context.Context, input *CreateBackupInput) (*CreateBackupOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -1153,9 +1014,6 @@ func (h *VolumeHandler) CreateBackup(ctx context.Context, input *CreateBackupInp
}
func (h *VolumeHandler) RestoreBackup(ctx context.Context, input *RestoreBackupInput) (*RestoreBackupOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -1191,10 +1049,6 @@ func (h *VolumeHandler) RestoreBackup(ctx context.Context, input *RestoreBackupI
}
func (h *VolumeHandler) RestoreBackupFiles(ctx context.Context, input *RestoreBackupFilesInput) (*RestoreBackupFilesOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -1236,10 +1090,6 @@ func (h *VolumeHandler) RestoreBackupFiles(ctx context.Context, input *RestoreBa
}
func (h *VolumeHandler) BackupHasPath(ctx context.Context, input *BackupHasPathInput) (*BackupHasPathOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if input.Path == "" {
return nil, huma.Error400BadRequest("path is required")
}
@@ -1258,10 +1108,6 @@ func (h *VolumeHandler) BackupHasPath(ctx context.Context, input *BackupHasPathI
}
func (h *VolumeHandler) ListBackupFiles(ctx context.Context, input *ListBackupFilesInput) (*ListBackupFilesOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
files, err := h.volumeService.ListBackupFiles(ctx, input.BackupID)
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
@@ -1276,9 +1122,6 @@ func (h *VolumeHandler) ListBackupFiles(ctx context.Context, input *ListBackupFi
}
func (h *VolumeHandler) DeleteBackup(ctx context.Context, input *DeleteBackupInput) (*DeleteBackupOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
user, _ := humamw.GetCurrentUserFromContext(ctx)
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
@@ -1310,9 +1153,6 @@ func (h *VolumeHandler) DeleteBackup(ctx context.Context, input *DeleteBackupInp
}
func (h *VolumeHandler) DownloadBackup(ctx context.Context, input *DownloadBackupInput) (*huma.StreamResponse, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
user, _ := humamw.GetCurrentUserFromContext(ctx)
reader, size, err := h.volumeService.DownloadBackup(ctx, input.BackupID, user)
if err != nil {
@@ -1334,23 +1174,14 @@ func (h *VolumeHandler) DownloadBackup(ctx context.Context, input *DownloadBacku
}
func (h *VolumeHandler) UploadAndRestore(ctx context.Context, input *UploadAndRestoreInput) (*UploadAndRestoreOutput, error) {
- if h.volumeService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
}
- files := input.RawBody.File["file"]
- if len(files) == 0 {
- return nil, huma.Error400BadRequest((&common.NoFileUploadedError{}).Error())
- }
-
- fileHeader := files[0]
- file, err := fileHeader.Open()
+ file, fileHeader, err := openUploadedFileInternal(input.RawBody)
if err != nil {
- return nil, huma.Error500InternalServerError((&common.FileUploadReadError{Err: err}).Error())
+ return nil, err
}
defer func() { _ = file.Close() }()
diff --git a/backend/api/handlers/vulnerabilities.go b/backend/api/handlers/vulnerabilities.go
index ba00851b5..20200b9af 100644
--- a/backend/api/handlers/vulnerabilities.go
+++ b/backend/api/handlers/vulnerabilities.go
@@ -137,10 +137,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
Summary: "Scan image for vulnerabilities",
Description: "Initiates a vulnerability scan for the specified image using Trivy",
Tags: []string{"Vulnerabilities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVulnsScan, h.ScanImage)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -150,10 +147,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
Summary: "Get vulnerability scan result",
Description: "Retrieves the most recent vulnerability scan result for an image",
Tags: []string{"Vulnerabilities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVulnsRead, h.GetScanResult)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -163,10 +157,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
Summary: "Get vulnerability scan summary",
Description: "Retrieves just the summary of vulnerabilities for an image (for list views)",
Tags: []string{"Vulnerabilities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVulnsRead, h.GetScanSummary)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -176,10 +167,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
Summary: "Get vulnerability scan summaries",
Description: "Retrieves scan summaries for a list of images (batch)",
Tags: []string{"Vulnerabilities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVulnsRead, h.GetScanSummaries)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -189,10 +177,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
Summary: "List image vulnerabilities",
Description: "Retrieves paginated vulnerabilities for an image",
Tags: []string{"Vulnerabilities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVulnsRead, h.ListImageVulnerabilities)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -202,10 +187,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
Summary: "Get vulnerability scanner status",
Description: "Check if the vulnerability scanner (Trivy) is available and get its version",
Tags: []string{"Vulnerabilities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVulnsRead, h.GetScannerStatus)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -215,10 +197,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
Summary: "Get environment vulnerability summary",
Description: "Retrieves aggregated vulnerability counts across all images in the environment",
Tags: []string{"Vulnerabilities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVulnsRead, h.GetEnvironmentSummary)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -228,10 +207,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
Summary: "List environment vulnerabilities",
Description: "Retrieves paginated vulnerabilities across all scanned images in the environment",
Tags: []string{"Vulnerabilities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVulnsRead, h.ListAllVulnerabilities)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -241,10 +217,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
Summary: "List vulnerability image options",
Description: "Retrieves available image filter options for environment vulnerabilities",
Tags: []string{"Vulnerabilities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVulnsRead, h.ListAllVulnerabilityImageOptions)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -254,10 +227,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
Summary: "Ignore a vulnerability",
Description: "Creates an ignore record for a specific vulnerability",
Tags: []string{"Vulnerabilities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVulnsManage, h.IgnoreVulnerability)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -267,10 +237,7 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
Summary: "Unignore a vulnerability",
Description: "Removes an ignore record for a vulnerability",
Tags: []string{"Vulnerabilities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVulnsManage, h.UnignoreVulnerability)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -280,19 +247,12 @@ func RegisterVulnerability(api huma.API, vulnerabilityService *services.Vulnerab
Summary: "List ignored vulnerabilities",
Description: "Retrieves a list of all ignored vulnerabilities for the environment",
Tags: []string{"Vulnerabilities"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermVulnsRead, h.ListIgnoredVulnerabilities)
}
// ScanImage initiates a vulnerability scan for an image.
func (h *VulnerabilityHandler) ScanImage(ctx context.Context, input *ScanImageInput) (*ScanImageOutput, error) {
- if h.vulnerabilityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -314,10 +274,6 @@ func (h *VulnerabilityHandler) ScanImage(ctx context.Context, input *ScanImageIn
// GetScanSummaries retrieves scan summaries for a list of image IDs.
func (h *VulnerabilityHandler) GetScanSummaries(ctx context.Context, input *GetScanSummariesInput) (*GetScanSummariesOutput, error) {
- if h.vulnerabilityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
imageIDs := input.Body.ImageIDs
if len(imageIDs) == 0 {
return &GetScanSummariesOutput{
@@ -347,10 +303,6 @@ func (h *VulnerabilityHandler) GetScanSummaries(ctx context.Context, input *GetS
// GetScanResult retrieves the vulnerability scan result for an image.
func (h *VulnerabilityHandler) GetScanResult(ctx context.Context, input *GetScanResultInput) (*GetScanResultOutput, error) {
- if h.vulnerabilityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
result, err := h.vulnerabilityService.GetScanResult(ctx, input.ImageID)
if err != nil {
return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())
@@ -370,10 +322,6 @@ func (h *VulnerabilityHandler) GetScanResult(ctx context.Context, input *GetScan
// GetScanSummary retrieves just the vulnerability summary for an image.
func (h *VulnerabilityHandler) GetScanSummary(ctx context.Context, input *GetScanSummaryInput) (*GetScanSummaryOutput, error) {
- if h.vulnerabilityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
summary, err := h.vulnerabilityService.GetScanSummary(ctx, input.ImageID)
if err != nil {
return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())
@@ -393,10 +341,6 @@ func (h *VulnerabilityHandler) GetScanSummary(ctx context.Context, input *GetSca
// ListImageVulnerabilities returns a paginated list of vulnerabilities for an image.
func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, input *ListImageVulnerabilitiesInput) (*ListImageVulnerabilitiesOutput, error) {
- if h.vulnerabilityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if params.Limit == 0 {
params.Limit = 20
@@ -425,10 +369,6 @@ func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, inp
// GetEnvironmentSummary returns aggregated vulnerability info for the current environment.
func (h *VulnerabilityHandler) GetEnvironmentSummary(ctx context.Context, input *GetEnvironmentSummaryInput) (*GetEnvironmentSummaryOutput, error) {
- if h.vulnerabilityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
summary, err := h.vulnerabilityService.GetEnvironmentSummary(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())
@@ -448,10 +388,6 @@ func (h *VulnerabilityHandler) GetEnvironmentSummary(ctx context.Context, input
// ListAllVulnerabilities returns a paginated list of vulnerabilities across all images.
func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, input *ListAllVulnerabilitiesInput) (*ListAllVulnerabilitiesOutput, error) {
- if h.vulnerabilityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if params.Limit == 0 {
params.Limit = 20
@@ -483,10 +419,6 @@ func (h *VulnerabilityHandler) ListAllVulnerabilities(ctx context.Context, input
// ListAllVulnerabilityImageOptions returns available image options for vulnerability filtering.
func (h *VulnerabilityHandler) ListAllVulnerabilityImageOptions(ctx context.Context, input *ListAllVulnerabilityImageOptionsInput) (*ListAllVulnerabilityImageOptionsOutput, error) {
- if h.vulnerabilityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
items, err := h.vulnerabilityService.ListAllVulnerabilityImageOptions(ctx, input.Severity)
if err != nil {
return nil, huma.Error500InternalServerError((&common.VulnerabilityScanRetrievalError{Err: err}).Error())
@@ -506,10 +438,6 @@ func (h *VulnerabilityHandler) ListAllVulnerabilityImageOptions(ctx context.Cont
// GetScannerStatus checks if the vulnerability scanner is available.
func (h *VulnerabilityHandler) GetScannerStatus(ctx context.Context, input *GetScannerStatusInput) (*GetScannerStatusOutput, error) {
- if h.vulnerabilityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
version := h.vulnerabilityService.GetTrivyVersion(ctx)
available := version != ""
@@ -535,10 +463,6 @@ type IgnoreVulnerabilityOutput struct {
// IgnoreVulnerability creates an ignore record for a vulnerability.
func (h *VulnerabilityHandler) IgnoreVulnerability(ctx context.Context, input *IgnoreVulnerabilityInput) (*IgnoreVulnerabilityOutput, error) {
- if h.vulnerabilityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
user, err := requireUserInternal(ctx)
if err != nil {
return nil, err
@@ -584,10 +508,6 @@ type UnignoreVulnerabilityOutput struct {
// UnignoreVulnerability removes an ignore record for a vulnerability.
func (h *VulnerabilityHandler) UnignoreVulnerability(ctx context.Context, input *UnignoreVulnerabilityInput) (*UnignoreVulnerabilityOutput, error) {
- if h.vulnerabilityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
if err := h.vulnerabilityService.UnignoreVulnerability(ctx, input.EnvironmentID, input.IgnoreID); err != nil {
if err.Error() == "ignore record not found" {
return nil, huma.Error404NotFound(err.Error())
@@ -617,10 +537,6 @@ type ListIgnoredVulnerabilitiesOutput struct {
// ListIgnoredVulnerabilities returns a list of ignored vulnerabilities.
func (h *VulnerabilityHandler) ListIgnoredVulnerabilities(ctx context.Context, input *ListIgnoredVulnerabilitiesInput) (*ListIgnoredVulnerabilitiesOutput, error) {
- if h.vulnerabilityService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
params := buildPaginationParamsInternal(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if params.Limit == 0 {
params.Limit = 20
diff --git a/backend/api/handlers/webhooks.go b/backend/api/handlers/webhooks.go
index db295d714..7ea79c70d 100644
--- a/backend/api/handlers/webhooks.go
+++ b/backend/api/handlers/webhooks.go
@@ -67,10 +67,7 @@ func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {
Summary: "List webhooks",
Description: "List all webhooks configured for this environment",
Tags: []string{"Webhooks"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermWebhooksList, h.ListWebhooks)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -80,10 +77,7 @@ func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {
Summary: "Create webhook",
Description: "Create a webhook that triggers a container or stack update. The token is only returned once.",
Tags: []string{"Webhooks"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermWebhooksCreate, h.CreateWebhook)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -93,10 +87,7 @@ func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {
Summary: "Update webhook",
Description: "Update a webhook's enabled state",
Tags: []string{"Webhooks"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermWebhooksUpdate, h.UpdateWebhook)
humamw.RegisterWithPermission(api, huma.Operation{
@@ -106,19 +97,12 @@ func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {
Summary: "Delete webhook",
Description: "Delete a webhook by ID",
Tags: []string{"Webhooks"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
+ Security: defaultOperationSecurityInternal(),
}, authz.PermWebhooksDelete, h.DeleteWebhook)
}
// ListWebhooks returns all webhooks for an environment (tokens are masked).
func (h *WebhookHandler) ListWebhooks(ctx context.Context, input *ListWebhooksInput) (*ListWebhooksOutput, error) {
- if h.webhookService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
webhooks, err := h.webhookService.ListWebhookSummaries(ctx, input.EnvironmentID)
if err != nil {
return nil, huma.Error500InternalServerError("failed to list webhooks")
@@ -134,9 +118,6 @@ func (h *WebhookHandler) ListWebhooks(ctx context.Context, input *ListWebhooksIn
// CreateWebhook creates a new webhook and returns the raw token (shown once only).
func (h *WebhookHandler) CreateWebhook(ctx context.Context, input *CreateWebhookInput) (*CreateWebhookOutput, error) {
- if h.webhookService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if input.Body == nil {
return nil, huma.Error400BadRequest("request body is required")
}
@@ -186,9 +167,6 @@ func (h *WebhookHandler) CreateWebhook(ctx context.Context, input *CreateWebhook
// UpdateWebhook updates a webhook's enabled state.
func (h *WebhookHandler) UpdateWebhook(ctx context.Context, input *UpdateWebhookInput) (*UpdateWebhookOutput, error) {
- if h.webhookService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
if input.Body == nil {
return nil, huma.Error400BadRequest("request body is required")
}
@@ -214,10 +192,6 @@ func (h *WebhookHandler) UpdateWebhook(ctx context.Context, input *UpdateWebhook
// DeleteWebhook removes a webhook.
func (h *WebhookHandler) DeleteWebhook(ctx context.Context, input *DeleteWebhookInput) (*DeleteWebhookOutput, error) {
- if h.webhookService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
actor := models.User{}
if currentUser, exists := humamw.GetCurrentUserFromContext(ctx); exists && currentUser != nil {
actor = *currentUser
diff --git a/backend/api/middleware/role.go b/backend/api/middleware/role.go
index 8a6aeca09..603fa7ff1 100644
--- a/backend/api/middleware/role.go
+++ b/backend/api/middleware/role.go
@@ -95,3 +95,19 @@ func RequireGlobalAdmin(api huma.API) huma.Middlewares {
next(ctx)
}}
}
+
+// RequireSudo restricts infrastructure-only operations to callers authenticated
+// through the agent-token path. Holding every user-facing permission is not
+// sufficient because these operations may expose materialized secret values.
+func RequireSudo(api huma.API) huma.Middlewares {
+ return huma.Middlewares{func(ctx huma.Context, next func(huma.Context)) {
+ ps, _ := PermissionsFromContext(ctx.Context())
+ if ps == nil || !ps.Sudo {
+ if err := huma.WriteErr(api, ctx, http.StatusForbidden, "permission denied: agent authentication required"); err != nil {
+ slog.WarnContext(ctx.Context(), "failed to write 403 response", "error", err)
+ }
+ return
+ }
+ next(ctx)
+ }}
+}
diff --git a/backend/api/middleware/role_test.go b/backend/api/middleware/role_test.go
index 8b18d9e6d..f56342489 100644
--- a/backend/api/middleware/role_test.go
+++ b/backend/api/middleware/role_test.go
@@ -145,6 +145,52 @@ func TestRequirePermission_SudoCallerAllowed(t *testing.T) {
require.True(t, handlerRan)
}
+func TestRequireSudoRejectsHumanAdminAndAllowsAgent(t *testing.T) {
+ tests := []struct {
+ name string
+ permission *authz.PermissionSet
+ wantStatus int
+ wantRan bool
+ }{
+ {name: "human admin", permission: func() *authz.PermissionSet {
+ ps := authz.NewPermissionSet()
+ ps.AddGlobal(authz.AllPermissions()...)
+ return ps
+ }(), wantStatus: http.StatusForbidden},
+ {name: "agent sudo", permission: authz.SudoPermissionSet(), wantStatus: http.StatusNoContent, wantRan: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ router := echo.New()
+ api := humaecho.NewWithGroup(router, router.Group("/api"), huma.DefaultConfig("test", "1.0.0"))
+ api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
+ next(huma.WithContext(ctx, context.WithValue(ctx.Context(), ContextKeyUserPermissions, tt.permission)))
+ })
+
+ handlerRan := false
+ huma.Register(api, huma.Operation{
+ OperationID: "materialized-variables-" + tt.name,
+ Method: http.MethodGet,
+ Path: "/environments/{id}/templates/variables",
+ Middlewares: RequireSudo(api),
+ }, func(_ context.Context, _ *struct {
+ ID string `path:"id"`
+ }) (*struct{}, error) {
+ handlerRan = true
+ return &struct{}{}, nil
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/0/templates/variables", nil)
+ rec := httptest.NewRecorder()
+ router.ServeHTTP(rec, req)
+
+ require.Equal(t, tt.wantStatus, rec.Code)
+ require.Equal(t, tt.wantRan, handlerRan)
+ })
+ }
+}
+
func TestRequireAnyEnvironmentPermission(t *testing.T) {
tests := []struct {
name string
diff --git a/backend/api/ws/handler.go b/backend/api/ws/handler.go
index f8998848a..87f63a771 100644
--- a/backend/api/ws/handler.go
+++ b/backend/api/ws/handler.go
@@ -367,7 +367,16 @@ func (h *WebSocketHandler) ProjectLogs(c echo.Context) error {
params := parseLogStreamParamsInternal(c)
h.serveLogStreamInternal(c, systemtypes.WSKindProjectLogs, projectID, params, func(streamKey string, onEmpty func(*wsLogStream)) *wsLogStream {
- return h.startProjectLogHub(streamKey, projectID, params.format, params.batched, params.follow, params.tail, params.since, params.timestamps, onEmpty)
+ return h.startLogHubInternal(
+ streamKey,
+ projectID,
+ "project",
+ params,
+ h.streamProjectLogsInternal,
+ normalizeProjectLogMessageInternal,
+ normalizeProjectLogTextInternal,
+ onEmpty,
+ )
})
return nil
}
@@ -391,22 +400,85 @@ func newWSLogStreamInternal(key, format string) (*wsLogStream, context.Context)
return ls, ctx
}
-func (h *WebSocketHandler) startProjectLogSourceInternal(ctx context.Context, key, projectID, format string, follow bool, tail, since string, timestamps bool, ls *wsLogStream) <-chan string {
- lines := make(chan string, 256)
+func waitForLogStreamSubscriberInternal(ctx context.Context, firstSubscriber <-chan struct{}) bool {
+ for {
+ select {
+ case <-ctx.Done():
+ return false
+ case <-firstSubscriber:
+ return true
+ }
+ }
+}
+
+func normalizeProjectLogMessageInternal(line string) wshub.LogMessage {
+ level, service, message, timestamp := wshub.NormalizeProjectLine(line)
+ return wshub.LogMessage{
+ Level: level,
+ Message: message,
+ Service: service,
+ Timestamp: timestamp,
+ }
+}
+
+func normalizeContainerLogMessageInternal(line string) wshub.LogMessage {
+ level, message, timestamp := wshub.NormalizeContainerLine(line)
+ return wshub.LogMessage{
+ Level: level,
+ Message: message,
+ Timestamp: timestamp,
+ }
+}
+
+func normalizeProjectLogTextInternal(line string) string {
+ _, _, message, _ := wshub.NormalizeProjectLine(line)
+ return message
+}
+
+func (h *WebSocketHandler) startLogHubInternal(
+ key, resourceID, label string,
+ params logStreamParams,
+ stream func(context.Context, string, chan<- string, bool, string, string, bool) error,
+ normalizeJSON func(string) wshub.LogMessage,
+ normalizeText func(string) string,
+ onEmptyHook func(*wsLogStream),
+) *wsLogStream {
+ ls, ctx := newWSLogStreamInternal(key, params.format)
+ ls.hub.SetOnEmpty(func() {
+ if onEmptyHook != nil {
+ onEmptyHook(ls)
+ }
+ slog.Debug("client disconnected, cleaning up "+label+" log hub", label+"ID", resourceID)
+ })
+
+ lines := h.startLogSourceInternal(ctx, key, resourceID, label, params, stream, ls)
+ startLogForwardersInternal(ctx, ls, lines, params, normalizeJSON, normalizeText)
+
+ return ls
+}
+
+func (h *WebSocketHandler) startLogSourceInternal(
+ ctx context.Context,
+ key, resourceID, label string,
+ params logStreamParams,
+ stream func(context.Context, string, chan<- string, bool, string, string, bool) error,
+ ls *wsLogStream,
+) <-chan string {
+ lines := make(chan string, 256)
go func() {
defer close(lines)
if !waitForLogStreamSubscriberInternal(ctx, ls.firstSubscriber) {
return
}
- if err := h.streamProjectLogsInternal(ctx, projectID, lines, follow, tail, since, timestamps); err != nil {
+ if err := stream(ctx, resourceID, lines, params.follow, params.tail, params.since, params.timestamps); err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return
}
h.markLogStreamDoneInternal(key, ls)
- h.broadcastProjectLogStreamErrorInternal(projectID, format, err, ls)
+ broadcastLogStreamErrorInternal(label+" log stream", "Failed to stream "+label+" logs: ", resourceID, params.format, err, ls)
return
}
@@ -418,86 +490,63 @@ func (h *WebSocketHandler) startProjectLogSourceInternal(ctx context.Context, ke
return lines
}
-func waitForLogStreamSubscriberInternal(ctx context.Context, firstSubscriber <-chan struct{}) bool {
- for {
- select {
- case <-ctx.Done():
- return false
- case <-firstSubscriber:
- return true
- }
- }
-}
-
-func (h *WebSocketHandler) broadcastProjectLogStreamErrorInternal(projectID, format string, err error, ls *wsLogStream) {
- broadcastLogStreamErrorInternal("project log stream", "Failed to stream project logs: ", projectID, format, err, ls)
-}
-
-func startProjectLogForwardersInternal(ctx context.Context, format string, batched bool, lines <-chan string, ls *wsLogStream) {
- if format == "json" {
- startProjectJSONForwarderInternal(ctx, batched, lines, ls)
- return
- }
-
- startProjectTextForwarderInternal(ctx, lines, ls)
-}
-
-func startProjectJSONForwarderInternal(ctx context.Context, batched bool, lines <-chan string, ls *wsLogStream) {
- msgs := make(chan wshub.LogMessage, 256)
- go func() {
- defer close(msgs)
- for line := range lines {
- level, service, msg, ts := wshub.NormalizeProjectLine(line)
- seq := ls.seq.Add(1)
- timestamp := ts
- if timestamp == "" {
- timestamp = wshub.NowRFC3339()
- }
- msgs <- wshub.LogMessage{
- Seq: seq,
- Level: level,
- Message: msg,
- Service: service,
- Timestamp: timestamp,
+func startLogForwardersInternal(
+ ctx context.Context,
+ ls *wsLogStream,
+ lines <-chan string,
+ params logStreamParams,
+ normalizeJSON func(string) wshub.LogMessage,
+ normalizeText func(string) string,
+) {
+ if params.format == "json" {
+ messages := mapLogLinesInternal(ctx, lines, func(line string) wshub.LogMessage {
+ message := normalizeJSON(line)
+ message.Seq = ls.seq.Add(1)
+ if message.Timestamp == "" {
+ message.Timestamp = wshub.NowRFC3339()
}
+ return message
+ })
+
+ if params.batched {
+ go wshub.ForwardLogJSONBatched(ctx, ls.hub, messages, 50, 400*time.Millisecond)
+ } else {
+ go wshub.ForwardLogJSON(ctx, ls.hub, messages)
}
- }()
- if batched {
- go wshub.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
return
}
- go wshub.ForwardLogJSON(ctx, ls.hub, msgs)
+ textLines := lines
+ if normalizeText != nil {
+ textLines = mapLogLinesInternal(ctx, lines, normalizeText)
+ }
+ go wshub.ForwardLines(ctx, ls.hub, textLines)
}
-func startProjectTextForwarderInternal(ctx context.Context, lines <-chan string, ls *wsLogStream) {
- cleanChan := make(chan string, 256)
+func mapLogLinesInternal[T any](ctx context.Context, lines <-chan string, transform func(string) T) <-chan T {
+ mapped := make(chan T, 256)
go func() {
- defer close(cleanChan)
- for line := range lines {
- _, _, msg, _ := wshub.NormalizeProjectLine(line)
- cleanChan <- msg
+ defer close(mapped)
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case line, ok := <-lines:
+ if !ok {
+ return
+ }
+
+ select {
+ case <-ctx.Done():
+ return
+ case mapped <- transform(line):
+ }
+ }
}
}()
- go wshub.ForwardLines(ctx, ls.hub, cleanChan)
-}
-
-func (h *WebSocketHandler) startProjectLogHub(key, projectID, format string, batched, follow bool, tail, since string, timestamps bool, onEmptyHook func(*wsLogStream)) *wsLogStream {
- ls, ctx := newWSLogStreamInternal(key, format)
-
- ls.hub.SetOnEmpty(func() {
- if onEmptyHook != nil {
- onEmptyHook(ls)
- }
- slog.Debug("client disconnected, cleaning up project log hub", "projectID", projectID)
- })
-
- lines := h.startProjectLogSourceInternal(ctx, key, projectID, format, follow, tail, since, timestamps, ls)
- startProjectLogForwardersInternal(ctx, format, batched, lines, ls)
-
- return ls
+ return mapped
}
// ============================================================================
@@ -526,78 +575,20 @@ func (h *WebSocketHandler) ContainerLogs(c echo.Context) error {
params := parseLogStreamParamsInternal(c)
h.serveLogStreamInternal(c, systemtypes.WSKindContainerLogs, containerID, params, func(streamKey string, onEmpty func(*wsLogStream)) *wsLogStream {
- return h.startContainerLogHub(streamKey, containerID, params.format, params.batched, params.follow, params.tail, params.since, params.timestamps, onEmpty)
+ return h.startLogHubInternal(
+ streamKey,
+ containerID,
+ "container",
+ params,
+ h.streamContainerLogsInternal,
+ normalizeContainerLogMessageInternal,
+ nil,
+ onEmpty,
+ )
})
return nil
}
-func (h *WebSocketHandler) startContainerLogHub(key, containerID, format string, batched, follow bool, tail, since string, timestamps bool, onEmptyHook func(*wsLogStream)) *wsLogStream {
- ls, ctx := newWSLogStreamInternal(key, format)
-
- ls.hub.SetOnEmpty(func() {
- if onEmptyHook != nil {
- onEmptyHook(ls)
- }
- slog.Debug("client disconnected, cleaning up container log hub", "containerID", containerID)
- })
-
- lines := make(chan string, 256)
- go func(ctx context.Context) {
- defer close(lines)
- if !waitForLogStreamSubscriberInternal(ctx, ls.firstSubscriber) {
- return
- }
-
- if err := h.streamContainerLogsInternal(ctx, containerID, lines, follow, tail, since, timestamps); err != nil {
- if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
- return
- }
-
- h.markLogStreamDoneInternal(key, ls)
- h.broadcastContainerLogStreamErrorInternal(containerID, format, err, ls)
- return
- }
-
- if ctx.Err() == nil {
- h.markLogStreamDoneInternal(key, ls)
- }
- }(ctx)
-
- if format == "json" {
- msgs := make(chan wshub.LogMessage, 256)
- go func() {
- defer close(msgs)
- for line := range lines {
- level, msg, ts := wshub.NormalizeContainerLine(line)
- seq := ls.seq.Add(1)
- timestamp := ts
- if timestamp == "" {
- timestamp = wshub.NowRFC3339()
- }
- msgs <- wshub.LogMessage{
- Seq: seq,
- Level: level,
- Message: msg,
- Timestamp: timestamp,
- }
- }
- }()
- if batched {
- go wshub.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
- } else {
- go wshub.ForwardLogJSON(ctx, ls.hub, msgs)
- }
- } else {
- go wshub.ForwardLines(ctx, ls.hub, lines)
- }
-
- return ls
-}
-
-func (h *WebSocketHandler) broadcastContainerLogStreamErrorInternal(containerID, format string, err error, ls *wsLogStream) {
- broadcastLogStreamErrorInternal("container log stream", "Failed to stream container logs: ", containerID, format, err, ls)
-}
-
// ============================================================================
// Swarm Service WebSocket/Streaming Endpoints
// ============================================================================
@@ -624,78 +615,20 @@ func (h *WebSocketHandler) ServiceLogs(c echo.Context) error {
params := parseLogStreamParamsInternal(c)
h.serveLogStreamInternal(c, systemtypes.WSKindServiceLogs, serviceID, params, func(streamKey string, onEmpty func(*wsLogStream)) *wsLogStream {
- return h.startServiceLogHub(streamKey, serviceID, params.format, params.batched, params.follow, params.tail, params.since, params.timestamps, onEmpty)
+ return h.startLogHubInternal(
+ streamKey,
+ serviceID,
+ "service",
+ params,
+ h.swarmService.StreamServiceLogs,
+ normalizeContainerLogMessageInternal,
+ nil,
+ onEmpty,
+ )
})
return nil
}
-func (h *WebSocketHandler) startServiceLogHub(key, serviceID, format string, batched, follow bool, tail, since string, timestamps bool, onEmptyHook func(*wsLogStream)) *wsLogStream {
- ls, ctx := newWSLogStreamInternal(key, format)
-
- ls.hub.SetOnEmpty(func() {
- if onEmptyHook != nil {
- onEmptyHook(ls)
- }
- slog.Debug("client disconnected, cleaning up service log hub", "serviceID", serviceID)
- })
-
- lines := make(chan string, 256)
- go func() {
- defer close(lines)
- if !waitForLogStreamSubscriberInternal(ctx, ls.firstSubscriber) {
- return
- }
-
- if err := h.swarmService.StreamServiceLogs(ctx, serviceID, lines, follow, tail, since, timestamps); err != nil {
- if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
- return
- }
-
- h.markLogStreamDoneInternal(key, ls)
- h.broadcastServiceLogStreamErrorInternal(serviceID, format, err, ls)
- return
- }
-
- if ctx.Err() == nil {
- h.markLogStreamDoneInternal(key, ls)
- }
- }()
-
- if format == "json" {
- msgs := make(chan wshub.LogMessage, 256)
- go func() {
- defer close(msgs)
- for line := range lines {
- level, msg, ts := wshub.NormalizeContainerLine(line)
- seq := ls.seq.Add(1)
- timestamp := ts
- if timestamp == "" {
- timestamp = wshub.NowRFC3339()
- }
- msgs <- wshub.LogMessage{
- Seq: seq,
- Level: level,
- Message: msg,
- Timestamp: timestamp,
- }
- }
- }()
- if batched {
- go wshub.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
- } else {
- go wshub.ForwardLogJSON(ctx, ls.hub, msgs)
- }
- } else {
- go wshub.ForwardLines(ctx, ls.hub, lines)
- }
-
- return ls
-}
-
-func (h *WebSocketHandler) broadcastServiceLogStreamErrorInternal(serviceID, format string, err error, ls *wsLogStream) {
- broadcastLogStreamErrorInternal("service log stream", "Failed to stream service logs: ", serviceID, format, err, ls)
-}
-
// ContainerStats streams container stats over WebSocket.
//
// @Summary Get container stats via WebSocket
diff --git a/backend/api/ws/handler_test.go b/backend/api/ws/handler_test.go
index a1d05c74c..ad46c1a9a 100644
--- a/backend/api/ws/handler_test.go
+++ b/backend/api/ws/handler_test.go
@@ -22,7 +22,7 @@ import (
"go.getarcane.app/sys/cgroup"
)
-func TestBroadcastContainerLogStreamErrorInternal_JSON(t *testing.T) {
+func TestBroadcastLogStreamErrorInternal_JSON(t *testing.T) {
hub := wshub.NewHub(10)
ctx := t.Context()
go hub.Run(ctx)
@@ -37,8 +37,7 @@ func TestBroadcastContainerLogStreamErrorInternal_JSON(t *testing.T) {
format: "json",
}
- handler := newTestWebSocketHandler()
- handler.broadcastContainerLogStreamErrorInternal("container-1", "json", errors.New("boom"), stream)
+ broadcastLogStreamErrorInternal("container log stream", "Failed to stream container logs: ", "container-1", "json", errors.New("boom"), stream)
_ = clientConn.SetReadDeadline(time.Now().Add(2 * time.Second))
_, payload, err := clientConn.ReadMessage()
@@ -52,7 +51,7 @@ func TestBroadcastContainerLogStreamErrorInternal_JSON(t *testing.T) {
require.NotEmpty(t, message.Timestamp)
}
-func TestBroadcastContainerLogStreamErrorInternal_Text(t *testing.T) {
+func TestBroadcastLogStreamErrorInternal_Text(t *testing.T) {
hub := wshub.NewHub(10)
ctx := t.Context()
go hub.Run(ctx)
@@ -67,8 +66,7 @@ func TestBroadcastContainerLogStreamErrorInternal_Text(t *testing.T) {
format: "text",
}
- handler := newTestWebSocketHandler()
- handler.broadcastContainerLogStreamErrorInternal("container-1", "text", errors.New("boom"), stream)
+ broadcastLogStreamErrorInternal("container log stream", "Failed to stream container logs: ", "container-1", "text", errors.New("boom"), stream)
_ = clientConn.SetReadDeadline(time.Now().Add(2 * time.Second))
_, payload, err := clientConn.ReadMessage()
diff --git a/backend/internal/services/build_workspace_service.go b/backend/internal/services/build_workspace_service.go
index 4225eaa64..6d9fb117b 100644
--- a/backend/internal/services/build_workspace_service.go
+++ b/backend/internal/services/build_workspace_service.go
@@ -13,6 +13,7 @@ import (
"log/slog"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"
)
@@ -34,7 +35,7 @@ func (s *BuildWorkspaceService) ListDirectory(ctx context.Context, dirPath strin
return nil, err
}
- cleaned, err := sanitizeBuildPath(dirPath)
+ cleaned, err := utils.SanitizeBrowsePath(dirPath)
if err != nil {
return nil, fmt.Errorf("invalid path: %w", err)
}
@@ -94,7 +95,7 @@ func (s *BuildWorkspaceService) GetFileContent(ctx context.Context, filePath str
return nil, "", err
}
- cleaned, err := sanitizeBuildPath(filePath)
+ cleaned, err := utils.SanitizeBrowsePath(filePath)
if err != nil {
return nil, "", fmt.Errorf("invalid path: %w", err)
}
@@ -138,7 +139,7 @@ func (s *BuildWorkspaceService) DownloadFile(ctx context.Context, filePath strin
return nil, 0, err
}
- cleaned, err := sanitizeBuildPath(filePath)
+ cleaned, err := utils.SanitizeBrowsePath(filePath)
if err != nil {
return nil, 0, fmt.Errorf("invalid path: %w", err)
}
@@ -176,7 +177,7 @@ func (s *BuildWorkspaceService) UploadFile(ctx context.Context, destPath string,
return err
}
- cleaned, err := sanitizeBuildPath(destPath)
+ cleaned, err := utils.SanitizeBrowsePath(destPath)
if err != nil {
return fmt.Errorf("invalid path: %w", err)
}
@@ -211,7 +212,7 @@ func (s *BuildWorkspaceService) CreateDirectory(ctx context.Context, dirPath str
return err
}
- cleaned, err := sanitizeBuildPath(dirPath)
+ cleaned, err := utils.SanitizeBrowsePath(dirPath)
if err != nil {
return fmt.Errorf("invalid path: %w", err)
}
@@ -239,7 +240,7 @@ func (s *BuildWorkspaceService) DeleteFile(ctx context.Context, filePath string)
return err
}
- cleaned, err := sanitizeBuildPath(filePath)
+ cleaned, err := utils.SanitizeBrowsePath(filePath)
if err != nil {
return fmt.Errorf("invalid path: %w", err)
}
@@ -282,26 +283,6 @@ func (s *BuildWorkspaceService) resolveRoot() (string, error) {
return cleaned, nil
}
-func sanitizeBuildPath(input string) (string, error) {
- trimmed := strings.TrimSpace(input)
- if trimmed == "" || trimmed == "/" {
- return "/", nil
- }
-
- cleaned := path.Clean(trimmed)
- if !path.IsAbs(cleaned) {
- cleaned = "/" + cleaned
- }
- if strings.Contains(cleaned, "/../") || strings.HasSuffix(cleaned, "/..") || cleaned == "/.." {
- return "", errors.New("invalid path: path traversal not allowed")
- }
- if !strings.HasPrefix(cleaned, "/") {
- return "", errors.New("invalid path: must be absolute")
- }
-
- return cleaned, nil
-}
-
func sanitizeUploadFilename(filename string) (string, error) {
name := strings.TrimSpace(filename)
if name == "" {
diff --git a/backend/internal/services/image_service.go b/backend/internal/services/image_service.go
index 42656f654..290a82844 100644
--- a/backend/internal/services/image_service.go
+++ b/backend/internal/services/image_service.go
@@ -17,6 +17,7 @@ import (
dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
utilsregistry "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth"
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"github.com/getarcaneapp/arcane/types/v2/containerregistry"
imagetypes "github.com/getarcaneapp/arcane/types/v2/image"
systemtypes "github.com/getarcaneapp/arcane/types/v2/system"
@@ -1081,27 +1082,20 @@ func determineRepoAndTag(di image.Summary) (repo, tag string) {
return "<none>", "<none>"
}
-func stringPtrValue(p *string) string {
- if p == nil {
- return ""
- }
- return *p
-}
-
func buildUpdateInfo(updateRecord *models.ImageUpdateRecord) *imagetypes.UpdateInfo {
return &imagetypes.UpdateInfo{
HasUpdate: updateRecord.HasUpdate,
UpdateType: updateRecord.UpdateType,
CurrentVersion: updateRecord.CurrentVersion,
- LatestVersion: stringPtrValue(updateRecord.LatestVersion),
- CurrentDigest: stringPtrValue(updateRecord.CurrentDigest),
- LatestDigest: stringPtrValue(updateRecord.LatestDigest),
+ LatestVersion: utils.DerefString(updateRecord.LatestVersion),
+ CurrentDigest: utils.DerefString(updateRecord.CurrentDigest),
+ LatestDigest: utils.DerefString(updateRecord.LatestDigest),
CheckTime: updateRecord.CheckTime,
ResponseTimeMs: updateRecord.ResponseTimeMs,
- Error: stringPtrValue(updateRecord.LastError),
- AuthMethod: stringPtrValue(updateRecord.AuthMethod),
- AuthUsername: stringPtrValue(updateRecord.AuthUsername),
- AuthRegistry: stringPtrValue(updateRecord.AuthRegistry),
+ Error: utils.DerefString(updateRecord.LastError),
+ AuthMethod: utils.DerefString(updateRecord.AuthMethod),
+ AuthUsername: utils.DerefString(updateRecord.AuthUsername),
+ AuthRegistry: utils.DerefString(updateRecord.AuthRegistry),
UsedCredential: updateRecord.UsedCredential,
}
}
diff --git a/backend/internal/services/image_update_service.go b/backend/internal/services/image_update_service.go
index c3c071c8e..b7316f08a 100644
--- a/backend/internal/services/image_update_service.go
+++ b/backend/internal/services/image_update_service.go
@@ -859,13 +859,6 @@ func stringToPtr(s string) *string {
return new(s)
}
-func stringPtrToString(s *string) string {
- if s == nil {
- return ""
- }
- return *s
-}
-
func buildImageUpdateRecord(imageID, repo, tag string, result *imageupdate.Response) *models.ImageUpdateRecord {
currentVersion := result.CurrentVersion
if currentVersion == "" {
@@ -916,7 +909,7 @@ func savePreparedUpdateResultWithTxInternal(tx *gorm.DB, imageID, repo, tag stri
if hasExisting &&
strings.TrimSpace(result.Error) != "" &&
isRateLimitErrorStringInternal(result.Error) &&
- strings.TrimSpace(stringPtrToString(existingRecord.LastError)) == "" {
+ strings.TrimSpace(utils.DerefString(existingRecord.LastError)) == "" {
slog.Debug("Preserving previous image update result; check hit a registry rate limit",
"imageID", imageID, "repository", repo, "tag", tag, "error", result.Error)
return nil
@@ -925,8 +918,8 @@ func savePreparedUpdateResultWithTxInternal(tx *gorm.DB, imageID, repo, tag stri
if hasExisting {
// Existing record found - check if we need to reset notification_sent
stateChanged := existingRecord.HasUpdate != updateRecord.HasUpdate
- digestChanged := stringPtrToString(existingRecord.LatestDigest) != stringPtrToString(updateRecord.LatestDigest)
- versionChanged := stringPtrToString(existingRecord.LatestVersion) != stringPtrToString(updateRecord.LatestVersion)
+ digestChanged := utils.DerefString(existingRecord.LatestDigest) != utils.DerefString(updateRecord.LatestDigest)
+ versionChanged := utils.DerefString(existingRecord.LatestVersion) != utils.DerefString(updateRecord.LatestVersion)
// Reset notification_sent if the update state changed in any way
if stateChanged || (updateRecord.HasUpdate && (digestChanged || versionChanged)) {
@@ -1432,15 +1425,15 @@ func (s *ImageUpdateService) sendBatchImageUpdateNotificationsInternal(ctx conte
HasUpdate: record.HasUpdate,
UpdateType: record.UpdateType,
CurrentVersion: record.CurrentVersion,
- LatestVersion: stringPtrToString(record.LatestVersion),
- CurrentDigest: stringPtrToString(record.CurrentDigest),
- LatestDigest: stringPtrToString(record.LatestDigest),
+ LatestVersion: utils.DerefString(record.LatestVersion),
+ CurrentDigest: utils.DerefString(record.CurrentDigest),
+ LatestDigest: utils.DerefString(record.LatestDigest),
CheckTime: record.CheckTime,
ResponseTimeMs: record.ResponseTimeMs,
- Error: stringPtrToString(record.LastError),
- AuthMethod: stringPtrToString(record.AuthMethod),
- AuthUsername: stringPtrToString(record.AuthUsername),
- AuthRegistry: stringPtrToString(record.AuthRegistry),
+ Error: utils.DerefString(record.LastError),
+ AuthMethod: utils.DerefString(record.AuthMethod),
+ AuthUsername: utils.DerefString(record.AuthUsername),
+ AuthRegistry: utils.DerefString(record.AuthRegistry),
UsedCredential: record.UsedCredential,
}
imageIDsToMark = append(imageIDsToMark, imageID)
diff --git a/backend/internal/services/image_update_service_test.go b/backend/internal/services/image_update_service_test.go
index 2870db7c7..b34d5d445 100644
--- a/backend/internal/services/image_update_service_test.go
+++ b/backend/internal/services/image_update_service_test.go
@@ -298,8 +298,8 @@ func TestImageUpdateService_DockerReferenceCompatibility(t *testing.T) {
}
}
-// TestStringPtrToString tests the helper function used for pointer comparison fix
-func TestStringPtrToString(t *testing.T) {
+// TestDerefString tests the shared helper used for pointer comparison.
+func TestDerefString(t *testing.T) {
tests := []struct {
name string
ptr *string
@@ -324,7 +324,7 @@ func TestStringPtrToString(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- result := stringPtrToString(tt.ptr)
+ result := utils.DerefString(tt.ptr)
assert.Equal(t, tt.want, result)
})
}
@@ -663,8 +663,8 @@ func TestImageUpdateService_CheckMultipleImages_SkippedDigestPinnedReferenceClea
require.NoError(t, db.WithContext(context.Background()).Where("id = ?", recordID).First(&saved).Error)
assert.False(t, saved.HasUpdate)
assert.Nil(t, saved.LastError)
- assert.Equal(t, pinnedDigest, stringPtrToString(saved.CurrentDigest))
- assert.Equal(t, pinnedDigest, stringPtrToString(saved.LatestDigest))
+ assert.Equal(t, pinnedDigest, utils.DerefString(saved.CurrentDigest))
+ assert.Equal(t, pinnedDigest, utils.DerefString(saved.LatestDigest))
}
func TestImageUpdateService_CheckMultipleImages_DigestPinnedTagPreservedWhenLocalImageHasNoRepoTags(t *testing.T) {
@@ -747,7 +747,7 @@ func TestImageUpdateService_CheckImageUpdate_UsesRegistryFallback(t *testing.T)
var saved models.ImageUpdateRecord
require.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:local-image-id").First(&saved).Error)
- assert.Equal(t, remoteDigest, stringPtrToString(saved.LatestDigest))
+ assert.Equal(t, remoteDigest, utils.DerefString(saved.LatestDigest))
}
func TestImageUpdateService_CheckMultipleImages_UsesRegistryFallback(t *testing.T) {
@@ -789,7 +789,7 @@ func TestImageUpdateService_CheckMultipleImages_UsesRegistryFallback(t *testing.
var saved models.ImageUpdateRecord
require.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:local-image-id").First(&saved).Error)
- assert.Equal(t, remoteDigest, stringPtrToString(saved.LatestDigest))
+ assert.Equal(t, remoteDigest, utils.DerefString(saved.LatestDigest))
}
func TestImageUpdateService_CheckMultipleImagesCompletesActivityWhenRequestContextCanceledInternal(t *testing.T) {
@@ -1040,7 +1040,7 @@ func TestImageUpdateService_SaveUpdateResultWithSnapshotInternal_PersistsRegistr
assert.Equal(t, repository, saved.Repository)
assert.Equal(t, "alpine", saved.Tag)
assert.True(t, saved.HasUpdate)
- assert.Equal(t, remoteDigest, stringPtrToString(saved.LatestDigest))
+ assert.Equal(t, remoteDigest, utils.DerefString(saved.LatestDigest))
assert.Nil(t, saved.LastError)
}
@@ -1121,8 +1121,8 @@ func TestImageUpdateService_MarkImageRefUpToDateAfterPull_ClearsMatchingRecordsA
assert.False(t, currentRecord.HasUpdate)
assert.Equal(t, repository, currentRecord.Repository)
assert.Equal(t, "1.2.3", currentRecord.Tag)
- assert.Equal(t, localDigest, stringPtrToString(currentRecord.CurrentDigest))
- assert.Equal(t, localDigest, stringPtrToString(currentRecord.LatestDigest))
+ assert.Equal(t, localDigest, utils.DerefString(currentRecord.CurrentDigest))
+ assert.Equal(t, localDigest, utils.DerefString(currentRecord.LatestDigest))
assert.Equal(t, "1.2.3", currentRecord.CurrentVersion)
require.NotNil(t, currentRecord.LatestVersion)
assert.Equal(t, "1.2.3", *currentRecord.LatestVersion)
@@ -1297,8 +1297,8 @@ func TestImageUpdateService_NotificationSentReset(t *testing.T) {
// This is the logic we're testing - comparing string values not pointers
stateChanged := existingRecord.HasUpdate != updateRecord.HasUpdate
- digestChanged := stringPtrToString(existingRecord.LatestDigest) != stringPtrToString(updateRecord.LatestDigest)
- versionChanged := stringPtrToString(existingRecord.LatestVersion) != stringPtrToString(updateRecord.LatestVersion)
+ digestChanged := utils.DerefString(existingRecord.LatestDigest) != utils.DerefString(updateRecord.LatestDigest)
+ versionChanged := utils.DerefString(existingRecord.LatestVersion) != utils.DerefString(updateRecord.LatestVersion)
if stateChanged || (updateRecord.HasUpdate && (digestChanged || versionChanged)) {
updateRecord.NotificationSent = false
@@ -1376,10 +1376,10 @@ func TestImageUpdateService_RateLimitErrorPreservesPreviousResult(t *testing.T)
if tt.expectPreserved {
assert.Nil(t, saved.LastError, "previous good record should be preserved")
- assert.Equal(t, "sha256:current", stringPtrToString(saved.LatestDigest))
+ assert.Equal(t, "sha256:current", utils.DerefString(saved.LatestDigest))
assert.Equal(t, checkTime, saved.CheckTime.UTC())
} else {
- assert.Equal(t, tt.resultError, stringPtrToString(saved.LastError))
+ assert.Equal(t, tt.resultError, utils.DerefString(saved.LastError))
assert.Nil(t, saved.LatestDigest)
}
})
diff --git a/backend/internal/services/project_service_test.go b/backend/internal/services/project_service_test.go
index 55ead3037..9f5b34c21 100644
--- a/backend/internal/services/project_service_test.go
+++ b/backend/internal/services/project_service_test.go
@@ -26,6 +26,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumes"
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
"github.com/getarcaneapp/arcane/backend/v2/pkg/projects"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/iconcatalog"
"github.com/getarcaneapp/arcane/types/v2/containerregistry"
imagetypes "github.com/getarcaneapp/arcane/types/v2/image"
@@ -714,8 +715,8 @@ func TestProjectService_PullProjectImages_UpdatesCurrentImageRecordAfterPull(t *
assert.False(t, currentRecord.HasUpdate)
assert.Equal(t, repository, currentRecord.Repository)
assert.Equal(t, "1.2.3", currentRecord.Tag)
- assert.Equal(t, imageDigest, stringPtrToString(currentRecord.CurrentDigest))
- assert.Equal(t, imageDigest, stringPtrToString(currentRecord.LatestDigest))
+ assert.Equal(t, imageDigest, utils.DerefString(currentRecord.CurrentDigest))
+ assert.Equal(t, imageDigest, utils.DerefString(currentRecord.LatestDigest))
}
func TestProjectService_EnsureImagesPresent_UpdatesCurrentImageRecordAfterPull(t *testing.T) {
@@ -767,7 +768,7 @@ func TestProjectService_EnsureImagesPresent_UpdatesCurrentImageRecordAfterPull(t
var currentRecord models.ImageUpdateRecord
require.NoError(t, db.WithContext(ctx).Where("id = ?", imageID).First(&currentRecord).Error)
assert.False(t, currentRecord.HasUpdate)
- assert.Equal(t, imageDigest, stringPtrToString(currentRecord.LatestDigest))
+ assert.Equal(t, imageDigest, utils.DerefString(currentRecord.LatestDigest))
}
func TestProjectService_PullImageForService_UpdatesCurrentImageRecordAfterPull(t *testing.T) {
@@ -816,7 +817,7 @@ func TestProjectService_PullImageForService_UpdatesCurrentImageRecordAfterPull(t
var currentRecord models.ImageUpdateRecord
require.NoError(t, db.WithContext(ctx).Where("id = ?", imageID).First(&currentRecord).Error)
assert.False(t, currentRecord.HasUpdate)
- assert.Equal(t, imageDigest, stringPtrToString(currentRecord.LatestDigest))
+ assert.Equal(t, imageDigest, utils.DerefString(currentRecord.LatestDigest))
}
func TestProjectService_ComposePullSelectedServicesInternal_ReconcilesOnlyOnSuccess(t *testing.T) {
@@ -931,12 +932,12 @@ func TestProjectService_ComposePullSelectedServicesInternal_ReconcilesOnlyOnSucc
var privateCurrentRecord models.ImageUpdateRecord
require.NoError(t, db.WithContext(ctx).Where("id = ?", privateImageID).First(&privateCurrentRecord).Error)
assert.False(t, privateCurrentRecord.HasUpdate)
- assert.Equal(t, privateImageDigest, stringPtrToString(privateCurrentRecord.LatestDigest))
+ assert.Equal(t, privateImageDigest, utils.DerefString(privateCurrentRecord.LatestDigest))
var publicCurrentRecord models.ImageUpdateRecord
require.NoError(t, db.WithContext(ctx).Where("id = ?", publicImageID).First(&publicCurrentRecord).Error)
assert.False(t, publicCurrentRecord.HasUpdate)
- assert.Equal(t, publicImageDigest, stringPtrToString(publicCurrentRecord.LatestDigest))
+ assert.Equal(t, publicImageDigest, utils.DerefString(publicCurrentRecord.LatestDigest))
}
func TestProjectService_ComposePullSelectedServicesInternal_LeavesRecordsWhenPullFails(t *testing.T) {
diff --git a/backend/internal/services/role_service_test.go b/backend/internal/services/role_service_test.go
index ae7ee74de..6006b4d37 100644
--- a/backend/internal/services/role_service_test.go
+++ b/backend/internal/services/role_service_test.go
@@ -91,6 +91,80 @@ func TestBackfillLegacyRoleAssignmentsIsNoOpWhenColumnAbsent(t *testing.T) {
require.NoError(t, roleSvc.BackfillLegacyRoleAssignments(ctx))
}
+func TestEnsureBuiltInRolesMigratesVariablePermissionsWithoutBackfillingCustomGrants(t *testing.T) {
+ ctx := context.Background()
+ userSvc, roleSvc := setupUserAndRoleServices(t)
+
+ customRole, err := roleSvc.CreateRole(ctx, "Template Reader", nil, []string{authz.PermTemplatesRead})
+ require.NoError(t, err)
+ owner := createTestUser(t, userSvc, "variable-migration-owner", "variable-migration-owner")
+ scopedKey := models.ApiKey{
+ Name: "Custom scoped key",
+ KeyHash: "variable-migration-hash",
+ KeyPrefix: "arc_vars",
+ Kind: models.ApiKeyKindScoped,
+ UserID: &owner.ID,
+ }
+ require.NoError(t, roleSvc.db.WithContext(ctx).Create(&scopedKey).Error)
+ require.NoError(t, roleSvc.db.WithContext(ctx).Create(&models.ApiKeyPermission{
+ ApiKeyID: scopedKey.ID,
+ Permission: authz.PermTemplatesRead,
+ }).Error)
+
+ oldEditorPermissions := slices.DeleteFunc(authz.BuiltInEditorPermissions(), func(permission string) bool {
+ return slices.Contains([]string{
+ authz.PermVariablesRead,
+ authz.PermVariablesCreate,
+ authz.PermVariablesUpdate,
+ authz.PermVariablesDelete,
+ authz.PermVariablesSync,
+ }, permission)
+ })
+ require.NoError(t, roleSvc.db.WithContext(ctx).Model(&models.Role{}).
+ Where("id = ?", authz.BuiltInRoleEditor).
+ Update("permissions", models.StringSlice(oldEditorPermissions)).Error)
+
+ require.NoError(t, roleSvc.EnsureBuiltInRoles(ctx))
+ require.NoError(t, roleSvc.BackfillApiKeyPermissions(ctx))
+
+ allVariablePermissions := []string{
+ authz.PermVariablesRead,
+ authz.PermVariablesCreate,
+ authz.PermVariablesUpdate,
+ authz.PermVariablesDelete,
+ authz.PermVariablesSync,
+ }
+ for _, roleID := range []string{authz.BuiltInRoleAdmin, authz.BuiltInRoleEditor, authz.BuiltInRoleNoShellEditor} {
+ role, getErr := roleSvc.GetRole(ctx, roleID)
+ require.NoError(t, getErr)
+ for _, permission := range allVariablePermissions {
+ require.Contains(t, []string(role.Permissions), permission, "role %s", roleID)
+ }
+ }
+ for _, roleID := range []string{authz.BuiltInRoleViewer, authz.BuiltInRoleDeployer} {
+ role, getErr := roleSvc.GetRole(ctx, roleID)
+ require.NoError(t, getErr)
+ require.Contains(t, []string(role.Permissions), authz.PermVariablesRead)
+ for _, permission := range allVariablePermissions[1:] {
+ require.NotContains(t, []string(role.Permissions), permission, "role %s", roleID)
+ }
+ }
+ monitor, err := roleSvc.GetRole(ctx, authz.BuiltInRoleMonitor)
+ require.NoError(t, err)
+ for _, permission := range allVariablePermissions {
+ require.NotContains(t, []string(monitor.Permissions), permission)
+ }
+
+ preservedCustomRole, err := roleSvc.GetRole(ctx, customRole.ID)
+ require.NoError(t, err)
+ require.Equal(t, []string{authz.PermTemplatesRead}, []string(preservedCustomRole.Permissions))
+
+ var keyPermissions []models.ApiKeyPermission
+ require.NoError(t, roleSvc.db.WithContext(ctx).Where("api_key_id = ?", scopedKey.ID).Find(&keyPermissions).Error)
+ require.Len(t, keyPermissions, 1)
+ require.Equal(t, authz.PermTemplatesRead, keyPermissions[0].Permission)
+}
+
func TestSetUserAssignmentsRejectsUnknownRole(t *testing.T) {
ctx := context.Background()
userSvc, roleSvc := setupUserAndRoleServices(t)
diff --git a/backend/internal/services/template_service.go b/backend/internal/services/template_service.go
index e5a265337..67ad0ea16 100644
--- a/backend/internal/services/template_service.go
+++ b/backend/internal/services/template_service.go
@@ -317,7 +317,7 @@ func (s *TemplateService) CreateTemplate(ctx context.Context, template *models.C
}
template.IsCustom = true
template.IsRemote = false
- setTemplateIconURL(template, s.resolveTemplateIconURL(ctx, template.Content, derefString(template.EnvContent)))
+ setTemplateIconURL(template, s.resolveTemplateIconURL(ctx, template.Content, utils.DerefString(template.EnvContent)))
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Create(template).Error; err != nil {
return fmt.Errorf("failed to create template: %w", err)
@@ -344,7 +344,7 @@ func (s *TemplateService) UpdateTemplate(ctx context.Context, id string, updates
existing.Description = updates.Description
existing.Content = updates.Content
existing.EnvContent = updates.EnvContent
- setTemplateIconURL(&existing, s.resolveTemplateIconURL(ctx, existing.Content, derefString(existing.EnvContent)))
+ setTemplateIconURL(&existing, s.resolveTemplateIconURL(ctx, existing.Content, utils.DerefString(existing.EnvContent)))
if err := tx.Save(&existing).Error; err != nil {
return fmt.Errorf("failed to update template: %w", err)
@@ -604,7 +604,7 @@ func (s *TemplateService) loadRemoteTemplates(ctx context.Context) ([]models.Com
defer mu.Unlock()
for _, template := range remoteTemplates {
template.Registry = cloneRegistry(&reg)
- template.RegistryID = stringPtr(reg.ID)
+ template.RegistryID = utils.StringPtrFromTrimmed(reg.ID)
templates = append(templates, template)
}
return nil
@@ -729,15 +729,15 @@ func (s *TemplateService) convertRemoteToLocal(remote tmpl.RemoteTemplate, regis
EnvContent: nil,
IsCustom: false,
IsRemote: true,
- RegistryID: stringPtr(registry.ID),
+ RegistryID: utils.StringPtrFromTrimmed(registry.ID),
Registry: cloneRegistry(registry),
Metadata: &models.ComposeTemplateMetadata{
- Version: stringPtr(remote.Version),
- Author: stringPtr(remote.Author),
+ Version: utils.StringPtrFromTrimmed(remote.Version),
+ Author: utils.StringPtrFromTrimmed(remote.Author),
Tags: remote.Tags,
- RemoteURL: stringPtr(remote.ComposeURL),
- EnvURL: stringPtr(remote.EnvURL),
- DocumentationURL: stringPtr(remote.DocumentationURL),
+ RemoteURL: utils.StringPtrFromTrimmed(remote.ComposeURL),
+ EnvURL: utils.StringPtrFromTrimmed(remote.EnvURL),
+ DocumentationURL: utils.StringPtrFromTrimmed(remote.DocumentationURL),
},
}
}
@@ -949,13 +949,13 @@ func cloneTemplateMetadata(meta *models.ComposeTemplateMetadata) *models.Compose
return nil
}
return &models.ComposeTemplateMetadata{
- Version: stringPtr(derefString(meta.Version)),
- Author: stringPtr(derefString(meta.Author)),
+ Version: utils.StringPtrFromTrimmed(utils.DerefString(meta.Version)),
+ Author: utils.StringPtrFromTrimmed(utils.DerefString(meta.Author)),
Tags: append([]string(nil), meta.Tags...),
- RemoteURL: stringPtr(derefString(meta.RemoteURL)),
- EnvURL: stringPtr(derefString(meta.EnvURL)),
- DocumentationURL: stringPtr(derefString(meta.DocumentationURL)),
- IconURL: stringPtr(derefString(meta.IconURL)),
+ RemoteURL: utils.StringPtrFromTrimmed(utils.DerefString(meta.RemoteURL)),
+ EnvURL: utils.StringPtrFromTrimmed(utils.DerefString(meta.EnvURL)),
+ DocumentationURL: utils.StringPtrFromTrimmed(utils.DerefString(meta.DocumentationURL)),
+ IconURL: utils.StringPtrFromTrimmed(utils.DerefString(meta.IconURL)),
}
}
@@ -967,7 +967,7 @@ func cloneRemoteTemplates(items []models.ComposeTemplate) []models.ComposeTempla
cloned := make([]models.ComposeTemplate, len(items))
for i := range items {
cloned[i] = items[i]
- cloned[i].RegistryID = stringPtr(derefString(items[i].RegistryID))
+ cloned[i].RegistryID = utils.StringPtrFromTrimmed(utils.DerefString(items[i].RegistryID))
cloned[i].Registry = cloneRegistry(items[i].Registry)
cloned[i].Metadata = cloneTemplateMetadata(items[i].Metadata)
}
@@ -997,7 +997,7 @@ func (s *TemplateService) SyncLocalTemplatesFromFilesystem(ctx context.Context)
}
func (s *TemplateService) upsertFilesystemTemplate(ctx context.Context, name, desc, compose string, envPtr *string) error {
- iconURL := s.resolveTemplateIconURL(ctx, compose, derefString(envPtr))
+ iconURL := s.resolveTemplateIconURL(ctx, compose, utils.DerefString(envPtr))
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var existing models.ComposeTemplate
@@ -1192,31 +1192,11 @@ func (s *TemplateService) resolveTemplateIconURL(ctx context.Context, composeCon
}
icon := utils.FirstNonEmpty(
- getFirstString(arcaneBlockMap[templateArcaneIconKey]),
- getFirstString(arcaneBlockMap[templateArcaneIconsAliasKey]),
+ utils.FirstNonEmpty(utils.Collect(arcaneBlockMap[templateArcaneIconKey], utils.ToString)...),
+ utils.FirstNonEmpty(utils.Collect(arcaneBlockMap[templateArcaneIconsAliasKey], utils.ToString)...),
)
- return stringPtr(icon)
-}
-
-func getFirstString(value any) string {
- values := utils.Collect(value, utils.ToString)
- return utils.FirstNonEmpty(values...)
-}
-
-func stringPtr(value string) *string {
- trimmed := strings.TrimSpace(value)
- if trimmed == "" {
- return nil
- }
- return &trimmed
-}
-
-func derefString(value *string) string {
- if value == nil {
- return ""
- }
- return *value
+ return utils.StringPtrFromTrimmed(icon)
}
func setTemplateIconURL(template *models.ComposeTemplate, iconURL *string) {
diff --git a/backend/internal/services/template_service_test.go b/backend/internal/services/template_service_test.go
index cc30370da..f416c1305 100644
--- a/backend/internal/services/template_service_test.go
+++ b/backend/internal/services/template_service_test.go
@@ -21,6 +21,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
httputils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"
tmpl "github.com/getarcaneapp/arcane/types/v2/template"
)
@@ -273,11 +274,11 @@ services:
Description: "Remote template",
IsRemote: true,
IsCustom: false,
- RegistryID: stringPtr("reg-1"),
+ RegistryID: utils.StringPtrFromTrimmed("reg-1"),
Metadata: &models.ComposeTemplateMetadata{
- RemoteURL: stringPtr(baseURL + "/compose.yaml"),
- EnvURL: stringPtr(baseURL + "/template.env"),
- IconURL: stringPtr("https://cdn.example/download.png"),
+ RemoteURL: utils.StringPtrFromTrimmed(baseURL + "/compose.yaml"),
+ EnvURL: utils.StringPtrFromTrimmed(baseURL + "/template.env"),
+ IconURL: utils.StringPtrFromTrimmed("https://cdn.example/download.png"),
},
}
@@ -334,7 +335,7 @@ func TestGetAllTemplatesPaginated_FiltersByType(t *testing.T) {
Description: "Remote template",
Content: "services: {}",
IsRemote: true,
- RegistryID: stringPtr("registry-one"),
+ RegistryID: utils.StringPtrFromTrimmed("registry-one"),
},
},
lastFetch: now,
diff --git a/backend/internal/services/variable_service_test.go b/backend/internal/services/variable_service_test.go
index 602ad5d3c..157530fa7 100644
--- a/backend/internal/services/variable_service_test.go
+++ b/backend/internal/services/variable_service_test.go
@@ -2,15 +2,21 @@ package services
import (
"context"
+ "encoding/json"
"fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
"os"
"path/filepath"
"strings"
+ "sync"
"testing"
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"
envtypes "github.com/getarcaneapp/arcane/types/v2/env"
sqlite "github.com/libtnb/sqlite"
"github.com/stretchr/testify/require"
@@ -89,6 +95,57 @@ func TestCreateVariable_SecretEncryptedAtRestAndRedactedOnList(t *testing.T) {
require.Empty(t, listed[0].Value)
}
+func TestUpdateVariable_OmittedSecretValuePreservesCiphertextAndRedactsResponse(t *testing.T) {
+ service, db, _ := setupVariableServiceTest(t)
+ ctx := context.Background()
+ created := createMaterializedSecretVariableInternal(t, service, "API_TOKEN", "super-secret")
+
+ var before models.GlobalVariable
+ require.NoError(t, db.WithContext(ctx).First(&before, "id = ?", created.ID).Error)
+ renamedKey := "RENAMED_API_TOKEN"
+ updated, err := service.UpdateVariable(ctx, created.ID, envtypes.UpdateGlobalVariableRequest{Key: &renamedKey})
+ require.NoError(t, err)
+ require.True(t, updated.IsSecret)
+ require.Empty(t, updated.Value)
+
+ var after models.GlobalVariable
+ require.NoError(t, db.WithContext(ctx).First(&after, "id = ?", created.ID).Error)
+ require.Equal(t, before.Value, after.Value, "omitting value must preserve the stored ciphertext")
+ decrypted, err := crypto.Decrypt(after.Value)
+ require.NoError(t, err)
+ require.Equal(t, "super-secret", decrypted)
+
+ listed, err := service.ListVariables(ctx)
+ require.NoError(t, err)
+ require.Len(t, listed, 1)
+ require.Empty(t, listed[0].Value)
+}
+
+func TestUpdateVariable_SecretToPlainRequiresReplacementValue(t *testing.T) {
+ service, db, _ := setupVariableServiceTest(t)
+ ctx := context.Background()
+ created := createMaterializedSecretVariableInternal(t, service, "API_TOKEN", "super-secret")
+
+ plain := false
+ _, err := service.UpdateVariable(ctx, created.ID, envtypes.UpdateGlobalVariableRequest{IsSecret: &plain})
+ require.Error(t, err)
+ require.True(t, common.IsGlobalVariableSecretValueRequiredError(err))
+
+ replacement := "public-value"
+ updated, err := service.UpdateVariable(ctx, created.ID, envtypes.UpdateGlobalVariableRequest{
+ Value: &replacement,
+ IsSecret: &plain,
+ })
+ require.NoError(t, err)
+ require.False(t, updated.IsSecret)
+ require.Equal(t, replacement, updated.Value)
+
+ var stored models.GlobalVariable
+ require.NoError(t, db.WithContext(ctx).First(&stored, "id = ?", created.ID).Error)
+ require.False(t, stored.IsSecret)
+ require.Equal(t, replacement, stored.Value)
+}
+
func TestResolveEffectiveVariables_EnvScopedOverridesAllEnv(t *testing.T) {
service, db, _ := setupVariableServiceTest(t)
ctx := context.Background()
@@ -156,3 +213,136 @@ func TestSyncEnvironment_LocalWritesEnvGlobalFile(t *testing.T) {
require.Len(t, statuses, 1)
require.Equal(t, "synced", statuses[0].Status)
}
+
+type capturedVariableSyncRequestInternal struct {
+ Method string
+ Path string
+ Headers map[string]string
+ Body []byte
+}
+
+func TestSyncEnvironment_DirectMaterializesSecretsThroughAgentRoute(t *testing.T) {
+ service, db, _ := setupVariableServiceTest(t)
+ token := "direct-agent-token"
+
+ var requestMu sync.Mutex
+ requests := make([]capturedVariableSyncRequestInternal, 0, 2)
+ server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+ body, err := io.ReadAll(request.Body)
+ require.NoError(t, err)
+ requestMu.Lock()
+ requests = append(requests, capturedVariableSyncRequestInternal{
+ Method: request.Method,
+ Path: request.URL.Path,
+ Headers: map[string]string{
+ remenv.HeaderAPIKey: request.Header.Get(remenv.HeaderAPIKey),
+ remenv.HeaderAgentToken: request.Header.Get(remenv.HeaderAgentToken),
+ },
+ Body: body,
+ })
+ requestMu.Unlock()
+
+ writer.Header().Set("Content-Type", "application/json")
+ if request.Method == http.MethodGet {
+ _, _ = writer.Write([]byte(`{"success":true,"data":[]}`))
+ return
+ }
+ _, _ = writer.Write([]byte(`{"success":true,"data":{"message":"updated"}}`))
+ }))
+ defer server.Close()
+
+ require.NoError(t, db.Create(&models.Environment{
+ BaseModel: models.BaseModel{ID: "env-direct"},
+ Name: "Direct",
+ ApiUrl: server.URL,
+ Status: string(models.EnvironmentStatusOnline),
+ Enabled: true,
+ AccessToken: &token,
+ }).Error)
+ service.environmentService = NewEnvironmentService(db, nil, nil, nil, service.settingsService, nil)
+ createMaterializedSecretVariableInternal(t, service, "API_TOKEN", "super-secret")
+
+ require.NoError(t, service.SyncEnvironment(context.Background(), "env-direct"))
+ requestMu.Lock()
+ captured := append([]capturedVariableSyncRequestInternal(nil), requests...)
+ requestMu.Unlock()
+ requireMaterializationRequestsInternal(t, captured, token)
+}
+
+func TestSyncEnvironment_EdgeMaterializesSecretsThroughAgentRoute(t *testing.T) {
+ service, db, _ := setupVariableServiceTest(t)
+ token := "edge-agent-token"
+ require.NoError(t, db.Create(&models.Environment{
+ BaseModel: models.BaseModel{ID: "env-edge"},
+ Name: "Edge",
+ ApiUrl: "http://edge.invalid",
+ Status: string(models.EnvironmentStatusOnline),
+ Enabled: true,
+ IsEdge: true,
+ AccessToken: &token,
+ }).Error)
+
+ environmentService := NewEnvironmentService(db, nil, nil, nil, service.settingsService, nil)
+ var requestMu sync.Mutex
+ requests := make([]capturedVariableSyncRequestInternal, 0, 2)
+ environmentService.remoteClient = remenv.NewClient(nil, remenv.TunnelTransportFuncs{
+ EnsureAvailableFunc: func(_ context.Context, environmentID string) error {
+ require.Equal(t, "env-edge", environmentID)
+ return nil
+ },
+ DoFunc: func(_ context.Context, environmentID, method, path string, headers map[string]string, body []byte) (*remenv.Response, error) {
+ require.Equal(t, "env-edge", environmentID)
+ requestMu.Lock()
+ requests = append(requests, capturedVariableSyncRequestInternal{
+ Method: method,
+ Path: path,
+ Headers: headers,
+ Body: append([]byte(nil), body...),
+ })
+ requestMu.Unlock()
+ if method == http.MethodGet {
+ return &remenv.Response{StatusCode: http.StatusOK, Body: []byte(`{"success":true,"data":[]}`)}, nil
+ }
+ return &remenv.Response{StatusCode: http.StatusOK, Body: []byte(`{"success":true,"data":{"message":"updated"}}`)}, nil
+ },
+ })
+ service.environmentService = environmentService
+ createMaterializedSecretVariableInternal(t, service, "API_TOKEN", "super-secret")
+
+ require.NoError(t, service.SyncEnvironment(context.Background(), "env-edge"))
+ requestMu.Lock()
+ captured := append([]capturedVariableSyncRequestInternal(nil), requests...)
+ requestMu.Unlock()
+ requireMaterializationRequestsInternal(t, captured, token)
+}
+
+func createMaterializedSecretVariableInternal(t *testing.T, service *VariableService, key, value string) *envtypes.GlobalVariable {
+ t.Helper()
+ created, err := service.CreateVariable(context.Background(), envtypes.CreateGlobalVariableRequest{
+ Key: key,
+ Value: value,
+ IsSecret: true,
+ AllEnvironments: true,
+ })
+ require.NoError(t, err)
+ return created
+}
+
+func requireMaterializationRequestsInternal(t *testing.T, requests []capturedVariableSyncRequestInternal, token string) {
+ t.Helper()
+ require.Len(t, requests, 2)
+
+ require.Equal(t, http.MethodGet, requests[0].Method)
+ require.Equal(t, agentVariablesPath, requests[0].Path)
+ require.Empty(t, requests[0].Body)
+ require.Equal(t, token, requests[0].Headers[remenv.HeaderAPIKey])
+ require.Equal(t, token, requests[0].Headers[remenv.HeaderAgentToken])
+
+ require.Equal(t, http.MethodPut, requests[1].Method)
+ require.Equal(t, agentVariablesPath, requests[1].Path)
+ require.Equal(t, token, requests[1].Headers[remenv.HeaderAPIKey])
+ require.Equal(t, token, requests[1].Headers[remenv.HeaderAgentToken])
+ var materialized envtypes.Summary
+ require.NoError(t, json.Unmarshal(requests[1].Body, &materialized))
+ require.Equal(t, []envtypes.Variable{{Key: "API_TOKEN", Value: "super-secret"}}, materialized.Variables)
+}
diff --git a/backend/internal/services/version_service.go b/backend/internal/services/version_service.go
index 159773153..9cbb41794 100644
--- a/backend/internal/services/version_service.go
+++ b/backend/internal/services/version_service.go
@@ -18,6 +18,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/buildables"
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cache"
"github.com/getarcaneapp/arcane/types/v2/version"
"go.getarcane.app/sys/cgroup"
@@ -292,7 +293,7 @@ func (s *VersionService) storedOrDigestBasedUpdateInternal(ctx context.Context,
if err != nil {
slog.WarnContext(ctx, "Failed to read stored Arcane image update state", "imageID", currentImageID, "error", err)
} else if found {
- return record.HasUpdate, stringPtrToString(record.LatestDigest)
+ return record.HasUpdate, utils.DerefString(record.LatestDigest)
}
}
diff --git a/backend/internal/services/volume_service.go b/backend/internal/services/volume_service.go
index 5aafe46f4..f743ffb0b 100644
--- a/backend/internal/services/volume_service.go
+++ b/backend/internal/services/volume_service.go
@@ -24,6 +24,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper"
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"
"github.com/google/uuid"
"github.com/moby/moby/api/pkg/stdcopy"
@@ -304,7 +305,7 @@ func (s *VolumeService) ListDirectory(ctx context.Context, volumeName, dirPath s
return nil, err
}
- sanitizedPath, err := s.sanitizeBrowsePathInternal(dirPath)
+ sanitizedPath, err := utils.SanitizeBrowsePath(dirPath)
if err != nil {
return nil, fmt.Errorf("invalid path: %w", err)
}
@@ -391,7 +392,7 @@ func (s *VolumeService) GetFileContent(ctx context.Context, volumeName, filePath
return nil, "", err
}
- sanitizedPath, err := s.sanitizeBrowsePathInternal(filePath)
+ sanitizedPath, err := utils.SanitizeBrowsePath(filePath)
if err != nil {
return nil, "", fmt.Errorf("invalid path: %w", err)
}
@@ -422,7 +423,7 @@ func (s *VolumeService) DownloadFile(ctx context.Context, volumeName, filePath s
return nil, 0, err
}
- sanitizedPath, err := s.sanitizeBrowsePathInternal(filePath)
+ sanitizedPath, err := utils.SanitizeBrowsePath(filePath)
if err != nil {
return nil, 0, fmt.Errorf("invalid path: %w", err)
}
@@ -1009,7 +1010,7 @@ func (s *VolumeService) execInContainerInternal(ctx context.Context, containerID
func (s *VolumeService) DeleteFile(ctx context.Context, volumeName, filePath string, user *models.User) error {
slog.DebugContext(ctx, "volume service: delete file", "volume", volumeName, "path", filePath)
- sanitizedPath, err := s.sanitizeBrowsePathInternal(filePath)
+ sanitizedPath, err := utils.SanitizeBrowsePath(filePath)
if err != nil {
return fmt.Errorf("invalid path: %w", err)
}
@@ -1050,7 +1051,7 @@ func (s *VolumeService) DeleteFile(ctx context.Context, volumeName, filePath str
func (s *VolumeService) CreateDirectory(ctx context.Context, volumeName, dirPath string, user *models.User) error {
slog.DebugContext(ctx, "volume service: create directory", "volume", volumeName, "path", dirPath)
- sanitizedPath, err := s.sanitizeBrowsePathInternal(dirPath)
+ sanitizedPath, err := utils.SanitizeBrowsePath(dirPath)
if err != nil {
return fmt.Errorf("invalid path: %w", err)
}
@@ -1087,7 +1088,7 @@ func (s *VolumeService) CreateDirectory(ctx context.Context, volumeName, dirPath
func (s *VolumeService) UploadFile(ctx context.Context, volumeName, destPath string, content io.Reader, filename string, user *models.User) error {
slog.DebugContext(ctx, "volume service: upload file", "volume", volumeName, "dest_path", destPath, "filename", filename)
- sanitizedPath, err := s.sanitizeBrowsePathInternal(destPath)
+ sanitizedPath, err := utils.SanitizeBrowsePath(destPath)
if err != nil {
return fmt.Errorf("invalid path: %w", err)
}
@@ -1528,29 +1529,6 @@ func (s *VolumeService) backupArchiveFilenameInternal(backupID string) (string,
return sanitizedBackupID + ".tar.gz", nil
}
-// sanitizeBrowsePath validates and cleans a path for file browser operations.
-// It ensures the path stays within the volume boundary.
-func (s *VolumeService) sanitizeBrowsePathInternal(input string) (string, error) {
- trimmed := strings.TrimSpace(input)
- if trimmed == "" || trimmed == "/" {
- return "/", nil // Root is valid for browse
- }
- cleaned := path.Clean(trimmed)
- // Ensure path starts with /
- if !path.IsAbs(cleaned) {
- cleaned = "/" + cleaned
- }
- // Check for path traversal attempts
- if strings.Contains(cleaned, "/../") || strings.HasSuffix(cleaned, "/..") || cleaned == "/.." {
- return "", errors.New("invalid path: path traversal not allowed")
- }
- // After cleaning, the path should not escape root
- if !strings.HasPrefix(cleaned, "/") {
- return "", errors.New("invalid path: must be absolute")
- }
- return cleaned, nil
-}
-
func (s *VolumeService) BackupHasPath(ctx context.Context, backupID string, filePath string) (bool, error) {
slog.DebugContext(ctx, "volume service: backup has path", "backup_id", backupID, "path", filePath)
cleaned, err := s.sanitizeBackupPathInternal(filePath)
diff --git a/backend/internal/services/vulnerability_service.go b/backend/internal/services/vulnerability_service.go
index e7bb59fa0..93afd7cc4 100644
--- a/backend/internal/services/vulnerability_service.go
+++ b/backend/internal/services/vulnerability_service.go
@@ -573,11 +573,6 @@ func (s *VulnerabilityService) GetScanSummary(ctx context.Context, imageID strin
s.markStaleScanIfNeeded(ctx, &record)
- var errPtr *string
- if record.Error != nil {
- errPtr = record.Error
- }
-
summary := &vulnerability.ScanSummary{
ImageID: record.ID,
ScanTime: record.ScanTime,
@@ -590,7 +585,7 @@ func (s *VulnerabilityService) GetScanSummary(ctx context.Context, imageID strin
Unknown: record.UnknownCount,
Total: record.TotalCount,
},
- Error: stringPtrValueOrEmptyInternal(errPtr),
+ Error: utils.DerefString(record.Error),
}
s.applyScanPhaseToSummaryInternal(summary)
@@ -3799,14 +3794,6 @@ func (s *VulnerabilityService) logScheduledScanEvent(ctx context.Context, envID
}
}
-// stringPtrValueOrEmptyInternal returns the string value from a pointer or empty string if nil
-func stringPtrValueOrEmptyInternal(p *string) string {
- if p == nil {
- return ""
- }
- return *p
-}
-
// IgnoreVulnerability creates a new ignore record for a vulnerability
func (s *VulnerabilityService) IgnoreVulnerability(ctx context.Context, envID string, payload *vulnerability.IgnorePayload) (*models.VulnerabilityIgnore, error) {
if s.db == nil {
diff --git a/backend/pkg/authz/access_policy.go b/backend/pkg/authz/access_policy.go
index 6258bf331..21aab5f53 100644
--- a/backend/pkg/authz/access_policy.go
+++ b/backend/pkg/authz/access_policy.go
@@ -87,6 +87,8 @@ var accessSurfacesInternal = []AccessSurface{
routeSurfaceInternal("route.swarm.configs", "/swarm/configs", "Configs", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmConfigs}, 0),
routeSurfaceInternal("route.swarm.secrets", "/swarm/secrets", "Secrets", AccessScopeModeSelectedEnvPlusGlobal, []string{PermSwarmSecrets}, 0),
routeSurfaceInternal("route.events", "/events", "Events", AccessScopeModeGlobalOnly, []string{PermEventsRead}, 110),
+ routeSurfaceInternal("route.activities", "", "Activities", AccessScopeModeAnyEffectiveScope, []string{PermActivitiesRead}, 0),
+ globalAdminRouteSurfaceInternal("route.oidc-role-mappings", "", "OIDC Role Mappings"),
routeSurfaceInternal("route.customize.templates.create", "/customize/templates/create", "Create template", AccessScopeModeGlobalOnly, []string{PermCustomizeManage, PermTemplatesList, PermTemplatesRead}, 0),
routeSurfaceInternal("route.customize.templates.default", "/customize/templates/default", "Default template", AccessScopeModeGlobalOnly, []string{PermCustomizeManage, PermTemplatesList, PermTemplatesRead}, 0),
routeSurfaceInternal("route.customize.templates.detail", "/customize/templates/{id}", "Template", AccessScopeModeGlobalOnly, []string{PermCustomizeManage, PermTemplatesList, PermTemplatesRead}, 0),
@@ -108,7 +110,7 @@ var accessSurfacesInternal = []AccessSurface{
customizeCategorySurfaceInternal("templates", "/customize/templates", "Templates", []string{PermCustomizeManage, PermTemplatesList, PermTemplatesRead}),
customizeCategorySurfaceInternal("registries", "/customize/registries", "Container Registries", []string{PermCustomizeManage, PermRegistriesList, PermRegistriesRead}),
- customizeCategorySurfaceInternal("variables", "/customize/variables", "Variables", []string{PermCustomizeManage, PermTemplatesRead}),
+ customizeCategorySurfaceInternal("variables", "/customize/variables", "Variables", []string{PermVariablesRead}),
customizeCategorySurfaceInternal("git-repositories", "/customize/git-repositories", "Git Repositories", []string{PermCustomizeManage, PermGitReposList, PermGitReposRead}),
}
@@ -237,6 +239,12 @@ func routeSurfaceInternal(id, url, label, scopeMode string, permissions []string
}
}
+func globalAdminRouteSurfaceInternal(id, url, label string) AccessSurface {
+ surface := routeSurfaceInternal(id, url, label, AccessScopeModeGlobalOnly, AllPermissions(), 0)
+ surface.MatchMode = AccessMatchModeAllOf
+ return surface
+}
+
func settingsCategorySurfaceInternal(categoryID, url, label, scopeMode string, permissions []string) AccessSurface {
return AccessSurface{
ID: "settings.category." + categoryID,
diff --git a/backend/pkg/authz/access_policy_test.go b/backend/pkg/authz/access_policy_test.go
index 3bd185792..2383913f1 100644
--- a/backend/pkg/authz/access_policy_test.go
+++ b/backend/pkg/authz/access_policy_test.go
@@ -36,6 +36,26 @@ func TestAccessSurfaceRegistryDefinesSettingsCustomizeAndLandingSemantics(t *tes
require.Equal(t, authz.AccessScopeModeGlobalOnly, templates.ScopeMode)
require.ElementsMatch(t, []string{authz.PermCustomizeManage, authz.PermTemplatesList, authz.PermTemplatesRead}, templates.Permissions)
+ variables := requireAccessSurfaceInternal(t, "customize.category.variables")
+ require.Equal(t, authz.AccessSurfaceKindCustomizeCategory, variables.Kind)
+ require.Equal(t, authz.AccessScopeModeGlobalOnly, variables.ScopeMode)
+ require.Equal(t, authz.AccessMatchModeAnyOf, variables.MatchMode)
+ require.ElementsMatch(t, []string{authz.PermVariablesRead}, variables.Permissions)
+ require.NotContains(t, variables.Permissions, authz.PermTemplatesRead)
+
+ activities := requireAccessSurfaceInternal(t, "route.activities")
+ require.Equal(t, authz.AccessSurfaceKindRoute, activities.Kind)
+ require.Empty(t, activities.URL)
+ require.Equal(t, authz.AccessScopeModeAnyEffectiveScope, activities.ScopeMode)
+ require.ElementsMatch(t, []string{authz.PermActivitiesRead}, activities.Permissions)
+
+ oidcRoleMappings := requireAccessSurfaceInternal(t, "route.oidc-role-mappings")
+ require.Equal(t, authz.AccessSurfaceKindRoute, oidcRoleMappings.Kind)
+ require.Empty(t, oidcRoleMappings.URL)
+ require.Equal(t, authz.AccessScopeModeGlobalOnly, oidcRoleMappings.ScopeMode)
+ require.Equal(t, authz.AccessMatchModeAllOf, oidcRoleMappings.MatchMode)
+ require.ElementsMatch(t, authz.AllPermissions(), oidcRoleMappings.Permissions)
+
settingsLanding := requireAccessSurfaceInternal(t, "landing.settings")
require.Equal(t, authz.AccessSurfaceKindLanding, settingsLanding.Kind)
require.Equal(t, "/settings", settingsLanding.URL)
@@ -74,6 +94,32 @@ func TestCanAccessSurfaceEvaluatesScopeModesAndLandingChildren(t *testing.T) {
require.True(t, authz.CanAccessSurface(customizePS, "customize.category.registries", "env-a"))
require.True(t, authz.CanAccessSurface(customizePS, "landing.customize", "env-a"))
+ variablePS := authz.NewPermissionSet()
+ variablePS.AddGlobal(authz.PermVariablesRead)
+ require.True(t, authz.CanAccessSurface(variablePS, "customize.category.variables", "env-a"))
+ require.True(t, authz.CanAccessSurface(variablePS, "landing.customize", "env-a"))
+ templatePS := authz.NewPermissionSet()
+ templatePS.AddGlobal(authz.PermTemplatesRead)
+ require.False(t, authz.CanAccessSurface(templatePS, "customize.category.variables", "env-a"))
+
+ activitiesPS := authz.NewPermissionSet()
+ activitiesPS.AddEnv("env-a", authz.PermActivitiesRead)
+ require.True(t, authz.CanAccessSurface(activitiesPS, "route.activities", "env-b"))
+ require.False(t, authz.CanAccessSurface(authz.NewPermissionSet(), "route.activities", "env-a"))
+
+ globalAdminPS := authz.NewPermissionSet()
+ globalAdminPS.AddGlobal(authz.AllPermissions()...)
+ require.True(t, authz.CanAccessSurface(globalAdminPS, "route.oidc-role-mappings", "env-a"))
+ require.True(t, authz.CanAccessSurface(authz.SudoPermissionSet(), "route.oidc-role-mappings", "env-a"))
+
+ nonAdminPS := authz.NewPermissionSet()
+ nonAdminPS.AddGlobal(authz.BuiltInEditorPermissions()...)
+ require.False(t, authz.CanAccessSurface(nonAdminPS, "route.oidc-role-mappings", "env-a"))
+
+ environmentAdminPS := authz.NewPermissionSet()
+ environmentAdminPS.AddEnv("env-a", authz.AllPermissions()...)
+ require.False(t, authz.CanAccessSurface(environmentAdminPS, "route.oidc-role-mappings", "env-a"))
+
require.False(t, authz.CanAccessSurface(authz.NewPermissionSet(), "missing.surface", "env-a"))
}
diff --git a/backend/pkg/authz/catalog.go b/backend/pkg/authz/catalog.go
index 7c7413236..0b2faf0dd 100644
--- a/backend/pkg/authz/catalog.go
+++ b/backend/pkg/authz/catalog.go
@@ -77,6 +77,13 @@ var permissionCatalog = []PermissionCatalogResource{
{"update", PermTemplatesUpdate, "Update", ""},
{"delete", PermTemplatesDelete, "Delete", ""},
}},
+ {"variables", "Variables", PermissionScopeGlobal, []PermissionCatalogAction{
+ {"read", PermVariablesRead, "Read", ""},
+ {"create", PermVariablesCreate, "Create", ""},
+ {"update", PermVariablesUpdate, "Update", ""},
+ {"delete", PermVariablesDelete, "Delete", ""},
+ {"sync", PermVariablesSync, "Sync", ""},
+ }},
{"git-repositories", "Git Repositories", PermissionScopeGlobal, []PermissionCatalogAction{
{"list", PermGitReposList, "List", ""},
{"read", PermGitReposRead, "Read", ""},
diff --git a/backend/pkg/authz/permission_set_test.go b/backend/pkg/authz/permission_set_test.go
index 37b6e085f..903b226fe 100644
--- a/backend/pkg/authz/permission_set_test.go
+++ b/backend/pkg/authz/permission_set_test.go
@@ -205,6 +205,71 @@ func TestBuiltInRolesOnlyReferenceKnownPermissions(t *testing.T) {
}
}
+func TestVariablePermissionsAreSeparateGlobalGrantsWithBuiltInAccess(t *testing.T) {
+ variablePermissions := []string{
+ PermVariablesRead,
+ PermVariablesCreate,
+ PermVariablesUpdate,
+ PermVariablesDelete,
+ PermVariablesSync,
+ }
+
+ for _, permission := range variablePermissions {
+ if !IsKnownPermission(permission) {
+ t.Fatalf("variable permission %q must be known", permission)
+ }
+ if !IsOrgLevel(permission) {
+ t.Fatalf("variable permission %q must be global", permission)
+ }
+ if permissionSliceContainsInternal(BuiltInMonitorPermissions(), permission) {
+ t.Fatalf("Monitor must not receive %q", permission)
+ }
+ }
+
+ for name, permissions := range map[string][]string{
+ "Admin": AllPermissions(),
+ "Editor": BuiltInEditorPermissions(),
+ "No-Shell Editor": BuiltInNoShellEditorPermissions(),
+ } {
+ for _, permission := range variablePermissions {
+ if !permissionSliceContainsInternal(permissions, permission) {
+ t.Fatalf("%s must receive %q", name, permission)
+ }
+ }
+ }
+
+ for name, permissions := range map[string][]string{
+ "Viewer": BuiltInViewerPermissions(),
+ "Deployer": BuiltInDeployerPermissions(),
+ } {
+ if !permissionSliceContainsInternal(permissions, PermVariablesRead) {
+ t.Fatalf("%s must receive %q", name, PermVariablesRead)
+ }
+ for _, permission := range variablePermissions[1:] {
+ if permissionSliceContainsInternal(permissions, permission) {
+ t.Fatalf("%s must not receive %q", name, permission)
+ }
+ }
+ }
+
+ templatesOnly := NewPermissionSet()
+ templatesOnly.AddGlobal(PermTemplatesRead, PermTemplatesCreate, PermTemplatesUpdate, PermTemplatesDelete)
+ for _, permission := range variablePermissions {
+ if templatesOnly.Allows(permission, "") {
+ t.Fatalf("template grants must not satisfy %q", permission)
+ }
+ }
+}
+
+func permissionSliceContainsInternal(permissions []string, permission string) bool {
+ for _, candidate := range permissions {
+ if candidate == permission {
+ return true
+ }
+ }
+ return false
+}
+
func TestPermissionCatalogDerivesKnownPermissionsAndScopes(t *testing.T) {
catalog := PermissionCatalog()
if len(catalog) == 0 {
diff --git a/backend/pkg/authz/permissions.go b/backend/pkg/authz/permissions.go
index ff975a469..598437da3 100644
--- a/backend/pkg/authz/permissions.go
+++ b/backend/pkg/authz/permissions.go
@@ -69,6 +69,12 @@ const (
PermTemplatesUpdate = "templates:update"
PermTemplatesDelete = "templates:delete"
+ PermVariablesRead = "variables:read"
+ PermVariablesCreate = "variables:create"
+ PermVariablesUpdate = "variables:update"
+ PermVariablesDelete = "variables:delete"
+ PermVariablesSync = "variables:sync"
+
PermGitReposList = "git-repositories:list"
PermGitReposRead = "git-repositories:read"
PermGitReposCreate = "git-repositories:create"
@@ -286,6 +292,7 @@ func BuiltInEditorPermissions() []string {
PermEnvironmentsList, PermEnvironmentsRead, PermEnvironmentsSync,
PermRegistriesList, PermRegistriesRead,
PermTemplatesList, PermTemplatesRead, PermTemplatesCreate, PermTemplatesUpdate, PermTemplatesDelete,
+ PermVariablesRead, PermVariablesCreate, PermVariablesUpdate, PermVariablesDelete, PermVariablesSync,
PermGitReposList, PermGitReposRead,
PermEventsRead,
// Full env-scoped Docker management
@@ -314,6 +321,7 @@ func BuiltInDeployerPermissions() []string {
PermEnvironmentsList, PermEnvironmentsRead,
PermRegistriesList, PermRegistriesRead,
PermTemplatesList, PermTemplatesRead,
+ PermVariablesRead,
PermEventsRead,
PermContainersList, PermContainersRead, PermContainersLogs, PermContainersStart, PermContainersStop, PermContainersRestart, PermContainersRedeploy, PermContainersKill, PermContainersPause,
PermProjectsList, PermProjectsRead, PermProjectsLogs, PermProjectsDeploy, PermProjectsDown, PermProjectsRestart,
@@ -342,6 +350,7 @@ func BuiltInViewerPermissions() []string {
PermEnvironmentsList, PermEnvironmentsRead,
PermRegistriesList, PermRegistriesRead,
PermTemplatesList, PermTemplatesRead,
+ PermVariablesRead,
PermGitReposList, PermGitReposRead,
PermEventsRead,
PermContainersList, PermContainersRead, PermContainersLogs,
diff --git a/backend/pkg/dockerutil/mount_utils.go b/backend/pkg/dockerutil/mount_utils.go
index f86ae7a39..6a8566609 100644
--- a/backend/pkg/dockerutil/mount_utils.go
+++ b/backend/pkg/dockerutil/mount_utils.go
@@ -13,7 +13,8 @@ import (
"go.getarcane.app/sys/cgroup"
)
-func getCurrentContainerInspectTargetInternal(currentContainerID func() (string, error), hostname func() (string, error)) (string, error) {
+// CurrentContainerInspectTarget resolves the identifier used to inspect Arcane's current container.
+func CurrentContainerInspectTarget(currentContainerID func() (string, error), hostname func() (string, error)) (string, error) {
if currentContainerID != nil {
if containerID, err := currentContainerID(); err == nil {
if containerID = strings.TrimSpace(containerID); containerID != "" {
@@ -44,7 +45,7 @@ func MountForCurrentContainerSubpath(ctx context.Context, dockerCli *client.Clie
if dockerCli == nil {
return nil, nil
}
- inspectTarget, err := getCurrentContainerInspectTargetInternal(cgroup.CurrentContainerID, os.Hostname)
+ inspectTarget, err := CurrentContainerInspectTarget(cgroup.CurrentContainerID, os.Hostname)
if err != nil {
return nil, err
}
diff --git a/backend/pkg/dockerutil/mount_utils_test.go b/backend/pkg/dockerutil/mount_utils_test.go
index 6ebd015c4..fabe4e7ca 100644
--- a/backend/pkg/dockerutil/mount_utils_test.go
+++ b/backend/pkg/dockerutil/mount_utils_test.go
@@ -1,6 +1,7 @@
package docker
import (
+ "errors"
"testing"
containertypes "github.com/moby/moby/api/types/container"
@@ -8,6 +9,49 @@ import (
"github.com/stretchr/testify/require"
)
+func TestCurrentContainerInspectTarget(t *testing.T) {
+ t.Run("prefers detected container id over hostname", func(t *testing.T) {
+ target, err := CurrentContainerInspectTarget(
+ func() (string, error) { return "0123456789ab", nil },
+ func() (string, error) { return "rpi4", nil },
+ )
+
+ require.NoError(t, err)
+ require.Equal(t, "0123456789ab", target)
+ })
+
+ t.Run("falls back to hostname when container id unavailable", func(t *testing.T) {
+ target, err := CurrentContainerInspectTarget(
+ func() (string, error) { return "", errors.New("no container id found") },
+ func() (string, error) { return "rpi4", nil },
+ )
+
+ require.NoError(t, err)
+ require.Equal(t, "rpi4", target)
+ })
+
+ t.Run("trims whitespace from detected container id", func(t *testing.T) {
+ target, err := CurrentContainerInspectTarget(
+ func() (string, error) { return " 0123456789ab ", nil },
+ func() (string, error) { return "rpi4", nil },
+ )
+
+ require.NoError(t, err)
+ require.Equal(t, "0123456789ab", target)
+ })
+
+ t.Run("returns hostname error when fallback fails", func(t *testing.T) {
+ target, err := CurrentContainerInspectTarget(
+ func() (string, error) { return "", errors.New("no container id found") },
+ func() (string, error) { return "", errors.New("hostname unavailable") },
+ )
+
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "hostname unavailable")
+ require.Equal(t, "", target)
+ })
+}
+
func TestMountForDestination(t *testing.T) {
tests := []struct {
name string
diff --git a/backend/pkg/libarcane/ws/goroutine_leak_test.go b/backend/pkg/libarcane/ws/goroutine_leak_test.go
index 085d2fac1..857ea33bb 100644
--- a/backend/pkg/libarcane/ws/goroutine_leak_test.go
+++ b/backend/pkg/libarcane/ws/goroutine_leak_test.go
@@ -279,7 +279,7 @@ func TestLeak_RepeatedConnectDisconnect(t *testing.T) {
// TestLeak_HubWithForwardLinesLifecycle tests the full pipeline:
// Hub.Run + ForwardLines + ServeClient, all cleaned up when client disconnects.
-// This mirrors startContainerLogHub() with format="text".
+// This mirrors the container text path through startLogHubInternal.
func TestLeak_HubWithForwardLinesLifecycle(t *testing.T) {
baseline := goroutineCount()
@@ -339,7 +339,7 @@ func TestLeak_HubWithForwardLinesLifecycle(t *testing.T) {
// TestLeak_HubWithForwardLogJSONBatchedLifecycle tests the batched JSON pipeline:
// Hub.Run + stream producer + normalizer + ForwardLogJSONBatched + ServeClient.
-// This mirrors startContainerLogHub() with format="json" and batched=true.
+// This mirrors the batched container JSON path through startLogHubInternal.
func TestLeak_HubWithForwardLogJSONBatchedLifecycle(t *testing.T) {
baseline := goroutineCount()
diff --git a/backend/pkg/projects/container_mounts.go b/backend/pkg/projects/container_mounts.go
index a967bc2fd..e1fab89ee 100644
--- a/backend/pkg/projects/container_mounts.go
+++ b/backend/pkg/projects/container_mounts.go
@@ -8,6 +8,7 @@ import (
mounttypes "github.com/moby/moby/api/types/mount"
"github.com/moby/moby/client"
+ dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
"go.getarcane.app/sys/cgroup"
)
@@ -22,7 +23,7 @@ func GetCurrentContainerMounts(ctx context.Context, dockerCli *client.Client) ([
}
// Prefer robust current-container detection and fall back to hostname.
- inspectTarget, err := getCurrentContainerInspectTargetInternal(cgroup.CurrentContainerID, os.Hostname)
+ inspectTarget, err := dockerutils.CurrentContainerInspectTarget(cgroup.CurrentContainerID, os.Hostname)
if err != nil {
return nil, err
}
@@ -63,24 +64,3 @@ func GetHostPathForContainerPath(ctx context.Context, dockerCli *client.Client,
return "", nil
}
-
-func getCurrentContainerInspectTargetInternal(currentContainerID func() (string, error), hostname func() (string, error)) (string, error) {
- if currentContainerID != nil {
- if containerID, err := currentContainerID(); err == nil {
- if containerID = strings.TrimSpace(containerID); containerID != "" {
- return containerID, nil
- }
- }
- }
-
- if hostname == nil {
- hostname = os.Hostname
- }
-
- value, err := hostname()
- if err != nil {
- return "", err
- }
-
- return strings.TrimSpace(value), nil
-}
diff --git a/backend/pkg/projects/container_mounts_test.go b/backend/pkg/projects/container_mounts_test.go
deleted file mode 100644
index 047dabc07..000000000
--- a/backend/pkg/projects/container_mounts_test.go
+++ /dev/null
@@ -1,51 +0,0 @@
-package projects
-
-import (
- "errors"
- "testing"
-
- "github.com/stretchr/testify/require"
-)
-
-func TestGetCurrentContainerInspectTargetInternal(t *testing.T) {
- t.Run("prefers detected container id over hostname", func(t *testing.T) {
- target, err := getCurrentContainerInspectTargetInternal(
- func() (string, error) { return "0123456789ab", nil },
- func() (string, error) { return "rpi4", nil },
- )
-
- require.NoError(t, err)
- require.Equal(t, "0123456789ab", target)
- })
-
- t.Run("falls back to hostname when container id unavailable", func(t *testing.T) {
- target, err := getCurrentContainerInspectTargetInternal(
- func() (string, error) { return "", errors.New("no container id found") },
- func() (string, error) { return "rpi4", nil },
- )
-
- require.NoError(t, err)
- require.Equal(t, "rpi4", target)
- })
-
- t.Run("trims whitespace from detected container id", func(t *testing.T) {
- target, err := getCurrentContainerInspectTargetInternal(
- func() (string, error) { return " 0123456789ab ", nil },
- func() (string, error) { return "rpi4", nil },
- )
-
- require.NoError(t, err)
- require.Equal(t, "0123456789ab", target)
- })
-
- t.Run("returns hostname error when fallback fails", func(t *testing.T) {
- target, err := getCurrentContainerInspectTargetInternal(
- func() (string, error) { return "", errors.New("no container id found") },
- func() (string, error) { return "", errors.New("hostname unavailable") },
- )
-
- require.Error(t, err)
- require.Contains(t, err.Error(), "hostname unavailable")
- require.Equal(t, "", target)
- })
-}
diff --git a/backend/pkg/projects/custom_labels.go b/backend/pkg/projects/custom_labels.go
index 9c5852ad5..41d080d85 100644
--- a/backend/pkg/projects/custom_labels.go
+++ b/backend/pkg/projects/custom_labels.go
@@ -154,9 +154,12 @@ func parseArcaneBlockInternal(block any) (IconSet, []string) {
return IconSet{}, nil
}
icon := IconSet{
- Icon: utils.FirstNonEmpty(getFirstString(arcaneBlock[arcaneIconKey]), getFirstString(arcaneBlock[arcaneIconsKey])),
- Light: getFirstString(arcaneBlock[arcaneIconLightKey]),
- Dark: getFirstString(arcaneBlock[arcaneIconDarkKey]),
+ Icon: utils.FirstNonEmpty(
+ utils.FirstNonEmpty(utils.Collect(arcaneBlock[arcaneIconKey], utils.ToString)...),
+ utils.FirstNonEmpty(utils.Collect(arcaneBlock[arcaneIconsKey], utils.ToString)...),
+ ),
+ Light: utils.FirstNonEmpty(utils.Collect(arcaneBlock[arcaneIconLightKey], utils.ToString)...),
+ Dark: utils.FirstNonEmpty(utils.Collect(arcaneBlock[arcaneIconDarkKey], utils.ToString)...),
}
urls := utils.UniqueNonEmptyStrings(utils.Collect(arcaneBlock[arcaneURLsKey], utils.ToString))
return icon, urls
@@ -337,16 +340,6 @@ func parseIncludePaths(composeFilePath string) ([]string, error) {
return paths, nil
}
-// getFirstString retrieves the first non-empty string from a value (single or slice).
-func getFirstString(v any) string {
- for _, s := range utils.Collect(v, utils.ToString) {
- if s != "" {
- return s
- }
- }
- return ""
-}
-
// FindArcaneIconSet attempts to locate Arcane icon labels within service labels.
// It supports both map[string]string and []string label formats.
func FindArcaneIconSet(labels any) IconSet {
diff --git a/backend/pkg/utils/path_util.go b/backend/pkg/utils/path_util.go
new file mode 100644
index 000000000..63e8ac6d0
--- /dev/null
+++ b/backend/pkg/utils/path_util.go
@@ -0,0 +1,28 @@
+package utils
+
+import (
+ "errors"
+ "path"
+ "strings"
+)
+
+// SanitizeBrowsePath normalizes a path within a rooted file browser.
+func SanitizeBrowsePath(input string) (string, error) {
+ trimmed := strings.TrimSpace(input)
+ if trimmed == "" || trimmed == "/" {
+ return "/", nil
+ }
+
+ cleaned := path.Clean(trimmed)
+ if !path.IsAbs(cleaned) {
+ cleaned = "/" + cleaned
+ }
+ if strings.Contains(cleaned, "/../") || strings.HasSuffix(cleaned, "/..") || cleaned == "/.." {
+ return "", errors.New("invalid path: path traversal not allowed")
+ }
+ if !strings.HasPrefix(cleaned, "/") {
+ return "", errors.New("invalid path: must be absolute")
+ }
+
+ return cleaned, nil
+}
diff --git a/types/base/response.go b/types/base/response.go
index bfdeee8b0..5fcbff543 100644
--- a/types/base/response.go
+++ b/types/base/response.go
@@ -32,3 +32,11 @@ type Paginated[T any] struct {
Data []T `json:"data" doc:"Array of items for the current page"`
Pagination PaginationResponse `json:"pagination" doc:"Pagination metadata"`
}
+
+// PaginatedWithCounts is a generic wrapper for paginated responses with aggregate counts.
+type PaginatedWithCounts[T, C any] struct {
+ Success bool `json:"success" doc:"Whether the request was successful"`
+ Data []T `json:"data" doc:"Array of items for the current page"`
+ Counts C `json:"counts" doc:"Aggregate counts for the filtered collection"`
+ Pagination PaginationResponse `json:"pagination" doc:"Pagination metadata"`
+}