This is an automated email from the ASF dual-hosted git repository.
DImuthuUpe pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/airavata.git
The following commit(s) were added to refs/heads/master by this push:
new 763da66b69 Ability to assign permissions to service accounts (#765)
763da66b69 is described below
commit 763da66b69a9750f1a43fba5544afd8df33e2094
Author: Dimuthu Wannipurage <[email protected]>
AuthorDate: Wed Nov 11 21:39:35 2026 -0500
Ability to assign permissions to service accounts (#765)
* Assign permissions to service accounts
* Ability to attach permissions to service accounts through dashboard
---
api/iam/controller/permission.go | 51 +++++
api/iam/dto/permission.go | 31 +++
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/permission.go | 57 +++++
api/iam/service/serviceaccount.go | 87 +++++++-
dashboard/src/app/globals.css | 27 +++
dashboard/src/app/service-accounts/page.tsx | 50 ++++-
dashboard/src/components/PermissionPicker.tsx | 114 ++++++++++
dashboard/src/lib/session.tsx | 6 +-
dashboard/src/lib/types.ts | 16 ++
docs/auth.md | 27 ++-
docs/openapi.yaml | 53 ++++-
internal/app/app.go | 10 +-
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 | 71 +++++++
internal/permission/permission_test.go | 55 +++++
internal/server/permission_test.go | 22 ++
internal/server/server.go | 1 +
internal/server/serviceaccount_permission_test.go | 230 +++++++++++++++++++++
28 files changed, 1178 insertions(+), 65 deletions(-)
diff --git a/api/iam/controller/permission.go b/api/iam/controller/permission.go
new file mode 100644
index 0000000000..193e7d0d39
--- /dev/null
+++ b/api/iam/controller/permission.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 controller
+
+import (
+ "net/http"
+
+ "github.com/apache/airavata/internal/httpx"
+
+ "github.com/apache/airavata/api/iam/service"
+)
+
+// PermissionController serves /api/v1/permissions.
+type PermissionController struct{ svc *service.PermissionService }
+
+// NewPermissionController returns a handler delegating to svc.
+func NewPermissionController(svc *service.PermissionService)
*PermissionController {
+ return &PermissionController{svc: svc}
+}
+
+// Register mounts the permission routes.
+func (h *PermissionController) Register(mux *http.ServeMux) {
+ mux.HandleFunc("GET /api/v1/permissions", h.list)
+}
+
+func (h *PermissionController) list(w http.ResponseWriter, r *http.Request) {
+ out, err := h.svc.List(r.Context())
+ if err != nil {
+ httpx.WriteError(w, r, err)
+ return
+ }
+ httpx.WriteJSON(w, http.StatusOK, out)
+}
diff --git a/api/iam/dto/permission.go b/api/iam/dto/permission.go
new file mode 100644
index 0000000000..abf70522b7
--- /dev/null
+++ b/api/iam/dto/permission.go
@@ -0,0 +1,31 @@
+/**
+*
+* 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 dto
+
+// PermissionResponse describes one permission, so a client can offer them for
granting.
+type PermissionResponse struct {
+ Permission string `json:"permission"`
+ Description string `json:"description"`
+
+ // GrantableToServiceAccount is false for the permissions no service
account may
+ // hold, which a client should not offer.
+ GrantableToServiceAccount bool `json:"grantableToServiceAccount"`
+}
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/permission.go b/api/iam/service/permission.go
new file mode 100644
index 0000000000..0a0d8d481e
--- /dev/null
+++ b/api/iam/service/permission.go
@@ -0,0 +1,57 @@
+/**
+*
+* 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 service
+
+import (
+ "context"
+
+ "github.com/apache/airavata/internal/auth"
+ "github.com/apache/airavata/internal/permission"
+
+ "github.com/apache/airavata/api/iam/dto"
+)
+
+// PermissionService lists the permissions that exist.
+//
+// The catalogue is the same for everyone and names nothing about any user, so
any
+// signed-in caller may read it; what a caller may grant from it is decided
where the
+// grant is made.
+type PermissionService struct{}
+
+// NewPermissionService returns a permission service.
+func NewPermissionService() *PermissionService { return &PermissionService{} }
+
+// List returns every permission with its description, sorted.
+func (s *PermissionService) List(ctx context.Context)
([]dto.PermissionResponse, error) {
+ if _, err := auth.RequireAuthenticated(ctx); err != nil {
+ return nil, err
+ }
+ catalog := permission.Catalog()
+ out := make([]dto.PermissionResponse, 0, len(catalog))
+ for _, info := range catalog {
+ out = append(out, dto.PermissionResponse{
+ Permission: string(info.Permission),
+ Description: info.Description,
+ GrantableToServiceAccount:
info.GrantableToServiceAccount,
+ })
+ }
+ return out, nil
+}
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/dashboard/src/app/globals.css b/dashboard/src/app/globals.css
index 4eb7b914d9..1fa82b8404 100644
--- a/dashboard/src/app/globals.css
+++ b/dashboard/src/app/globals.css
@@ -487,6 +487,33 @@ a:focus-visible {
box-shadow: var(--focus-ring);
}
+.perm-list {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ max-height: 300px;
+ overflow-y: auto;
+}
+.perm-group {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 8px 12px;
+}
+.perm-group legend {
+ font-size: 12px;
+ color: var(--muted);
+}
+.perm-row {
+ align-items: flex-start;
+}
+.perm-row input {
+ margin-top: 3px;
+}
+.perm-row[title] {
+ opacity: 0.7;
+}
+
fieldset {
border: 1px solid var(--border);
border-radius: var(--radius);
diff --git a/dashboard/src/app/service-accounts/page.tsx
b/dashboard/src/app/service-accounts/page.tsx
index a85d948fbf..a88864a998 100644
--- a/dashboard/src/app/service-accounts/page.tsx
+++ b/dashboard/src/app/service-accounts/page.tsx
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
+import { PermissionPicker, sameSet } from "@/components/PermissionPicker";
import { Alert, Card, ConfirmButton, Field, formatTime, Modal, numOrNull,
PageHead, StatusBadge, strOrNull, Table } from "@/components/ui";
import { api, API_BASE, errorText } from "@/lib/api";
import { useAction, useResource } from "@/lib/hooks";
@@ -26,10 +27,12 @@ type Dialog =
| { kind: "token"; minted: ServiceAccountToken; regenerated: boolean };
export default function ServiceAccountsPage() {
- const { isAdmin } = useSession();
+ const { can } = useSession();
+ const canRead = can("serviceaccount:read");
+ const canManage = can("serviceaccount:manage");
const accounts = useResource(
- () => (isAdmin ? api.get<ServiceAccount[]>("/api/v1/service-accounts") :
Promise.resolve([])),
- [isAdmin],
+ () => (canRead ? api.get<ServiceAccount[]>("/api/v1/service-accounts") :
Promise.resolve([])),
+ [canRead],
);
const [dialog, setDialog] = useState<Dialog | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -40,11 +43,11 @@ export default function ServiceAccountsPage() {
void accounts.reload();
};
- if (!isAdmin) {
+ if (!canRead) {
return (
<div className="stack">
<PageHead title="Service accounts" />
- <Alert kind="info">Only administrators can manage service
accounts.</Alert>
+ <Alert kind="info">You don't have permission to view service
accounts.</Alert>
</div>
);
}
@@ -53,11 +56,13 @@ export default function ServiceAccountsPage() {
<div className="stack">
<PageHead
title="Service accounts"
- sub="Identities for automation such as CI pipelines and gateways. They
act as ordinary users and can never be administrators. Each has one token,
which expires."
+ sub="Identities for automation such as CI pipelines and gateways. They
act as ordinary users, can never be administrators, and can do more only where
you grant them a permission. Each has one token, which expires."
>
- <button className="primary" onClick={() => setDialog({ kind: "create"
})}>
- Create service account
- </button>
+ {canManage && (
+ <button className="primary" onClick={() => setDialog({ kind:
"create" })}>
+ Create service account
+ </button>
+ )}
</PageHead>
<Alert>{accounts.error || error}</Alert>
<Card flush>
@@ -78,6 +83,7 @@ export default function ServiceAccountsPage() {
),
},
{ header: "Status", cell: (sa) => <StatusBadge status={sa.status}
/> },
+ { header: "Permissions", cell: (sa) => <PermissionSummary
permissions={sa.permissions} /> },
{ header: "Token", cell: (sa) => <TokenExpiry
expiresAt={sa.tokenExpiresAt} /> },
{
header: "Description",
@@ -101,7 +107,8 @@ export default function ServiceAccountsPage() {
{
header: "",
className: "actions",
- cell: (sa) => (
+ cell: (sa) =>
+ !canManage ? null : (
<div className="row" style={{ justifyContent: "flex-end" }}>
<button className="small" onClick={() => setDialog({ kind:
"edit", sa })}>
Edit
@@ -127,7 +134,7 @@ export default function ServiceAccountsPage() {
Delete
</ConfirmButton>
</div>
- ),
+ ),
},
]}
/>
@@ -150,6 +157,16 @@ export default function ServiceAccountsPage() {
);
}
+// PermissionSummary shows how many permissions an account holds, and which on
hover.
+function PermissionSummary({ permissions }: { permissions: string[] }) {
+ if (permissions.length === 0) return <span className="muted">None</span>;
+ return (
+ <span className="badge info" title={permissions.join("\n")}>
+ {permissions.length} {permissions.length === 1 ? "permission" :
"permissions"}
+ </span>
+ );
+}
+
function TokenExpiry({ expiresAt }: { expiresAt: number }) {
const left = expiresAt - Date.now();
const when = formatTime(expiresAt);
@@ -181,6 +198,7 @@ function ValidityField({ value, onChange }: { value:
string; onChange: (v: strin
function CreateDialog({ onClose, onCreated }: { onClose: () => void;
onCreated: (t: ServiceAccountToken) => void }) {
const [f, setF] = useState({ name: "", displayName: "", description: "",
email: "", validityDays: String(DEFAULT_VALIDITY_DAYS) });
+ const [permissions, setPermissions] = useState<string[]>([]);
const set = (patch: Partial<typeof f>) => setF((x) => ({ ...x, ...patch }));
const nameOk = f.name === "" || NAME_PATTERN.test(f.name);
@@ -191,6 +209,7 @@ function CreateDialog({ onClose, onCreated }: { onClose: ()
=> void; onCreated:
description: strOrNull(f.description),
email: strOrNull(f.email),
validityDays: numOrNull(f.validityDays),
+ permissions,
};
onCreated(await api.post<ServiceAccountToken>("/api/v1/service-accounts",
body));
});
@@ -225,6 +244,7 @@ function CreateDialog({ onClose, onCreated }: { onClose: ()
=> void; onCreated:
<input type="email" value={f.email} onChange={(e) => set({ email:
e.target.value })} />
</Field>
<ValidityField value={f.validityDays} onChange={(validityDays) =>
set({ validityDays })} />
+ <PermissionPicker value={permissions} onChange={setPermissions} />
<p className="muted small" style={{ margin: 0 }}>
The account always has <code>USER</code> authority. Share records
with it, or add it to groups, by its user id.
</p>
@@ -241,6 +261,7 @@ function EditDialog({ sa, onClose, onSaved }: { sa:
ServiceAccount; onClose: ()
email: sa.email ?? "",
status: (sa.status ?? "ACTIVE") as UserStatus,
});
+ const [permissions, setPermissions] = useState<string[]>(sa.permissions);
const set = (patch: Partial<typeof f>) => setF((x) => ({ ...x, ...patch }));
const save = useAction(async () => {
@@ -251,6 +272,9 @@ function EditDialog({ sa, onClose, onSaved }: { sa:
ServiceAccount; onClose: ()
if (f.description !== (sa.description ?? "")) body.description =
f.description;
if (f.email !== (sa.email ?? "")) body.email = f.email;
if (f.status !== sa.status) body.status = f.status;
+ // The list replaces the account's whole set on the server, so it is sent
only when
+ // it changed, and then in full.
+ if (!sameSet(permissions, sa.permissions)) body.permissions = permissions;
await api.put(path(sa), body);
onSaved();
});
@@ -290,6 +314,10 @@ function EditDialog({ sa, onClose, onSaved }: { sa:
ServiceAccount; onClose: ()
The token stops working as soon as you save. It is kept, so
setting the account back to Active restores access.
</Alert>
)}
+ <PermissionPicker value={permissions} onChange={setPermissions}
initial={sa.permissions} />
+ {!sameSet(permissions, sa.permissions) && (
+ <Alert kind="info">Permission changes apply to the account's
next request.</Alert>
+ )}
<Alert>{save.error}</Alert>
</div>
</Modal>
diff --git a/dashboard/src/components/PermissionPicker.tsx
b/dashboard/src/components/PermissionPicker.tsx
new file mode 100644
index 0000000000..7f36b30b90
--- /dev/null
+++ b/dashboard/src/components/PermissionPicker.tsx
@@ -0,0 +1,114 @@
+"use client";
+
+import { useMemo } from "react";
+import { Alert } from "@/components/ui";
+import { api } from "@/lib/api";
+import { useResource } from "@/lib/hooks";
+import { useSession } from "@/lib/session";
+import type { PermissionInfo } from "@/lib/types";
+
+// sameSet reports whether two permission lists hold the same permissions,
ignoring order.
+export function sameSet(a: string[], b: string[]): boolean {
+ return a.length === b.length && a.every((p) => b.includes(p));
+}
+
+// Headings for the part of a permission before the colon. An unknown one
falls back to
+// its capitalised name, so a permission added on the server still appears.
+const GROUP_LABELS: Record<string, string> = {
+ audit: "Audit log",
+ user: "Users",
+ admin: "Administrators",
+ group: "Groups",
+ serviceaccount: "Service accounts",
+ cluster: "Clusters",
+ clusterconfig: "Cluster configs",
+ template: "Application templates",
+ deployment: "Deployments",
+ storage: "Storages",
+ dataproduct: "Data products",
+ virtualdirectory: "Virtual data directories",
+ resource: "Shareable records",
+ process: "Processes",
+};
+const groupLabel = (g: string) => GROUP_LABELS[g] ?? g.charAt(0).toUpperCase()
+ g.slice(1);
+
+// PermissionPicker lets an administrator choose what a service account may do.
+//
+// It offers only the permissions a service account may hold, grouped by what
they act
+// on. A permission the signed-in administrator doesn't hold themselves is
shown but
+// can't be added, because the server refuses to let anyone grant what they
lack. One the
+// account already has stays removable either way.
+//
+// `initial` is what the account holds now (empty when creating), which is
what decides
+// whether a permission the administrator lacks can still be unticked.
+export function PermissionPicker({
+ value,
+ onChange,
+ initial = [],
+}: {
+ value: string[];
+ onChange: (next: string[]) => void;
+ initial?: string[];
+}) {
+ const { can } = useSession();
+ const catalogue = useResource(() =>
api.get<PermissionInfo[]>("/api/v1/permissions"), []);
+
+ const groups = useMemo(() => {
+ const out = new Map<string, PermissionInfo[]>();
+ for (const p of catalogue.data ?? []) {
+ if (!p.grantableToServiceAccount) continue;
+ const group = p.permission.split(":")[0];
+ out.set(group, [...(out.get(group) ?? []), p]);
+ }
+ return [...out.entries()];
+ }, [catalogue.data]);
+
+ const toggle = (permission: string, on: boolean) =>
+ onChange(on ? [...value, permission].sort() : value.filter((p) => p !==
permission));
+
+ return (
+ <div className="stack" style={{ gap: 6 }}>
+ <div className="row" style={{ justifyContent: "space-between" }}>
+ <strong>Permissions</strong>
+ <span className="muted small">
+ {value.length === 0 ? "none selected" : `${value.length} selected`}
+ </span>
+ </div>
+ <p className="muted small" style={{ margin: 0 }}>
+ The account can do only what is ticked here, on top of working with
its own records. It gets nothing from any role.
+ </p>
+ <Alert>{catalogue.error}</Alert>
+ <div className="perm-list" role="group" aria-label="Permissions">
+ {catalogue.loading && !catalogue.data && <span className="muted
small">Loading…</span>}
+ {groups.map(([group, perms]) => (
+ <fieldset key={group} className="perm-group">
+ <legend>{groupLabel(group)}</legend>
+ {perms.map((p) => {
+ const checked = value.includes(p.permission);
+ const lacks = !can(p.permission) &&
!initial.includes(p.permission);
+ return (
+ <label
+ key={p.permission}
+ className="check perm-row"
+ title={lacks ? "You don't hold this permission, so you can't
grant it." : undefined}
+ >
+ <input
+ type="checkbox"
+ checked={checked}
+ disabled={lacks}
+ onChange={(e) => toggle(p.permission, e.target.checked)}
+ />
+ <span>
+ <code className="small">{p.permission}</code>
+ <span className="muted small"> — {p.description}</span>
+ {lacks && <span className="badge warn"> you lack
this</span>}
+ </span>
+ </label>
+ );
+ })}
+ </fieldset>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/dashboard/src/lib/session.tsx b/dashboard/src/lib/session.tsx
index c002fabd27..4f65ae47b7 100644
--- a/dashboard/src/lib/session.tsx
+++ b/dashboard/src/lib/session.tsx
@@ -12,6 +12,9 @@ interface Session {
// me is the signed-in caller, null until it has been read.
me: CurrentUser | null;
isAdmin: boolean;
+ // can reports whether the caller holds a permission. It only decides what
the page
+ // offers: the server refuses an action the caller may not take whatever the
page shows.
+ can: (permission: string) => boolean;
// active is false for an account an administrator has not activated, or has
// suspended. The server refuses such an account everything but
/api/v1/users/me.
active: boolean;
@@ -102,10 +105,11 @@ export function SessionProvider({ children }: { children:
React.ReactNode }) {
);
const isAdmin = !!me?.admin;
+ const can = (permission: string) => !!me?.permissions?.includes(permission);
const active = !me || me.status === "ACTIVE";
return (
- <SessionContext.Provider value={{ token, me, isAdmin, active, refreshMe,
signIn, signInWithCILogon, signOut }}>
+ <SessionContext.Provider value={{ token, me, isAdmin, can, active,
refreshMe, signIn, signInWithCILogon, signOut }}>
{children}
</SessionContext.Provider>
);
diff --git a/dashboard/src/lib/types.ts b/dashboard/src/lib/types.ts
index 3f5fcbfa95..fb795beb9a 100644
--- a/dashboard/src/lib/types.ts
+++ b/dashboard/src/lib/types.ts
@@ -69,10 +69,21 @@ export interface CurrentUser {
userId: string;
status: UserStatus;
authorities: string[];
+ // What the caller's roles grant, such as "audit:read". Use it to hide what
the caller
+ // cannot do; the server enforces it regardless.
+ permissions: string[];
admin: boolean;
user: UserAccount | null;
}
+// GET /api/v1/permissions: every permission, for pages that let an
administrator choose.
+export interface PermissionInfo {
+ permission: string; // "resource:action"
+ description: string;
+ // False for the permissions no service account may hold.
+ grantableToServiceAccount: boolean;
+}
+
// Service accounts (admin only)
export interface ServiceAccount {
@@ -86,6 +97,8 @@ export interface ServiceAccount {
createdAt: number;
tokenIssuedAt: number;
tokenExpiresAt: number;
+ // What the account may do, sorted.
+ permissions: string[];
}
// Returned on create and regenerate: the only times the token is ever sent.
@@ -100,6 +113,7 @@ export interface ServiceAccountCreate {
description: string | null;
email: string | null;
validityDays: number | null;
+ permissions: string[];
}
export interface ServiceAccountUpdate {
@@ -107,6 +121,8 @@ export interface ServiceAccountUpdate {
description?: string | null;
email?: string | null;
status?: UserStatus;
+ // Replaces the account's whole set. Leave out to keep it as it is.
+ permissions?: string[];
}
// Credentials
diff --git a/docs/auth.md b/docs/auth.md
index 61e1b4ff21..cd5792acf3 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,26 @@ 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"]}'
+```
+
+On the dashboard, the **Service accounts** page has a permission picker in
both the create and edit dialogs. It lists the permissions a service account
may hold, grouped by what they act on, with a description of each. A permission
you don't hold yourself is shown but can't be ticked, and the table shows how
many permissions each account has. The picker is filled from `GET
/api/v1/permissions`, which lists every permission with its description and
whether a service account may hold it, f [...]
+
+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..3639353bb7 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -275,6 +275,30 @@ paths:
"502": { $ref: "#/components/responses/BadGateway" }
"500": { $ref: "#/components/responses/InternalError" }
+ # ------------------------------------------------------ Permissions
+
+ /api/v1/permissions:
+ get:
+ tags: [Service Accounts]
+ summary: List permissions
+ description: |
+ Any signed-in caller. Every permission that exists, with a description
of what it
+ allows, sorted by name. `grantableToServiceAccount` is false for the
permissions no
+ service account may hold. What a caller may grant from the list is
decided where
+ the grant is made. See docs/auth.md.
+ operationId: listPermissions
+ responses:
+ "200":
+ description: Every permission.
+ content:
+ application/json:
+ schema:
+ type: array
+ items: { $ref: "#/components/schemas/Permission" }
+ "401": { $ref: "#/components/responses/Unauthorized" }
+ "502": { $ref: "#/components/responses/BadGateway" }
+ "500": { $ref: "#/components/responses/InternalError" }
+
# ------------------------------------------------------ Service accounts
/api/v1/service-accounts:
@@ -3405,6 +3429,14 @@ components:
status: { $ref: "#/components/schemas/UserStatus" }
required: [status]
+ Permission:
+ type: object
+ properties:
+ permission: { type: string, description: "`resource:action`, such as
`process:list`." }
+ description: { type: string }
+ grantableToServiceAccount: { type: boolean }
+ required: [permission, description, grantableToServiceAccount]
+
ServiceAccountCreate:
type: object
properties:
@@ -3420,6 +3452,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 +3473,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 +3535,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..6166afeb39 100644
--- a/internal/app/app.go
+++ b/internal/app/app.go
@@ -80,6 +80,8 @@ type Services struct {
GroupMember *iamsvc.GroupMemberService
// ServiceAccount administers non-human users and their expiring tokens.
ServiceAccount *iamsvc.ServiceAccountService
+ // Permission lists the permissions that exist.
+ Permission *iamsvc.PermissionService
// Credentials.
SSHCredential *credentialssvc.SSHCredentialService
@@ -190,6 +192,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 +253,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 +262,8 @@ 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),
+ Permission: iamsvc.NewPermissionService(),
// 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..e271b7ea75 100644
--- a/internal/permission/permission.go
+++ b/internal/permission/permission.go
@@ -111,6 +111,77 @@ var superAdminOnly = map[Permission]bool{
AdminManage: true,
}
+// descriptions say, in a line, what each permission allows. They are what an
+// administrator sees when choosing what to grant, so they are written for
that reader.
+var descriptions = map[Permission]string{
+ Permission("audit:read"): "read the audit log",
+ Permission("user:create"): "create a user record ahead of the
user's first sign-in",
+ Permission("user:list"): "list every user",
+ Permission("user:read_any"): "read another user's record",
+ Permission("user:update_any"): "edit another user's profile",
+ Permission("user:set_status"): "activate, suspend or deactivate a
user",
+ Permission("admin:manage"): "appoint and remove
administrators, and change an administrator's status",
+ Permission("group:list"): "list every group",
+ Permission("group:read_any"): "read a group the caller is not
in",
+ Permission("group:manage_any"): "rename, delete and manage members
of any group",
+ Permission("serviceaccount:read"): "list and read service accounts",
+ Permission("serviceaccount:manage"): "create, edit, delete and re-issue
tokens",
+ Permission("cluster:manage"): "create, edit and delete clusters
and their partitions",
+ Permission("cluster:discover"): "discover a cluster's partitions
over SSH",
+ Permission("clusterconfig:list"): "list every cluster config",
+ Permission("template:manage"): "create, edit and delete
application templates",
+ Permission("deployment:manage"): "create, edit and delete batch
deployments",
+ Permission("storage:list"): "list every data storage",
+ Permission("dataproduct:list"): "list every data product",
+ Permission("virtualdirectory:list"): "list every virtual data
directory",
+ Permission("resource:manage_any"): "act as the owner of any cluster
config, data storage, data product or virtual data directory",
+ Permission("process:list"): "list every process",
+ Permission("process:update"): "edit any process directly",
+ Permission("process:delete"): "delete any process",
+ Permission("process:manage_any"): "read, launch and edit the tasks,
statuses and workflows of any process",
+}
+
+// Description returns what p allows, or "" for a permission that is not
defined.
+func (p Permission) Description() string { return descriptions[p] }
+
+// Info describes one permission for a client that lets an administrator
choose them.
+type Info struct {
+ Permission Permission
+ Description string
+ GrantableToServiceAccount bool
+}
+
+// Catalog returns every defined permission with its description, sorted.
+func Catalog() []Info {
+ out := make([]Info, 0, len(all))
+ for _, p := range All() {
+ out = append(out, Info{Permission: p, Description:
p.Description(), GrantableToServiceAccount: p.GrantableToServiceAccount()})
+ }
+ return out
+}
+
+// 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/permission/permission_test.go
b/internal/permission/permission_test.go
new file mode 100644
index 0000000000..d7cba5ec85
--- /dev/null
+++ b/internal/permission/permission_test.go
@@ -0,0 +1,55 @@
+/**
+*
+* 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 permission_test
+
+import (
+ "testing"
+
+ "github.com/apache/airavata/internal/permission"
+)
+
+// An administrator picks permissions from their descriptions, so none may be
missing.
+func TestEveryPermissionIsDescribed(t *testing.T) {
+ for _, info := range permission.Catalog() {
+ if info.Description == "" {
+ t.Errorf("%s has no description", info.Permission)
+ }
+ }
+ if got, want := len(permission.Catalog()), len(permission.All()); got
!= want {
+ t.Errorf("catalogue has %d entries, want %d", got, want)
+ }
+ if permission.Permission("bogus:x").Description() != "" {
+ t.Error("an undefined permission has a description")
+ }
+}
+
+func TestServiceAccountGrantability(t *testing.T) {
+ for _, p := range []permission.Permission{permission.AdminManage,
permission.UserUpdateAny, permission.ServiceAccountManage, "bogus:x"} {
+ if p.GrantableToServiceAccount() {
+ t.Errorf("%s is grantable to a service account", p)
+ }
+ }
+ for _, p := range []permission.Permission{permission.ProcessList,
permission.UserCreate, permission.UserSetStatus} {
+ if !p.GrantableToServiceAccount() {
+ t.Errorf("%s is not grantable to a service account", p)
+ }
+ }
+}
diff --git a/internal/server/permission_test.go
b/internal/server/permission_test.go
index 5c31bdcf62..a10ed885b5 100644
--- a/internal/server/permission_test.go
+++ b/internal/server/permission_test.go
@@ -140,3 +140,25 @@ func TestEachPermissionGatesItsAction(t *testing.T) {
})
}
}
+
+func TestPermissionCatalogueIsListedForSignedInCallers(t *testing.T) {
+ h := newHarness(t)
+ if rec := h.do("GET", "/api/v1/permissions", "", nil); rec.Code !=
http.StatusUnauthorized {
+ t.Fatalf("anonymous: status = %d, want 401", rec.Code)
+ }
+ got := h.list("/api/v1/permissions", tokenAlice)
+ if len(got) != len(permission.All()) {
+ t.Fatalf("listed %d permissions, want %d", len(got),
len(permission.All()))
+ }
+ byName := map[string]map[string]any{}
+ for _, p := range got {
+ byName[p["permission"].(string)] = p
+ if p["description"] == "" {
+ t.Errorf("%v has no description", p["permission"])
+ }
+ }
+ if byName["admin:manage"]["grantableToServiceAccount"] != false ||
byName["process:list"]["grantableToServiceAccount"] != true {
+ t.Errorf("grantability is wrong: admin:manage=%v
process:list=%v",
+ byName["admin:manage"]["grantableToServiceAccount"],
byName["process:list"]["grantableToServiceAccount"])
+ }
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index a0298bd916..d4235bfe0b 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -52,6 +52,7 @@ func New(cfg config.Config, svcs *app.Services, introspector
auth.Introspector)
iamctl.NewGroupController(svcs.Group).Register(mux)
iamctl.NewGroupMemberController(svcs.GroupMember).Register(mux)
iamctl.NewServiceAccountController(svcs.ServiceAccount).Register(mux)
+ iamctl.NewPermissionController(svcs.Permission).Register(mux)
credentialsctl.NewSSHCredentialController(svcs.SSHCredential).Register(mux)
credentialsctl.NewInteractiveAuthController(svcs.InteractiveAuth).Register(mux)
computectl.NewSlurmClusterController(svcs.SlurmCluster).Register(mux)
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)
+ }
+}