This is an automated email from the ASF dual-hosted git repository. lahirujayathilake pushed a commit to branch allocation-views in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit 6188476d7606507bb6b5d62a6b004d02e0d0ef93 Author: lahiruj <[email protected]> AuthorDate: Fri Nov 6 01:29:01 2026 -0500 Allocation readers see analytics for every allocation --- connectors/Analytics/api/analytics.openapi.yaml | 21 ++++---- .../pkg/analytics/analytics_integration_test.go | 59 ++++++++++++++++----- connectors/Analytics/pkg/analytics/handlers.go | 18 ++++--- connectors/Analytics/pkg/analytics/service.go | 61 +++++++++++++--------- connectors/Analytics/pkg/analytics/store.go | 40 +++++++++++--- .../core/analytics/components/AnalyticsPage.tsx | 18 ++++--- web/src/features/core/analytics/schemas.ts | 3 +- web/src/shared/casl/permissions.ts | 2 + 8 files changed, 155 insertions(+), 67 deletions(-) diff --git a/connectors/Analytics/api/analytics.openapi.yaml b/connectors/Analytics/api/analytics.openapi.yaml index 51518a430..380507663 100644 --- a/connectors/Analytics/api/analytics.openapi.yaml +++ b/connectors/Analytics/api/analytics.openapi.yaml @@ -125,11 +125,9 @@ info: paths: /connectors/analytics/allocations/{id}/jobs: get: - description: A page of usage records (a job's charge) the newest first, with - the total count. Access is membership-scoped like the usage summary. Plain - members always see only their own records; project managers see everyone's - by default and can narrow to their own with mine=true. Non-members receive - 404. + description: |- + A page of usage records (a job's charge) the newest first, with the total count. Access is membership-scoped like the usage summary. + Plain members always see only their own records; project managers and core:allocations:read holders see everyone's by default and can narrow to their own with mine=true. Non-members receive 404. parameters: - description: Compute allocation ID in: path @@ -183,10 +181,9 @@ paths: - Analytics /connectors/analytics/allocations/{id}/usage-summary: get: - description: 'Aggregated usage for one allocation. Access is membership-scoped: - the caller must hold a membership on the allocation or a governance role on - its project. The per-member breakdown is populated only for project managers. - Callers without access receive 404 so allocation existence is not leaked.' + description: |- + Aggregated usage for one allocation. The caller must hold a membership on the allocation, a governance role on its project, or core:allocations:read. + The per-member breakdown is populated only for project managers and core:allocations:read holders. Callers without access receive 404 so allocation existence is not leaked. parameters: - description: Compute allocation ID in: path @@ -228,9 +225,9 @@ paths: - Analytics /connectors/analytics/contexts: get: - description: Projects the caller belongs to (through a role or allocation membership), - each with the caller's role and its allocations. No privilege required; scoped - to the caller's own memberships. + description: |- + Projects the caller belongs to (through a role or allocation membership), each with the caller's role and its allocations. + A caller with core:allocations:read gets every project, with a null role where they hold none. produces: - application/json responses: diff --git a/connectors/Analytics/pkg/analytics/analytics_integration_test.go b/connectors/Analytics/pkg/analytics/analytics_integration_test.go index cab0e2445..205dad25c 100644 --- a/connectors/Analytics/pkg/analytics/analytics_integration_test.go +++ b/connectors/Analytics/pkg/analytics/analytics_integration_test.go @@ -162,8 +162,8 @@ func TestAnalyticsContexts_PIRoleAndAllocations(t *testing.T) { t.Fatalf("contexts: got %d, want 1", len(got)) } c := got[0] - if c.Role != string(models.ProjectRolePI) { - t.Errorf("role: got %q, want PI", c.Role) + if roleOf(c) != string(models.ProjectRolePI) { + t.Errorf("role: got %q, want PI", roleOf(c)) } if len(c.Allocations) != 2 { t.Fatalf("allocations: got %d, want 2", len(c.Allocations)) @@ -202,8 +202,8 @@ func TestAnalyticsContexts_MemberViaAllocationOnly(t *testing.T) { if len(got) != 1 { t.Fatalf("contexts: got %d, want 1", len(got)) } - if got[0].Role != roleMember { - t.Errorf("role: got %q, want MEMBER (derived from allocation membership)", got[0].Role) + if roleOf(got[0]) != roleMember { + t.Errorf("role: got %q, want MEMBER (derived from allocation membership)", roleOf(got[0])) } } @@ -425,9 +425,8 @@ func TestUsageSummary_MemberWithoutNameFallsBackToEmail(t *testing.T) { } } -// Access is membership-only: a site-wide privilege does not open an allocation -// the caller has no membership or role on. -func TestUsageSummary_SitePrivilegeAloneDoesNotGrantAccess_404(t *testing.T) { +// Make sure core:allocations:read opens an allocation's full usage. +func TestUsageSummary_AllocationsReadGivesFullView(t *testing.T) { database, _, srv := setupTestStack(t) pi := seedUser(t, database, "[email protected]") admin := seedUser(t, database, "[email protected]") @@ -439,11 +438,47 @@ func TestUsageSummary_SitePrivilegeAloneDoesNotGrantAccess_404(t *testing.T) { seedUsage(t, database, alloc, res, pi, 400, 40, time.Now().UTC().AddDate(0, 0, -1)) rr := httptest.NewRecorder() - // admin has no membership on this allocation, only site allocations:read. req := withTestCaller(httptest.NewRequest(http.MethodGet, "/connectors/analytics/allocations/"+alloc+"/usage-summary", nil), admin, models.AllocationsRead) srv.ServeHTTP(rr, req) - if rr.Code != http.StatusNotFound { - t.Errorf("status: got %d, want 404 (site privilege must not grant access)", rr.Code) + if rr.Code != http.StatusOK { + t.Fatalf("status: got %d, want 200; body=%s", rr.Code, rr.Body.String()) + } + var got UsageSummary + if err := json.NewDecoder(rr.Body).Decode(&got); err != nil { + t.Fatalf("decode: %v", err) + } + if len(got.ByMember) != 1 || got.ByMember[0].UserID != pi { + t.Errorf("by_member: got %+v, want the PI's usage", got.ByMember) + } +} + +func roleOf(c ProjectContext) string { + if c.Role == nil { + return "" + } + return *c.Role +} + +// Make sure core:allocations:read lists every project, with a null role where the caller has none. +func TestAnalyticsContexts_AllocationsReadListsEveryProject(t *testing.T) { + database, _, srv := setupTestStack(t) + pi := seedUser(t, database, "[email protected]") + admin := seedUser(t, database, "[email protected]") + cluster := seedCluster(t, database) + project := seedProject(t, database, pi) + alloc := seedAllocation(t, database, project, cluster, 1000, time.Now().UTC().AddDate(0, 0, -2), time.Now().UTC().AddDate(0, 0, 28)) + + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, withTestCaller(httptest.NewRequest(http.MethodGet, "/connectors/analytics/contexts", nil), admin, models.AllocationsRead)) + if rr.Code != http.StatusOK { + t.Fatalf("status: got %d, want 200; body=%s", rr.Code, rr.Body.String()) + } + var got []ProjectContext + if err := json.NewDecoder(rr.Body).Decode(&got); err != nil { + t.Fatalf("decode: %v", err) + } + if len(got) != 1 || got[0].Role != nil || len(got[0].Allocations) != 1 || got[0].Allocations[0].ID != alloc { + t.Errorf("contexts: got %+v, want the project with a null role and its allocation", got) } } @@ -658,8 +693,8 @@ func TestAnalyticsContexts_CoPIMemberAndProjectWithoutAllocations(t *testing.T) } allocs := map[string][]Allocation{} for _, c := range got { - if c.Role != string(models.ProjectRoleCoPI) { - t.Errorf("project %s role: got %q, want CO_PI", c.ProjectID, c.Role) + if roleOf(c) != string(models.ProjectRoleCoPI) { + t.Errorf("project %s role: got %q, want CO_PI", c.ProjectID, roleOf(c)) } allocs[c.ProjectID] = c.Allocations } diff --git a/connectors/Analytics/pkg/analytics/handlers.go b/connectors/Analytics/pkg/analytics/handlers.go index 51a6df80b..0b794f055 100644 --- a/connectors/Analytics/pkg/analytics/handlers.go +++ b/connectors/Analytics/pkg/analytics/handlers.go @@ -46,7 +46,8 @@ func (h *Handlers) RegisterRoutes(router *identity.Router) { } // @Summary List the caller's analytics contexts -// @Description Projects the caller belongs to (through a role or allocation membership), each with the caller's role and its allocations. No privilege required; scoped to the caller's own memberships. +// @Description Projects the caller belongs to (through a role or allocation membership), each with the caller's role and its allocations. +// @Description A caller with core:allocations:read gets every project, with a null role where they hold none. // @Tags Analytics // @Security BearerAuth // @Produce json @@ -58,7 +59,7 @@ func (h *Handlers) getCallerAnalyticsContexts(w http.ResponseWriter, r *http.Req if caller == nil { return } - contexts, err := h.svc.AnalyticsContexts(r.Context(), caller.UserID) + contexts, err := h.svc.AnalyticsContexts(r.Context(), caller.UserID, identity.HasPrivilege(r.Context(), models.AllocationsRead)) if err != nil { common.WriteServiceError(w, err) return @@ -67,7 +68,8 @@ func (h *Handlers) getCallerAnalyticsContexts(w http.ResponseWriter, r *http.Req } // @Summary Get an allocation's usage summary -// @Description Aggregated usage for one allocation. Access is membership-scoped: the caller must hold a membership on the allocation or a governance role on its project. The per-member breakdown is populated only for project managers. Callers without access receive 404 so allocation existence is not leaked. +// @Description Aggregated usage for one allocation. The caller must hold a membership on the allocation, a governance role on its project, or core:allocations:read. +// @Description The per-member breakdown is populated only for project managers and core:allocations:read holders. Callers without access receive 404 so allocation existence is not leaked. // @Tags Analytics // @Security BearerAuth // @Produce json @@ -114,7 +116,8 @@ func (h *Handlers) getAllocationUsageSummary(w http.ResponseWriter, r *http.Requ } // @Summary List an allocation's jobs (usage records) -// @Description A page of usage records (a job's charge) the newest first, with the total count. Access is membership-scoped like the usage summary. Plain members always see only their own records; project managers see everyone's by default and can narrow to their own with mine=true. Non-members receive 404. +// @Description A page of usage records (a job's charge) the newest first, with the total count. Access is membership-scoped like the usage summary. +// @Description Plain members always see only their own records; project managers and core:allocations:read holders see everyone's by default and can narrow to their own with mine=true. Non-members receive 404. // @Tags Analytics // @Security BearerAuth // @Produce json @@ -167,9 +170,12 @@ func (h *Handlers) getAllocationJobs(w http.ResponseWriter, r *http.Request) { // allocationAccess resolves the caller's standing on an allocation. canManage // is true for project managers (PI/co-PI/allocation manager) and gates the // per-member breakdown; hasAccess additionally admits plain allocation members -// (their own scoped view). Access comes from membership alone, never a -// site-wide privilege. +// (their own scoped view). The allocation read privilege gives the full view, +// as it does for the allocation itself. func (h *Handlers) allocationAccess(r *http.Request, alloc *models.ComputeAllocation, userID string) (canManage, hasAccess bool, err error) { + if identity.HasPrivilege(r.Context(), models.AllocationsRead) { + return true, true, nil + } role, err := h.svc.AllocationRoleForUser(r.Context(), alloc.ID, userID) return models.IsGovernanceRole(role), role != "", err } diff --git a/connectors/Analytics/pkg/analytics/service.go b/connectors/Analytics/pkg/analytics/service.go index c86eb4605..ac1ee0b61 100644 --- a/connectors/Analytics/pkg/analytics/service.go +++ b/connectors/Analytics/pkg/analytics/service.go @@ -50,11 +50,12 @@ type Allocation struct { } // ProjectContext is one project the caller belongs to, their role on it, and -// its allocations. +// its allocations. Role is null when the caller has no role on the project and +// sees it because of core:allocations:read. type ProjectContext struct { ProjectID string `json:"project_id"` ProjectName string `json:"project_name"` - Role string `json:"role"` + Role *string `json:"role"` Allocations []Allocation `json:"allocations"` } @@ -183,29 +184,13 @@ func (s *Service) AllocationJobsPage(ctx context.Context, allocationID, callerID } // AnalyticsContexts returns the projects the caller touches, each with the -// caller's role and its allocations. Empty (not nil) when the caller belongs -// to nothing. -func (s *Service) AnalyticsContexts(ctx context.Context, userID string) ([]ProjectContext, error) { - projRows, err := s.store.ProjectsForUser(ctx, userID) - if err != nil { - return nil, err - } - if len(projRows) == 0 { - return []ProjectContext{}, nil - } - allocs, err := s.core.ListComputeAllocationsForParticipant(ctx, userID) +// caller's role and its allocations. readAll returns every project instead. +// Empty (not nil) when there are none. +func (s *Service) AnalyticsContexts(ctx context.Context, userID string, readAll bool) ([]ProjectContext, error) { + projRows, allocRows, err := s.contextRows(ctx, userID, readAll) if err != nil { return nil, err } - ids := make([]string, len(allocs)) - for i, a := range allocs { - ids[i] = a.ID - } - allocRows, err := s.store.AllocationsByID(ctx, ids) - if err != nil { - return nil, err - } - byProject := make(map[string][]Allocation, len(projRows)) for _, a := range allocRows { byProject[a.ProjectID] = append(byProject[a.ProjectID], Allocation{ @@ -221,9 +206,12 @@ func (s *Service) AnalyticsContexts(ctx context.Context, userID string) ([]Proje out := make([]ProjectContext, 0, len(projRows)) for _, p := range projRows { - role := roleMember + var role *string if p.Role.Valid && p.Role.String != "" { - role = p.Role.String + role = &p.Role.String + } else if !readAll { + member := roleMember + role = &member } allocs := byProject[p.ProjectID] if allocs == nil { @@ -239,6 +227,31 @@ func (s *Service) AnalyticsContexts(ctx context.Context, userID string) ([]Proje return out, nil } +func (s *Service) contextRows(ctx context.Context, userID string, readAll bool) ([]ProjectRow, []AllocationRow, error) { + if readAll { + projRows, err := s.store.AllProjects(ctx, userID) + if err != nil { + return nil, nil, err + } + allocRows, err := s.store.AllAllocations(ctx) + return projRows, allocRows, err + } + projRows, err := s.store.ProjectsForUser(ctx, userID) + if err != nil || len(projRows) == 0 { + return nil, nil, err + } + allocs, err := s.core.ListComputeAllocationsForParticipant(ctx, userID) + if err != nil { + return nil, nil, err + } + ids := make([]string, len(allocs)) + for i, a := range allocs { + ids[i] = a.ID + } + allocRows, err := s.store.AllocationsByID(ctx, ids) + return projRows, allocRows, err +} + // AllocationUsageSummary aggregates one allocation's usage. includeMembers // controls whether the per-member breakdown is populated; when false ByMember // is left nil so the response serializes it as null. diff --git a/connectors/Analytics/pkg/analytics/store.go b/connectors/Analytics/pkg/analytics/store.go index 76f079142..8e3753a85 100644 --- a/connectors/Analytics/pkg/analytics/store.go +++ b/connectors/Analytics/pkg/analytics/store.go @@ -95,8 +95,12 @@ type Store interface { // ProjectsForUser returns the projects the user touches through a governance // role or an active allocation membership. Role is null for a plain member. ProjectsForUser(ctx context.Context, userID string) ([]ProjectRow, error) + // AllProjects returns every project with the user's governance role, null when none. + AllProjects(ctx context.Context, userID string) ([]ProjectRow, error) // AllocationsByID returns the given allocations with their consumed credits, oldest first. AllocationsByID(ctx context.Context, ids []string) ([]AllocationRow, error) + // AllAllocations returns every allocation with its consumed credits, oldest first. + AllAllocations(ctx context.Context) ([]AllocationRow, error) // TotalUsed returns the credits consumed against an allocation. TotalUsed(ctx context.Context, allocationID string) (float64, error) // DailyUsage returns per-day, per-resource credits for one allocation. @@ -135,17 +139,31 @@ func (s *pgStore) ProjectsForUser(ctx context.Context, userID string) ([]Project return rows, nil } -func (s *pgStore) AllocationsByID(ctx context.Context, ids []string) ([]AllocationRow, error) { - if len(ids) == 0 { - return nil, nil +func (s *pgStore) AllProjects(ctx context.Context, userID string) ([]ProjectRow, error) { + var rows []ProjectRow + err := s.db.SelectContext(ctx, &rows, + `SELECT p.id, p.title, r.role + FROM projects p + LEFT JOIN project_roles r ON r.project_id = p.id AND r.user_id = $1 AND r.compute_allocation_id IS NULL + ORDER BY p.title`, userID) + if err != nil { + return nil, err } - query, args, err := sqlx.In( - `SELECT ca.project_id, ca.id, ca.name, ca.status, + return rows, nil +} + +const allocationsWithUsage = `SELECT ca.project_id, ca.id, ca.name, ca.status, ca.initial_su_amount, ca.start_time, ca.end_time, COALESCE(SUM(u.used_su_amount), 0) AS used_su_amount FROM compute_allocations ca LEFT JOIN compute_allocation_usages u - ON u.compute_allocation_id = ca.id AND `+inAllocationPeriod+` + ON u.compute_allocation_id = ca.id AND ` + inAllocationPeriod + +func (s *pgStore) AllocationsByID(ctx context.Context, ids []string) ([]AllocationRow, error) { + if len(ids) == 0 { + return nil, nil + } + query, args, err := sqlx.In(allocationsWithUsage+` WHERE ca.id IN (?) GROUP BY ca.id ORDER BY ca.start_time`, ids) @@ -159,6 +177,16 @@ func (s *pgStore) AllocationsByID(ctx context.Context, ids []string) ([]Allocati return rows, nil } +func (s *pgStore) AllAllocations(ctx context.Context) ([]AllocationRow, error) { + var rows []AllocationRow + if err := s.db.SelectContext(ctx, &rows, allocationsWithUsage+` + GROUP BY ca.id + ORDER BY ca.start_time`); err != nil { + return nil, err + } + return rows, nil +} + func (s *pgStore) TotalUsed(ctx context.Context, allocationID string) (float64, error) { var total float64 err := s.db.GetContext(ctx, &total, diff --git a/web/src/features/core/analytics/components/AnalyticsPage.tsx b/web/src/features/core/analytics/components/AnalyticsPage.tsx index 64466ca64..772684b87 100644 --- a/web/src/features/core/analytics/components/AnalyticsPage.tsx +++ b/web/src/features/core/analytics/components/AnalyticsPage.tsx @@ -18,6 +18,7 @@ "use client"; import type { Allocation, UsageSummary } from "@/generated/analytics/zod.gen"; +import { usePermissions } from "@/shared/casl/permissions"; import { EmptyState } from "@/shared/ui/EmptyState"; import { ErrorState } from "@/shared/ui/ErrorState"; import { Skeleton } from "@/shared/ui/skeleton"; @@ -25,7 +26,7 @@ import { ChartColumn } from "lucide-react"; import * as React from "react"; import { buildResourceSeries } from "../lib"; import { useAnalyticsContexts, useUsageSummary } from "../queries"; -import type { AnalyticsContext } from "../schemas"; +import type { AnalyticsContext, AnalyticsRole } from "../schemas"; import { useAnalyticsSelection } from "../useAnalyticsSelection"; import { ContextSwitcher } from "./ContextSwitcher"; import { HERO_TILE_COUNT, HeroTiles } from "./HeroTiles"; @@ -36,7 +37,7 @@ import { UsageOverTimeBars } from "./UsageOverTimeBars"; const MANAGER_ROLES = new Set(["PI", "CO_PI", "ALLOCATION_MANAGER"]); -const ROLE_LABEL: Record<AnalyticsContext["role"], string> = { +const ROLE_LABEL: Record<AnalyticsRole, string> = { PI: "PI on this project", CO_PI: "Co-PI on this project", ALLOCATION_MANAGER: "Allocation manager", @@ -50,7 +51,10 @@ export function AnalyticsPage() { const { project, allocation, select } = useAnalyticsSelection(contexts); const summaryQuery = useUsageSummary(allocation?.id); - const isManager = project ? MANAGER_ROLES.has(project.role) : false; + const can = usePermissions(); + const managerRoleLabel = + project?.role && MANAGER_ROLES.has(project.role) ? ROLE_LABEL[project.role] : null; + const isManager = managerRoleLabel !== null || can.allocationsRead; return ( <div className="space-y-6"> @@ -61,7 +65,9 @@ export function AnalyticsPage() { How your allocation is being used and how long it will last. </p> </div> - {project && isManager ? <RoleChip role={project.role} /> : null} + {project && isManager ? ( + <RoleChip label={managerRoleLabel ?? "Viewing all allocations"} /> + ) : null} </header> {contextsQuery.isLoading ? ( @@ -170,10 +176,10 @@ function TileSkeletons() { } // Only rendered for managers; the chip explains why the extra cards appear. -function RoleChip({ role }: { role: AnalyticsContext["role"] }) { +function RoleChip({ label }: { label: string }) { return ( <span className="inline-flex items-center rounded-full bg-[color:var(--tone-info-bg)] px-3 py-1 text-xs font-medium text-[color:var(--tone-info-fg)]"> - {ROLE_LABEL[role]} + {label} </span> ); } diff --git a/web/src/features/core/analytics/schemas.ts b/web/src/features/core/analytics/schemas.ts index 7f0189d02..f004c9ba2 100644 --- a/web/src/features/core/analytics/schemas.ts +++ b/web/src/features/core/analytics/schemas.ts @@ -21,8 +21,9 @@ import { z } from "zod"; export const analyticsRoleSchema = z.enum(["PI", "CO_PI", "ALLOCATION_MANAGER", "MEMBER"]); export type AnalyticsRole = z.infer<typeof analyticsRoleSchema>; +// role is null for a project the caller reads only through core:allocations:read. export const analyticsContextSchema = zProjectContext.extend({ - role: analyticsRoleSchema, + role: analyticsRoleSchema.nullable(), }); export type AnalyticsContext = z.infer<typeof analyticsContextSchema>; diff --git a/web/src/shared/casl/permissions.ts b/web/src/shared/casl/permissions.ts index 89a367b66..a2dd71cdd 100644 --- a/web/src/shared/casl/permissions.ts +++ b/web/src/shared/casl/permissions.ts @@ -23,6 +23,7 @@ import { useAbility } from "./AbilityProvider"; // control and a 403 never disagree. const PERMISSIONS = { projectsWrite: { action: "manage", subject: "Project", privilege: "core:projects:write" }, + allocationsRead: { action: "read", subject: "Allocation", privilege: "core:allocations:read" }, allocationsWrite: { action: "manage", subject: "Allocation", @@ -39,6 +40,7 @@ export function usePermissions(): Record<Permission, boolean> { const can = (p: Permission) => ability.can(PERMISSIONS[p].action, PERMISSIONS[p].subject); return { projectsWrite: can("projectsWrite"), + allocationsRead: can("allocationsRead"), allocationsWrite: can("allocationsWrite"), usersRead: can("usersRead"), clustersRead: can("clustersRead"),
