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 6f4a4ee436 Bringing native RBAC support
6f4a4ee436 is described below
commit 6f4a4ee4367b04818301363ce2c873f43c368061
Author: DImuthuUpe <[email protected]>
AuthorDate: Wed Nov 11 21:02:15 2026 -0500
Bringing native RBAC support
---
api/application/service/service.go | 13 +-
api/audit/service/event.go | 7 +-
api/compute/service/cluster.go | 13 +-
api/compute/service/cluster_test.go | 3 +-
api/compute/service/config.go | 5 +-
api/compute/service/config_test.go | 3 +-
api/compute/service/discovery.go | 3 +-
api/data/service/product.go | 5 +-
api/data/service/storage.go | 5 +-
api/data/service/virtual.go | 5 +-
api/data/service/virtual_tree.go | 3 +-
api/iam/dto/user.go | 7 +-
api/iam/model/rolepermission.go | 51 ++++++
api/iam/repository/permissions.go | 140 ++++++++++++++++
api/iam/repository/permissions_test.go | 125 ++++++++++++++
api/iam/service/group.go | 13 +-
api/iam/service/serviceaccount.go | 17 +-
api/iam/service/user.go | 22 +--
api/process/service/launch.go | 3 +-
api/process/service/process.go | 9 +-
api/process/service/task.go | 3 +-
api/process/service/task_status.go | 3 +-
api/process/service/workflow.go | 3 +-
api/sharing/service/sharing.go | 3 +-
docs/audit.md | 2 +-
docs/auth.md | 46 +++++-
docs/openapi.yaml | 6 +-
internal/app/app.go | 7 +
internal/auth/middleware.go | 10 +-
internal/auth/permission.go | 88 ++++++++++
internal/auth/permission_test.go | 107 ++++++++++++
internal/auth/principal.go | 31 +---
internal/db/migrate.go | 35 +++-
internal/db/migrations/0015_role_permissions.sql | 14 ++
.../db/migrations/0016_role_permissions_all.sql | 33 ++++
internal/db/role_permissions_test.go | 106 ++++++++++++
internal/permission/permission.go | 181 +++++++++++++++++++++
internal/server/audit_test.go | 54 ++++++
internal/server/permission_test.go | 142 ++++++++++++++++
internal/server/server.go | 2 +-
40 files changed, 1236 insertions(+), 92 deletions(-)
diff --git a/api/application/service/service.go
b/api/application/service/service.go
index aeedc00b12..00fd2c3605 100644
--- a/api/application/service/service.go
+++ b/api/application/service/service.go
@@ -31,6 +31,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
dto "github.com/apache/airavata/api/application/dto"
model "github.com/apache/airavata/api/application/model"
@@ -86,7 +87,7 @@ func (s *TemplateService) Get(ctx context.Context, id string)
(*dto.TemplateResp
// Create registers a template together with its declarations.
func (s *TemplateService) Create(ctx context.Context, req
*dto.TemplateRequest) (*dto.TemplateResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.TemplateManage);
err != nil {
return nil, err
}
@@ -118,7 +119,7 @@ func (s *TemplateService) Create(ctx context.Context, req
*dto.TemplateRequest)
// Update replaces a template's fields and its declaration set.
func (s *TemplateService) Update(ctx context.Context, id string, req
*dto.TemplateRequest) (*dto.TemplateResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.TemplateManage);
err != nil {
return nil, err
}
@@ -160,7 +161,7 @@ func (s *TemplateService) Update(ctx context.Context, id
string, req *dto.Templa
// endpoints, so removing the template out from under them is rejected rather
than
// cascaded.
func (s *TemplateService) Delete(ctx context.Context, id string) error {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.TemplateManage);
err != nil {
return err
}
@@ -233,7 +234,7 @@ func (s *BatchDeploymentService) Get(ctx context.Context,
id string) (*dto.Batch
// Create registers a deployment and the resource request it owns.
func (s *BatchDeploymentService) Create(ctx context.Context, req
*dto.BatchDeploymentRequest) (*dto.BatchDeploymentResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.DeploymentManage);
err != nil {
return nil, err
}
@@ -275,7 +276,7 @@ func (s *BatchDeploymentService) Create(ctx
context.Context, req *dto.BatchDeplo
// Update changes a deployment, mutating its owned config in place so the
config row
// survives the edit rather than being replaced.
func (s *BatchDeploymentService) Update(ctx context.Context, id string, req
*dto.BatchDeploymentRequest) (*dto.BatchDeploymentResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.DeploymentManage);
err != nil {
return nil, err
}
@@ -322,7 +323,7 @@ func (s *BatchDeploymentService) Update(ctx
context.Context, id string, req *dto
// Delete removes a deployment and its owned config.
func (s *BatchDeploymentService) Delete(ctx context.Context, id string) error {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.DeploymentManage);
err != nil {
return err
}
deployment, err := s.deployments.FindByID(ctx, id)
diff --git a/api/audit/service/event.go b/api/audit/service/event.go
index 114665118e..4817936a6b 100644
--- a/api/audit/service/event.go
+++ b/api/audit/service/event.go
@@ -25,12 +25,13 @@ import (
"context"
"github.com/apache/airavata/internal/auth"
+ "github.com/apache/airavata/internal/permission"
"github.com/apache/airavata/api/audit/dto"
"github.com/apache/airavata/api/audit/repository"
)
-// EventService reads the audit log. Every call needs ADMIN or SUPER_ADMIN:
the log
+// EventService reads the audit log. Every call needs the audit:read
permission: the log
// names what every user did.
type EventService struct{ events *repository.EventRepository }
@@ -41,7 +42,7 @@ func NewEventService(events *repository.EventRepository)
*EventService {
// List returns one page of events matching q, newest first.
func (s *EventService) List(ctx context.Context, q *dto.EventQuery)
(*dto.EventPage, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.AuditRead); err !=
nil {
return nil, err
}
found, err := s.events.Find(ctx, q)
@@ -64,7 +65,7 @@ func (s *EventService) List(ctx context.Context, q
*dto.EventQuery) (*dto.EventP
// EntityTypes lists the entity types the log holds events for.
func (s *EventService) EntityTypes(ctx context.Context) ([]string, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.AuditRead); err !=
nil {
return nil, err
}
out, err := s.events.EntityTypes(ctx)
diff --git a/api/compute/service/cluster.go b/api/compute/service/cluster.go
index 4b0d5422ac..2988020bc4 100644
--- a/api/compute/service/cluster.go
+++ b/api/compute/service/cluster.go
@@ -31,6 +31,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
dto "github.com/apache/airavata/api/compute/dto"
model "github.com/apache/airavata/api/compute/model"
@@ -100,7 +101,7 @@ func (s *SlurmClusterService) Get(ctx context.Context, id
string) (*dto.SlurmClu
// that gains partitions later adds them through
// POST /api/v1/slurm-clusters/{slurmClusterId}/partitions instead.
func (s *SlurmClusterService) Create(ctx context.Context, req
*dto.SlurmClusterRequest) (*dto.SlurmClusterResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.ClusterManage); err
!= nil {
return nil, err
}
@@ -144,7 +145,7 @@ func (s *SlurmClusterService) Create(ctx context.Context,
req *dto.SlurmClusterR
// caller never mentioned, and ignoring it would silently drop what the caller
asked
// for. The partition endpoints are where a cluster's layout changes.
func (s *SlurmClusterService) Update(ctx context.Context, id string, req
*dto.SlurmClusterRequest) (*dto.SlurmClusterResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.ClusterManage); err
!= nil {
return nil, err
}
if len(req.Partitions) > 0 {
@@ -183,7 +184,7 @@ func (s *SlurmClusterService) Update(ctx context.Context,
id string, req *dto.Sl
// configs still point at it. Their owners have to retire them, since an admin
deleting
// the cluster out from under them would silently strand every share on those
configs.
func (s *SlurmClusterService) Delete(ctx context.Context, id string) error {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.ClusterManage); err
!= nil {
return err
}
cluster, err := s.clusters.FindByID(ctx, id)
@@ -244,7 +245,7 @@ func (s *ClusterPartitionService) Get(ctx context.Context,
clusterID, partitionI
// Create adds a partition to a cluster.
func (s *ClusterPartitionService) Create(ctx context.Context, clusterID
string, req *dto.ClusterPartitionRequest) (*dto.ClusterPartitionResponse,
error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.ClusterManage); err
!= nil {
return nil, err
}
cluster, err := s.requireCluster(ctx, clusterID)
@@ -263,7 +264,7 @@ func (s *ClusterPartitionService) Create(ctx
context.Context, clusterID string,
// Update changes a partition of a cluster.
func (s *ClusterPartitionService) Update(ctx context.Context, clusterID,
partitionID string, req *dto.ClusterPartitionRequest)
(*dto.ClusterPartitionResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.ClusterManage); err
!= nil {
return nil, err
}
partition, err := s.requirePartition(ctx, clusterID, partitionID)
@@ -280,7 +281,7 @@ func (s *ClusterPartitionService) Update(ctx
context.Context, clusterID, partiti
// Delete removes a partition from a cluster.
func (s *ClusterPartitionService) Delete(ctx context.Context, clusterID,
partitionID string) error {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.ClusterManage); err
!= nil {
return err
}
partition, err := s.requirePartition(ctx, clusterID, partitionID)
diff --git a/api/compute/service/cluster_test.go
b/api/compute/service/cluster_test.go
index 5837dc324e..f207503540 100644
--- a/api/compute/service/cluster_test.go
+++ b/api/compute/service/cluster_test.go
@@ -31,6 +31,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/db"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
dto "github.com/apache/airavata/api/compute/dto"
computerepo "github.com/apache/airavata/api/compute/repository"
@@ -60,7 +61,7 @@ func setup(t *testing.T) (*service.SlurmClusterService,
*service.ClusterPartitio
clusters := computerepo.NewSlurmClusterRepository(gdb)
partitions := computerepo.NewClusterPartitionRepository(gdb)
configs := computerepo.NewSlurmClusterConfigRepository(gdb)
- ctx := auth.WithPrincipal(context.Background(), &auth.Principal{Name:
"root", Authorities: []string{"ADMIN"}})
+ ctx := auth.WithPrincipal(context.Background(), &auth.Principal{Name:
"root", Authorities: []string{"ADMIN"}, Permissions:
permission.SetOf(permission.All()...)})
return service.NewSlurmClusterService(gdb, clusters, partitions,
configs),
service.NewClusterPartitionService(gdb, partitions, clusters),
ctx
diff --git a/api/compute/service/config.go b/api/compute/service/config.go
index bf1f5fb60c..686e62f8d9 100644
--- a/api/compute/service/config.go
+++ b/api/compute/service/config.go
@@ -27,6 +27,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
dto "github.com/apache/airavata/api/compute/dto"
model "github.com/apache/airavata/api/compute/model"
@@ -179,10 +180,10 @@ func NewSlurmClusterConfigService(
}
}
-// List returns every config across every owner. Admin only — it names who may
submit
+// List returns every config across every owner. Needs clusterconfig:list — it
names who may submit
// as whom, and where.
func (s *SlurmClusterConfigService) List(ctx context.Context)
([]dto.SlurmClusterConfigResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.ClusterConfigList);
err != nil {
return nil, err
}
configs, err := s.configs.FindAll(ctx)
diff --git a/api/compute/service/config_test.go
b/api/compute/service/config_test.go
index a23df496f2..802f420d10 100644
--- a/api/compute/service/config_test.go
+++ b/api/compute/service/config_test.go
@@ -28,6 +28,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
dto "github.com/apache/airavata/api/compute/dto"
computemodel "github.com/apache/airavata/api/compute/model"
@@ -71,7 +72,7 @@ func userCtx(name string) context.Context {
}
func adminCtx(name string) context.Context {
- return auth.WithPrincipal(context.Background(), &auth.Principal{Name:
name, Authorities: []string{"ADMIN"}})
+ return auth.WithPrincipal(context.Background(), &auth.Principal{Name:
name, Authorities: []string{"ADMIN"}, Permissions:
permission.SetOf(permission.All()...)})
}
func newConfigFixture(t *testing.T) *configFixture {
diff --git a/api/compute/service/discovery.go b/api/compute/service/discovery.go
index 065645b974..ea34e51fd7 100644
--- a/api/compute/service/discovery.go
+++ b/api/compute/service/discovery.go
@@ -33,6 +33,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
"github.com/apache/airavata/internal/ssh"
dto "github.com/apache/airavata/api/compute/dto"
@@ -79,7 +80,7 @@ func (s *ClusterDiscoveryService) WithRunner(run
CommandRunner) *ClusterDiscover
// under a key the caller owns: it is a way to make the server open an SSH
session to
// a host of the caller's choosing, which nobody else's key may be lent to.
func (s *ClusterDiscoveryService) DiscoverPartitions(ctx context.Context, req
*dto.PartitionDiscoveryRequest) (*dto.PartitionDiscoveryResponse, error) {
- principal, err := auth.RequireAdmin(ctx)
+ principal, err := auth.RequirePermission(ctx,
permission.ClusterDiscover)
if err != nil {
return nil, err
}
diff --git a/api/data/service/product.go b/api/data/service/product.go
index 284e515ce9..4f728ca888 100644
--- a/api/data/service/product.go
+++ b/api/data/service/product.go
@@ -28,6 +28,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
dto "github.com/apache/airavata/api/data/dto"
model "github.com/apache/airavata/api/data/model"
@@ -131,10 +132,10 @@ func NewDataProductService(
}
}
-// List returns every product across every owner. Admin only — it names who
holds what
+// List returns every product across every owner. Needs dataproduct:list — it
names who holds what
// data.
func (s *DataProductService) List(ctx context.Context)
([]dto.DataProductResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.DataProductList);
err != nil {
return nil, err
}
products, err := s.products.FindAll(ctx)
diff --git a/api/data/service/storage.go b/api/data/service/storage.go
index 1f548597c2..5504543016 100644
--- a/api/data/service/storage.go
+++ b/api/data/service/storage.go
@@ -27,6 +27,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
credmodel "github.com/apache/airavata/api/credentials/model"
credsvc "github.com/apache/airavata/api/credentials/service"
@@ -149,10 +150,10 @@ func NewSCPDataStorageService(
}
}
-// List returns every storage across every owner. Admin only — it names who
stages what
+// List returns every storage across every owner. Needs storage:list — it
names who stages what
// where.
func (s *SCPDataStorageService) List(ctx context.Context)
([]dto.SCPDataStorageResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.StorageList); err
!= nil {
return nil, err
}
storages, err := s.storages.FindAll(ctx)
diff --git a/api/data/service/virtual.go b/api/data/service/virtual.go
index c6ee1d5759..589b7d69e9 100644
--- a/api/data/service/virtual.go
+++ b/api/data/service/virtual.go
@@ -27,6 +27,7 @@ import (
"gorm.io/gorm"
"github.com/apache/airavata/internal/auth"
+ "github.com/apache/airavata/internal/permission"
dto "github.com/apache/airavata/api/data/dto"
model "github.com/apache/airavata/api/data/model"
@@ -64,10 +65,10 @@ func NewVirtualDataDirectoryService(
}
}
-// List returns every directory node across every dataset. Admin only — it
names who
+// List returns every directory node across every dataset. Needs
virtualdirectory:list — it names who
// holds what data.
func (s *VirtualDataDirectoryService) List(ctx context.Context)
([]dto.VirtualDataDirectoryResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx,
permission.VirtualDirectoryList); err != nil {
return nil, err
}
dirs, err := s.directories.FindAll(ctx)
diff --git a/api/data/service/virtual_tree.go b/api/data/service/virtual_tree.go
index aa3ebfcb8b..a131f2037a 100644
--- a/api/data/service/virtual_tree.go
+++ b/api/data/service/virtual_tree.go
@@ -28,6 +28,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/data/model"
"github.com/apache/airavata/api/data/repository"
@@ -121,7 +122,7 @@ func (a directoryAccess) permissionOf(ctx context.Context,
dir *model.VirtualDat
if err != nil {
return sharingmodel.AccessPermissionNone, false, err
}
- if principal.IsAdmin() {
+ if principal.Can(permission.ResourceManageAny) {
return sharingmodel.AccessPermissionWrite, true, nil
}
diff --git a/api/iam/dto/user.go b/api/iam/dto/user.go
index 4da488213f..88404f5cba 100644
--- a/api/iam/dto/user.go
+++ b/api/iam/dto/user.go
@@ -109,8 +109,11 @@ type CurrentUserResponse struct {
UserID string `json:"userId"`
// Status is ACTIVE for the root account and service accounts, whose
standing is
// not kept on a user record.
- Status string `json:"status"`
- Authorities []string `json:"authorities"`
+ Status string `json:"status"`
+ Authorities []string `json:"authorities"`
+ // Permissions is what the caller's roles grant, sorted. A client can
use it to hide
+ // what the caller cannot do; the server enforces it regardless.
+ Permissions []string `json:"permissions"`
Admin bool `json:"admin"`
User *UserAccountResponse `json:"user"`
}
diff --git a/api/iam/model/rolepermission.go b/api/iam/model/rolepermission.go
new file mode 100644
index 0000000000..b76611bcb7
--- /dev/null
+++ b/api/iam/model/rolepermission.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"
+)
+
+// RolePermission grants one permission to every holder of one role. The
primary key is
+// the (role, permission) pair, so a role holds each permission at most once.
+//
+// There is no foreign key to a roles table because roles are a fixed set (see
+// internal/role), validated where a user is given one. There is none to a
permissions
+// table either: the catalogue is in code, since a handler can only ask for a
permission
+// the code knows about.
+type RolePermission struct {
+ Role Role
`gorm:"column:role;primaryKey;type:varchar(32)" json:"role"`
+ Permission permission.Permission
`gorm:"column:permission;primaryKey;type:varchar(64)" json:"permission"`
+}
+
+// TableName returns the table backing RolePermission.
+func (RolePermission) TableName() string { return "role_permissions" }
+
+// BeforeSave rejects an unrecognised role or permission, so a typo cannot be
stored as a
+// grant that silently never matches anything.
+func (r *RolePermission) BeforeSave(*gorm.DB) error {
+ if !r.Role.Valid() || !r.Permission.Valid() {
+ return gorm.ErrInvalidValue
+ }
+ return nil
+}
diff --git a/api/iam/repository/permissions.go
b/api/iam/repository/permissions.go
new file mode 100644
index 0000000000..e4e0fdfc9e
--- /dev/null
+++ b/api/iam/repository/permissions.go
@@ -0,0 +1,140 @@
+/**
+*
+* 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 repository
+
+import (
+ "context"
+ "log/slog"
+ "sync"
+ "time"
+
+ "gorm.io/gorm"
+
+ "github.com/apache/airavata/internal/permission"
+ "github.com/apache/airavata/internal/role"
+
+ model "github.com/apache/airavata/api/iam/model"
+)
+
+// DefaultPermissionTTL is how long a role's permissions are remembered. It
bounds how
+// 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.
+//
+// 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 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.
+type PermissionResolver struct {
+ db *gorm.DB
+ ttl time.Duration
+ now func() time.Time
+
+ mu sync.RWMutex
+ cache map[role.Role]cachedPermissions
+}
+
+type cachedPermissions struct {
+ perms permission.Set
+ expires time.Time
+}
+
+// NewPermissionResolver returns a resolver over db. A ttl of zero or less
means
+// DefaultPermissionTTL.
+func NewPermissionResolver(db *gorm.DB, ttl time.Duration) *PermissionResolver
{
+ if ttl <= 0 {
+ ttl = DefaultPermissionTTL
+ }
+ return &PermissionResolver{
+ db: db,
+ ttl: ttl,
+ now: time.Now,
+ cache: make(map[role.Role]cachedPermissions),
+ }
+}
+
+// Permissions implements auth.PermissionResolver: 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 {
+ out := permission.Set{}
+ for _, a := range authorities {
+ ro := role.Role(a)
+ if !ro.Valid() {
+ continue
+ }
+ if ro == role.SuperAdmin {
+ for _, p := range permission.All() {
+ out[p] = struct{}{}
+ }
+ continue
+ }
+ for p := range r.forRole(ctx, ro) {
+ out[p] = struct{}{}
+ }
+ }
+ return out
+}
+
+// Invalidate forgets every cached role, so the next request reads the table
again. Call
+// it after changing role_permissions.
+func (r *PermissionResolver) Invalidate() {
+ r.mu.Lock()
+ r.cache = make(map[role.Role]cachedPermissions)
+ r.mu.Unlock()
+}
+
+func (r *PermissionResolver) forRole(ctx context.Context, ro role.Role)
permission.Set {
+ r.mu.RLock()
+ hit, ok := r.cache[ro]
+ r.mu.RUnlock()
+ if ok && r.now().Before(hit.expires) {
+ return hit.perms
+ }
+
+ var rows []model.RolePermission
+ if err := r.db.WithContext(ctx).Where("role = ?",
string(ro)).Find(&rows).Error; err != nil {
+ // Fail closed, and do not cache the failure: the next request
should try again
+ // rather than deny for a whole TTL because of one bad moment.
+ slog.Error("failed to look up role permissions; granting none",
+ "role", ro, "error", err)
+ return nil
+ }
+ perms := make(permission.Set, len(rows))
+ for _, row := range rows {
+ // A row naming a permission this build does not define (a
downgrade, a manual
+ // insert) cannot match any check, so it is dropped rather than
carried.
+ if row.Permission.Valid() {
+ perms[row.Permission] = struct{}{}
+ }
+ }
+
+ r.mu.Lock()
+ r.cache[ro] = cachedPermissions{perms: perms, expires:
r.now().Add(r.ttl)}
+ r.mu.Unlock()
+ return perms
+}
diff --git a/api/iam/repository/permissions_test.go
b/api/iam/repository/permissions_test.go
new file mode 100644
index 0000000000..990d06a907
--- /dev/null
+++ b/api/iam/repository/permissions_test.go
@@ -0,0 +1,125 @@
+/**
+*
+* 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 repository_test
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/apache/airavata/internal/permission"
+ "github.com/apache/airavata/internal/role"
+
+ model "github.com/apache/airavata/api/iam/model"
+ iamrepo "github.com/apache/airavata/api/iam/repository"
+)
+
+func TestPermissionResolver(t *testing.T) {
+ gdb := openTestDB(t) // seeded with the defaults: ADMIN holds audit:read
+ r := iamrepo.NewPermissionResolver(gdb, time.Hour)
+ ctx := context.Background()
+
+ for _, tc := range []struct {
+ name string
+ authorities []string
+ want bool
+ }{
+ {"admin by default", []string{"ADMIN"}, true},
+ {"user by default", []string{"USER"}, false},
+ {"super admin holds everything", []string{"SUPER_ADMIN"}, true},
+ {"union across roles", []string{"USER", "ADMIN"}, true},
+ {"unknown authority", []string{"WIZARD"}, false},
+ {"no authorities", nil, false},
+ } {
+ 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)
+ }
+ }
+}
+
+func TestPermissionResolverCachesUntilInvalidatedOrExpired(t *testing.T) {
+ gdb := openTestDB(t)
+ r := iamrepo.NewPermissionResolver(gdb, time.Hour)
+ ctx := context.Background()
+ user := []string{"USER"}
+
+ 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) {
+ 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) {
+ 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)
+ 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) {
+ t.Error("the revoked grant outlived its TTL")
+ }
+}
+
+// A failed lookup denies, and is not remembered.
+func TestPermissionResolverFailsClosed(t *testing.T) {
+ gdb := openTestDB(t)
+ r := iamrepo.NewPermissionResolver(gdb, time.Hour)
+ if err := gdb.Migrator().DropTable(&model.RolePermission{}); err != nil
{
+ t.Fatal(err)
+ }
+ 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) {
+ t.Error("SUPER_ADMIN was locked out by a broken
role_permissions table")
+ }
+ if err := gdb.AutoMigrate(&model.RolePermission{}); err != nil {
+ t.Fatal(err)
+ }
+ 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) {
+ t.Error("the failure was cached")
+ }
+}
+
+func TestRolePermissionRejectsUnknownValues(t *testing.T) {
+ gdb := openTestDB(t)
+ for _, rp := range []model.RolePermission{
+ {Role: "WIZARD", Permission: permission.AuditRead},
+ {Role: role.User, Permission: "audit:typo"},
+ } {
+ if err := gdb.Create(&rp).Error; err == nil {
+ t.Errorf("stored %+v", rp)
+ }
+ }
+}
diff --git a/api/iam/service/group.go b/api/iam/service/group.go
index b2d2c27987..6a2f505b8a 100644
--- a/api/iam/service/group.go
+++ b/api/iam/service/group.go
@@ -29,6 +29,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
dto "github.com/apache/airavata/api/iam/dto"
model "github.com/apache/airavata/api/iam/model"
@@ -81,7 +82,7 @@ func (a groupAccess) requireReader(ctx context.Context, group
*model.Group) (*au
if err != nil {
return nil, err
}
- if principal.IsAdmin() || group.OwnedBy(principal.Name) {
+ if principal.Can(permission.GroupReadAny) ||
principal.Can(permission.GroupManageAny) || group.OwnedBy(principal.Name) {
return principal, nil
}
member, err := a.membership(ctx, group.ID, principal.Name)
@@ -101,7 +102,7 @@ func (a groupAccess) requireManager(ctx context.Context,
group *model.Group) (*a
if err != nil {
return nil, err
}
- if principal.IsAdmin() || group.OwnedBy(principal.Name) {
+ if principal.Can(permission.GroupManageAny) ||
group.OwnedBy(principal.Name) {
return principal, nil
}
member, err := a.membership(ctx, group.ID, principal.Name)
@@ -122,7 +123,7 @@ func (a groupAccess) requireOwner(ctx context.Context,
group *model.Group) (*aut
if err != nil {
return nil, err
}
- if principal.IsAdmin() || group.OwnedBy(principal.Name) {
+ if principal.Can(permission.GroupManageAny) ||
group.OwnedBy(principal.Name) {
return principal, nil
}
return nil, httpx.Forbidden("Access denied: you may only modify a group
you own")
@@ -155,10 +156,10 @@ func NewGroupService(db *gorm.DB, groups
*repository.GroupRepository, members *r
}
}
-// List returns every group across every owner. Admin only — this exposes who
is
+// List returns every group across every owner. Needs group:list — this
exposes who is
// working with whom.
func (s *GroupService) List(ctx context.Context) ([]dto.GroupResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.GroupList); err !=
nil {
return nil, err
}
groups, err := s.groups.FindAll(ctx)
@@ -392,7 +393,7 @@ func (s *GroupMemberService) Update(ctx context.Context,
groupID, userID string,
if err != nil {
return nil, err
}
- if group.OwnedBy(userID) && !(principal.IsAdmin() ||
group.OwnedBy(principal.Name)) {
+ if group.OwnedBy(userID) && !(principal.Can(permission.GroupManageAny)
|| group.OwnedBy(principal.Name)) {
return nil, httpx.Forbidden("Access denied: only the group
owner may change their own membership")
}
diff --git a/api/iam/service/serviceaccount.go
b/api/iam/service/serviceaccount.go
index 89c0260f16..9183058f61 100644
--- a/api/iam/service/serviceaccount.go
+++ b/api/iam/service/serviceaccount.go
@@ -29,6 +29,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
dto "github.com/apache/airavata/api/iam/dto"
model "github.com/apache/airavata/api/iam/model"
@@ -40,7 +41,7 @@ import (
// ServiceAccountService administers service accounts: non-human users that
// authenticate with an Airavata-issued, expiring token.
//
-// Every operation is admin only. A service account is otherwise an ordinary
user —
+// 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.
@@ -62,7 +63,7 @@ func NewServiceAccountService(db *gorm.DB, accounts
*repository.ServiceAccountRe
// Create registers a service account and mints its first token. The token is
in the
// response and nowhere else; it cannot be read back later.
func (s *ServiceAccountService) Create(ctx context.Context, req
*dto.ServiceAccountCreate) (*dto.ServiceAccountTokenResponse, error) {
- admin, err := auth.RequireAdmin(ctx)
+ admin, err := auth.RequirePermission(ctx,
permission.ServiceAccountManage)
if err != nil {
return nil, err
}
@@ -115,7 +116,7 @@ func (s *ServiceAccountService) Create(ctx context.Context,
req *dto.ServiceAcco
// List returns every service account.
func (s *ServiceAccountService) List(ctx context.Context)
([]dto.ServiceAccountResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx,
permission.ServiceAccountRead); err != nil {
return nil, err
}
users, err := s.accounts.FindAll(ctx)
@@ -131,7 +132,7 @@ func (s *ServiceAccountService) List(ctx context.Context)
([]dto.ServiceAccountR
// Get returns one service account.
func (s *ServiceAccountService) Get(ctx context.Context, id string)
(*dto.ServiceAccountResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx,
permission.ServiceAccountRead); err != nil {
return nil, err
}
user, err := s.require(ctx, s.accounts, id)
@@ -146,7 +147,7 @@ func (s *ServiceAccountService) Get(ctx context.Context, id
string) (*dto.Servic
// Setting the status to anything but ACTIVE stops its token working
immediately,
// without discarding it, so the account can be re-enabled.
func (s *ServiceAccountService) Update(ctx context.Context, id string, req
*dto.ServiceAccountUpdate) (*dto.ServiceAccountResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx,
permission.ServiceAccountManage); err != nil {
return nil, err
}
@@ -184,7 +185,7 @@ func (s *ServiceAccountService) Update(ctx context.Context,
id string, req *dto.
// itself is unchanged, so whatever holds it keeps working. An expired token
can be
// renewed back into use.
func (s *ServiceAccountService) RenewToken(ctx context.Context, id string, req
*dto.ServiceAccountTokenRequest) (*dto.ServiceAccountResponse, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx,
permission.ServiceAccountManage); err != nil {
return nil, err
}
@@ -207,7 +208,7 @@ func (s *ServiceAccountService) RenewToken(ctx
context.Context, id string, req *
// RegenerateToken replaces the token with a new one. The old token stops
working in
// the same write; this is how a leaked token is revoked.
func (s *ServiceAccountService) RegenerateToken(ctx context.Context, id
string, req *dto.ServiceAccountTokenRequest) (*dto.ServiceAccountTokenResponse,
error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx,
permission.ServiceAccountManage); err != nil {
return nil, err
}
@@ -244,7 +245,7 @@ func (s *ServiceAccountService) RegenerateToken(ctx
context.Context, id string,
// transferred implicitly — and gets 409. Disabling it (status INACTIVE)
revokes its
// access while keeping what it owns.
func (s *ServiceAccountService) Delete(ctx context.Context, id string) error {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx,
permission.ServiceAccountManage); err != nil {
return err
}
diff --git a/api/iam/service/user.go b/api/iam/service/user.go
index 9d6f326284..6131579815 100644
--- a/api/iam/service/user.go
+++ b/api/iam/service/user.go
@@ -29,6 +29,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
dto "github.com/apache/airavata/api/iam/dto"
model "github.com/apache/airavata/api/iam/model"
@@ -56,7 +57,7 @@ func NewUserService(db *gorm.DB, repo
*repository.UserRepository) *UserService {
// Status and creation time are set here rather than taken from the request,
so a
// caller cannot register an account that is already suspended or backdated.
func (s *UserService) Register(ctx context.Context, req *dto.UserRegistration)
(*dto.UserResponse, error) {
- if _, err := auth.RequireSuperAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.UserCreate); err !=
nil {
return nil, err
}
// Service accounts have their own API, which is what issues their
token. One
@@ -92,7 +93,7 @@ func (s *UserService) Register(ctx context.Context, req
*dto.UserRegistration) (
// Get returns one user. Admins may read anyone; everyone else may read only
// themselves.
func (s *UserService) Get(ctx context.Context, userID string)
(*dto.UserResponse, error) {
- if _, err := auth.RequireSelfOrAdmin(ctx, userID,
+ if _, err := auth.RequireSelfOrPermission(ctx, userID,
permission.UserReadAny,
"Access denied: You can only access your own user
information"); err != nil {
return nil, err
}
@@ -106,9 +107,9 @@ func (s *UserService) Get(ctx context.Context, userID
string) (*dto.UserResponse
}
// List returns every user, with the email, auth method and roles an
administrator
-// needs to decide on them. Admin only.
+// needs to decide on them. Needs user:list.
func (s *UserService) List(ctx context.Context) ([]dto.UserAccountResponse,
error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.UserList); err !=
nil {
return nil, err
}
@@ -134,6 +135,7 @@ func (s *UserService) Me(ctx context.Context)
(*dto.CurrentUserResponse, error)
UserID: principal.Name,
Status: principal.Status,
Authorities: principal.Authorities,
+ Permissions: principal.Permissions.Sorted(),
Admin: principal.IsAdmin(),
}
if out.Status == "" {
@@ -150,14 +152,14 @@ func (s *UserService) Me(ctx context.Context)
(*dto.CurrentUserResponse, error)
return out, nil
}
-// SetStatus activates, deactivates or suspends a user. Admin only.
+// SetStatus activates, deactivates or suspends a user. Needs user:set_status.
//
// An administrator cannot change their own status, which would be a way to
lock the
// last administrator out. Only a Super Admin may change another
administrator's
// status, so an ADMIN cannot suspend the people who appoint admins. Service
accounts
// have their own lifecycle under /api/v1/service-accounts.
func (s *UserService) SetStatus(ctx context.Context, userID string, req
*dto.UserStatusUpdate) (*dto.UserAccountResponse, error) {
- principal, err := auth.RequireAdmin(ctx)
+ principal, err := auth.RequirePermission(ctx, permission.UserSetStatus)
if err != nil {
return nil, err
}
@@ -173,7 +175,7 @@ func (s *UserService) SetStatus(ctx context.Context, userID
string, req *dto.Use
return nil, httpx.Invalid([]httpx.FieldError{{Field: "userId",
Message: "Service accounts are managed through
/api/v1/service-accounts"}})
}
- if user.IsAdmin() &&
!principal.HasAnyAuthority(string(model.RoleSuperAdmin)) {
+ if user.IsAdmin() && !principal.Can(permission.AdminManage) {
return nil, httpx.Forbidden("Only a Super Admin can change an
administrator's status")
}
@@ -186,13 +188,13 @@ func (s *UserService) SetStatus(ctx context.Context,
userID string, req *dto.Use
return &out, nil
}
-// SetAdmin grants or withdraws the ADMIN role. Super Admin only.
+// SetAdmin grants or withdraws the ADMIN role. Needs admin:manage, which only
SUPER_ADMIN holds by default.
//
// A Super Admin cannot change their own role, and a Super Admin's standing is
not
// something this call touches: SUPER_ADMIN accounts are rejected. Service
accounts
// never hold administrator rights.
func (s *UserService) SetAdmin(ctx context.Context, userID string, req
*dto.UserAdminUpdate) (*dto.UserAccountResponse, error) {
- principal, err := auth.RequireSuperAdmin(ctx)
+ principal, err := auth.RequirePermission(ctx, permission.AdminManage)
if err != nil {
return nil, err
}
@@ -239,7 +241,7 @@ func (s *UserService) Update(ctx context.Context, userID
string, req *dto.UserRe
if err != nil {
return nil, err
}
- if principal.Name != userID &&
!principal.HasAnyAuthority(string(model.RoleSuperAdmin)) {
+ if principal.Name != userID && !principal.Can(permission.UserUpdateAny)
{
return nil, httpx.Forbidden("Access denied: You can only update
your own user information")
}
diff --git a/api/process/service/launch.go b/api/process/service/launch.go
index 0dc914db44..644b3b8218 100644
--- a/api/process/service/launch.go
+++ b/api/process/service/launch.go
@@ -34,6 +34,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
appdto "github.com/apache/airavata/api/application/dto"
appmod "github.com/apache/airavata/api/application/model"
@@ -155,7 +156,7 @@ func (s *LaunchService) requireOwnership(ctx
context.Context, proc *dto.Response
return err
}
owned := proc.UserID != nil && *proc.UserID == principal.Name
- if !owned && !principal.IsAdmin() {
+ if !owned && !principal.Can(permission.ProcessManageAny) {
return httpx.Forbidden("Access denied: you may only launch your
own processes")
}
return nil
diff --git a/api/process/service/process.go b/api/process/service/process.go
index 03396e07e6..41faa1890e 100644
--- a/api/process/service/process.go
+++ b/api/process/service/process.go
@@ -31,6 +31,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
applicationdto "github.com/apache/airavata/api/application/dto"
applicationmodel "github.com/apache/airavata/api/application/model"
@@ -88,9 +89,9 @@ func NewProcessService(
}
}
-// List returns every process across every user. Admin only.
+// List returns every process across every user. Needs process:list.
func (s *ProcessService) List(ctx context.Context) ([]dto.Response, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.ProcessList); err
!= nil {
return nil, err
}
found, err := s.processes.FindAll(ctx)
@@ -192,7 +193,7 @@ func (s *ProcessService) Create(ctx context.Context, req
*dto.Request) (*dto.Res
// BATCH_JOB turned into something else would strand its batch process with no
way to
// reach it.
func (s *ProcessService) Update(ctx context.Context, id string, req
*dto.Request) (*dto.Response, error) {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.ProcessUpdate); err
!= nil {
return nil, err
}
@@ -229,7 +230,7 @@ func (s *ProcessService) Update(ctx context.Context, id
string, req *dto.Request
// section's resource request, its status history, its tasks and its mappings.
Admin
// only.
func (s *ProcessService) Delete(ctx context.Context, id string) error {
- if _, err := auth.RequireAdmin(ctx); err != nil {
+ if _, err := auth.RequirePermission(ctx, permission.ProcessDelete); err
!= nil {
return err
}
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
diff --git a/api/process/service/task.go b/api/process/service/task.go
index a6cc83bd0d..a9dcf3d34c 100644
--- a/api/process/service/task.go
+++ b/api/process/service/task.go
@@ -27,6 +27,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
dto "github.com/apache/airavata/api/process/dto"
model "github.com/apache/airavata/api/process/model"
@@ -156,7 +157,7 @@ func (s *TaskService[T, Req]) requireProcessWith(ctx
context.Context, processes
if err != nil {
return nil, notFoundAs(err, "Process not found: %s", processID)
}
- if !proc.OwnedBy(principal.Name) && !principal.IsAdmin() {
+ if !proc.OwnedBy(principal.Name) &&
!principal.Can(permission.ProcessManageAny) {
return nil, httpx.Forbidden("Access denied: you may only work
with tasks of your own processes")
}
return proc, nil
diff --git a/api/process/service/task_status.go
b/api/process/service/task_status.go
index 68840336c1..cca6145604 100644
--- a/api/process/service/task_status.go
+++ b/api/process/service/task_status.go
@@ -25,6 +25,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
dto "github.com/apache/airavata/api/process/dto"
"github.com/apache/airavata/api/process/repository"
@@ -85,7 +86,7 @@ func (s *TaskStatusService) requireProcess(ctx
context.Context, processID string
if err != nil {
return notFoundAs(err, "Process not found: %s", processID)
}
- if !proc.OwnedBy(principal.Name) && !principal.IsAdmin() {
+ if !proc.OwnedBy(principal.Name) &&
!principal.Can(permission.ProcessManageAny) {
return httpx.Forbidden("Access denied: you may only work with
tasks of your own processes")
}
return nil
diff --git a/api/process/service/workflow.go b/api/process/service/workflow.go
index 4e97bf570d..67fbc0b322 100644
--- a/api/process/service/workflow.go
+++ b/api/process/service/workflow.go
@@ -27,6 +27,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
dto "github.com/apache/airavata/api/process/dto"
model "github.com/apache/airavata/api/process/model"
@@ -122,7 +123,7 @@ func (s *WorkflowService) requireProcess(ctx
context.Context, processID string)
if err != nil {
return notFoundAs(err, "Process not found: %s", processID)
}
- if !proc.OwnedBy(principal.Name) && !principal.IsAdmin() {
+ if !proc.OwnedBy(principal.Name) &&
!principal.Can(permission.ProcessManageAny) {
return httpx.Forbidden("Access denied: you may only work with
workflows of your own processes")
}
return nil
diff --git a/api/sharing/service/sharing.go b/api/sharing/service/sharing.go
index 4e18675835..4b432042ba 100644
--- a/api/sharing/service/sharing.go
+++ b/api/sharing/service/sharing.go
@@ -36,6 +36,7 @@ import (
"github.com/apache/airavata/internal/auth"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
iamrepo "github.com/apache/airavata/api/iam/repository"
dto "github.com/apache/airavata/api/sharing/dto"
@@ -75,7 +76,7 @@ func (a Access) PermissionOf(ctx context.Context, ownerID
*string, shares []mode
if err != nil {
return model.AccessPermissionNone, false, err
}
- if principal.IsAdmin() || (ownerID != nil && *ownerID ==
principal.Name) {
+ if principal.Can(permission.ResourceManageAny) || (ownerID != nil &&
*ownerID == principal.Name) {
return model.AccessPermissionWrite, true, nil
}
diff --git a/docs/audit.md b/docs/audit.md
index d35c72d573..cbce04a213 100644
--- a/docs/audit.md
+++ b/docs/audit.md
@@ -27,7 +27,7 @@ When a record is deleted, anything the database removes along
with it, such as a
## Reading the log
-Only `ADMIN` and `SUPER_ADMIN` can read it, because it names what every user
did.
+Reading it needs the `audit:read` permission, which `ADMIN` and `SUPER_ADMIN`
have by default, because the log names what every user did. See
[Permissions](auth.md#permissions).
```
GET /api/v1/audit-events
diff --git a/docs/auth.md b/docs/auth.md
index 61a5e0b934..61e1b4ff21 100644
--- a/docs/auth.md
+++ b/docs/auth.md
@@ -171,7 +171,7 @@ Administrators activate, suspend and deactivate users on
the dashboard's **Users
| Route | Who | Purpose |
|---|---|---|
-| `GET /api/v1/users/me` | Any signed-in caller, active or not | `{userId,
status, authorities, admin, user}`: who the server thinks the caller is |
+| `GET /api/v1/users/me` | Any signed-in caller, active or not | `{userId,
status, authorities, permissions, admin, user}`: who the server thinks the
caller is |
| `GET /api/v1/users` | `ADMIN`, `SUPER_ADMIN` | Every user, with email,
sign-in method, roles and status |
| `POST /api/v1/users/{userId}/status` | `ADMIN`, `SUPER_ADMIN` | `{"status":
"ACTIVE" \| "SUSPENDED" \| "INACTIVE"}` |
@@ -299,6 +299,50 @@ Roles are stored in Airavata's `user_roles` table and
looked up on every request
| `ADMIN` | Platform-wide listings (every process, config, storage and user),
and activating and suspending users other than administrators. |
| `SUPER_ADMIN` | Everything `ADMIN` can do, plus changing administrators'
status and creating user records ahead of a first sign-in. The root account has
this role. |
+### Permissions
+
+Actions that need privilege are gated by a **permission** such as
`audit:read`, not by a role name. Each role is granted a set of permissions in
Airavata's `role_permissions` table, and a caller holds the union of what their
roles grant. Which roles may do something is therefore data, not code. `GET
/api/v1/users/me` lists the caller's permissions.
+
+| Permission | Allows | Default |
+|---|---|---|
+| `audit:read` | Reading the [audit log](audit.md) | `ADMIN` |
+| `user:list` | Listing every user | `ADMIN` |
+| `user:read_any` | Reading another user's record | `ADMIN` |
+| `user:set_status` | Activating, suspending and deactivating users | `ADMIN` |
+| `user:create` | Creating a user record ahead of the user's first sign-in |
`SUPER_ADMIN` only |
+| `user:update_any` | Editing another user's profile | `SUPER_ADMIN` only |
+| `admin:manage` | Appointing and removing administrators, and changing an
administrator's status | `SUPER_ADMIN` only |
+| `group:list` | Listing every group | `ADMIN` |
+| `group:read_any` | Reading a group the caller is not in | `ADMIN` |
+| `group:manage_any` | Renaming, deleting and managing the members of any
group | `ADMIN` |
+| `serviceaccount:read` | Listing and reading service accounts | `ADMIN` |
+| `serviceaccount:manage` | Creating, editing and deleting service accounts,
and re-issuing their tokens | `ADMIN` |
+| `cluster:manage` | Creating, editing and deleting clusters and their
partitions | `ADMIN` |
+| `cluster:discover` | Discovering a cluster's partitions over SSH | `ADMIN` |
+| `clusterconfig:list` | Listing every cluster config | `ADMIN` |
+| `template:manage` | Creating, editing and deleting application templates |
`ADMIN` |
+| `deployment:manage` | Creating, editing and deleting batch deployments |
`ADMIN` |
+| `storage:list` | Listing every data storage | `ADMIN` |
+| `dataproduct:list` | Listing every data product | `ADMIN` |
+| `virtualdirectory:list` | Listing every virtual data directory | `ADMIN` |
+| `resource:manage_any` | Acting as the owner of any cluster config, data
storage, data product or virtual data directory. SSH credentials are not
included: they stay visible to their owner only | `ADMIN` |
+| `process:list` | Listing every process | `ADMIN` |
+| `process:update` | Editing any process directly | `ADMIN` |
+| `process:delete` | Deleting any process | `ADMIN` |
+| `process:manage_any` | Reading, launching and editing the tasks, statuses
and workflows of any process | `ADMIN` |
+
+A name ending in `_any` is an override that reaches records the caller does
not own. A caller can always act on their own records, and on records shared
with them, without any permission. Granting only one of these permissions
grants exactly that: a role holding `process:update` can edit a process, but
still needs access to the cluster config the process names.
+
+Where the API reference says an endpoint is "admin only", read it as "needs
the permission listed here, which `ADMIN` holds by default".
+
+`SUPER_ADMIN` holds every permission by definition and is never looked up in
the table, so no change to `role_permissions` can lock the last administrator
out. To let another role read the audit log, for example:
+
+```sql
+INSERT INTO role_permissions (role, permission) VALUES ('USER', 'audit:read');
+```
+
+Grants are cached for a minute, so a change made directly in the database
reaches every request within that time.
+
### Ownership
Anything a user creates belongs to them. The owner is always taken from the
token, never from the request body, and cannot be transferred. Owners can read,
change, delete and share their records. Admins have the same rights, with one
exception: **SSH credentials are visible to their owner only**, admins
included, because a credential is the secret itself.
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index b969f1e9a0..8a757c2941 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -3387,13 +3387,17 @@ components:
authorities:
type: array
items: { type: string }
+ permissions:
+ description: What the caller's roles grant, sorted, such as
`audit:read`.
+ type: array
+ items: { type: string }
admin: { type: boolean }
user:
description: The caller's user record, or null if they have none.
oneOf:
- { $ref: "#/components/schemas/UserAccount" }
- { type: "null" }
- required: [userId, status, authorities, admin, user]
+ required: [userId, status, authorities, permissions, admin, user]
UserStatusUpdate:
type: object
diff --git a/internal/app/app.go b/internal/app/app.go
index eda686d2c8..c2189b2240 100644
--- a/internal/app/app.go
+++ b/internal/app/app.go
@@ -66,6 +66,11 @@ type Services struct {
Config config.Config
DB *gorm.DB
+ // Permissions resolves roles to the permissions they grant. The HTTP
middleware
+ // resolves each caller through it, and whatever changes
role_permissions calls
+ // Invalidate on it so the change takes effect at once.
+ Permissions *iamrepo.PermissionResolver
+
// Audit log.
Audit *auditsvc.EventService
@@ -243,6 +248,8 @@ func NewServices(cfg config.Config, db *gorm.DB, repos
*Repositories, workflowBa
Config: cfg,
DB: db,
+ Permissions: iamrepo.NewPermissionResolver(db,
iamrepo.DefaultPermissionTTL),
+
Audit: auditsvc.NewEventService(repos.AuditEvents),
User: iamsvc.NewUserService(db, users),
diff --git a/internal/auth/middleware.go b/internal/auth/middleware.go
index d756bf4141..97d360d786 100644
--- a/internal/auth/middleware.go
+++ b/internal/auth/middleware.go
@@ -37,7 +37,11 @@ import (
// is a token that is present but unusable: a caller who supplies a bad token
gets 401
// rather than being silently downgraded to anonymous, which would otherwise
turn a
// typo'd token into a confusing 403 further down.
-func Middleware(introspector Introspector) func(http.Handler) http.Handler {
+func Middleware(introspector Introspector, opts ...Option) func(http.Handler)
http.Handler {
+ var cfg middlewareConfig
+ for _, opt := range opts {
+ opt(&cfg)
+ }
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r
*http.Request) {
token := bearerToken(r)
@@ -70,6 +74,10 @@ func Middleware(introspector Introspector)
func(http.Handler) http.Handler {
return
}
+ if cfg.permissions != nil {
+ principal.Permissions =
cfg.permissions.Permissions(r.Context(), principal.Authorities)
+ }
+
next.ServeHTTP(w,
r.WithContext(WithPrincipal(r.Context(), principal)))
})
}
diff --git a/internal/auth/permission.go b/internal/auth/permission.go
new file mode 100644
index 0000000000..b3f3432e22
--- /dev/null
+++ b/internal/auth/permission.go
@@ -0,0 +1,88 @@
+/**
+*
+* 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 auth
+
+import (
+ "context"
+
+ "github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
+)
+
+// PermissionResolver turns a caller's authorities (their role names) into the
+// permissions those roles grant.
+//
+// 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
+}
+
+// Option configures Middleware.
+type Option func(*middlewareConfig)
+
+type middlewareConfig struct {
+ permissions PermissionResolver
+}
+
+// WithPermissions makes Middleware resolve each authenticated principal's
permissions
+// onto the principal, so the guards below can answer from it. Without it, no
principal
+// holds any permission.
+func WithPermissions(r PermissionResolver) Option {
+ return func(c *middlewareConfig) { c.permissions = r }
+}
+
+// Can reports whether the principal holds permission p. A nil principal, an
anonymous
+// caller, holds none.
+func (p *Principal) Can(perm permission.Permission) bool {
+ return p != nil && p.Permissions.Has(perm)
+}
+
+// RequirePermission is the guard for an action gated by a permission.
Handlers and
+// services use it instead of naming the roles that happen to grant the
permission.
+//
+// An anonymous caller gets 401 and an authenticated one without the
permission gets
+// 403, as RequireAnyAuthority does.
+func RequirePermission(ctx context.Context, perm permission.Permission)
(*Principal, error) {
+ p, err := RequireAuthenticated(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if !p.Can(perm) {
+ return nil, httpx.Forbidden("Access denied")
+ }
+ return p, nil
+}
+
+// RequireSelfOrPermission allows the record's owner, or any caller holding
perm. It is
+// the imperative check the user service uses where an annotation cannot see
the owner.
+// The message is caller-supplied because each service phrases its own.
+func RequireSelfOrPermission(ctx context.Context, ownerID string, perm
permission.Permission, message string) (*Principal, error) {
+ p, err := RequireAuthenticated(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if p.Name == ownerID || p.Can(perm) {
+ return p, nil
+ }
+ return nil, httpx.Forbidden("%s", message)
+}
diff --git a/internal/auth/permission_test.go b/internal/auth/permission_test.go
new file mode 100644
index 0000000000..d4da73ae3f
--- /dev/null
+++ b/internal/auth/permission_test.go
@@ -0,0 +1,107 @@
+/**
+*
+* 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 auth_test
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/apache/airavata/internal/auth"
+ "github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
+)
+
+func TestRequirePermission(t *testing.T) {
+ granted := &auth.Principal{Name: "a", Permissions:
permission.Set{permission.AuditRead: {}}}
+ denied := &auth.Principal{Name: "b"}
+
+ if _, err :=
auth.RequirePermission(auth.WithPrincipal(context.Background(), granted),
permission.AuditRead); err != nil {
+ t.Errorf("holder was refused: %v", err)
+ }
+
+ for name, tc := range map[string]struct {
+ ctx context.Context
+ status int
+ }{
+ "anonymous": {context.Background(),
http.StatusUnauthorized},
+ "without grant": {auth.WithPrincipal(context.Background(),
denied), http.StatusForbidden},
+ } {
+ _, err := auth.RequirePermission(tc.ctx, permission.AuditRead)
+ var he *httpx.Error
+ if err == nil || !errors.As(err, &he) || he.Status != tc.status
{
+ t.Errorf("%s: err = %v, want status %d", name, err,
tc.status)
+ }
+ }
+}
+
+// Authorities alone grant nothing: a principal that did not come through the
+// middleware's resolver holds no permission, even one named ADMIN.
+func TestAuthorityDoesNotImplyPermission(t *testing.T) {
+ p := &auth.Principal{Name: "x", Authorities: []string{"SUPER_ADMIN"}}
+ if p.Can(permission.AuditRead) {
+ t.Error("an unresolved principal holds a permission")
+ }
+ var anon *auth.Principal
+ if anon.Can(permission.AuditRead) {
+ t.Error("a nil principal holds a permission")
+ }
+}
+
+type fakeResolver map[string]permission.Set
+
+func (f fakeResolver) Permissions(_ context.Context, authorities []string)
permission.Set {
+ out := permission.Set{}
+ for _, a := range authorities {
+ for p := range f[a] {
+ out[p] = struct{}{}
+ }
+ }
+ return out
+}
+
+type roleIntrospector struct{}
+
+func (roleIntrospector) Introspect(context.Context, string) (*auth.Principal,
error) {
+ return &auth.Principal{Name: "alice", Authorities:
[]string{"AUDITOR"}}, nil
+}
+
+func TestMiddlewareResolvesPermissions(t *testing.T) {
+ resolver := fakeResolver{"AUDITOR": {permission.AuditRead: {}}}
+ var got *auth.Principal
+ next := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
got = auth.FromContext(r.Context()) })
+
+ req := httptest.NewRequest(http.MethodGet, "/x", nil)
+ req.Header.Set("Authorization", "Bearer t")
+ auth.Middleware(roleIntrospector{},
auth.WithPermissions(resolver))(next).ServeHTTP(httptest.NewRecorder(), req)
+ if got == nil || !got.Can(permission.AuditRead) {
+ t.Fatalf("principal = %+v, want audit:read resolved", got)
+ }
+
+ // Without a resolver configured nothing is granted.
+ got = nil
+
auth.Middleware(roleIntrospector{})(next).ServeHTTP(httptest.NewRecorder(), req)
+ if got == nil || got.Can(permission.AuditRead) {
+ t.Fatalf("principal = %+v, want no permissions", got)
+ }
+}
diff --git a/internal/auth/principal.go b/internal/auth/principal.go
index ecc78bcee1..7d78782cd5 100644
--- a/internal/auth/principal.go
+++ b/internal/auth/principal.go
@@ -26,6 +26,7 @@ import (
"context"
"github.com/apache/airavata/internal/httpx"
+ "github.com/apache/airavata/internal/permission"
"github.com/apache/airavata/internal/role"
)
@@ -42,6 +43,12 @@ type Principal struct {
Authorities []string
Attributes map[string]any
+ // Permissions is what Authorities grant, resolved by Middleware once
per request.
+ // An introspector never sets it: like the authorities, it is looked up
server-side
+ // rather than read from the token. It is empty for a principal that
did not come
+ // through Middleware, which therefore holds no permission.
+ Permissions permission.Set
+
// Status is the user record's status for a CILogon principal, and
empty for the
// root account and service accounts, whose standing is decided
elsewhere.
Status string
@@ -115,27 +122,3 @@ func RequireAnyAuthority(ctx context.Context, want
...string) (*Principal, error
}
return p, nil
}
-
-// RequireAdmin is shorthand for the ADMIN/SUPER_ADMIN pairing.
-func RequireAdmin(ctx context.Context) (*Principal, error) {
- return RequireAnyAuthority(ctx, string(role.Admin),
string(role.SuperAdmin))
-}
-
-// RequireSuperAdmin gates the user-registration path.
-func RequireSuperAdmin(ctx context.Context) (*Principal, error) {
- return RequireAnyAuthority(ctx, string(role.SuperAdmin))
-}
-
-// RequireSelfOrAdmin allows the owner or any admin, and is the imperative
check the
-// credential, data and user services use in place of an annotation. The
message is
-// caller-supplied because each service phrases its own.
-func RequireSelfOrAdmin(ctx context.Context, ownerID string, message string)
(*Principal, error) {
- p, err := RequireAuthenticated(ctx)
- if err != nil {
- return nil, err
- }
- if p.Name == ownerID || p.IsAdmin() {
- return p, nil
- }
- return nil, httpx.Forbidden("%s", message)
-}
diff --git a/internal/db/migrate.go b/internal/db/migrate.go
index 471762c919..d5c9e1ae01 100644
--- a/internal/db/migrate.go
+++ b/internal/db/migrate.go
@@ -24,6 +24,8 @@ package db
import (
"gorm.io/gorm"
+ "github.com/apache/airavata/internal/permission"
+
applicationmodel "github.com/apache/airavata/api/application/model"
auditmodel "github.com/apache/airavata/api/audit/model"
computemodel "github.com/apache/airavata/api/compute/model"
@@ -48,6 +50,7 @@ func Entities() []any {
// One level in.
&iammodel.UserRole{},
+ &iammodel.RolePermission{},
&iammodel.ServiceAccount{},
&iammodel.Group{},
&computemodel.SlurmCluster{},
@@ -125,5 +128,35 @@ func Entities() []any {
// indexes but never drops or narrows anything. Production schema changes
belong in
// versioned migrations.
func AutoMigrate(gdb *gorm.DB) error {
- return gdb.AutoMigrate(Entities()...)
+ if err := gdb.AutoMigrate(Entities()...); err != nil {
+ return err
+ }
+ return seedRolePermissions(gdb)
+}
+
+// seedRolePermissions gives a fresh schema the default grants, the way
migration
+// 0015_role_permissions.sql does for a versioned one.
+//
+// It seeds only an empty table. Once any grant exists the table is the
administrators'
+// to edit, and re-inserting the defaults on every start would quietly undo a
revoked
+// permission. A permission added by a later release reaches an existing
database
+// through a migration, not through here.
+func seedRolePermissions(gdb *gorm.DB) error {
+ var existing int64
+ if err := gdb.Model(&iammodel.RolePermission{}).Count(&existing).Error;
err != nil {
+ return err
+ }
+ if existing > 0 {
+ return nil
+ }
+ var rows []iammodel.RolePermission
+ for r, perms := range permission.Defaults() {
+ for _, p := range perms {
+ rows = append(rows, iammodel.RolePermission{Role: r,
Permission: p})
+ }
+ }
+ if len(rows) == 0 {
+ return nil
+ }
+ return gdb.Create(&rows).Error
}
diff --git a/internal/db/migrations/0015_role_permissions.sql
b/internal/db/migrations/0015_role_permissions.sql
new file mode 100644
index 0000000000..6504a59cc2
--- /dev/null
+++ b/internal/db/migrations/0015_role_permissions.sql
@@ -0,0 +1,14 @@
+-- Permission-based authorization: which permissions each role grants.
+--
+-- Handlers check a permission such as "audit:read"; this table says which
roles hold it,
+-- so changing who may do something is a data change. The first statement is
what GORM
+-- emits for iam/model.RolePermission, which keeps this file and AutoMigrate in
+-- agreement — see TestBaselineMigrationMatchesAutoMigrate.
+--
+-- The rows are the defaults in internal/permission.Defaults, which reproduce
what the
+-- ADMIN/SUPER_ADMIN checks allowed before permissions existed. SUPER_ADMIN
has no rows:
+-- it holds every permission by definition and is never read from this table.
+
+CREATE TABLE "role_permissions" ("role" varchar(32),"permission"
varchar(64),PRIMARY KEY ("role","permission"));
+
+INSERT INTO "role_permissions" ("role","permission") VALUES
('ADMIN','audit:read');
diff --git a/internal/db/migrations/0016_role_permissions_all.sql
b/internal/db/migrations/0016_role_permissions_all.sql
new file mode 100644
index 0000000000..2cb843c0e1
--- /dev/null
+++ b/internal/db/migrations/0016_role_permissions_all.sql
@@ -0,0 +1,33 @@
+-- Permission checks for the remaining administrative actions.
+--
+-- 0015 introduced role_permissions with audit:read. This grants ADMIN the
permissions
+-- that replace the rest of the ADMIN/SUPER_ADMIN role checks, so behaviour is
unchanged:
+-- ADMIN keeps everything it could do, and the three actions reserved to
SUPER_ADMIN
+-- (user:create, user:update_any, admin:manage) are granted to no role, since
SUPER_ADMIN
+-- holds every permission without a row.
+--
+-- The rows are the defaults in internal/permission.Defaults;
TestDefaultsMatchMigrations
+-- keeps the two in step.
+
+INSERT INTO "role_permissions" ("role","permission") VALUES
+ ('ADMIN','cluster:discover'),
+ ('ADMIN','cluster:manage'),
+ ('ADMIN','clusterconfig:list'),
+ ('ADMIN','dataproduct:list'),
+ ('ADMIN','deployment:manage'),
+ ('ADMIN','group:list'),
+ ('ADMIN','group:manage_any'),
+ ('ADMIN','group:read_any'),
+ ('ADMIN','process:delete'),
+ ('ADMIN','process:list'),
+ ('ADMIN','process:manage_any'),
+ ('ADMIN','process:update'),
+ ('ADMIN','resource:manage_any'),
+ ('ADMIN','serviceaccount:manage'),
+ ('ADMIN','serviceaccount:read'),
+ ('ADMIN','storage:list'),
+ ('ADMIN','template:manage'),
+ ('ADMIN','user:list'),
+ ('ADMIN','user:read_any'),
+ ('ADMIN','user:set_status'),
+ ('ADMIN','virtualdirectory:list');
diff --git a/internal/db/role_permissions_test.go
b/internal/db/role_permissions_test.go
new file mode 100644
index 0000000000..8e6cea95ea
--- /dev/null
+++ b/internal/db/role_permissions_test.go
@@ -0,0 +1,106 @@
+/**
+*
+* 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 db_test
+
+import (
+ "regexp"
+ "sort"
+ "strings"
+ "testing"
+
+ "github.com/apache/airavata/internal/db"
+ "github.com/apache/airavata/internal/permission"
+
+ iammodel "github.com/apache/airavata/api/iam/model"
+)
+
+func grants(t *testing.T, rows []iammodel.RolePermission) []string {
+ t.Helper()
+ out := make([]string, 0, len(rows))
+ for _, r := range rows {
+ out = append(out, string(r.Role)+" "+string(r.Permission))
+ }
+ sort.Strings(out)
+ return out
+}
+
+func TestAutoMigrateSeedsDefaultsOnce(t *testing.T) {
+ gdb := newTestDB(t)
+
+ var seeded []iammodel.RolePermission
+ if err := gdb.Find(&seeded).Error; err != nil {
+ t.Fatal(err)
+ }
+ var want []string
+ for r, perms := range permission.Defaults() {
+ for _, p := range perms {
+ want = append(want, string(r)+" "+string(p))
+ }
+ }
+ sort.Strings(want)
+ if got := grants(t, seeded); strings.Join(got, ",") !=
strings.Join(want, ",") {
+ t.Fatalf("seeded %v, want %v", got, want)
+ }
+
+ // An administrator's revocation must survive the next start.
+ if err := gdb.Where("1 = 1").Delete(&iammodel.RolePermission{}).Error;
err != nil {
+ t.Fatal(err)
+ }
+ if err := gdb.Create(&iammodel.RolePermission{Role: "USER", Permission:
permission.AuditRead}).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := db.AutoMigrate(gdb); err != nil {
+ t.Fatal(err)
+ }
+ var after []iammodel.RolePermission
+ if err := gdb.Find(&after).Error; err != nil {
+ t.Fatal(err)
+ }
+ if got := grants(t, after); len(got) != 1 || got[0] != "USER
audit:read" {
+ t.Errorf("AutoMigrate re-seeded over an edited table: %v", got)
+ }
+}
+
+// The versioned migrations and the in-code defaults seed the same grants.
+func TestDefaultsMatchMigrations(t *testing.T) {
+ row := regexp.MustCompile(`\('([A-Z_]+)','([a-z_:]+)'\)`)
+ var got []string
+ for _, m := range db.Migrations() {
+ if !strings.Contains(m.SQL, `INSERT INTO "role_permissions"`) {
+ continue
+ }
+ for _, r := range row.FindAllStringSubmatch(m.SQL, -1) {
+ got = append(got, r[1]+" "+r[2])
+ }
+ }
+ sort.Strings(got)
+
+ var want []string
+ for r, perms := range permission.Defaults() {
+ for _, p := range perms {
+ want = append(want, string(r)+" "+string(p))
+ }
+ }
+ sort.Strings(want)
+ if strings.Join(got, ",") != strings.Join(want, ",") {
+ t.Errorf("migrations seed\n %v\nbut permission.Defaults has\n
%v", got, want)
+ }
+}
diff --git a/internal/permission/permission.go
b/internal/permission/permission.go
new file mode 100644
index 0000000000..222b00f0c3
--- /dev/null
+++ b/internal/permission/permission.go
@@ -0,0 +1,181 @@
+/**
+*
+* 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 defines what a caller may be allowed to do.
+//
+// A permission names one action on one kind of record, written
"resource:action". The
+// handlers and services ask for permissions, never for roles: which roles
grant a
+// permission is data (the role_permissions table), so changing who may do
something
+// does not mean changing the code that does it.
+//
+// It is a leaf package like internal/role, so the model, the auth guards and
the
+// resolver can all share the definitions without importing one another.
+package permission
+
+import (
+ "sort"
+
+ "github.com/apache/airavata/internal/role"
+)
+
+// Permission is one grantable action.
+//
+// Naming: "resource:action". An action ending in "_any" is an override that
reaches
+// records the caller does not own; without it the caller can still act on
their own.
+// "list" returns every user's records rather than the caller's.
+type Permission string
+
+const (
+ // Audit log.
+ AuditRead Permission = "audit:read" // read the audit log
+
+ // Users.
+ UserCreate Permission = "user:create" // create a user record
ahead of the user's first sign-in
+ UserList Permission = "user:list" // list every user
+ UserReadAny Permission = "user:read_any" // read another user's
record
+ UserUpdateAny Permission = "user:update_any" // edit another user's
profile
+ UserSetStatus Permission = "user:set_status" // activate, suspend or
deactivate a user
+ // AdminManage is the authority over administrators themselves:
appointing and
+ // removing ADMINs, and changing an administrator's status.
+ AdminManage Permission = "admin:manage"
+
+ // Groups.
+ GroupList Permission = "group:list" // list every group
+ GroupReadAny Permission = "group:read_any" // read a group the
caller is not in
+ GroupManageAny Permission = "group:manage_any" // rename, delete and
manage members of any group
+
+ // Service accounts.
+ ServiceAccountRead Permission = "serviceaccount:read" // list and
read service accounts
+ ServiceAccountManage Permission = "serviceaccount:manage" // create,
edit, delete and re-issue tokens
+
+ // Compute.
+ ClusterManage Permission = "cluster:manage" // create, edit and
delete clusters and their partitions
+ ClusterDiscover Permission = "cluster:discover" // discover a
cluster's partitions over SSH
+ ClusterConfigList Permission = "clusterconfig:list" // list every
cluster config
+
+ // Applications.
+ TemplateManage Permission = "template:manage" // create, edit and
delete application templates
+ DeploymentManage Permission = "deployment:manage" // create, edit and
delete batch deployments
+
+ // Data.
+ StorageList Permission = "storage:list" // list every
data storage
+ DataProductList Permission = "dataproduct:list" // list every
data product
+ VirtualDirectoryList Permission = "virtualdirectory:list" // list every
virtual data directory
+
+ // ResourceManageAny reaches any shareable record — cluster configs,
data storages,
+ // data products and virtual data directories — as if the caller owned
it. SSH
+ // credentials are not among them: they are visible to their owner only.
+ ResourceManageAny Permission = "resource:manage_any"
+
+ // Processes.
+ ProcessList Permission = "process:list" // list every process
+ ProcessUpdate Permission = "process:update" // edit any process
directly
+ ProcessDelete Permission = "process:delete" // delete any process
+ ProcessManageAny Permission = "process:manage_any" // read, launch and
edit the tasks, statuses and workflows of any process
+)
+
+// all is the catalogue, in the order it is documented.
+var all = []Permission{
+ AuditRead,
+ UserCreate, UserList, UserReadAny, UserUpdateAny, UserSetStatus,
AdminManage,
+ GroupList, GroupReadAny, GroupManageAny,
+ ServiceAccountRead, ServiceAccountManage,
+ ClusterManage, ClusterDiscover, ClusterConfigList,
+ TemplateManage, DeploymentManage,
+ StorageList, DataProductList, VirtualDirectoryList, ResourceManageAny,
+ ProcessList, ProcessUpdate, ProcessDelete, ProcessManageAny,
+}
+
+// superAdminOnly are the permissions ADMIN does not hold by default, because
before
+// permissions existed only SUPER_ADMIN could do them.
+var superAdminOnly = map[Permission]bool{
+ UserCreate: true,
+ UserUpdateAny: true,
+ AdminManage: true,
+}
+
+// All returns every defined permission, sorted.
+func All() []Permission {
+ out := append([]Permission(nil), all...)
+ sort.Slice(out, func(i, j int) bool { return out[i] < out[j] })
+ return out
+}
+
+// Valid reports whether p is a defined permission.
+func (p Permission) Valid() bool {
+ for _, known := range all {
+ if p == known {
+ return true
+ }
+ }
+ return false
+}
+
+// Set is a collection of permissions with constant-time membership.
+type Set map[Permission]struct{}
+
+// SetOf returns a Set holding ps.
+func SetOf(ps ...Permission) Set {
+ s := make(Set, len(ps))
+ for _, p := range ps {
+ s[p] = struct{}{}
+ }
+ return s
+}
+
+// Has reports whether s contains p. It is safe on a nil Set, which contains
nothing.
+func (s Set) Has(p Permission) bool {
+ _, ok := s[p]
+ return ok
+}
+
+// Sorted lists the members in a stable order, for responses and logs.
+func (s Set) Sorted() []string {
+ out := make([]string, 0, len(s))
+ for p := range s {
+ out = append(out, string(p))
+ }
+ sort.Strings(out)
+ return out
+}
+
+// Defaults is what each role is granted on a fresh install, before an
administrator
+// changes anything. It reproduces what the role checks allowed before
permissions
+// existed: ADMIN could do every administrative thing except the few reserved
to
+// SUPER_ADMIN, and USER none.
+//
+// SUPER_ADMIN is deliberately absent. It holds every permission by definition
and is
+// never looked up in role_permissions, so no edit to that table can lock the
last
+// administrator out.
+//
+// The same rows are inserted by the versioned migrations (0015, 0016);
+// TestDefaultsMatchMigrations keeps them in step.
+func Defaults() map[role.Role][]Permission {
+ var admin []Permission
+ for _, p := range All() {
+ if !superAdminOnly[p] {
+ admin = append(admin, p)
+ }
+ }
+ return map[role.Role][]Permission{
+ role.Admin: admin,
+ role.User: {},
+ }
+}
diff --git a/internal/server/audit_test.go b/internal/server/audit_test.go
index bebd6095ae..a200bea971 100644
--- a/internal/server/audit_test.go
+++ b/internal/server/audit_test.go
@@ -32,6 +32,8 @@ import (
auditmodel "github.com/apache/airavata/api/audit/model"
iammodel "github.com/apache/airavata/api/iam/model"
"github.com/apache/airavata/internal/auth"
+ "github.com/apache/airavata/internal/permission"
+ "github.com/apache/airavata/internal/role"
"gorm.io/gorm"
)
@@ -248,3 +250,55 @@ func TestAuditEndpointRejectsBadQuery(t *testing.T) {
}
}
}
+
+// Audit access follows the permission, not the role name: granting audit:read
to USER
+// opens the log to a plain user, and revoking it closes it again.
+func TestAuditAccessFollowsRolePermissions(t *testing.T) {
+ h := newHarness(t)
+ const path = "/api/v1/audit-events"
+
+ if rec := h.do("GET", path, tokenAlice, nil); rec.Code !=
http.StatusForbidden {
+ t.Fatalf("user without the permission: status = %d, want 403",
rec.Code)
+ }
+ if rec := h.do("GET", path, "", nil); rec.Code !=
http.StatusUnauthorized {
+ t.Fatalf("anonymous: status = %d, want 401", rec.Code)
+ }
+
+ grant := iammodel.RolePermission{Role: role.User, Permission:
permission.AuditRead}
+ if err := h.db.Create(&grant).Error; err != nil {
+ t.Fatal(err)
+ }
+ h.svcs.Permissions.Invalidate()
+ if rec := h.do("GET", path, tokenAlice, nil); rec.Code != http.StatusOK
{
+ t.Fatalf("user after grant: status = %d, want 200", rec.Code)
+ }
+
+ if err := h.db.Delete(&grant).Error; err != nil {
+ t.Fatal(err)
+ }
+ h.svcs.Permissions.Invalidate()
+ if rec := h.do("GET", path, tokenAlice, nil); rec.Code !=
http.StatusForbidden {
+ t.Fatalf("user after revoke: status = %d, want 403", rec.Code)
+ }
+ // ADMIN still has its default grant.
+ if rec := h.do("GET", path, tokenAdmin, nil); rec.Code != http.StatusOK
{
+ t.Fatalf("admin: status = %d, want 200", rec.Code)
+ }
+}
+
+func TestCurrentUserListsPermissions(t *testing.T) {
+ h := newHarness(t)
+ admin := h.mustDo("GET", "/api/v1/users/me", tokenAdmin, nil,
http.StatusOK)
+ got, _ := admin["permissions"].([]any)
+ has := map[any]bool{}
+ for _, p := range got {
+ has[p] = true
+ }
+ if !has["audit:read"] || !has["user:set_status"] || has["admin:manage"]
{
+ t.Errorf("admin permissions = %v, want the ADMIN defaults
without admin:manage", got)
+ }
+ alice := h.mustDo("GET", "/api/v1/users/me", tokenAlice, nil,
http.StatusOK)
+ if got, ok := alice["permissions"].([]any); !ok || len(got) != 0 {
+ t.Errorf("user permissions = %v, want []", alice["permissions"])
+ }
+}
diff --git a/internal/server/permission_test.go
b/internal/server/permission_test.go
new file mode 100644
index 0000000000..5c31bdcf62
--- /dev/null
+++ b/internal/server/permission_test.go
@@ -0,0 +1,142 @@
+/**
+*
+* 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"
+)
+
+type permissionProbe struct {
+ perm permission.Permission
+ method string
+ path string
+ body any
+}
+
+// Every permission gates what it says it gates: a plain USER is refused,
granting that
+// one permission to USER lets the same request through, and nothing else
changes. This is
+// what proves the guards check permissions rather than the ADMIN role name.
+func TestEachPermissionGatesItsAction(t *testing.T) {
+ h := newHarness(t)
+
+ // Records owned by bob, which alice has no standing on.
+ bobGroup := h.seedGroup("bobs-group", tokenBob)
+ _, bobStorage := h.seedStorage("bobs-storage", tokenBob)
+ bobProcess := h.seedProcess("bobs-run", tokenBob)
+ aliceKey := h.seedSSHCredential("alices-key", tokenAlice)
+ template := h.mustDo("POST", "/api/v1/application-templates",
tokenAdmin,
+ map[string]any{"templateName": "probe"}, http.StatusCreated)
+ clusterID := h.seedCluster("probe-cluster")
+ // A body that passes validation, so the request reaches the
authorization check. The
+ // config is alice's: editing a process also checks the caller's access
to the config
+ // it names, which is a separate matter from the right to edit the
process.
+ configID, configClusterID := h.seedClusterConfig(tokenAlice,
"probe-config")
+ deployment := h.mustDo("POST", "/api/v1/slurm-deployments", tokenAdmin,
map[string]any{
+ "templateId": template["templateId"], "slurmRunSection": "run",
"slurmClusterId": configClusterID,
+ "defaultBatchJobConfig": map[string]any{"wallTimeMinutes": 60,
"allocation": "DEFAULT"},
+ }, http.StatusCreated)
+ processUpdate := map[string]any{
+ "processType": "BATCH_JOB",
+ "batchProcess": map[string]any{
+ "deploymentId": deployment["deploymentId"],
+ "slurmClusterConfigId": configID,
+ "batchJobConfig":
map[string]any{"wallTimeMinutes": 60, "allocation": "ALLOC"},
+ },
+ }
+ // The delete probe succeeds once granted, so it gets a process of its
own.
+ doomedProcess := h.seedProcess("bobs-doomed-run", tokenBob)
+
+ probes := []permissionProbe{
+ {permission.UserCreate, "POST", "/api/v1/users",
map[string]any{"userId": "cilogon:9", "email": "[email protected]", "firstName":
"N", "lastName": "N"}},
+ {permission.UserList, "GET", "/api/v1/users", nil},
+ {permission.UserReadAny, "GET", "/api/v1/users/bob", nil},
+ {permission.UserUpdateAny, "POST", "/api/v1/users/bob",
map[string]any{"userId": "bob", "email": "[email protected]", "firstName": "B",
"lastName": "B"}},
+ {permission.UserSetStatus, "POST", "/api/v1/users/bob/status",
map[string]any{"status": "ACTIVE"}},
+ {permission.AdminManage, "POST", "/api/v1/users/bob/admin",
map[string]any{"admin": true}},
+
+ {permission.GroupList, "GET", "/api/v1/groups", nil},
+ {permission.GroupReadAny, "GET", "/api/v1/groups/" + bobGroup,
nil},
+ {permission.GroupManageAny, "PUT", "/api/v1/groups/" +
bobGroup, map[string]any{"groupName": "renamed"}},
+
+ {permission.ServiceAccountRead, "GET",
"/api/v1/service-accounts", nil},
+ {permission.ServiceAccountManage, "POST",
"/api/v1/service-accounts", map[string]any{"name": "ci", "description": "d",
"expiresInDays": 30}},
+
+ {permission.ClusterManage, "POST", "/api/v1/slurm-clusters",
map[string]any{"clusterName": "c", "headnodeHost": "login.hpc.example.edu",
"headnodePort": 22}},
+ {permission.ClusterDiscover, "POST",
"/api/v1/slurm-clusters/discover-partitions", map[string]any{"headnodeHost":
"127.0.0.1", "headnodePort": 1, "loginUser": "runner", "sshCredentialId":
aliceKey}},
+ {permission.ClusterConfigList, "GET",
"/api/v1/slurm-cluster-configs", nil},
+
+ {permission.TemplateManage, "POST",
"/api/v1/application-templates", map[string]any{"templateName": "t"}},
+ {permission.DeploymentManage, "POST",
"/api/v1/slurm-deployments", map[string]any{
+ "templateId": template["templateId"],
"slurmRunSection": "run", "slurmClusterId": clusterID,
+ "defaultBatchJobConfig":
map[string]any{"wallTimeMinutes": 60, "allocation": "DEFAULT"},
+ }},
+
+ {permission.StorageList, "GET", "/api/v1/scp-data-storages",
nil},
+ {permission.DataProductList, "GET", "/api/v1/data-products",
nil},
+ {permission.VirtualDirectoryList, "GET",
"/api/v1/virtual-data-directories", nil},
+ {permission.ResourceManageAny, "GET",
"/api/v1/scp-data-storages/" + bobStorage, nil},
+
+ {permission.ProcessList, "GET", "/api/v1/processes", nil},
+ {permission.ProcessUpdate, "PUT", "/api/v1/processes/" +
bobProcess, processUpdate},
+ {permission.ProcessDelete, "DELETE", "/api/v1/processes/" +
doomedProcess, nil},
+ {permission.ProcessManageAny, "GET", "/api/v1/processes/" +
bobProcess + "/workflows", nil},
+ }
+
+ covered := map[permission.Permission]bool{permission.AuditRead: true}
// see TestAuditAccessFollowsRolePermissions
+ for _, p := range probes {
+ covered[p.perm] = true
+ }
+ for _, p := range permission.All() {
+ if !covered[p] {
+ t.Errorf("permission %s has no probe in this test", p)
+ }
+ }
+
+ denied := map[int]bool{http.StatusForbidden: true, http.StatusNotFound:
true}
+ for _, p := range probes {
+ t.Run(string(p.perm), func(t *testing.T) {
+ if rec := h.do(p.method, p.path, tokenAlice, p.body);
!denied[rec.Code] {
+ t.Fatalf("%s %s without the grant: status = %d,
want 403 or 404\n%s", p.method, p.path, rec.Code, rec.Body.String())
+ }
+
+ grant := iammodel.RolePermission{Role: role.User,
Permission: p.perm}
+ if err := h.db.Create(&grant).Error; err != nil {
+ t.Fatal(err)
+ }
+ h.svcs.Permissions.Invalidate()
+ defer func() {
+ h.db.Delete(&grant)
+ h.svcs.Permissions.Invalidate()
+ }()
+
+ rec := h.do(p.method, p.path, tokenAlice, p.body)
+ if rec.Code == http.StatusUnauthorized ||
denied[rec.Code] {
+ t.Fatalf("%s %s with only %s granted: status =
%d\n%s", p.method, p.path, p.perm, rec.Code, rec.Body.String())
+ }
+ })
+ }
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index 14f48f6fce..a0298bd916 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -92,7 +92,7 @@ func New(cfg config.Config, svcs *app.Services, introspector
auth.Introspector)
// Outermost first: CORS answers preflights before authentication runs,
since a
// preflight carries no credentials by definition.
- return cors(cfg.CORSAllowedOrigins)(auth.Middleware(introspector)(mux))
+ return cors(cfg.CORSAllowedOrigins)(auth.Middleware(introspector,
auth.WithPermissions(svcs.Permissions))(mux))
}
// cors applies the airavata.cors.allowed-origins policy.