This is an automated email from the ASF dual-hosted git repository. DImuthuUpe pushed a commit to branch permission-impl in repository https://gitbox.apache.org/repos/asf/airavata.git
commit 3b6fbe5a91e79aee898eed81fcf154c691c23c72 Author: DImuthuUpe <[email protected]> AuthorDate: Wed Nov 11 21:28:42 2026 -0500 Assign permissions to service accounts --- api/iam/dto/serviceaccount.go | 54 ++++- api/iam/model/serviceaccount.go | 5 + api/iam/model/serviceaccountpermission.go | 51 +++++ api/iam/repository/permissions.go | 90 ++++++-- api/iam/repository/permissions_test.go | 67 +++++- api/iam/repository/serviceaccount.go | 43 +++- api/iam/service/serviceaccount.go | 87 +++++++- docs/auth.md | 25 ++- docs/openapi.yaml | 21 +- internal/app/app.go | 7 +- internal/auth/middleware.go | 2 +- internal/auth/permission.go | 7 +- internal/auth/permission_test.go | 2 +- internal/db/migrate.go | 1 + .../0017_service_account_permissions.sql | 13 ++ internal/permission/permission.go | 22 ++ internal/server/serviceaccount_permission_test.go | 230 +++++++++++++++++++++ 17 files changed, 674 insertions(+), 53 deletions(-) diff --git a/api/iam/dto/serviceaccount.go b/api/iam/dto/serviceaccount.go index 2e1244c656..760494b5ef 100644 --- a/api/iam/dto/serviceaccount.go +++ b/api/iam/dto/serviceaccount.go @@ -26,6 +26,7 @@ import ( "github.com/apache/airavata/internal/auth" "github.com/apache/airavata/internal/httpx" + "github.com/apache/airavata/internal/permission" model "github.com/apache/airavata/api/iam/model" ) @@ -52,6 +53,10 @@ type ServiceAccountCreate struct { // ValidityDays is how long the first token lives. Defaults to 90. ValidityDays *int `json:"validityDays"` + + // Permissions is what the account may do. Empty means it can act only on its own + // records and what is shared with it. + Permissions []string `json:"permissions"` } // Validate implements httpx.Validator. @@ -63,16 +68,21 @@ func (r *ServiceAccountCreate) Validate() []httpx.FieldError { c.Email("email", "Email should be valid", r.Email) validateDescription(&c, r.Description) validateValidity(&c, r.ValidityDays) + validatePermissions(&c, r.Permissions) return c.Fields() } -// ServiceAccountUpdate changes an account's profile or status. Absent fields are left -// as they are. +// ServiceAccountUpdate changes an account's profile, status or permissions. Absent +// fields are left as they are. type ServiceAccountUpdate struct { DisplayName *string `json:"displayName"` Description *string `json:"description"` Email *string `json:"email"` Status *model.UserStatus `json:"status"` + + // Permissions, when present, replaces the account's whole set; an empty list + // removes every grant. Absent leaves the set as it is. + Permissions *[]string `json:"permissions"` } // Validate implements httpx.Validator. @@ -83,6 +93,9 @@ func (r *ServiceAccountUpdate) Validate() []httpx.FieldError { if r.Status != nil && !r.Status.Valid() { c.Add("status", "Status must be one of ACTIVE, INACTIVE, SUSPENDED") } + if r.Permissions != nil { + validatePermissions(&c, *r.Permissions) + } return c.Fields() } @@ -113,6 +126,34 @@ func validateValidity(c *httpx.Constraints, v *int) { } } +// validatePermissions rejects a permission that does not exist, and one that a service +// account may never hold, naming it so the caller can see which. +func validatePermissions(c *httpx.Constraints, ps []string) { + for _, p := range ps { + perm := permission.Permission(p) + switch { + case !perm.Valid(): + c.Add("permissions", "Unknown permission: "+p) + case !perm.GrantableToServiceAccount(): + c.Add("permissions", "Permission "+p+" cannot be granted to a service account") + } + } +} + +// ToPermissions converts validated names to permissions, dropping duplicates. +func ToPermissions(ps []string) []permission.Permission { + seen := make(map[permission.Permission]bool, len(ps)) + out := make([]permission.Permission, 0, len(ps)) + for _, p := range ps { + perm := permission.Permission(p) + if !seen[perm] { + seen[perm] = true + out = append(out, perm) + } + } + return out +} + func validateDescription(c *httpx.Constraints, d *string) { if d != nil && len(*d) > 1024 { c.Add("description", "Description must be at most 1024 characters") @@ -132,6 +173,9 @@ type ServiceAccountResponse struct { CreatedAt int64 `json:"createdAt"` TokenIssuedAt int64 `json:"tokenIssuedAt"` TokenExpiresAt int64 `json:"tokenExpiresAt"` + + // Permissions is what the account is allowed to do, sorted. + Permissions []string `json:"permissions"` } // ServiceAccountTokenResponse is returned when a token is minted: on create and on @@ -151,12 +195,18 @@ func ToServiceAccountResponse(u *model.User) ServiceAccountResponse { Email: u.Email, Status: u.Status, CreatedAt: u.CreatedAt, + Permissions: []string{}, } if sa := u.ServiceAccount; sa != nil { out.Description = sa.Description out.CreatedBy = sa.CreatedBy out.TokenIssuedAt = sa.TokenIssuedAt out.TokenExpiresAt = sa.TokenExpiresAt + set := make(permission.Set, len(sa.Permissions)) + for _, p := range sa.Permissions { + set[p.Permission] = struct{}{} + } + out.Permissions = set.Sorted() } return out } diff --git a/api/iam/model/serviceaccount.go b/api/iam/model/serviceaccount.go index 881718e913..0db70e2ca7 100644 --- a/api/iam/model/serviceaccount.go +++ b/api/iam/model/serviceaccount.go @@ -42,6 +42,11 @@ type ServiceAccount struct { TokenHash string `gorm:"column:token_hash;type:varchar(64);not null;uniqueIndex:uk_service_account_token_hash" json:"-"` TokenIssuedAt int64 `gorm:"column:token_issued_at;not null" json:"tokenIssuedAt"` TokenExpiresAt int64 `gorm:"column:token_expires_at;not null" json:"tokenExpiresAt"` + + // Permissions is what the account is allowed to do beyond acting on its own + // records. Owned by the account: deleting it deletes the rows. Services write them + // through the permission set operations, not by mutating this slice. + Permissions []ServiceAccountPermission `gorm:"foreignKey:UserID;references:UserID;constraint:OnDelete:CASCADE,OnUpdate:CASCADE" json:"-"` } // TableName pins the table name. diff --git a/api/iam/model/serviceaccountpermission.go b/api/iam/model/serviceaccountpermission.go new file mode 100644 index 0000000000..a6d657c183 --- /dev/null +++ b/api/iam/model/serviceaccountpermission.go @@ -0,0 +1,51 @@ +/** +* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. + */ + +package model + +import ( + "gorm.io/gorm" + + "github.com/apache/airavata/internal/permission" +) + +// ServiceAccountPermission grants one permission to one service account. The primary +// key is the (user_id, permission) pair, so an account holds each permission at most +// once. +// +// A service account's permissions are exactly these rows. It holds no role that grants +// any, so granting a permission to a role never reaches a service account, and each +// account can differ from the next. The rows belong to the account and go with it. +type ServiceAccountPermission struct { + UserID string `gorm:"column:user_id;primaryKey;type:varchar(255)" json:"userId"` + Permission permission.Permission `gorm:"column:permission;primaryKey;type:varchar(64)" json:"permission"` +} + +// TableName returns the table backing ServiceAccountPermission. +func (ServiceAccountPermission) TableName() string { return "service_account_permissions" } + +// BeforeSave rejects a permission that does not exist or that no service account may +// hold, so neither can be stored by any path, including one that skips the service. +func (p *ServiceAccountPermission) BeforeSave(*gorm.DB) error { + if !p.Permission.GrantableToServiceAccount() { + return gorm.ErrInvalidValue + } + return nil +} diff --git a/api/iam/repository/permissions.go b/api/iam/repository/permissions.go index e4e0fdfc9e..0bc79a40a7 100644 --- a/api/iam/repository/permissions.go +++ b/api/iam/repository/permissions.go @@ -28,6 +28,7 @@ import ( "gorm.io/gorm" + "github.com/apache/airavata/internal/auth" "github.com/apache/airavata/internal/permission" "github.com/apache/airavata/internal/role" @@ -38,22 +39,28 @@ import ( // stale a grant can be on a server that did not itself make the change. const DefaultPermissionTTL = time.Minute -// PermissionResolver resolves roles to permissions from the role_permissions table. +// PermissionResolver resolves a caller to the permissions they hold. // -// The cache is keyed by role rather than by user. There are few roles and many users, -// so it stays small however many people are signed in, and a change to a role is one -// Invalidate rather than a hunt for every user holding it. +// A person holds what their roles grant, read from the role_permissions table. The +// cache for that is keyed by role rather than by user: there are few roles and many +// users, so it stays small however many people are signed in, and a change to a role is +// one Invalidate rather than a hunt for every user holding it. // -// A change made through this process calls Invalidate and takes effect at once. A -// change made by another server instance, or directly in the database, is picked up -// when the cached entry expires. +// A service account holds what has been granted to that account in +// service_account_permissions, and nothing from any role. Those are cached per account, +// which is bounded by the number of service accounts. +// +// A change made through this process calls Invalidate or InvalidateUser and takes +// effect at once. A change made by another server instance, or directly in the +// database, is picked up when the cached entry expires. type PermissionResolver struct { db *gorm.DB ttl time.Duration now func() time.Time - mu sync.RWMutex - cache map[role.Role]cachedPermissions + mu sync.RWMutex + cache map[role.Role]cachedPermissions + accounts map[string]cachedPermissions } type cachedPermissions struct { @@ -68,19 +75,27 @@ func NewPermissionResolver(db *gorm.DB, ttl time.Duration) *PermissionResolver { ttl = DefaultPermissionTTL } return &PermissionResolver{ - db: db, - ttl: ttl, - now: time.Now, - cache: make(map[role.Role]cachedPermissions), + db: db, + ttl: ttl, + now: time.Now, + cache: make(map[role.Role]cachedPermissions), + accounts: make(map[string]cachedPermissions), } } -// Permissions implements auth.PermissionResolver: the union of what every authority -// grants. An authority that is not a recognised role grants nothing. +// Permissions implements auth.PermissionResolver. +// +// For a service account (told apart by its reserved id prefix, which no identity +// provider can produce) it is the account's own grants. For anyone else it is the union +// of what every authority grants; an authority that is not a recognised role grants +// nothing. // // SUPER_ADMIN holds every permission without a lookup, so the bootstrap account keeps // working whatever state the table is in. -func (r *PermissionResolver) Permissions(ctx context.Context, authorities []string) permission.Set { +func (r *PermissionResolver) Permissions(ctx context.Context, name string, authorities []string) permission.Set { + if auth.IsServiceAccountID(name) { + return r.forAccount(ctx, name) + } out := permission.Set{} for _, a := range authorities { ro := role.Role(a) @@ -100,12 +115,51 @@ func (r *PermissionResolver) Permissions(ctx context.Context, authorities []stri return out } -// Invalidate forgets every cached role, so the next request reads the table again. Call -// it after changing role_permissions. +// Invalidate forgets everything cached, so the next request reads the tables again. +// Call it after changing role_permissions. func (r *PermissionResolver) Invalidate() { r.mu.Lock() r.cache = make(map[role.Role]cachedPermissions) + r.accounts = make(map[string]cachedPermissions) + r.mu.Unlock() +} + +// InvalidateUser forgets one service account's permissions. Call it after changing or +// deleting that account's grants. +func (r *PermissionResolver) InvalidateUser(id string) { + r.mu.Lock() + delete(r.accounts, id) + r.mu.Unlock() +} + +func (r *PermissionResolver) forAccount(ctx context.Context, id string) permission.Set { + r.mu.RLock() + hit, ok := r.accounts[id] + r.mu.RUnlock() + if ok && r.now().Before(hit.expires) { + return hit.perms + } + + var rows []model.ServiceAccountPermission + if err := r.db.WithContext(ctx).Where("user_id = ?", id).Find(&rows).Error; err != nil { + slog.Error("failed to look up service account permissions; granting none", + "serviceAccount", id, "error", err) + return nil + } + perms := make(permission.Set, len(rows)) + for _, row := range rows { + // Re-checked on read, not only on write: a row inserted around the service, or + // kept from a build with a different catalogue, must not hand a service account + // a permission it may never hold. + if row.Permission.GrantableToServiceAccount() { + perms[row.Permission] = struct{}{} + } + } + + r.mu.Lock() + r.accounts[id] = cachedPermissions{perms: perms, expires: r.now().Add(r.ttl)} r.mu.Unlock() + return perms } func (r *PermissionResolver) forRole(ctx context.Context, ro role.Role) permission.Set { diff --git a/api/iam/repository/permissions_test.go b/api/iam/repository/permissions_test.go index 990d06a907..5c09108106 100644 --- a/api/iam/repository/permissions_test.go +++ b/api/iam/repository/permissions_test.go @@ -49,7 +49,7 @@ func TestPermissionResolver(t *testing.T) { {"unknown authority", []string{"WIZARD"}, false}, {"no authorities", nil, false}, } { - if got := r.Permissions(ctx, tc.authorities).Has(permission.AuditRead); got != tc.want { + if got := r.Permissions(ctx, "", tc.authorities).Has(permission.AuditRead); got != tc.want { t.Errorf("%s: has audit:read = %v, want %v", tc.name, got, tc.want) } } @@ -61,28 +61,28 @@ func TestPermissionResolverCachesUntilInvalidatedOrExpired(t *testing.T) { ctx := context.Background() user := []string{"USER"} - if r.Permissions(ctx, user).Has(permission.AuditRead) { + if r.Permissions(ctx, "", user).Has(permission.AuditRead) { t.Fatal("USER holds audit:read before any grant") } if err := gdb.Create(&model.RolePermission{Role: role.User, Permission: permission.AuditRead}).Error; err != nil { t.Fatal(err) } - if r.Permissions(ctx, user).Has(permission.AuditRead) { + if r.Permissions(ctx, "", user).Has(permission.AuditRead) { t.Error("a change was visible before Invalidate or expiry; the cache is not caching") } r.Invalidate() - if !r.Permissions(ctx, user).Has(permission.AuditRead) { + if !r.Permissions(ctx, "", user).Has(permission.AuditRead) { t.Error("the grant is not visible after Invalidate") } // A fresh resolver with a tiny TTL picks changes up on its own. short := iamrepo.NewPermissionResolver(gdb, time.Millisecond) - short.Permissions(ctx, user) + short.Permissions(ctx, "", user) if err := gdb.Delete(&model.RolePermission{}, "role = ? AND permission = ?", "USER", "audit:read").Error; err != nil { t.Fatal(err) } time.Sleep(5 * time.Millisecond) - if short.Permissions(ctx, user).Has(permission.AuditRead) { + if short.Permissions(ctx, "", user).Has(permission.AuditRead) { t.Error("the revoked grant outlived its TTL") } } @@ -94,11 +94,11 @@ func TestPermissionResolverFailsClosed(t *testing.T) { if err := gdb.Migrator().DropTable(&model.RolePermission{}); err != nil { t.Fatal(err) } - if r.Permissions(context.Background(), []string{"ADMIN"}).Has(permission.AuditRead) { + if r.Permissions(context.Background(), "", []string{"ADMIN"}).Has(permission.AuditRead) { t.Error("a failed lookup granted a permission") } // SUPER_ADMIN needs no lookup, so it survives a broken table. - if !r.Permissions(context.Background(), []string{"SUPER_ADMIN"}).Has(permission.AuditRead) { + if !r.Permissions(context.Background(), "", []string{"SUPER_ADMIN"}).Has(permission.AuditRead) { t.Error("SUPER_ADMIN was locked out by a broken role_permissions table") } if err := gdb.AutoMigrate(&model.RolePermission{}); err != nil { @@ -107,7 +107,7 @@ func TestPermissionResolverFailsClosed(t *testing.T) { if err := gdb.Create(&model.RolePermission{Role: role.Admin, Permission: permission.AuditRead}).Error; err != nil { t.Fatal(err) } - if !r.Permissions(context.Background(), []string{"ADMIN"}).Has(permission.AuditRead) { + if !r.Permissions(context.Background(), "", []string{"ADMIN"}).Has(permission.AuditRead) { t.Error("the failure was cached") } } @@ -123,3 +123,52 @@ func TestRolePermissionRejectsUnknownValues(t *testing.T) { } } } + +// A service account resolves from its own grants only, cached per account until +// InvalidateUser, and ignores what any role grants. +func TestPermissionResolverForServiceAccounts(t *testing.T) { + gdb := openTestDB(t) + r := iamrepo.NewPermissionResolver(gdb, time.Hour) + ctx := context.Background() + const id = "sa:ci" + if err := gdb.Create(&model.User{ID: id, CreatedAt: 1}).Error; err != nil { + t.Fatal(err) + } + if err := gdb.Create(&model.ServiceAccount{UserID: id, CreatedBy: "admin", TokenHash: "h", TokenIssuedAt: 1, TokenExpiresAt: 2}).Error; err != nil { + t.Fatal(err) + } + + // USER=none, ADMIN=audit:read by default; the account's USER authority must not matter. + if r.Permissions(ctx, id, []string{"ADMIN"}).Has(permission.AuditRead) { + t.Fatal("a service account inherited a role's grant") + } + + if err := gdb.Create(&model.ServiceAccountPermission{UserID: id, Permission: permission.ProcessList}).Error; err != nil { + t.Fatal(err) + } + if r.Permissions(ctx, id, nil).Has(permission.ProcessList) { + t.Error("a change was visible before invalidation; the cache is not caching") + } + r.InvalidateUser(id) + if !r.Permissions(ctx, id, nil).Has(permission.ProcessList) { + t.Error("the grant is not visible after InvalidateUser") + } + + // A forbidden permission inserted around the model is ignored. + if err := gdb.Exec("INSERT INTO service_account_permissions (user_id, permission) VALUES (?, ?)", id, "admin:manage").Error; err != nil { + t.Fatal(err) + } + r.Invalidate() + if r.Permissions(ctx, id, nil).Has(permission.AdminManage) { + t.Error("a service account holds admin:manage") + } +} + +func TestServiceAccountPermissionRejectsForbiddenValues(t *testing.T) { + gdb := openTestDB(t) + for _, p := range []permission.Permission{permission.AdminManage, permission.ServiceAccountManage, "bogus:x"} { + if err := gdb.Create(&model.ServiceAccountPermission{UserID: "sa:x", Permission: p}).Error; err == nil { + t.Errorf("stored %s", p) + } + } +} diff --git a/api/iam/repository/serviceaccount.go b/api/iam/repository/serviceaccount.go index ed0a12cb45..b34c06ca29 100644 --- a/api/iam/repository/serviceaccount.go +++ b/api/iam/repository/serviceaccount.go @@ -27,8 +27,10 @@ import ( "time" "gorm.io/gorm" + "gorm.io/gorm/clause" "github.com/apache/airavata/internal/auth" + "github.com/apache/airavata/internal/permission" model "github.com/apache/airavata/api/iam/model" ) @@ -51,6 +53,7 @@ func (r *ServiceAccountRepository) FindAll(ctx context.Context) ([]model.User, e var out []model.User err := r.db.WithContext(ctx). Preload("ServiceAccount"). + Preload("ServiceAccount.Permissions"). Where("auth_method = ?", model.AuthMethodServiceAccount). Order("user_id"). Find(&out).Error @@ -63,6 +66,7 @@ func (r *ServiceAccountRepository) FindByID(ctx context.Context, id string) (*mo var out model.User err := r.db.WithContext(ctx). Preload("ServiceAccount"). + Preload("ServiceAccount.Permissions"). Where("auth_method = ?", model.AuthMethodServiceAccount). First(&out, "user_id = ?", id).Error if err != nil { @@ -74,9 +78,44 @@ func (r *ServiceAccountRepository) FindByID(ctx context.Context, id string) (*mo return &out, nil } -// Save inserts or updates a service account row. +// Save inserts or updates a service account row. Its permissions are written only +// through ReplacePermissions, never as a side effect of saving the account. func (r *ServiceAccountRepository) Save(ctx context.Context, sa *model.ServiceAccount) error { - return r.db.WithContext(ctx).Save(sa).Error + return r.db.WithContext(ctx).Omit(clause.Associations).Save(sa).Error +} + +// ReplacePermissions makes want the account's complete set of grants: rows not in want +// are deleted and missing ones inserted, and rows already present are left alone, so an +// unchanged permission leaves no trace in the audit log. +func (r *ServiceAccountRepository) ReplacePermissions(ctx context.Context, id string, want []permission.Permission) error { + db := r.db.WithContext(ctx) + + var have []model.ServiceAccountPermission + if err := db.Where("user_id = ?", id).Find(&have).Error; err != nil { + return err + } + keep := make(map[permission.Permission]bool, len(want)) + for _, p := range want { + keep[p] = true + } + present := make(map[permission.Permission]bool, len(have)) + for _, row := range have { + present[row.Permission] = true + if !keep[row.Permission] { + if err := db.Delete(&row).Error; err != nil { + return err + } + } + } + for _, p := range want { + if present[p] { + continue + } + if err := db.Create(&model.ServiceAccountPermission{UserID: id, Permission: p}).Error; err != nil { + return err + } + } + return nil } // ServiceAccountTokenLookup resolves service account tokens against the database. It diff --git a/api/iam/service/serviceaccount.go b/api/iam/service/serviceaccount.go index 9183058f61..2e257ea142 100644 --- a/api/iam/service/serviceaccount.go +++ b/api/iam/service/serviceaccount.go @@ -41,23 +41,45 @@ import ( // ServiceAccountService administers service accounts: non-human users that // authenticate with an Airavata-issued, expiring token. // -// Every operation needs serviceaccount:read or serviceaccount:manage, which ADMIN holds by default. A service account is otherwise an ordinary user — -// it owns what it creates, can be shared with and can join groups — but it can never -// administer anything: its token always resolves to USER authority, and since -// creating service accounts needs ADMIN, a service account cannot mint another. +// Every operation needs serviceaccount:read or serviceaccount:manage, which ADMIN holds +// by default. A service account is otherwise an ordinary user — it owns what it +// creates, can be shared with and can join groups — and what more it may do is the set +// of permissions granted to that account alone. It holds no role that grants any. +// +// The permissions that manage identities and privileges can never be granted to one, so +// a service account cannot become an administrator or mint another account. And nobody +// can grant what they do not hold themselves. type ServiceAccountService struct { db *gorm.DB accounts *repository.ServiceAccountRepository users *repository.UserRepository shares *sharingrepo.Repository + perms PermissionInvalidator // now is the clock, replaceable in tests. now func() time.Time } +// PermissionInvalidator is told when a service account's grants change, so the +// resolver stops serving the old ones. +type PermissionInvalidator interface { + InvalidateUser(id string) +} + // NewServiceAccountService returns a service account service. -func NewServiceAccountService(db *gorm.DB, accounts *repository.ServiceAccountRepository, users *repository.UserRepository, shares *sharingrepo.Repository) *ServiceAccountService { - return &ServiceAccountService{db: db, accounts: accounts, users: users, shares: shares, now: time.Now} +func NewServiceAccountService(db *gorm.DB, accounts *repository.ServiceAccountRepository, users *repository.UserRepository, shares *sharingrepo.Repository, perms PermissionInvalidator) *ServiceAccountService { + return &ServiceAccountService{db: db, accounts: accounts, users: users, shares: shares, perms: perms, now: time.Now} +} + +// requireHeld refuses a grant the caller could not make for themselves. Without it, an +// administrator limited to some permissions could hand an account the rest. +func requireHeld(grantor *auth.Principal, granted []permission.Permission) error { + for _, p := range granted { + if !grantor.Can(p) { + return httpx.Forbidden("You cannot grant %s because you do not hold it", p) + } + } + return nil } // Create registers a service account and mints its first token. The token is in the @@ -68,6 +90,11 @@ func (s *ServiceAccountService) Create(ctx context.Context, req *dto.ServiceAcco return nil, err } + granted := dto.ToPermissions(req.Permissions) + if err := requireHeld(admin, granted); err != nil { + return nil, err + } + id := auth.ServiceAccountIDPrefix + req.Name token, hash, err := auth.GenerateServiceAccountToken() if err != nil { @@ -93,6 +120,10 @@ func (s *ServiceAccountService) Create(ctx context.Context, req *dto.ServiceAcco TokenExpiresAt: expiry(now, dto.ValidityDaysOrDefault(req.ValidityDays)), }, } + for _, p := range granted { + user.ServiceAccount.Permissions = append(user.ServiceAccount.Permissions, + model.ServiceAccountPermission{UserID: id, Permission: p}) + } err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { if _, err := s.users.WithTx(tx).FindByID(ctx, id); err == nil { @@ -143,20 +174,48 @@ func (s *ServiceAccountService) Get(ctx context.Context, id string) (*dto.Servic return &out, nil } -// Update changes a service account's display name, description, email or status. -// Setting the status to anything but ACTIVE stops its token working immediately, -// without discarding it, so the account can be re-enabled. +// Update changes a service account's display name, description, email, status or +// permissions. Setting the status to anything but ACTIVE stops its token working +// immediately, without discarding it, so the account can be re-enabled. Setting the +// permissions replaces the whole set, and takes effect on the account's next request. func (s *ServiceAccountService) Update(ctx context.Context, id string, req *dto.ServiceAccountUpdate) (*dto.ServiceAccountResponse, error) { - if _, err := auth.RequirePermission(ctx, permission.ServiceAccountManage); err != nil { + admin, err := auth.RequirePermission(ctx, permission.ServiceAccountManage) + if err != nil { return nil, err } var user *model.User - err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { var err error if user, err = s.require(ctx, s.accounts.WithTx(tx), id); err != nil { return err } + if req.Permissions != nil { + want := dto.ToPermissions(*req.Permissions) + // Only what is being added needs the caller to hold it: leaving a grant + // the caller could not make themselves in place is not granting it. + have := make(map[permission.Permission]bool, len(user.ServiceAccount.Permissions)) + for _, p := range user.ServiceAccount.Permissions { + have[p.Permission] = true + } + var added []permission.Permission + for _, p := range want { + if !have[p] { + added = append(added, p) + } + } + if err := requireHeld(admin, added); err != nil { + return err + } + if err := s.accounts.WithTx(tx).ReplacePermissions(ctx, id, want); err != nil { + return err + } + user.ServiceAccount.Permissions = user.ServiceAccount.Permissions[:0] + for _, p := range want { + user.ServiceAccount.Permissions = append(user.ServiceAccount.Permissions, + model.ServiceAccountPermission{UserID: id, Permission: p}) + } + } if req.DisplayName != nil { user.FirstName = req.DisplayName } @@ -177,6 +236,9 @@ func (s *ServiceAccountService) Update(ctx context.Context, id string, req *dto. if err != nil { return nil, err } + // After the commit, so a request racing the change cannot cache the old grants + // after the invalidation and keep them for a whole TTL. + s.perms.InvalidateUser(id) out := dto.ToServiceAccountResponse(user) return &out, nil } @@ -260,6 +322,9 @@ func (s *ServiceAccountService) Delete(ctx context.Context, id string) error { // Memberships, roles and the token row cascade with the user. return tx.Delete(&model.User{}, "user_id = ?", user.ID).Error }) + if err == nil { + s.perms.InvalidateUser(id) + } if isForeignKeyViolation(s.db, err) { return httpx.Conflict("Service account %s still owns records and cannot be deleted; set its status to INACTIVE to revoke its access instead", id) } diff --git a/docs/auth.md b/docs/auth.md index 61e1b4ff21..8e9062c6cf 100644 --- a/docs/auth.md +++ b/docs/auth.md @@ -37,10 +37,11 @@ If CILogon cannot be reached, the request fails with `502 Unable to validate bea A service account is an identity for software rather than a person. An admin creates it, and Airavata issues it a token. The token expires, and an admin can renew or regenerate it. -A service account is an ordinary user in every way but two: +A service account is an ordinary user in every way but three: -- **It is never an admin.** Its token always authenticates with `USER` authority. Rows in `user_roles` are ignored for service accounts, so it can't be promoted. Because of this, a service account can't create or manage other service accounts. -- **Only admins create and manage it.** Every `/api/v1/service-accounts` endpoint requires `ADMIN` or `SUPER_ADMIN`. +- **It is never an admin.** Its token always authenticates with `USER` authority. Rows in `user_roles` are ignored for service accounts, so it can't be promoted. A service account can't create or manage other service accounts either. +- **Only admins create and manage it.** Every `/api/v1/service-accounts` endpoint needs `serviceaccount:read` or `serviceaccount:manage`, which `ADMIN` and `SUPER_ADMIN` hold. +- **Its permissions are its own.** See [Permissions for a service account](#permissions-for-a-service-account). Apart from that, it does what a user does. It owns the SSH credentials, cluster configs, storages and runs it creates. Other users can share records with it, by user id or through a group, and add it to groups. @@ -80,6 +81,24 @@ curl -s localhost:9095/api/v1/ssh-credentials -H "Authorization: Bearer $SA_TOKE Service account tokens start with `airavata_sa_`. The server checks them against its own database and never sends them to CILogon. The `airavata_sa_` prefix also helps secret scanners recognise a leaked token. +#### Permissions for a service account + +By default a service account can do only what any user can do with their own records and what is shared with them. To let it do more, grant it [permissions](#permissions). Each account has its own set, so one can read every process while another can only use its own. + +```bash +curl -X POST https://airavata.example.org/api/v1/service-accounts \ + -H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \ + -d '{"name": "monitor", "permissions": ["process:list", "cluster:discover"]}' +``` + +Change the set later with `PUT /api/v1/service-accounts/{id}`. A `permissions` list **replaces** the whole set, an empty list removes every grant, and leaving it out changes nothing. The change applies on the account's next request. `GET /api/v1/service-accounts/{id}` and `GET /api/v1/users/me` (called with the account's token) both list what it holds. + +Three rules keep this from becoming a way round the limits above: + +- **A service account holds only what was granted to it.** It gets nothing from a role. Granting a permission to `USER` reaches people, not service accounts. +- **Some permissions can never be granted to one:** `admin:manage`, `user:update_any` and `serviceaccount:manage`. A token holding them could appoint administrators, rewrite another user's profile, or mint service accounts, which would widen its own access. The API refuses them with `400`, and a row inserted into the database by hand is ignored. `user:create` and `user:set_status` can be granted, for an onboarding integration, but they don't reach administrators: changing an administrato [...] +- **You can only grant what you hold yourself.** An admin missing a permission can't hand it out. The API answers `403`. + #### Manage the token Each service account has one token at a time. diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 8a757c2941..e706ee9b6f 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -3420,6 +3420,14 @@ components: minimum: 1 maximum: 365 description: How long the first token lives. Defaults to 90. + permissions: + type: array + items: { type: string } + description: >- + What the account may do, such as `process:list`. Empty or absent means it can + act only on its own records and what is shared with it. Refused with 400: + an unknown permission, and `admin:manage`, `user:update_any` and + `serviceaccount:manage`, which no service account may hold. Refused with 403: a permission the caller does not hold themselves. required: [name] ServiceAccountUpdate: @@ -3433,6 +3441,13 @@ components: oneOf: - { $ref: "#/components/schemas/UserStatus" } - { type: "null" } + permissions: + type: [array, "null"] + items: { type: string } + description: >- + Replaces the account's whole set; an empty list removes every grant, and + absent leaves the set as it is. Takes effect on the account's next request. + The same rules as on create apply to what is being added. ServiceAccountTokenRequest: type: object @@ -3488,7 +3503,11 @@ components: createdAt: { type: integer, format: int64, description: Milliseconds since the epoch. } tokenIssuedAt: { type: integer, format: int64, description: Milliseconds since the epoch. } tokenExpiresAt: { type: integer, format: int64, description: Milliseconds since the epoch. } - required: [serviceAccountId, name, displayName, description, email, status, createdBy, createdAt, tokenIssuedAt, tokenExpiresAt] + permissions: + type: array + items: { type: string } + description: What the account may do, sorted. + required: [serviceAccountId, name, displayName, description, email, status, createdBy, createdAt, tokenIssuedAt, tokenExpiresAt, permissions] ServiceAccountTokenResponse: type: object diff --git a/internal/app/app.go b/internal/app/app.go index c2189b2240..e84cab1673 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -190,6 +190,9 @@ func NewRepositories(db *gorm.DB) *Repositories { // The repositories stay local: they are an implementation detail of the services above // them, and nothing outside this function has ever wanted one directly. func NewServices(cfg config.Config, db *gorm.DB, repos *Repositories, workflowBackend backend.Backend) *Services { + // Built first: the service account service tells it when a grant changes. + permissions := iamrepo.NewPermissionResolver(db, iamrepo.DefaultPermissionTTL) + // Repositories. users := repos.Users groups := repos.Groups @@ -248,7 +251,7 @@ func NewServices(cfg config.Config, db *gorm.DB, repos *Repositories, workflowBa Config: cfg, DB: db, - Permissions: iamrepo.NewPermissionResolver(db, iamrepo.DefaultPermissionTTL), + Permissions: permissions, Audit: auditsvc.NewEventService(repos.AuditEvents), @@ -257,7 +260,7 @@ func NewServices(cfg config.Config, db *gorm.DB, repos *Repositories, workflowBa GroupMember: iamsvc.NewGroupMemberService(db, groups, groupMembers, users), // A deleted service account takes the shares granted to it along, hence the // sharing repository. - ServiceAccount: iamsvc.NewServiceAccountService(db, repos.ServiceAccounts, users, shares), + ServiceAccount: iamsvc.NewServiceAccountService(db, repos.ServiceAccounts, users, shares, permissions), // A key is deleted only when nothing presents it, and what can present one // lives in other verticals — hence both repositories here. diff --git a/internal/auth/middleware.go b/internal/auth/middleware.go index 97d360d786..1c72aade97 100644 --- a/internal/auth/middleware.go +++ b/internal/auth/middleware.go @@ -75,7 +75,7 @@ func Middleware(introspector Introspector, opts ...Option) func(http.Handler) ht } if cfg.permissions != nil { - principal.Permissions = cfg.permissions.Permissions(r.Context(), principal.Authorities) + principal.Permissions = cfg.permissions.Permissions(r.Context(), principal.Name, principal.Authorities) } next.ServeHTTP(w, r.WithContext(WithPrincipal(r.Context(), principal))) diff --git a/internal/auth/permission.go b/internal/auth/permission.go index b3f3432e22..1e9eef90ce 100644 --- a/internal/auth/permission.go +++ b/internal/auth/permission.go @@ -27,14 +27,15 @@ import ( "github.com/apache/airavata/internal/permission" ) -// PermissionResolver turns a caller's authorities (their role names) into the -// permissions those roles grant. +// PermissionResolver turns a caller into the permissions they hold: what their +// authorities (role names) grant, or for a service account what has been granted to +// that account itself. // // An implementation must not fail open. When it cannot tell what a role grants it // returns fewer permissions, never more, so a fault in the lookup denies rather than // allows. type PermissionResolver interface { - Permissions(ctx context.Context, authorities []string) permission.Set + Permissions(ctx context.Context, name string, authorities []string) permission.Set } // Option configures Middleware. diff --git a/internal/auth/permission_test.go b/internal/auth/permission_test.go index d4da73ae3f..9c00b172e1 100644 --- a/internal/auth/permission_test.go +++ b/internal/auth/permission_test.go @@ -70,7 +70,7 @@ func TestAuthorityDoesNotImplyPermission(t *testing.T) { type fakeResolver map[string]permission.Set -func (f fakeResolver) Permissions(_ context.Context, authorities []string) permission.Set { +func (f fakeResolver) Permissions(_ context.Context, _ string, authorities []string) permission.Set { out := permission.Set{} for _, a := range authorities { for p := range f[a] { diff --git a/internal/db/migrate.go b/internal/db/migrate.go index d5c9e1ae01..22d1bbefe4 100644 --- a/internal/db/migrate.go +++ b/internal/db/migrate.go @@ -52,6 +52,7 @@ func Entities() []any { &iammodel.UserRole{}, &iammodel.RolePermission{}, &iammodel.ServiceAccount{}, + &iammodel.ServiceAccountPermission{}, &iammodel.Group{}, &computemodel.SlurmCluster{}, &datamodel.SCPDataStorage{}, diff --git a/internal/db/migrations/0017_service_account_permissions.sql b/internal/db/migrations/0017_service_account_permissions.sql new file mode 100644 index 0000000000..dd2b6dd49c --- /dev/null +++ b/internal/db/migrations/0017_service_account_permissions.sql @@ -0,0 +1,13 @@ +-- Per-account permissions for service accounts. +-- +-- A service account holds no role that grants anything, so what it may do beyond acting +-- on its own records is exactly the rows here, and each account can differ from the +-- next. The rows belong to the account and are deleted with it. The permissions that +-- manage identities and privileges are refused on write by the API and ignored on read +-- by the resolver (see permission.GrantableToServiceAccount), so no row here can make a +-- service account an administrator. +-- +-- The statement is what GORM emits for iam/model.ServiceAccountPermission, which keeps +-- this file and AutoMigrate in agreement — see TestBaselineMigrationMatchesAutoMigrate. + +CREATE TABLE "service_account_permissions" ("user_id" varchar(255),"permission" varchar(64),PRIMARY KEY ("user_id","permission"),CONSTRAINT "fk_service_accounts_permissions" FOREIGN KEY ("user_id") REFERENCES "service_accounts"("user_id") ON DELETE CASCADE ON UPDATE CASCADE); diff --git a/internal/permission/permission.go b/internal/permission/permission.go index 222b00f0c3..c0afc5d751 100644 --- a/internal/permission/permission.go +++ b/internal/permission/permission.go @@ -111,6 +111,28 @@ var superAdminOnly = map[Permission]bool{ AdminManage: true, } +// notForServiceAccounts are the permissions a service account can never hold, however +// an administrator asks. They are the ones that let a token widen access beyond what it +// was given: appointing administrators, rewriting another user's profile, and creating +// or administering service accounts. The guarantee that a service account cannot become +// an administrator or mint another service account depends on them staying out of +// reach. +// +// user:create and user:set_status are deliberately not here. They let an account +// register users and activate or suspend them, which an integration such as an +// onboarding system legitimately needs, and neither reaches an administrator: changing +// an administrator's status still needs admin:manage. +var notForServiceAccounts = map[Permission]bool{ + AdminManage: true, + UserUpdateAny: true, + ServiceAccountManage: true, +} + +// GrantableToServiceAccount reports whether p may be granted to a service account. +func (p Permission) GrantableToServiceAccount() bool { + return p.Valid() && !notForServiceAccounts[p] +} + // All returns every defined permission, sorted. func All() []Permission { out := append([]Permission(nil), all...) diff --git a/internal/server/serviceaccount_permission_test.go b/internal/server/serviceaccount_permission_test.go new file mode 100644 index 0000000000..8c427eb504 --- /dev/null +++ b/internal/server/serviceaccount_permission_test.go @@ -0,0 +1,230 @@ +/** +* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. + */ + +package server_test + +import ( + "net/http" + "testing" + + "github.com/apache/airavata/internal/permission" + "github.com/apache/airavata/internal/role" + + iammodel "github.com/apache/airavata/api/iam/model" +) + +// createServiceAccountWith creates an account holding perms and returns its id and token. +func (h *harness) createServiceAccountWith(name string, perms ...string) (id, token string) { + h.t.Helper() + out := h.mustDo(http.MethodPost, "/api/v1/service-accounts", tokenAdmin, + map[string]any{"name": name, "permissions": perms}, http.StatusCreated) + sa := out["serviceAccount"].(map[string]any) + return sa["serviceAccountId"].(string), out["token"].(string) +} + +func (h *harness) status(method, path, token string, body any) int { + h.t.Helper() + return h.do(method, path, token, body).Code +} + +func names(v any) []string { + var out []string + for _, p := range v.([]any) { + out = append(out, p.(string)) + } + return out +} + +// Each service account holds its own permissions: one account can list every process +// while its neighbour, created the same way, cannot. +func TestServiceAccountsHoldTheirOwnPermissions(t *testing.T) { + h := newServiceAccountHarness(t) + _, lister := h.createServiceAccountWith("lister", "process:list") + _, plain := h.createServiceAccountWith("plain") + + if got := h.status("GET", "/api/v1/processes", lister, nil); got != http.StatusOK { + t.Errorf("account granted process:list: status = %d, want 200", got) + } + if got := h.status("GET", "/api/v1/processes", plain, nil); got != http.StatusForbidden { + t.Errorf("account with no grants: status = %d, want 403", got) + } + // A grant opens exactly its own door. + if got := h.status("GET", "/api/v1/users", lister, nil); got != http.StatusForbidden { + t.Errorf("account granted only process:list reached user:list: status = %d, want 403", got) + } + + me := h.mustDo("GET", "/api/v1/users/me", lister, nil, http.StatusOK) + if got := names(me["permissions"]); len(got) != 1 || got[0] != "process:list" { + t.Errorf("/users/me permissions = %v, want [process:list]", got) + } +} + +func TestServiceAccountPermissionsAreReadableAndReplaceable(t *testing.T) { + h := newServiceAccountHarness(t) + id, token := h.createServiceAccountWith("ci", "process:list", "storage:list") + + got := h.mustDo("GET", "/api/v1/service-accounts/"+id, tokenAdmin, nil, http.StatusOK) + if p := names(got["permissions"]); len(p) != 2 || p[0] != "process:list" || p[1] != "storage:list" { + t.Fatalf("permissions = %v, want [process:list storage:list]", p) + } + + // Replacing takes effect on the account's very next request, with no waiting out a cache. + h.mustDo("PUT", "/api/v1/service-accounts/"+id, tokenAdmin, + map[string]any{"permissions": []string{"storage:list"}}, http.StatusOK) + if got := h.status("GET", "/api/v1/processes", token, nil); got != http.StatusForbidden { + t.Errorf("revoked process:list still works: status = %d, want 403", got) + } + if got := h.status("GET", "/api/v1/scp-data-storages", token, nil); got != http.StatusOK { + t.Errorf("kept storage:list: status = %d, want 200", got) + } + + // Leaving permissions out of an update leaves them as they are. + h.mustDo("PUT", "/api/v1/service-accounts/"+id, tokenAdmin, + map[string]any{"description": "renamed"}, http.StatusOK) + if got := h.status("GET", "/api/v1/scp-data-storages", token, nil); got != http.StatusOK { + t.Errorf("an unrelated update dropped the grants: status = %d", got) + } + + // An empty list clears them. + cleared := h.mustDo("PUT", "/api/v1/service-accounts/"+id, tokenAdmin, + map[string]any{"permissions": []string{}}, http.StatusOK) + if p := names(cleared["permissions"]); len(p) != 0 { + t.Errorf("permissions after clearing = %v, want none", p) + } + if got := h.status("GET", "/api/v1/scp-data-storages", token, nil); got != http.StatusForbidden { + t.Errorf("cleared account still has storage:list: status = %d, want 403", got) + } +} + +// Whatever is requested, a service account cannot be given the permissions that manage +// identities and privileges, nor ones that do not exist. +func TestServiceAccountsCannotBeGrantedPrivilegePermissions(t *testing.T) { + h := newServiceAccountHarness(t) + for _, p := range []string{ + "admin:manage", "user:update_any", "serviceaccount:manage", + "no:such_permission", + } { + rec := h.do("POST", "/api/v1/service-accounts", tokenAdmin, + map[string]any{"name": "bad", "permissions": []string{p}}) + if rec.Code != http.StatusBadRequest { + t.Errorf("create with %s: status = %d, want 400\n%s", p, rec.Code, rec.Body.String()) + } + } + id, _ := h.createServiceAccountWith("fine") + if got := h.status("PUT", "/api/v1/service-accounts/"+id, tokenAdmin, + map[string]any{"permissions": []string{"admin:manage"}}); got != http.StatusBadRequest { + t.Errorf("update with admin:manage: status = %d, want 400", got) + } +} + +// A row that got into the table around the API is still ignored when it is read, so the +// guarantee does not rest on every writer behaving. +func TestServiceAccountForbiddenGrantIsIgnoredOnRead(t *testing.T) { + h := newServiceAccountHarness(t) + id, token := h.createServiceAccountWith("sneaky") + if err := h.db.Exec( + "INSERT INTO service_account_permissions (user_id, permission) VALUES (?, ?)", id, "admin:manage", + ).Error; err != nil { + t.Fatal(err) + } + h.svcs.Permissions.Invalidate() + if got := h.status("POST", "/api/v1/users/bob/admin", token, map[string]any{"admin": true}); got != http.StatusForbidden { + t.Errorf("a directly inserted admin:manage worked: status = %d, want 403", got) + } +} + +// Nobody can hand out a permission they do not hold themselves. +func TestServiceAccountGrantsRequireHoldingThePermission(t *testing.T) { + h := newServiceAccountHarness(t) + if err := h.db.Delete(&iammodel.RolePermission{}, "role = ? AND permission = ?", "ADMIN", "process:list").Error; err != nil { + t.Fatal(err) + } + h.svcs.Permissions.Invalidate() + + rec := h.do("POST", "/api/v1/service-accounts", tokenAdmin, + map[string]any{"name": "greedy", "permissions": []string{"process:list"}}) + if rec.Code != http.StatusForbidden { + t.Fatalf("granting an unheld permission: status = %d, want 403\n%s", rec.Code, rec.Body.String()) + } + h.mustDo("POST", "/api/v1/service-accounts", tokenAdmin, + map[string]any{"name": "modest", "permissions": []string{"storage:list"}}, http.StatusCreated) +} + +// A service account holds no role that grants anything: granting a permission to USER +// reaches people, not service accounts. +func TestRoleGrantsDoNotReachServiceAccounts(t *testing.T) { + h := newServiceAccountHarness(t) + _, token := h.createServiceAccountWith("plain") + if err := h.db.Create(&iammodel.RolePermission{Role: role.User, Permission: permission.ProcessList}).Error; err != nil { + t.Fatal(err) + } + h.svcs.Permissions.Invalidate() + + if got := h.status("GET", "/api/v1/processes", tokenAlice, nil); got != http.StatusOK { + t.Fatalf("a person holding USER: status = %d, want 200", got) + } + if got := h.status("GET", "/api/v1/processes", token, nil); got != http.StatusForbidden { + t.Errorf("a service account inherited USER's grant: status = %d, want 403", got) + } +} + +func TestDeletingAServiceAccountRemovesItsGrants(t *testing.T) { + h := newServiceAccountHarness(t) + id, _ := h.createServiceAccountWith("short-lived", "process:list") + h.mustDo("DELETE", "/api/v1/service-accounts/"+id, tokenAdmin, nil, http.StatusNoContent) + + var n int64 + h.db.Model(&iammodel.ServiceAccountPermission{}).Where("user_id = ?", id).Count(&n) + if n != 0 { + t.Errorf("%d grants outlived the account", n) + } +} + +// An onboarding integration can register users and activate them, but that reaches no +// administrator: changing an administrator's status still needs admin:manage. +func TestServiceAccountMayHoldUserCreateAndSetStatus(t *testing.T) { + h := newServiceAccountHarness(t) + // user:create is held only by SUPER_ADMIN by default, so an ADMIN cannot hand it out. + if rec := h.do("POST", "/api/v1/service-accounts", tokenAdmin, + map[string]any{"name": "onboarding", "permissions": []string{"user:create"}}); rec.Code != http.StatusForbidden { + t.Fatalf("an ADMIN granting user:create: status = %d, want 403", rec.Code) + } + if err := h.db.Create(&iammodel.RolePermission{Role: role.Admin, Permission: permission.UserCreate}).Error; err != nil { + t.Fatal(err) + } + h.svcs.Permissions.Invalidate() + + _, token := h.createServiceAccountWith("onboarding", "user:create", "user:set_status") + + created := h.do("POST", "/api/v1/users", token, map[string]any{ + "userId": "cilogon:777", "email": "[email protected]", "firstName": "New", "lastName": "User"}) + if created.Code != http.StatusOK { + t.Fatalf("create user: status = %d\n%s", created.Code, created.Body.String()) + } + h.mustDo("POST", "/api/v1/users/cilogon:777/status", token, map[string]any{"status": "SUSPENDED"}, http.StatusOK) + + // It still cannot touch an administrator, appoint one, or edit a profile. + if got := h.status("POST", "/api/v1/users/admin-user/status", token, map[string]any{"status": "SUSPENDED"}); got != http.StatusForbidden { + t.Errorf("changing an administrator's status: status = %d, want 403", got) + } + if got := h.status("POST", "/api/v1/users/bob/admin", token, map[string]any{"admin": true}); got != http.StatusForbidden { + t.Errorf("appointing an administrator: status = %d, want 403", got) + } +}
