This is an automated email from the ASF dual-hosted git repository.

DImuthuUpe pushed a commit to branch permission-impl
in repository https://gitbox.apache.org/repos/asf/airavata.git


The following commit(s) were added to refs/heads/permission-impl by this push:
     new df89be6ba4 Ability to attach permissions to service accounts through 
dashboard
df89be6ba4 is described below

commit df89be6ba446dee2a205a79e1ccf5bb8435d03cd
Author: DImuthuUpe <[email protected]>
AuthorDate: Wed Nov 11 21:38:42 2026 -0500

    Ability to attach permissions to service accounts through dashboard
---
 api/iam/controller/permission.go              |  51 ++++++++++++
 api/iam/dto/permission.go                     |  31 +++++++
 api/iam/service/permission.go                 |  57 +++++++++++++
 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                                  |   2 +
 docs/openapi.yaml                             |  32 ++++++++
 internal/app/app.go                           |   3 +
 internal/permission/permission.go             |  49 +++++++++++
 internal/permission/permission_test.go        |  55 +++++++++++++
 internal/server/permission_test.go            |  22 +++++
 internal/server/server.go                     |   1 +
 15 files changed, 504 insertions(+), 12 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/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/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&apos;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&apos;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 8e9062c6cf..cd5792acf3 100644
--- a/docs/auth.md
+++ b/docs/auth.md
@@ -91,6 +91,8 @@ curl -X POST 
https://airavata.example.org/api/v1/service-accounts \
   -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:
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index e706ee9b6f..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:
diff --git a/internal/app/app.go b/internal/app/app.go
index e84cab1673..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
@@ -261,6 +263,7 @@ func NewServices(cfg config.Config, db *gorm.DB, repos 
*Repositories, workflowBa
                // A deleted service account takes the shares granted to it 
along, hence the
                // sharing repository.
                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/permission/permission.go 
b/internal/permission/permission.go
index c0afc5d751..e271b7ea75 100644
--- a/internal/permission/permission.go
+++ b/internal/permission/permission.go
@@ -111,6 +111,55 @@ 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
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)

Reply via email to