Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: user based api keys are capped at users permissions check (#2918)
Kyle Mendell45cd6490e9d6
diff --git a/backend/api/handlers/apikeys.go b/backend/api/handlers/apikeys.goindex 570c392fc..fe77e9859 100644--- a/backend/api/handlers/apikeys.go+++ b/backend/api/handlers/apikeys.go@@ -44,6 +44,10 @@ type CreateApiKeyInput struct {Body apikey.CreateApiKey}+type CreateMyApiKeyInput struct {+ Body apikey.CreateUserApiKey+}+type CreateApiKeyOutput struct {Body base.ApiResponse[apikey.ApiKeyCreatedDto]}@@ -168,16 +172,18 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {},}, h.ListMyApiKeys)+ // Personal keys inherit the owner's permissions, so creating or deleting+ // them is session-only (BearerAuth, no ApiKeyAuth): a stolen API key must+ // not be able to mint or remove persistence credentials.huma.Register(api, huma.Operation{OperationID: "create-my-api-key",Method: http.MethodPost,Path: "/auth/me/api-keys",Summary: "Create my API key",- Description: "Create a new API key owned by the current user",+ Description: "Create a new personal API key owned by the current user. Personal keys inherit the owner's role permissions.",Tags: []string{"API Keys"},Security: []map[string][]string{{"BearerAuth": {}},- {"ApiKeyAuth": {}},},}, h.CreateMyApiKey)@@ -190,7 +196,6 @@ func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {Tags: []string{"API Keys"},Security: []map[string][]string{{"BearerAuth": {}},- {"ApiKeyAuth": {}},},}, h.DeleteMyApiKey)}@@ -217,9 +222,33 @@ func (h *ApiKeyHandler) ListApiKeys(ctx context.Context, input *ListApiKeysInput}, nil}-// CreateApiKey creates a new API key.+// 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) {- return h.createCurrentUserApiKeyInternal(ctx, input)+ if h.apiKeyService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ user, err := requireUserInternal(ctx)+ if err != nil {+ return nil, err+ }++ callerPerms, _ := humamw.PermissionsFromContext(ctx)+ apiKey, err := h.apiKeyService.CreateApiKey(ctx, user.ID, callerPerms, input.Body)+ if err != nil {+ if errors.Is(err, services.ErrApiKeyPermissionEscalation) {+ return nil, huma.Error403Forbidden(err.Error())+ }+ return nil, huma.Error500InternalServerError((&common.ApiKeyCreationError{Err: err}).Error())+ }++ return &CreateApiKeyOutput{+ Body: base.ApiResponse[apikey.ApiKeyCreatedDto]{+ Success: true,+ Data: *apiKey,+ },+ }, nil}// GetApiKey returns details of a specific API key.@@ -247,12 +276,12 @@ func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInpreturn nil, huma.Error500InternalServerError("service not available")}- user, err := requireUserInternal(ctx)- if err != nil {+ if _, err := requireUserInternal(ctx); err != nil {return nil, err}- apiKey, err := h.apiKeyService.UpdateApiKey(ctx, user.ID, input.ID, input.Body)+ callerPerms, _ := humamw.PermissionsFromContext(ctx)+ apiKey, err := h.apiKeyService.UpdateApiKey(ctx, callerPerms, input.ID, input.Body)if err != nil {if errors.Is(err, services.ErrApiKeyNotFound) {return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())@@ -263,6 +292,9 @@ func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInpif errors.Is(err, services.ErrApiKeyPermissionEscalation) {return nil, huma.Error403Forbidden(err.Error())}+ if errors.Is(err, services.ErrApiKeyPersonalNoGrants) {+ return nil, huma.Error400BadRequest(err.Error())+ }return nil, huma.Error500InternalServerError((&common.ApiKeyUpdateError{Err: err}).Error())}@@ -324,26 +356,27 @@ func (h *ApiKeyHandler) ListMyApiKeys(ctx context.Context, input *struct{}) (*Li}, nil}-// CreateMyApiKey creates a new API key owned by the current user (self-service).-func (h *ApiKeyHandler) CreateMyApiKey(ctx context.Context, input *CreateApiKeyInput) (*CreateApiKeyOutput, error) {- return h.createCurrentUserApiKeyInternal(ctx, input)-}--func (h *ApiKeyHandler) createCurrentUserApiKeyInternal(ctx context.Context, input *CreateApiKeyInput) (*CreateApiKeyOutput, error) {+// CreateMyApiKey creates a new personal API key owned by the current user+// (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 {+ return nil, huma.Error403Forbidden("personal API keys can only be managed from an interactive session")+ }+user, err := requireUserInternal(ctx)if err != nil {return nil, err}- apiKey, err := h.apiKeyService.CreateApiKey(ctx, user.ID, input.Body)+ apiKey, err := h.apiKeyService.CreatePersonalApiKey(ctx, user.ID, input.Body)if err != nil {- if errors.Is(err, services.ErrApiKeyPermissionEscalation) {- return nil, huma.Error403Forbidden(err.Error())- }return nil, huma.Error500InternalServerError((&common.ApiKeyCreationError{Err: err}).Error())}@@ -363,6 +396,12 @@ func (h *ApiKeyHandler) DeleteMyApiKey(ctx context.Context, input *DeleteApiKeyIreturn 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 {+ return nil, huma.Error403Forbidden("personal API keys can only be managed from an interactive session")+ }+user, err := requireUserInternal(ctx)if err != nil {return nil, errdiff --git a/backend/api/middleware/auth.go b/backend/api/middleware/auth.goindex 9fa767bcd..4a6d48dba 100644--- a/backend/api/middleware/auth.go+++ b/backend/api/middleware/auth.go@@ -138,20 +138,20 @@ func tryBearerAuthInternal(ctx huma.Context, authService *services.AuthService)}// tryApiKeyAuthInternal checks if API key authentication should be allowed-// through. Returns the resolved user plus the API key's database ID so the-// caller can fetch the key's own permission set.-func tryApiKeyAuthInternal(ctx huma.Context, apiKeyService *services.ApiKeyService) (*models.User, string, bool) {+// through. Returns the resolved user plus the API key record so the caller+// can resolve permissions according to the key's kind.+func tryApiKeyAuthInternal(ctx huma.Context, apiKeyService *services.ApiKeyService) (*models.User, *models.ApiKey, bool) {apiKey := ctx.Header(pkgutils.HeaderApiKey)if apiKey == "" {- return nil, "", false+ return nil, nil, false}- user, keyID, err := apiKeyService.ValidateApiKeyWithID(ctx.Context(), apiKey)+ user, key, err := apiKeyService.ValidateApiKeyWithID(ctx.Context(), apiKey)if err != nil || user == nil {- return nil, "", false+ return nil, nil, false}- return user, keyID, true+ return user, key, true}func tryEnvironmentAccessTokenAuthInternal(ctx huma.Context, resolver environmentAccessTokenResolver, token string) (*models.User, bool) {@@ -292,8 +292,15 @@ func opportunisticBearerAuthInternal(ctx huma.Context, authService *services.Aut// handleApiKeyAuthInternal handles the API-key-present branch. If validation// fails, it writes 401 directly — Bearer is not attempted as fallback.func handleApiKeyAuthInternal(api huma.API, ctx huma.Context, apiKeyService *services.ApiKeyService, permResolver PermissionResolver, envTokenResolver environmentAccessTokenResolver, next func(huma.Context)) {- if user, keyID, ok := tryApiKeyAuthInternal(ctx, apiKeyService); ok {- ps := resolveApiKeyPermissionsInternal(ctx.Context(), permResolver, keyID)+ if user, key, ok := tryApiKeyAuthInternal(ctx, apiKeyService); ok {+ // Personal keys inherit the owner's role permissions (same resolution+ // as session auth); scoped keys are limited to their own grants.+ var ps *authz.PermissionSet+ if key.Kind == models.ApiKeyKindPersonal {+ ps = resolveUserPermissionsInternal(ctx.Context(), permResolver, user)+ } else {+ ps = resolveApiKeyPermissionsInternal(ctx.Context(), permResolver, key.ID)+ }newCtx := setUserInContextInternal(ctx.Context(), user, ps)next(huma.WithContext(ctx, newCtx))returndiff --git a/backend/api/middleware/auth_test.go b/backend/api/middleware/auth_test.goindex a8e19b99d..c30e73e4d 100644--- a/backend/api/middleware/auth_test.go+++ b/backend/api/middleware/auth_test.go@@ -89,6 +89,41 @@ func TestNewAuthBridge_AcceptsEnvironmentAccessTokenViaAPIKey(t *testing.T) {require.Contains(t, rec.Body.String(), "environment:env-self")}+// A valid API key presented to a BearerAuth-only operation must be rejected:+// the bridge only attempts API-key auth when the operation declares ApiKeyAuth.+// This is the gate that makes personal-key create/delete session-only.+func TestNewAuthBridge_RejectsApiKeyOnBearerOnlyOperation(t *testing.T) {+ router := echo.New()+ apiGroup := router.Group("/api")++ humaConfig := huma.DefaultConfig("test", "1.0.0")+ humaConfig.Components.SecuritySchemes = map[string]*huma.SecurityScheme{+ "BearerAuth": {Type: "http", Scheme: "bearer"},+ "ApiKeyAuth": {Type: "apiKey", In: "header", Name: "X-API-Key"},+ }++ api := humaecho.NewWithGroup(router, apiGroup, humaConfig)+ api.UseMiddleware(NewAuthBridge(api, &services.AuthService{}, nil, nil, nil, &config.Config{}))++ huma.Register(api, huma.Operation{+ OperationID: "bearer-only",+ Method: http.MethodPost,+ Path: "/bearer-only",+ Security: []map[string][]string{{"BearerAuth": {}}},+ }, func(ctx context.Context, _ *secureInput) (*secureOutput, error) {+ t.Fatal("handler must not be reached with API key auth")+ return &secureOutput{}, nil+ })++ req := httptest.NewRequest(http.MethodPost, "/api/bearer-only", nil)+ req.Header.Set("X-API-Key", "arc_whatever-valid-or-not-never-consulted")+ rec := httptest.NewRecorder()++ router.ServeHTTP(rec, req)++ require.Equal(t, http.StatusUnauthorized, rec.Code)+}+type testOperationProvider struct {operation *huma.Operation}diff --git a/backend/internal/middleware/auth_middleware.go b/backend/internal/middleware/auth_middleware.goindex da6605b65..4c274f6c4 100644--- a/backend/internal/middleware/auth_middleware.go+++ b/backend/internal/middleware/auth_middleware.go@@ -34,7 +34,7 @@ type AuthOptions struct {}type ApiKeyValidator interface {- ValidateApiKeyWithID(ctx context.Context, rawKey string) (*models.User, string, error)+ ValidateApiKeyWithID(ctx context.Context, rawKey string) (*models.User, *models.ApiKey, error)}type EnvironmentAccessTokenResolver interface {@@ -187,31 +187,7 @@ func (m *AuthMiddleware) managerAuth(ctx context.Context, c echo.Context, next e// First, check for API key in X-API-Key headerif apiKey := req.Header.Get(pkgutils.HeaderApiKey); apiKey != "" {- if m.apiKeyValidator != nil {- user, keyID, err := m.apiKeyValidator.ValidateApiKeyWithID(ctx, apiKey)- if err == nil && user != nil {- ps := m.resolveApiKeyPermissionsOrDeny(ctx, keyID)- if m.options.AdminRequired && !ps.IsGlobalAdmin() {- return c.JSON(http.StatusForbidden, models.APIError{- Code: "FORBIDDEN",- Message: "You don't have permission to access this resource",- })- }- c.Set(echoCtxKeyUserID, user.ID)- c.Set(echoCtxKeyCurrentUser, user)- c.Set(echoCtxKeyUserPermissions, ps)- c.Set(echoCtxKeyAuthMethod, "api_key")- return next(c)- }- }- if env, ok := m.resolveEnvironmentAccessToken(ctx, apiKey); ok {- environmentSudoInternal(c, env)- return next(c)- }- return c.JSON(http.StatusUnauthorized, models.APIError{- Code: models.APIErrorCodeUnauthorized,- Message: "Invalid or expired API key",- })+ return m.apiKeyHeaderAuth(ctx, c, next, apiKey)}token := extractBearerOrCookieTokenInternal(c)@@ -259,6 +235,43 @@ func (m *AuthMiddleware) managerAuth(ctx context.Context, c echo.Context, next ereturn next(c)}+// apiKeyHeaderAuth authenticates an X-API-Key credential: a user-owned API key+// first, then an environment access token presented through the same header.+func (m *AuthMiddleware) apiKeyHeaderAuth(ctx context.Context, c echo.Context, next echo.HandlerFunc, apiKey string) error {+ if m.apiKeyValidator != nil {+ user, key, err := m.apiKeyValidator.ValidateApiKeyWithID(ctx, apiKey)+ if err == nil && user != nil {+ // Personal keys inherit the owner's role permissions (same+ // resolution as session auth); scoped keys use their own grants.+ var ps *authz.PermissionSet+ if key.Kind == models.ApiKeyKindPersonal {+ ps = m.resolvePermissionsOrDeny(ctx, user)+ } else {+ ps = m.resolveApiKeyPermissionsOrDeny(ctx, key.ID)+ }+ if m.options.AdminRequired && !ps.IsGlobalAdmin() {+ return c.JSON(http.StatusForbidden, models.APIError{+ Code: "FORBIDDEN",+ Message: "You don't have permission to access this resource",+ })+ }+ c.Set(echoCtxKeyUserID, user.ID)+ c.Set(echoCtxKeyCurrentUser, user)+ c.Set(echoCtxKeyUserPermissions, ps)+ c.Set(echoCtxKeyAuthMethod, "api_key")+ return next(c)+ }+ }+ if env, ok := m.resolveEnvironmentAccessToken(ctx, apiKey); ok {+ environmentSudoInternal(c, env)+ return next(c)+ }+ return c.JSON(http.StatusUnauthorized, models.APIError{+ Code: models.APIErrorCodeUnauthorized,+ Message: "Invalid or expired API key",+ })+}+// resolvePermissionsOrDeny returns the user's permission set, or an empty// (deny-all) set if the resolver is unavailable or fails. Resolver failures// are logged.diff --git a/backend/internal/middleware/auth_middleware_test.go b/backend/internal/middleware/auth_middleware_test.goindex 032c5846c..313d2e0c5 100644--- a/backend/internal/middleware/auth_middleware_test.go+++ b/backend/internal/middleware/auth_middleware_test.go@@ -8,6 +8,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/models"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/labstack/echo/v4""github.com/stretchr/testify/require")@@ -25,6 +26,78 @@ func (r testEnvironmentTokenResolver) ResolveEnvironmentByAccessToken(_ context.var ErrInvalidEnvironmentAccessTokenForTest = context.Canceled+type testApiKeyValidator struct {+ user *models.User+ key *models.ApiKey+}++func (v testApiKeyValidator) ValidateApiKeyWithID(_ context.Context, rawKey string) (*models.User, *models.ApiKey, error) {+ if rawKey == "valid-key" {+ return v.user, v.key, nil+ }+ return nil, nil, context.Canceled+}++// testPermissionResolver returns distinguishable sets so tests can tell which+// resolution path the middleware took: user roles vs per-key grants.+type testPermissionResolver struct{}++func (testPermissionResolver) ResolvePermissions(_ context.Context, _ *models.User) (*authz.PermissionSet, error) {+ ps := authz.NewPermissionSet()+ ps.AddGlobal("containers:list")+ return ps, nil+}++func (testPermissionResolver) ResolveApiKeyPermissions(_ context.Context, _ string) (*authz.PermissionSet, error) {+ ps := authz.NewPermissionSet()+ ps.AddGlobal("images:list")+ return ps, nil+}++func TestAuthMiddleware_ManagerAuthResolvesPermissionsByKeyKind(t *testing.T) {+ userID := "key-owner"+ user := &models.User{BaseModel: models.BaseModel{ID: userID}, Username: "owner"}++ cases := []struct {+ name string+ kind string+ wantAllowed string+ wantDenied string+ }{+ {name: "personal key inherits owner role permissions", kind: models.ApiKeyKindPersonal, wantAllowed: "containers:list", wantDenied: "images:list"},+ {name: "scoped key limited to its own grants", kind: models.ApiKeyKindScoped, wantAllowed: "images:list", wantDenied: "containers:list"},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ router := echo.New()+ router.Use(+ NewAuthMiddleware(nil, &config.Config{}).+ WithApiKeyValidator(testApiKeyValidator{+ user: user,+ key: &models.ApiKey{BaseModel: models.BaseModel{ID: "key-1"}, Kind: tc.kind, UserID: &userID},+ }).+ WithPermissionResolver(testPermissionResolver{}).+ Add(),+ )+ router.GET("/secure", func(c echo.Context) error {+ ps, ok := c.Get("userPermissions").(*authz.PermissionSet)+ require.True(t, ok)+ require.True(t, ps.Allows(tc.wantAllowed, ""))+ require.False(t, ps.Allows(tc.wantDenied, ""))+ return c.JSON(http.StatusOK, map[string]any{"ok": true})+ })++ req := httptest.NewRequest(http.MethodGet, "/secure", nil)+ req.Header.Set("X-API-Key", "valid-key")+ rec := httptest.NewRecorder()++ router.ServeHTTP(rec, req)+ require.Equal(t, http.StatusOK, rec.Code)+ })+ }+}+func TestAuthMiddleware_ManagerAuthAcceptsEnvironmentAccessTokenViaAPIKey(t *testing.T) {token := "env-access-token"router := echo.New()diff --git a/backend/internal/models/api_key.go b/backend/internal/models/api_key.goindex 6a0c21eb1..cbe9729cd 100644--- a/backend/internal/models/api_key.go+++ b/backend/internal/models/api_key.go@@ -4,6 +4,14 @@ import ("time")+const (+ // ApiKeyKindScoped keys carry their own permission grant rows.+ ApiKeyKindScoped = "scoped"+ // ApiKeyKindPersonal keys have no grants; they inherit the owner's role+ // permissions at authentication time.+ ApiKeyKindPersonal = "personal"+)+type ApiKey struct {BaseModel@@ -12,6 +20,7 @@ type ApiKey struct {KeyHash string `json:"-" gorm:"column:key_hash;not null"`KeyPrefix string `json:"keyPrefix" gorm:"column:key_prefix;not null"`ManagedBy *string `json:"-" gorm:"column:managed_by"`+ Kind string `json:"kind" gorm:"column:kind;not null;default:scoped"`UserID *string `json:"userId,omitempty" gorm:"column:user_id"`EnvironmentID *string `json:"environmentId,omitempty" gorm:"column:environment_id"`ExpiresAt *time.Time `json:"expiresAt,omitempty" gorm:"column:expires_at" sortable:"true"`diff --git a/backend/internal/services/api_key_service.go b/backend/internal/services/api_key_service.goindex 86ae15ac9..2b712029f 100644--- a/backend/internal/services/api_key_service.go+++ b/backend/internal/services/api_key_service.go@@ -112,8 +112,11 @@ func (s *ApiKeyService) markApiKeyUsedAsync(ctx context.Context, keyID string) {}(keyID)}-func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, req apikey.CreateApiKey) (*apikey.ApiKeyCreatedDto, error) {- if err := s.validateGrantsAgainstUserInternal(ctx, userID, req.Permissions); err != nil {+func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, callerPerms *authz.PermissionSet, req apikey.CreateApiKey) (*apikey.ApiKeyCreatedDto, error) {+ if err := validateGrantsAgainstPermissionSetInternal(callerPerms, req.Permissions); err != nil {+ return nil, err+ }+ if err := s.validateGrantsAgainstOwnerInternal(ctx, userID, req.Permissions); err != nil {return nil, err}rawKey, err := s.generateApiKey()@@ -121,7 +124,7 @@ func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, req apireturn nil, err}- created, err := s.createAPIKeyWithRawKey(ctx, &userID, rawKey, req, nil, nil)+ created, err := s.createAPIKeyWithRawKey(ctx, &userID, rawKey, req, nil, nil, models.ApiKeyKindScoped)if err != nil {return nil, err}@@ -141,28 +144,46 @@ func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, req api// API key permissions they themselves do not hold.var ErrApiKeyPermissionEscalation = errors.New("cannot grant a permission you do not have")-// validateGrantsAgainstUserInternal refuses requests that would grant the new key-// permissions that the requesting user doesn't hold. Sudo callers bypass this-// (they always pass). If RoleService is unavailable validation is skipped (used-// only in the boot-bootstrap path where no human caller exists).-func (s *ApiKeyService) validateGrantsAgainstUserInternal(ctx context.Context, userID string, grants []apikey.PermissionGrant) error {+// ErrApiKeyPersonalNoGrants is returned when a caller attempts to attach+// permission grants to a personal key, which has none of its own — it inherits+// the owner's role permissions at authentication time.+var ErrApiKeyPersonalNoGrants = errors.New("personal API keys inherit the owner's permissions and cannot carry grants")++// validateGrantsAgainstOwnerInternal caps grants at the key owner's role+// permissions, so no holder of apikeys:create/update — sudo included — can+// push a key above what its owner is allowed to do. Complements the caller-set+// check: the caller cap uses the credential's live context permissions, this+// one re-resolves the owner's roles from the DB. Skipped when RoleService is+// unavailable (bootstrap path only, where no human caller exists).+func (s *ApiKeyService) validateGrantsAgainstOwnerInternal(ctx context.Context, ownerID string, grants []apikey.PermissionGrant) error {if s.roleService == nil || len(grants) == 0 {return nil}- user, err := s.userService.GetUserByID(ctx, userID)+ user, err := s.userService.GetUserByID(ctx, ownerID)if err != nil {- return fmt.Errorf("load user for permission validation: %w", err)+ return fmt.Errorf("load owner for permission validation: %w", err)}ps, err := s.roleService.ResolvePermissions(ctx, user)if err != nil {- return fmt.Errorf("resolve user permissions: %w", err)+ return fmt.Errorf("resolve owner permissions: %w", err)+ }+ if err := validateGrantsAgainstPermissionSetInternal(ps, grants); err != nil {+ return fmt.Errorf("owner's roles do not allow this grant: %w", err)}+ return nil+}++// validateGrantsAgainstPermissionSetInternal refuses requests that would grant+// a key permissions the calling credential does not itself hold right now —+// session callers are capped by their role permissions, API-key callers by+// their own grants. Sudo callers always pass; a nil set denies everything.+func validateGrantsAgainstPermissionSetInternal(callerPerms *authz.PermissionSet, grants []apikey.PermissionGrant) error {for _, g := range grants {envID := ""if g.EnvironmentID != nil {envID = *g.EnvironmentID}- if !ps.Allows(g.Permission, envID) {+ if !callerPerms.Allows(g.Permission, envID) {return fmt.Errorf("%w: %s (env=%q)", ErrApiKeyPermissionEscalation, g.Permission, envID)}}@@ -181,6 +202,27 @@ func toApiKeyPermissionRowsInternal(apiKeyID string, grants []apikey.PermissionGreturn out}+// CreatePersonalApiKey creates a personal key for userID. Personal keys carry+// no permission grants of their own; the auth middleware resolves them to the+// owner's role permissions, so there is nothing to validate or escalate here.+func (s *ApiKeyService) CreatePersonalApiKey(ctx context.Context, userID string, req apikey.CreateUserApiKey) (*apikey.ApiKeyCreatedDto, error) {+ rawKey, err := s.generateApiKey()+ if err != nil {+ return nil, err+ }++ created, err := s.createAPIKeyWithRawKey(ctx, &userID, rawKey, apikey.CreateApiKey{+ Name: req.Name,+ Description: req.Description,+ ExpiresAt: req.ExpiresAt,+ }, nil, nil, models.ApiKeyKindPersonal)+ if err != nil {+ return nil, err+ }+ created.Permissions = []apikey.PermissionGrant{}+ return created, nil+}+func (s *ApiKeyService) createAPIKeyWithRawKey(ctx context.Context,userID *string,@@ -188,6 +230,7 @@ func (s *ApiKeyService) createAPIKeyWithRawKey(req apikey.CreateApiKey,managedBy *string,environmentID *string,+ kind string,) (*apikey.ApiKeyCreatedDto, error) {rawKey = normalizeAPIKeyInputInternal(rawKey)keyPrefix, err := parseAPIKeyPrefixInternal(rawKey)@@ -206,6 +249,7 @@ func (s *ApiKeyService) createAPIKeyWithRawKey(KeyHash: keyHash,KeyPrefix: keyPrefix,ManagedBy: managedBy,+ Kind: kind,UserID: userID,EnvironmentID: environmentID,ExpiresAt: req.ExpiresAt,@@ -243,6 +287,7 @@ func toAPIKeyDTOInternal(ak *models.ApiKey) apikey.ApiKey {Description: ak.Description,KeyPrefix: ak.KeyPrefix,UserID: ak.UserID,+ Kind: ak.Kind,IsStatic: isStaticAPIKeyInternal(*ak),IsBootstrap: isEnvironmentBootstrapKeyInternal(*ak),ExpiresAt: ak.ExpiresAt,@@ -264,7 +309,7 @@ func (s *ApiKeyService) CreateDefaultAdminAPIKey(ctx context.Context, userID, rareturn s.createAPIKeyWithRawKey(ctx, &userID, rawKey, apikey.CreateApiKey{Name: defaultAdminAPIKeyName,Description: defaultAdminAPIKeyDescription,- }, new(managedByAdminBootstrap), nil)+ }, new(managedByAdminBootstrap), nil, models.ApiKeyKindScoped)}func (s *ApiKeyService) getDefaultAdminUser(ctx context.Context) (*models.User, error) {@@ -412,7 +457,7 @@ func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environmentcreated, err := s.createAPIKeyWithRawKey(ctx, nil, rawKey, apikey.CreateApiKey{Name: name,Description: new("Auto-generated key for environment pairing"),- }, nil, &environmentID)+ }, nil, &environmentID, models.ApiKeyKindScoped)if err != nil {return nil, err}@@ -501,7 +546,7 @@ func (s *ApiKeyService) ListApiKeysByUser(ctx context.Context, userID string) ([return result, nil}-func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerUserID, id string, req apikey.UpdateApiKey) (*apikey.ApiKey, error) {+func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerPerms *authz.PermissionSet, id string, req apikey.UpdateApiKey) (*apikey.ApiKey, error) {var ak models.ApiKeyif err := s.db.WithContext(ctx).Where("id = ?", id).First(&ak).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {@@ -514,15 +559,25 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerUserID, id strin}if req.Permissions != nil {- // Validate against the key owner's permissions, not the caller's, so a- // holder of apikeys:update cannot escalate another user's key beyond- // what that user's own roles allow. Owner-less keys (env bootstrap)- // fall back to the caller — static admin keys are rejected above.- ownerID := callerUserID- if ak.UserID != nil {- ownerID = *ak.UserID+ if ak.Kind == models.ApiKeyKindPersonal {+ return nil, ErrApiKeyPersonalNoGrants+ }+ // Grants are capped twice: by the calling credential's effective+ // permissions (a holder of apikeys:update cannot grant anything the+ // credential itself cannot do right now) AND by the key owner's role+ // permissions (no caller can push another user's key above what that+ // user's own roles allow).+ if err := validateGrantsAgainstPermissionSetInternal(callerPerms, req.Permissions); err != nil {+ return nil, err+ }+ if ak.UserID == nil {+ // No owner to cap against. The only legitimate ownerless keys are+ // environment bootstrap keys, rejected as protected above — refuse+ // grant edits on any other ownerless row rather than fall back to+ // a weaker caller-only check.+ return nil, ErrApiKeyProtected}- if err := s.validateGrantsAgainstUserInternal(ctx, ownerID, req.Permissions); err != nil {+ if err := s.validateGrantsAgainstOwnerInternal(ctx, *ak.UserID, req.Permissions); err != nil {return nil, err}}@@ -562,6 +617,7 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerUserID, id strinDescription: ak.Description,KeyPrefix: ak.KeyPrefix,UserID: ak.UserID,+ Kind: ak.Kind,IsStatic: isStaticAPIKeyInternal(ak),IsBootstrap: isEnvironmentBootstrapKeyInternal(ak),ExpiresAt: ak.ExpiresAt,@@ -622,41 +678,41 @@ func (s *ApiKeyService) ValidateApiKey(ctx context.Context, rawKey string) (*mod}// ValidateApiKeyWithID is like ValidateApiKey but additionally returns the-// API key's database ID so callers can resolve per-key permissions.-func (s *ApiKeyService) ValidateApiKeyWithID(ctx context.Context, rawKey string) (*models.User, string, error) {+// API key record so callers can resolve permissions according to its kind.+func (s *ApiKeyService) ValidateApiKeyWithID(ctx context.Context, rawKey string) (*models.User, *models.ApiKey, error) {keyPrefix, err := parseAPIKeyPrefixInternal(rawKey)if err != nil {- return nil, "", err+ return nil, nil, err}var apiKeys []models.ApiKeyif err := s.db.WithContext(ctx).Where("key_prefix = ?", keyPrefix).Find(&apiKeys).Error; err != nil {- return nil, "", fmt.Errorf("failed to find API keys: %w", err)+ return nil, nil, fmt.Errorf("failed to find API keys: %w", err)}rawKey = normalizeAPIKeyInputInternal(rawKey)for _, apiKey := range apiKeys {if err := s.validateApiKeyHash(apiKey.KeyHash, rawKey); err == nil {if apiKey.ExpiresAt != nil && apiKey.ExpiresAt.Before(time.Now()) {- return nil, "", ErrApiKeyExpired+ return nil, nil, ErrApiKeyExpired}if apiKey.UserID == nil {- return nil, "", ErrApiKeyInvalid+ return nil, nil, ErrApiKeyInvalid}s.markApiKeyUsedAsync(ctx, apiKey.ID)user, err := s.userService.GetUserByID(ctx, *apiKey.UserID)if err != nil {- return nil, "", fmt.Errorf("failed to get user for API key: %w", err)+ return nil, nil, fmt.Errorf("failed to get user for API key: %w", err)}- return user, apiKey.ID, nil+ return user, &apiKey, nil}}- return nil, "", ErrApiKeyInvalid+ return nil, nil, ErrApiKeyInvalid}func (s *ApiKeyService) GetEnvironmentByApiKey(ctx context.Context, rawKey string) (*string, error) {diff --git a/backend/internal/services/api_key_service_test.go b/backend/internal/services/api_key_service_test.goindex de507788d..4ad5e2dbc 100644--- a/backend/internal/services/api_key_service_test.go+++ b/backend/internal/services/api_key_service_test.go@@ -190,7 +190,7 @@ func TestUpdateApiKeyRejectsStaticKey(t *testing.T) {created, err := service.CreateDefaultAdminAPIKey(ctx, adminUser.ID, "arc_bootstrapupdateprotected1234567890")require.NoError(t, err)- updated, err := service.UpdateApiKey(ctx, adminUser.ID, created.ApiKey.ID, apikey.UpdateApiKey{+ updated, err := service.UpdateApiKey(ctx, authz.SudoPermissionSet(), created.ApiKey.ID, apikey.UpdateApiKey{Name: new("renamed"),Description: new("updated description"),})@@ -216,10 +216,10 @@ func TestUpdateApiKeyRollsBackMetadataWhenPermissionUpdateFails(t *testing.T) {admin := createTestUser(t, userSvc, "admin-update-rollback", "admin-update-rollback")grantGlobalAdmin(t, roleSvc, admin.ID)- created, err := service.CreateApiKey(ctx, admin.ID, apikey.CreateApiKey{Name: "original"})+ created, err := service.CreateApiKey(ctx, admin.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "original"})require.NoError(t, err)- updated, err := service.UpdateApiKey(ctx, admin.ID, created.ApiKey.ID, apikey.UpdateApiKey{+ updated, err := service.UpdateApiKey(ctx, authz.SudoPermissionSet(), created.ApiKey.ID, apikey.UpdateApiKey{Name: new("renamed"),Permissions: []apikey.PermissionGrant{{Permission: authz.PermContainersList},@@ -233,6 +233,89 @@ func TestUpdateApiKeyRollsBackMetadataWhenPermissionUpdateFails(t *testing.T) {require.Equal(t, "original", stored.Name)}+func TestCreateApiKeyRejectsGrantsBeyondCallerPermissions(t *testing.T) {+ ctx := context.Background()+ service, _, userService := setupAPIKeyService(t)+ user := createTestAPIKeyUser(t, ctx, userService, "user-escalation")++ callerPerms := authz.NewPermissionSet()+ callerPerms.AddGlobal(authz.PermContainersList)++ // A grant the caller does not hold must be rejected.+ _, err := service.CreateApiKey(ctx, user.ID, callerPerms, apikey.CreateApiKey{+ Name: "escalated",+ Permissions: []apikey.PermissionGrant{{Permission: authz.PermApiKeysCreate}},+ })+ require.ErrorIs(t, err, ErrApiKeyPermissionEscalation)++ // A grant within the caller's set succeeds.+ created, err := service.CreateApiKey(ctx, user.ID, callerPerms, apikey.CreateApiKey{+ Name: "allowed",+ Permissions: []apikey.PermissionGrant{{Permission: authz.PermContainersList}},+ })+ require.NoError(t, err)+ require.Equal(t, models.ApiKeyKindScoped, created.ApiKey.Kind)+}++func TestApiKeyGrantsAreCappedByOwnerRoles(t *testing.T) {+ ctx := context.Background()+ db := setupAuthServiceTestDB(t)++ roleSvc := NewRoleService(db)+ require.NoError(t, roleSvc.EnsureBuiltInRoles(ctx))+ userSvc := NewUserService(db).WithRoleService(roleSvc)+ service := NewApiKeyService(db, userSvc).WithRoleService(roleSvc)+ // Owner has no roles at all — their permission ceiling is empty.+ owner := createTestUser(t, userSvc, "roleless-owner", "roleless-owner")++ // Create path: even a sudo caller cannot mint a key above the owner's roles.+ _, err := service.CreateApiKey(ctx, owner.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{+ Name: "above-owner",+ Permissions: []apikey.PermissionGrant{{Permission: authz.PermContainersList}},+ })+ require.ErrorIs(t, err, ErrApiKeyPermissionEscalation)++ // Update path: a grantless key cannot gain permissions the owner lacks.+ created, err := service.CreateApiKey(ctx, owner.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "grantless"})+ require.NoError(t, err)+ _, err = service.UpdateApiKey(ctx, authz.SudoPermissionSet(), created.ApiKey.ID, apikey.UpdateApiKey{+ Permissions: []apikey.PermissionGrant{{Permission: authz.PermContainersList}},+ })+ require.ErrorIs(t, err, ErrApiKeyPermissionEscalation)++ // Ownerless rows (not env-bootstrap; no production path creates these)+ // have no owner ceiling to validate against — grant edits are refused.+ require.NoError(t, db.WithContext(ctx).Create(&models.ApiKey{+ Name: "orphaned",+ KeyHash: "hash",+ KeyPrefix: "arc_orph",+ }).Error)+ var orphan models.ApiKey+ require.NoError(t, db.WithContext(ctx).Where("key_prefix = ?", "arc_orph").First(&orphan).Error)+ _, err = service.UpdateApiKey(ctx, authz.SudoPermissionSet(), orphan.ID, apikey.UpdateApiKey{+ Permissions: []apikey.PermissionGrant{{Permission: authz.PermContainersList}},+ })+ require.ErrorIs(t, err, ErrApiKeyProtected)+}++func TestCreatePersonalApiKeyHasNoGrantsAndCannotGainAny(t *testing.T) {+ ctx := context.Background()+ service, db, userService := setupAPIKeyService(t)+ user := createTestAPIKeyUser(t, ctx, userService, "user-personal")++ created, err := service.CreatePersonalApiKey(ctx, user.ID, apikey.CreateUserApiKey{Name: "personal"})+ require.NoError(t, err)+ require.Equal(t, models.ApiKeyKindPersonal, created.ApiKey.Kind)+ require.Empty(t, created.ApiKey.Permissions)+ require.Equal(t, models.ApiKeyKindPersonal, fetchAPIKey(t, db, created.ApiKey.ID).Kind)++ // Attaching grants to a personal key is rejected even for sudo callers.+ _, err = service.UpdateApiKey(ctx, authz.SudoPermissionSet(), created.ApiKey.ID, apikey.UpdateApiKey{+ Permissions: []apikey.PermissionGrant{{Permission: authz.PermContainersList}},+ })+ require.ErrorIs(t, err, ErrApiKeyPersonalNoGrants)+}+func TestReconcileDefaultAdminAPIKeyNoOpWhenUnchanged(t *testing.T) {ctx := context.Background()service, db, userService := setupAPIKeyService(t)@@ -290,7 +373,7 @@ func TestReconcileDefaultAdminAPIKeyPreservesUserManagedKeys(t *testing.T) {service, db, userService := setupAPIKeyService(t)adminUser := createDefaultAdminUser(t, ctx, userService)- userCreated, err := service.CreateApiKey(ctx, adminUser.ID, apikey.CreateApiKey{Name: "manual-key"})+ userCreated, err := service.CreateApiKey(ctx, adminUser.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "manual-key"})require.NoError(t, err)require.NoError(t, service.ReconcileDefaultAdminAPIKey(ctx, "arc_bootstrapmanualsafe1234567890"))@@ -361,7 +444,7 @@ func TestValidateAPIKeyUpdatesLastUsedAt(t *testing.T) {service, db, userService := setupAPIKeyService(t)user := createTestAPIKeyUser(t, ctx, userService, "user-validate")- created, err := service.CreateApiKey(ctx, user.ID, apikey.CreateApiKey{Name: "validate-key"})+ created, err := service.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "validate-key"})require.NoError(t, err)require.Nil(t, fetchAPIKey(t, db, created.ApiKey.ID).LastUsedAt)@@ -396,7 +479,7 @@ func TestValidateAPIKeyInvalidDoesNotUpdateLastUsedAt(t *testing.T) {service, db, userService := setupAPIKeyService(t)user := createTestAPIKeyUser(t, ctx, userService, "user-invalid")- created, err := service.CreateApiKey(ctx, user.ID, apikey.CreateApiKey{Name: "invalid-key"})+ created, err := service.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "invalid-key"})require.NoError(t, err)_, err = service.ValidateApiKey(ctx, invalidateAPIKey(created.Key))diff --git a/backend/internal/services/playwright_service.go b/backend/internal/services/playwright_service.goindex f8e7eb196..7265b1957 100644--- a/backend/internal/services/playwright_service.go+++ b/backend/internal/services/playwright_service.go@@ -40,9 +40,8 @@ func (ps *PlaywrightService) CreateTestApiKeys(ctx context.Context, count int) (}// Grant every recognized permission globally so the test key behaves like- // the legacy "admin-everywhere" credential the e2e suite expects. The- // owner is the `arcane` bootstrap user, who holds global Admin and- // therefore satisfies validateGrantsAgainstUserInternal.+ // the legacy "admin-everywhere" credential the e2e suite expects. There is+ // no request context here, so grant validation runs against a sudo set.allPerms := authz.AllPermissions()grants := make([]apikey.PermissionGrant, len(allPerms))for i, p := range allPerms {@@ -58,7 +57,7 @@ func (ps *PlaywrightService) CreateTestApiKeys(ctx context.Context, count int) (Permissions: grants,}- apiKey, err := ps.apiKeyService.CreateApiKey(ctx, user.ID, req)+ apiKey, err := ps.apiKeyService.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), req)if err != nil {return nil, fmt.Errorf("failed to create test API key %d: %w", i+1, err)}diff --git a/backend/resources/migrations/postgres/059_add_api_key_kind.sql b/backend/resources/migrations/postgres/059_add_api_key_kind.sqlnew file mode 100644index 000000000..88b9cafe2--- /dev/null+++ b/backend/resources/migrations/postgres/059_add_api_key_kind.sql@@ -0,0 +1,5 @@+-- +goose Up+ALTER TABLE api_keys ADD COLUMN IF NOT EXISTS kind TEXT NOT NULL DEFAULT 'scoped';++-- +goose Down+ALTER TABLE api_keys DROP COLUMN IF EXISTS kind;diff --git a/backend/resources/migrations/sqlite/059_add_api_key_kind.sql b/backend/resources/migrations/sqlite/059_add_api_key_kind.sqlnew file mode 100644index 000000000..9b2bc3ab9--- /dev/null+++ b/backend/resources/migrations/sqlite/059_add_api_key_kind.sql@@ -0,0 +1,5 @@+-- +goose Up+ALTER TABLE api_keys ADD COLUMN kind TEXT NOT NULL DEFAULT 'scoped';++-- +goose Down+ALTER TABLE api_keys DROP COLUMN kind;diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex a0c75b450..5478b23f2 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -3035,6 +3035,7 @@"_comment_api_key_permissions": "=== API KEY PERMISSIONS ===","api_key_permissions_description": "Choose the permissions this key may use. You cannot grant a permission you do not hold yourself.","api_key_permissions_required": "Pick at least one permission",+ "api_key_personal_inherits_description": "This key has the same permissions as your account.","api_key_scope_all": "All permissions","api_key_scope_role": "Matches {role}","api_key_scope_count": "{count} {count, plural, one {permission} other {permissions}}",diff --git a/frontend/src/lib/components/sheets/api-key-form-sheet.svelte b/frontend/src/lib/components/sheets/api-key-form-sheet.svelteindex fb99f9d29..4d9cb9e00 100644--- a/frontend/src/lib/components/sheets/api-key-form-sheet.svelte+++ b/frontend/src/lib/components/sheets/api-key-form-sheet.svelte@@ -13,14 +13,15 @@type ApiKeyFormProps = {open: boolean;apiKeyToEdit: ApiKey | null;- manifest: PermissionsManifest;+ mode?: 'admin' | 'personal';+ manifest?: PermissionsManifest;availablePermissions?: ApiKeyPermissionGrant[];onSubmit: (data: {apiKey: {name: string;description?: string;expiresAt?: string;- permissions: ApiKeyPermissionGrant[];+ permissions?: ApiKeyPermissionGrant[];};isEditMode: boolean;apiKeyId?: string;@@ -31,6 +32,7 @@let {open = $bindable(false),apiKeyToEdit = $bindable(),+ mode = 'admin',manifest,availablePermissions = [],onSubmit,@@ -41,22 +43,31 @@let isStaticApiKey = $derived(apiKeyToEdit?.isStatic ?? false);let isBootstrapApiKey = $derived(apiKeyToEdit?.isBootstrap ?? false);let isReadOnlyApiKey = $derived(isStaticApiKey || isBootstrapApiKey);+ // Personal keys carry no grants; they inherit the owner's role permissions.+ const hidePermissions = $derived(mode === 'personal' || apiKeyToEdit?.kind === 'personal');- const formSchema = z.object({- name: z.string().min(1, m.common_field_required({ field: m.api_key_name() })),- description: z.string().optional(),- expiresAt: z.date().optional(),- permissions: z.array(z.string()).min(1, m.api_key_permissions_required())- });+ const formSchema = $derived(+ z.object({+ name: z.string().min(1, m.common_field_required({ field: m.api_key_name() })),+ description: z.string().optional(),+ expiresAt: z.date().optional(),+ permissions: hidePermissions+ ? z.array(z.string()).default([])+ : z.array(z.string()).min(1, m.api_key_permissions_required())+ })+ );let formData = $derived({name: apiKeyToEdit?.name || '',description: apiKeyToEdit?.description || '',expiresAt: apiKeyToEdit?.expiresAt ? new Date(apiKeyToEdit.expiresAt) : undefined,- permissions: normalizePermissionSelection(- manifest,- availablePermissions.map((p) => p.permission)- )+ permissions:+ hidePermissions || !manifest+ ? []+ : normalizePermissionSelection(+ manifest,+ availablePermissions.map((p) => p.permission)+ )});let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));@@ -72,8 +83,8 @@description: data.description || undefined,expiresAt: data.expiresAt ? data.expiresAt.toISOString() : undefined,// v1: persist all picks as global grants (environmentId undefined).- // env-scoped picking is a follow-up.- permissions: data.permissions.map((p) => ({ permission: p }))+ // env-scoped picking is a follow-up. Personal keys carry no grants.+ ...(hidePermissions ? {} : { permissions: data.permissions.map((p) => ({ permission: p })) })};onSubmit({ apiKey: apiKeyData, isEditMode, apiKeyId: apiKeyToEdit?.id });@@ -136,14 +147,18 @@disabled={isReadOnlyApiKey}/>{#if !isReadOnlyApiKey}- <div>- <label for="permissions" class="text-sm font-medium">{m.roles_permissions_label()}</label>- <p class="text-muted-foreground mb-3 text-xs">{m.api_key_permissions_description()}</p>- <PermissionPicker {manifest} bind:selected={$inputs.permissions.value} showSearch />- {#if $inputs.permissions.error}- <p class="text-destructive mt-1 text-xs">{$inputs.permissions.error}</p>- {/if}- </div>+ {#if hidePermissions}+ <p class="text-muted-foreground text-sm">{m.api_key_personal_inherits_description()}</p>+ {:else if manifest}+ <div>+ <label for="permissions" class="text-sm font-medium">{m.roles_permissions_label()}</label>+ <p class="text-muted-foreground mb-3 text-xs">{m.api_key_permissions_description()}</p>+ <PermissionPicker {manifest} bind:selected={$inputs.permissions.value} showSearch />+ {#if $inputs.permissions.error}+ <p class="text-destructive mt-1 text-xs">{$inputs.permissions.error}</p>+ {/if}+ </div>+ {/if}{/if}</form>{/snippet}diff --git a/frontend/src/lib/services/api-key-service.ts b/frontend/src/lib/services/api-key-service.tsindex f24ed1db6..b9bee31f1 100644--- a/frontend/src/lib/services/api-key-service.ts+++ b/frontend/src/lib/services/api-key-service.ts@@ -1,5 +1,5 @@import BaseAPIService from './api-service';-import type { ApiKey, ApiKeyCreated, CreateApiKey, UpdateApiKey } from '$lib/types/auth';+import type { ApiKey, ApiKeyCreated, CreateApiKey, CreateUserApiKey, UpdateApiKey } from '$lib/types/auth';import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';import { transformPaginationParams } from '$lib/utils/tables';@@ -30,7 +30,7 @@ class ApiKeyAPIService extends BaseAPIService {return this.handleResponse(this.api.get('/auth/me/api-keys')) as Promise<ApiKey[]>;}- async createMine(apiKey: CreateApiKey): Promise<ApiKeyCreated> {+ async createMine(apiKey: CreateUserApiKey): Promise<ApiKeyCreated> {return this.handleResponse(this.api.post('/auth/me/api-keys', apiKey)) as Promise<ApiKeyCreated>;}diff --git a/frontend/src/lib/types/auth.ts b/frontend/src/lib/types/auth.tsindex dda97e3b2..bcd44c4aa 100644--- a/frontend/src/lib/types/auth.ts+++ b/frontend/src/lib/types/auth.ts@@ -203,6 +203,7 @@ export type ApiKey = {description?: string;keyPrefix: string;userId: string;+ kind?: 'scoped' | 'personal';isStatic: boolean;isBootstrap: boolean;expiresAt?: string;@@ -223,6 +224,13 @@ export type CreateApiKey = {permissions: ApiKeyPermissionGrant[];};+// Personal keys carry no grants; they inherit the owner's role permissions.+export type CreateUserApiKey = {+ name: string;+ description?: string;+ expiresAt?: string;+};+export type UpdateApiKey = {name?: string;description?: string;diff --git a/frontend/src/routes/(app)/account/+page.svelte b/frontend/src/routes/(app)/account/+page.svelteindex 5f4987e14..beb7271c0 100644--- a/frontend/src/routes/(app)/account/+page.svelte+++ b/frontend/src/routes/(app)/account/+page.svelte@@ -17,12 +17,11 @@import { m } from '$lib/paraglide/messages';import { userService } from '$lib/services/user-service';import { apiKeyService } from '$lib/services/api-key-service';- import { roleService } from '$lib/services/role-service';import userStore from '$lib/stores/user-store';import settingsStore from '$lib/stores/config-store';import { getDefaultProfilePicture } from '$lib/utils/docker';import { GLOBAL_SCOPE } from '$lib/types/auth';- import type { ApiKey, ApiKeyCreated, CreateApiKey, PermissionsManifest } from '$lib/types/auth';+ import type { ApiKey, ApiKeyCreated, ApiKeyPermissionGrant, CreateUserApiKey } from '$lib/types/auth';import { UserIcon, LogoutIcon, ShieldAlertIcon, SunIcon, MoonIcon, ApiKeyIcon, AddIcon, CopyIcon, TrashIcon } from '$lib/icons';let { data: _data }: PageProps = $props();@@ -82,7 +81,6 @@let showCreateKeyForm = $state(false);let creatingKey = $state(false);let createdKey = $state<ApiKeyCreated | null>(null);- let permissionsManifest = $state<PermissionsManifest | null>(null);$effect(() => {if (!profileLoaded && currentUser) {@@ -171,18 +169,22 @@}}- async function loadPermissionsManifest() {- try {- permissionsManifest = await roleService.getPermissionsManifest();- } catch (err) {- toast.error(err instanceof Error ? err.message : 'Failed to load available permissions');- }- }-- async function createApiKey({ apiKey }: { apiKey: CreateApiKey; isEditMode: boolean; apiKeyId?: string }) {+ async function createApiKey({+ apiKey+ }: {+ apiKey: { name: string; description?: string; expiresAt?: string; permissions?: ApiKeyPermissionGrant[] };+ isEditMode: boolean;+ apiKeyId?: string;+ }) {creatingKey = true;try {- const created = await apiKeyService.createMine(apiKey);+ // Personal keys carry no grants; they inherit the owner's role permissions.+ const payload: CreateUserApiKey = {+ name: apiKey.name,+ description: apiKey.description,+ expiresAt: apiKey.expiresAt+ };+ const created = await apiKeyService.createMine(payload);createdKey = created;showCreateKeyForm = false;await loadApiKeys();@@ -211,7 +213,6 @@onMount(() => {void loadApiKeys();- void loadPermissionsManifest();});async function logoutAllOther() {@@ -248,7 +249,7 @@{#if currentUser}<div class="grid gap-6 lg:grid-cols-3">- <!-- Left column: profile + password + preferences -->+ <!-- Left column: profile + password + API keys --><div class="space-y-6 lg:col-span-2"><!-- Profile --><Card class="overflow-hidden">@@ -257,19 +258,29 @@<p class="text-muted-foreground mt-1 text-xs sm:text-sm">Update your display name and email</p></div><div class="space-y-5 p-4 sm:p-6">- <div class="flex items-center gap-4">- <Avatar.Root class="size-16 rounded-xl">- <Avatar.Image src={avatarUrl} alt={currentUser.displayName ?? currentUser.username} />- <Avatar.Fallback- class="from-primary/20 to-primary/10 text-primary border-primary/20 rounded-xl border bg-linear-to-br text-xl font-semibold"- >- {(currentUser.displayName ?? currentUser.username).charAt(0).toUpperCase()}- </Avatar.Fallback>- </Avatar.Root>- <div class="min-w-0">- <div class="text-sm font-medium">@{currentUser.username}</div>- <div class="text-muted-foreground text-xs">- {isOidcUser ? 'Single sign-on account' : 'Local account'}+ <div class="flex items-center justify-between gap-4">+ <div class="flex min-w-0 items-center gap-4">+ <Avatar.Root class="size-16 rounded-xl">+ <Avatar.Image src={avatarUrl} alt={currentUser.displayName ?? currentUser.username} />+ <Avatar.Fallback+ class="from-primary/20 to-primary/10 text-primary border-primary/20 rounded-xl border bg-linear-to-br text-xl font-semibold"+ >+ {(currentUser.displayName ?? currentUser.username).charAt(0).toUpperCase()}+ </Avatar.Fallback>+ </Avatar.Root>+ <div class="min-w-0">+ <div class="text-sm font-medium">@{currentUser.username}</div>+ <div class="text-muted-foreground text-xs">+ {isOidcUser ? 'Single sign-on account' : 'Local account'}+ </div>+ </div>+ </div>+ <div class="hidden text-right sm:block">+ {#if safeFormatDate(currentUser.createdAt, 'PP')}+ <div class="text-muted-foreground text-xs">Member since {safeFormatDate(currentUser.createdAt, 'PP')}</div>+ {/if}+ <div class="text-muted-foreground text-xs" title={currentUser.lastLogin ?? ''}>+ Last login {safeFormatRelative(currentUser.lastLogin) ?? 'Never'}</div></div></div>@@ -290,22 +301,26 @@/></div></div>- <div class="flex justify-end gap-2">- <ArcaneButton- action="cancel"- tone="outline"- customLabel="Reset"- onclick={resetProfile}- disabled={!profileDirty || profileSaving}- />- <ArcaneButton- action="save"- customLabel="Save profile"- onclick={saveProfile}- loading={profileSaving}- disabled={!profileDirty || profileSaving || isOidcUser}- />- </div>+ {#if !isOidcUser}+ <div class="flex justify-end gap-2">+ <ArcaneButton+ action="cancel"+ tone="outline"+ customLabel="Reset"+ onclick={resetProfile}+ disabled={!profileDirty || profileSaving}+ />+ <ArcaneButton+ action="save"+ customLabel="Save profile"+ onclick={saveProfile}+ loading={profileSaving}+ disabled={!profileDirty || profileSaving}+ />+ </div>+ {:else}+ <p class="text-muted-foreground text-xs">Profile details are managed by your identity provider.</p>+ {/if}</div></Card>@@ -353,49 +368,6 @@</Card>{/if}- <!-- Preferences -->- <Card class="overflow-hidden">- <div class="border-b p-4 sm:p-6">- <h2 class="text-base font-semibold tracking-tight sm:text-lg">Preferences</h2>- <p class="text-muted-foreground mt-1 text-xs sm:text-sm">Personal display preferences</p>- </div>- <div class="divide-y p-2">- <div class="flex items-center justify-between gap-4 p-3">- <div class="min-w-0">- <div class="text-sm font-medium">Theme</div>- <div class="text-muted-foreground text-xs">Switch between light and dark mode</div>- </div>- <button- type="button"- onclick={toggleMode}- class="border-border hover:bg-muted/60 flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm font-medium transition-colors"- >- {#if mode.current === 'dark'}- <MoonIcon class="size-4" />- Dark- {:else}- <SunIcon class="size-4" />- Light- {/if}- </button>- </div>- <div class="flex items-center justify-between gap-4 p-3">- <div class="min-w-0">- <div class="text-sm font-medium">Language</div>- <div class="text-muted-foreground text-xs">UI language for this account</div>- </div>- <LocalePicker inline />- </div>- <div class="flex items-center justify-between gap-4 p-3">- <div class="min-w-0">- <div class="text-sm font-medium">{m.font_size()}</div>- <div class="text-muted-foreground text-xs">{m.font_size_description()}</div>- </div>- <FontSizePicker />- </div>- </div>- </Card>-<!-- API keys --><Card class="overflow-hidden"><div class="flex items-start justify-between gap-3 border-b p-4 sm:p-6">@@ -411,7 +383,6 @@customLabel="New key"icon={AddIcon}onclick={() => (showCreateKeyForm = true)}- disabled={!permissionsManifest}/>{/if}</div>@@ -498,35 +469,49 @@</Card></div>- <!-- Right column: account info + roles + danger zone -->+ <!-- Right column: preferences + roles + danger zone --><div class="space-y-6">- <!-- Account info -->+ <!-- Preferences --><Card class="overflow-hidden"><div class="border-b p-4 sm:p-6">- <h2 class="text-base font-semibold tracking-tight sm:text-lg">Account info</h2>+ <h2 class="text-base font-semibold tracking-tight sm:text-lg">Preferences</h2>+ <p class="text-muted-foreground mt-1 text-xs sm:text-sm">Personal display preferences</p></div>- <dl class="divide-y p-2 text-sm">+ <div class="divide-y p-2"><div class="flex items-center justify-between gap-4 p-3">- <dt class="text-muted-foreground">Username</dt>- <dd class="font-medium tabular-nums">@{currentUser.username}</dd>+ <div class="min-w-0">+ <div class="text-sm font-medium">Theme</div>+ <div class="text-muted-foreground text-xs">Switch between light and dark mode</div>+ </div>+ <button+ type="button"+ onclick={toggleMode}+ class="border-border hover:bg-muted/60 flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm font-medium transition-colors"+ >+ {#if mode.current === 'dark'}+ <MoonIcon class="size-4" />+ Dark+ {:else}+ <SunIcon class="size-4" />+ Light+ {/if}+ </button></div><div class="flex items-center justify-between gap-4 p-3">- <dt class="text-muted-foreground">Account type</dt>- <dd class="font-medium">{isOidcUser ? 'Single sign-on' : 'Local'}</dd>- </div>- {#if safeFormatDate(currentUser.createdAt, 'PP')}- <div class="flex items-center justify-between gap-4 p-3">- <dt class="text-muted-foreground">Member since</dt>- <dd class="font-medium">{safeFormatDate(currentUser.createdAt, 'PP')}</dd>+ <div class="min-w-0">+ <div class="text-sm font-medium">Language</div>+ <div class="text-muted-foreground text-xs">UI language for this account</div></div>- {/if}+ <LocalePicker inline />+ </div><div class="flex items-center justify-between gap-4 p-3">- <dt class="text-muted-foreground">Last login</dt>- <dd class="text-right font-medium" title={currentUser.lastLogin ?? ''}>- {safeFormatRelative(currentUser.lastLogin) ?? 'Never'}- </dd>+ <div class="min-w-0">+ <div class="text-sm font-medium">{m.font_size()}</div>+ <div class="text-muted-foreground text-xs">{m.font_size_description()}</div>+ </div>+ <FontSizePicker /></div>- </dl>+ </div></Card><!-- Roles & access -->@@ -619,13 +604,10 @@{/if}</div>-{#if permissionsManifest}- <ApiKeyFormSheet- bind:open={showCreateKeyForm}- apiKeyToEdit={null}- manifest={permissionsManifest}- availablePermissions={[]}- onSubmit={createApiKey}- isLoading={creatingKey}- />-{/if}+<ApiKeyFormSheet+ bind:open={showCreateKeyForm}+ apiKeyToEdit={null}+ mode="personal"+ onSubmit={createApiKey}+ isLoading={creatingKey}+/>diff --git a/frontend/src/routes/(app)/settings/api-keys/+page.svelte b/frontend/src/routes/(app)/settings/api-keys/+page.svelteindex 571b8d7a2..07a18581a 100644--- a/frontend/src/routes/(app)/settings/api-keys/+page.svelte+++ b/frontend/src/routes/(app)/settings/api-keys/+page.svelte@@ -51,7 +51,7 @@isEditMode,apiKeyId}: {- apiKey: CreateApiKey;+ apiKey: Omit<CreateApiKey, 'permissions'> & Partial<Pick<CreateApiKey, 'permissions'>>;isEditMode: boolean;apiKeyId?: string;}) {@@ -75,7 +75,7 @@});} else {const safeName = apiKey.name?.trim() || 'Unknown';- const result = await tryCatch(apiKeyService.create(apiKey));+ const result = await tryCatch(apiKeyService.create({ ...apiKey, permissions: apiKey.permissions ?? [] }));handleApiResultWithCallbacks({result,message: m.api_key_create_failed({ name: safeName }),diff --git a/types/apikey/apikey.go b/types/apikey/apikey.goindex c91daede0..dda1c61f3 100644--- a/types/apikey/apikey.go+++ b/types/apikey/apikey.go@@ -17,6 +17,15 @@ type CreateApiKey struct {Permissions []PermissionGrant `json:"permissions" minItems:"1" doc:"Permissions granted to this key. Cannot exceed the creator's own permissions."`}+// CreateUserApiKey represents the request body for creating a personal API key.+// Personal keys carry no grants of their own; they inherit the owner's role+// permissions at authentication time.+type CreateUserApiKey struct {+ Name string `json:"name" minLength:"1" maxLength:"255" doc:"Name of the API key" example:"My API Key"`+ Description *string `json:"description,omitempty" maxLength:"1000" doc:"Optional description of the API key"`+ ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"Optional expiration date for the API key"`+}+// ApiKey represents an API key without the secret.type ApiKey struct {ID string `json:"id" doc:"Unique identifier of the API key"`@@ -24,6 +33,7 @@ type ApiKey struct {Description *string `json:"description,omitempty" doc:"Description of the API key"`KeyPrefix string `json:"keyPrefix" doc:"Prefix of the API key for identification"`UserID *string `json:"userId,omitempty" doc:"ID of the user who owns the API key"`+ Kind string `json:"kind" doc:"Key kind: 'scoped' keys use their own permission grants, 'personal' keys inherit the owner's role permissions"`IsStatic bool `json:"isStatic" doc:"Whether the API key is environment-managed and protected from deletion"`IsBootstrap bool `json:"isBootstrap" doc:"Whether the API key is an auto-generated environment bootstrap key (locked from manual edit / delete)"`ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"Expiration date of the API key"`