From d6196e7c279d58e8f73edb9638e1436594a3f219 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 14:01:25 +0000 Subject: [PATCH 1/3] =?UTF-8?q?feat(identity):=20RBAC=20v2=20=E2=80=94=20f?= =?UTF-8?q?ive=20roles,=20one=20permission=20matrix,=20per-board=20members?= =?UTF-8?q?hips=20(E1.2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Roles viewer · developer · approver · auditor · admin; PermissionMatrix (SharedKernel) maps every role onto a [Flags] Permission set via a FrozenDictionary — the single place the rules live. Legacy `member` stays an alias (developer + approver + ManageWorkspaces) so existing users keep working; platform-admin unchanged. - Enforced on endpoints: one "perm:" policy per permission (Identity module), applied to Tenants, Workspaces, Sessions, Pipeline, Settings, MCP and the Web export routes; board-scoped routes re-check the board's memberships (WorkspaceScopeFilter), restricted boards are 404 to outsiders. - Per-board membership: workspaces.workspace_members (migration AddWorkspaceMembers, RLS-bound), EF + in-memory stores, IWorkspaceAccess / WorkspaceAccessMap; assigned in Users → Board access and /tenants/{tenantId}/boards/{boardId}/members, audited. - Desktop: DesktopApp.Requires gates dock / Activities / Settings hub + search / shell actions; WindowHost refuses an app the role can't open; gated pages, Board, Workflow, Home and design decisions re-check in their handlers. - Keycloak: realm import + deploy hooks + lab sync carry the new roles; KeycloakAdminClient creates a missing managed role on first assignment. IRoleClaimMapper + RoleClaimsTransformation = the IdP-group hook for E1.1. - Tests: every role × permission, policy per role, endpoint authorization per role over TestServer, membership isolation, desktop gating. Docs: CONFIG (matrix + mapping), SECURITY, scorecard row 3, threat model, CHANGELOG. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Twi9kwvd5zRHSPhSN9mL3 --- CHANGELOG.md | 6 + Directory.Packages.props | 1 + SECURITY.md | 5 + .../helm/agentos-net/files/configure-realm.sh | 17 +- docs/CONFIG.md | 46 +++ docs/plans/enterprise-readiness.md | 2 +- docs/security/threat-model.md | 2 +- infra/hooks/postdeploy.ps1 | 19 ++ infra/hooks/postdeploy.sh | 17 + infra/keycloak/agentic-realm.json | 6 +- infra/lab/lab.ps1 | 13 + src/AgentOs.Api/Program.cs | 4 +- .../Endpoints/SettingsEndpoints.cs | 8 +- .../RbacServiceCollectionExtensions.cs | 129 +++++++ .../IdentityModule.cs | 6 +- src/AgentOs.Modules.Mcp/McpModule.cs | 3 +- .../Endpoints/PipelineEndpoints.cs | 16 +- .../Endpoints/PairingEndpoints.cs | 4 +- .../Endpoints/SessionEndpoints.cs | 38 ++- .../Endpoints/TicketFileEndpoints.cs | 7 +- .../AgentOs.Modules.Tenants.csproj | 2 + .../ApiTokens/ApiTokenService.cs | 6 +- .../Endpoints/TenantEndpoints.cs | 136 ++++++-- src/AgentOs.Modules.Tenants/IAuditLog.cs | 2 + .../Keycloak/IKeycloakAdminClient.cs | 5 +- .../Keycloak/KeycloakAdminClient.cs | 72 +++- src/AgentOs.Modules.Tenants/MemberRoles.cs | 55 +++ .../Access/WorkspaceMemberships.cs | 161 +++++++++ .../Endpoints/WorkspaceEndpoints.cs | 28 +- .../Entities/WorkspaceMemberEntity.cs | 23 ++ ...1103133324_AddWorkspaceMembers.Designer.cs | 308 +++++++++++++++++ .../20261103133324_AddWorkspaceMembers.cs | 67 ++++ .../WorkspacesDbContextModelSnapshot.cs | 54 ++- .../Persistence/WorkspacesDbContext.cs | 22 ++ .../WorkspacesModule.cs | 5 + .../Identity/IRoleClaimMapper.cs | 18 + .../Identity/Permission.cs | 45 +++ .../Identity/PermissionEndpointExtensions.cs | 20 ++ .../Identity/PermissionMatrix.cs | 215 ++++++++++++ .../Identity/WorkspaceAccess.cs | 93 ++++++ .../Identity/WorkspaceScopeFilter.cs | 49 +++ .../Persistence/RowLevelSecurity.cs | 1 + src/AgentOs.Web.Shell/Services/DesktopApp.cs | 18 +- .../Services/IAppRegistry.cs | 4 +- src/AgentOs.Web.Shell/UI/Taskbar.razor | 6 +- src/AgentOs.Web.Shell/UI/WindowHost.razor | 20 +- src/AgentOs.Web/Auth/DevAutoAuthHandler.cs | 2 +- .../Components/Layout/AppShellLayout.razor | 14 +- .../Components/Pages/AgentProfilesApp.razor | 2 +- .../Components/Pages/ApiTokensApp.razor | 10 +- .../Components/Pages/AuditLogApp.razor | 10 +- .../Pages/AutopilotSettingsApp.razor | 2 +- .../Components/Pages/BoardApp.razor | 168 +++++++--- .../Components/Pages/DataApp.razor | 2 +- .../Components/Pages/EvidenceApp.razor | 12 +- .../Components/Pages/HomeApp.razor | 9 +- .../Pages/OrchestrationStudio.razor | 7 +- .../Components/Pages/PolicyApp.razor | 2 +- .../Components/Pages/PromptsApp.razor | 2 +- .../Components/Pages/Settings.razor | 2 +- .../Components/Pages/SettingsHub.razor | 65 ++-- .../Components/Pages/UsersApp.razor | 241 +++++++++++-- .../Components/UI/DesignChecks.razor | 6 +- .../Components/UI/DesignPanel.razor | 2 + src/AgentOs.Web/Components/UI/TopBar.razor | 10 +- src/AgentOs.Web/Program.cs | 12 +- src/AgentOs.Web/Services/AppCatalog.cs | 31 +- .../Services/AppCatalogRegistry.cs | 2 +- src/AgentOs.Web/Services/SettingsSearch.cs | 87 +++-- src/AgentOs.Web/Services/ShellActions.cs | 19 +- .../AgentOsUi/RowLevelSecurityRealDbTests.cs | 1 + tests/AgentOs.Tests/AgentOs.Tests.csproj | 2 + .../EndpointAuthorizationByRoleTests.cs | 316 ++++++++++++++++++ .../Identity/PermissionMatrixTests.cs | 203 +++++++++++ .../Identity/RbacAuthorizationTests.cs | 133 ++++++++ .../Persistence/RowLevelSecurityTests.cs | 3 +- .../TenantEndpointAuthorizationTests.cs | 25 +- tests/AgentOs.Tests/Web/DesktopGatingTests.cs | 122 +++++++ .../Workspaces/WorkspaceMembershipTests.cs | 115 +++++++ 79 files changed, 3121 insertions(+), 302 deletions(-) create mode 100644 src/AgentOs.Modules.Identity/Authorization/RbacServiceCollectionExtensions.cs create mode 100644 src/AgentOs.Modules.Tenants/MemberRoles.cs create mode 100644 src/AgentOs.Modules.Workspaces/Access/WorkspaceMemberships.cs create mode 100644 src/AgentOs.Modules.Workspaces/Persistence/Entities/WorkspaceMemberEntity.cs create mode 100644 src/AgentOs.Modules.Workspaces/Persistence/Migrations/20261103133324_AddWorkspaceMembers.Designer.cs create mode 100644 src/AgentOs.Modules.Workspaces/Persistence/Migrations/20261103133324_AddWorkspaceMembers.cs create mode 100644 src/AgentOs.SharedKernel/Identity/IRoleClaimMapper.cs create mode 100644 src/AgentOs.SharedKernel/Identity/Permission.cs create mode 100644 src/AgentOs.SharedKernel/Identity/PermissionEndpointExtensions.cs create mode 100644 src/AgentOs.SharedKernel/Identity/PermissionMatrix.cs create mode 100644 src/AgentOs.SharedKernel/Identity/WorkspaceAccess.cs create mode 100644 src/AgentOs.SharedKernel/Identity/WorkspaceScopeFilter.cs create mode 100644 tests/AgentOs.Tests/Identity/EndpointAuthorizationByRoleTests.cs create mode 100644 tests/AgentOs.Tests/Identity/PermissionMatrixTests.cs create mode 100644 tests/AgentOs.Tests/Identity/RbacAuthorizationTests.cs create mode 100644 tests/AgentOs.Tests/Web/DesktopGatingTests.cs create mode 100644 tests/AgentOs.Tests/Workspaces/WorkspaceMembershipTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 83ac0dd7..f17b39ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,9 @@ Everything on `main` before the first tagged release. AgentOS.NET has not shippe - **UI-first configuration** ([ADR-0011](docs/adr/0011-ui-first-configuration.md)): one flat Settings rail with search, Agent profiles (pick a model, the provider follows), Model keys per provider with Test, Platform settings for platform admins, Autopilot settings and agent run time limits. +- **RBAC v2** (E1.2): roles viewer · developer · approver · auditor · admin over one permission matrix in code, + enforced on every endpoint and in the desktop; per-board memberships (Users → Board access) restrict a board + to its members; an `IRoleClaimMapper` hook for IdP groups (E1.1). - **Enterprise basics.** API tokens / service accounts, tenant export + purge (Settings → Data), audit log of every settings and config write, workspace rules + versioned agent prompts, per-tenant run admission (concurrency + burst), scheduled runs (once or cron). @@ -97,5 +100,8 @@ Everything on `main` before the first tagged release. AgentOS.NET has not shippe ### Migration notes - None — there is no earlier tagged release to upgrade from. +- RBAC v2: the `workspaces.workspace_members` table is added by the Workspaces module's migration at startup. + Existing `member` users keep their access (alias = developer + approver + manage boards); new invitations default + to `developer`. Existing Keycloak realms get the new roles from the deploy hooks or on first assignment. [Unreleased]: https://github.com/hoangsnowy/AgentOS.NET/commits/main diff --git a/Directory.Packages.props b/Directory.Packages.props index 49b775a8..7295911c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -57,6 +57,7 @@ + diff --git a/SECURITY.md b/SECURITY.md index 2d2d116e..6f7ba138 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -43,6 +43,11 @@ When reporting, include: affected component, reproduction steps, and impact. - **Operator locks** — Production pins the riskiest settings so the Settings UI cannot change them ([CONFIG.md](docs/CONFIG.md#production-locks-appsettingsproductionjson-api--web)); platform-wide settings require the `platform-admin` role. +- **Role-based access (RBAC v2)** — five tenant roles (viewer · developer · approver · auditor · admin) map onto + permissions in one matrix in code (`PermissionMatrix`), enforced by authorization policies on every endpoint and + re-checked in every desktop handler — hiding a button is never the only gate. Boards can be restricted to their + members (per-board role); admins and auditors stay tenant-wide. Role and membership changes are audited. Matrix + and the legacy `member` mapping: [CONFIG.md](docs/CONFIG.md#roles-and-permissions-rbac-v2). - **Audit trail** — every settings change (old → new, secrets masked), every direct config write (LLM keys, tokens, prompts, tool policy, budget — recorded as *set / cleared*, never the value), member lifecycle, invitations and sign-in land in an append-only audit log, viewable in **Settings → Audit log** and diff --git a/deploy/helm/agentos-net/files/configure-realm.sh b/deploy/helm/agentos-net/files/configure-realm.sh index 48194cef..df3bd20e 100755 --- a/deploy/helm/agentos-net/files/configure-realm.sh +++ b/deploy/helm/agentos-net/files/configure-realm.sh @@ -15,7 +15,8 @@ # secret = KEYCLOAK_ADMIN_CLIENT_SECRET. The hosts use it (client_credentials) instead of the master # admin, so the bootstrap admin can be rotated or disabled after setup. # 3. verifyEmail on only when SMTP is configured (KC_SMTP_HOST), else off (signup would dead-end). -# 4. Ensures the platform-admin realm role (an existing realm is never re-imported). +# 4. Ensures the platform-admin + RBAC v2 (viewer/developer/approver/auditor) realm roles (an existing realm is +# never re-imported). # 5. FIRST RUN ONLY (realm attribute agentosSeedApplied): sets the seed `operator` (first admin) password to # OPERATOR_PASSWORD — required, the import's is public — and sets `member` to MEMBER_PASSWORD, or # DISABLES it when that is unset. Later runs never touch them again, so a password changed in Keycloak @@ -132,6 +133,20 @@ else echo " role platform-admin created" fi +# 4b. RBAC v2 realm roles (E1.2) — viewer / developer / approver / auditor (the hosts also create one on first use). +ensure_role() { + if kc get "roles/$1" -r "$REALM" >/dev/null 2>&1; then + echo " role $1 present" + else + kc create roles -r "$REALM" -s "name=$1" -s "description=$2" >/dev/null + echo " role $1 created" + fi +} +ensure_role viewer "Read-only access to the tenant's work" +ensure_role developer "Runs agents and works tickets" +ensure_role approver "Decides design checks and approvals" +ensure_role auditor "Read-only audit log and evidence" + # 5. Seed users — first run only. The marker is a realm attribute (free-form, unlike user attributes, which # the declarative user profile governs). # (`--fields attributes` returns an empty map in kcadm 26 — read the whole representation.) diff --git a/docs/CONFIG.md b/docs/CONFIG.md index 48090475..56511863 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -360,6 +360,52 @@ starve the others. Separate from the monthly budget cap, which still applies. - **Per-viewer preferences** (theme, wallpaper, glass, clock, *Animations*) — System → Appearance, stored in the browser only. +## Roles and permissions (RBAC v2) + +Who may do what is **not a setting**: it is one permission matrix in code +([`PermissionMatrix`](../src/AgentOs.SharedKernel/Identity/PermissionMatrix.cs)), enforced on every Api/Web endpoint +(`perm:` authorization policies) **and** in the desktop (apps, Settings pages, Activities search and +buttons are hidden or disabled; every handler re-checks). Roles are Keycloak realm roles, assigned in +**Settings → People & data → Users** (or `PATCH /tenants/{tenantId}/members/{userId}`); they are additive. + +| Permission | viewer | developer | approver | auditor | admin | +|---|:-:|:-:|:-:|:-:|:-:| +| `ViewWork` — boards, tasks, runs, insights, files | ✓ | ✓ | ✓ | ✓ | ✓ | +| `RunAgents` — run/stop agents, work tickets, pair a computer, ticket files | | ✓ | | | ✓ | +| `ApproveWork` — design checks, approvals (E1.5 policies) | | | ✓ | | ✓ | +| `ViewAudit` — audit log, tool-call evidence, audit CSV | | | | ✓ | ✓ | +| `ManageWorkspaces` — connect/remove boards + repos, Autopilot | | | | | ✓ | +| `ManageMembers` — invite, roles, board memberships | | | | | ✓ | +| `ManageSettings` — model keys, agents, prompts, tool policy, MCP | | | | | ✓ | +| `ManageApiTokens` | | | | | ✓ | +| `ExportData` — tenant export, cost CSV | | | | | ✓ | + +**Existing users keep working — role mapping.** No migration is needed: + +| Before E1.2 | Now | +|---|---| +| `admin` | `admin` (same name, every permission) | +| `member` | kept as a legacy alias = `developer` + `approver` + `ManageWorkspaces` — exactly what a member could do before (run agents, decide design checks on their own tasks, connect boards). Choosing one of the five roles for that user in Users replaces it. | +| `platform-admin` | unchanged, orthogonal (platform-wide settings only; grants nothing tenant-scoped) | + +API tokens take the same roles (Settings → API tokens); existing `member` tokens keep the alias. + +**Per-board (workspace) membership.** **Users → Board access** (or +`PUT /tenants/{tenantId}/boards/{boardId}/members/{userId}` with `{ "role": "viewer|developer|approver" }`) gives a +member a role on one board, stored in `workspaces.workspace_members` (RLS-bound). A board with no memberships is +**open**: tenant roles apply. Its first membership makes it **restricted**: only its members (with their board +role, which replaces their viewer/developer/approver realm role there — it may raise or lower it) plus tenant-wide +`admin` and `auditor` see it; it is 404 to everyone else (board list, `/workspaces/{id}`, its sessions and ticket +files). Every change is audited (`member.board_role_set`, `member.board_role_removed`). + +**IdP groups (E1.1 hook).** `IRoleClaimMapper` (SharedKernel) maps claims onto roles on every request +(`RoleClaimsTransformation`); register one to turn Entra ID / Okta groups into AgentOS.NET roles. The built-in one +maps the legacy `member` role. Unknown role names grant nothing. + +**Keycloak.** The realm import carries the five roles; an existing realm (never re-imported) gets them from the +azd `postdeploy` hook, the Helm/compose `configure-realm.sh`, `lab.ps1`, or — on first assignment — from the hosts +themselves (`KeycloakAdminClient` creates a missing managed role). + ## Legacy `/settings` endpoint `POST /settings` (admin) still accepts exactly `Llm:ForceProvider`, `Llm:Claude:ApiKey`, diff --git a/docs/plans/enterprise-readiness.md b/docs/plans/enterprise-readiness.md index 9601c45f..558b2601 100644 --- a/docs/plans/enterprise-readiness.md +++ b/docs/plans/enterprise-readiness.md @@ -73,7 +73,7 @@ Status: ✅ shipped + verified · 🟡 partial · ❌ absent. "Where" cites the |---|---|---|---|---|---| | 1 | SSO | Entra ID / Okta / ADFS / Google via OIDC or SAML, MFA policy, JIT provisioning | ❌ Keycloak local users only | realm has no `identityProviders` | **E1.1** | | 2 | Provisioning | SCIM 2.0 create/update/**deprovision** → sessions revoked | ❌ | — | **E2.1** | -| 3 | RBAC | viewer · developer · approver · admin · auditor; per-workspace scope; custom roles later | 🟡 3 roles | `IdentityModule.cs:23-25` | **E1.2** | +| 3 | RBAC | viewer · developer · approver · admin · auditor; per-workspace scope; custom roles later | 🟡 5 roles + permission matrix + per-board memberships shipped (E1.2), enforced on endpoints + desktop; pending lab / full-stack verification per role; custom roles later | `PermissionMatrix.cs`, `WorkspaceMemberships.cs`, [CONFIG.md](../CONFIG.md#roles-and-permissions-rbac-v2) | **E1.2** | | 4 | Machine access | API tokens / service accounts, scoped + expiring, for CI and the CLI | ❌ JWT only | — | **E1.3** | | 5 | API contract | versioned REST (`/v1`), published OpenAPI, deprecation policy | 🟡 unversioned | Scalar UI on Api | **E1.3** | | 6 | Tenant isolation | DB-enforced, proven by test | 🟡 EF filters + E2E (#192), no RLS | plan 0.9 | **E0.1** | diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 86cd7352..0c4f87f6 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -70,7 +70,7 @@ Diagrams of these boundaries and the data that crosses them are in [data-flow.md | W-5 | S | Open redirect after login | `SafeLocalReturn` on `/account/login` (`src/AgentOs.Web/Program.cs:496-500,533-536`); return URL limited to local paths on callback failure (`src/AgentOs.Web/Auth/AuthCookies.cs:122-126`) | None known | | W-6 | I | Circuit runs without tenant → RLS and settings resolve the wrong tenant | `CircuitIdentityHandler` pushes the signed-in tenant/user as ambient identity for every inbound circuit activity (`src/AgentOs.Web/Services/CircuitIdentityHandler.cs:15-28`, registered `Program.cs:285`) | Several Web paths fall back to `"default"` when the claim is missing (`src/AgentOs.Web/Program.cs:433,446,467`; `ApiTokensApp.razor:121`, `AuditLogApp.razor:102`, `DataApp.razor:112`) instead of failing closed like `HttpTenantContext`. Low — **GAP-17** | | W-7 | D | Circuit / request flooding | Kestrel header cap (`src/AgentOs.ServiceDefaults/Extensions.cs:51-52`); per-tenant run admission — concurrency 4, 30 runs/min (`src/AgentOs.Modules.Pipeline/Limits/RunAdmission.cs:25-41,79-81`); pairing exchange limited to 10/min/IP (`src/AgentOs.Web/Program.cs:294-306`) | **No global rate limiter on the Web host** (only `pairing-exchange`); anonymous `/signup` circuit is not rate-limited. Circuit options left at defaults. Medium — **GAP-02** | -| W-8 | E | Desktop app reachable by a non-admin | Pages default to `[Authorize]` (`src/AgentOs.Web/Components/_Imports.razor:33`); Settings is admin-gated in the component (see [DEPLOYMENT.md](../DEPLOYMENT.md#per-tenant-llm-keys)); tenant purge checks platform-admin + typed confirmation in `DataApp.razor:119-121` | `TenantDataService.PurgeAsync` has **no authorization of its own** (`src/AgentOs.Modules.Tenants/Data/TenantDataService.cs:88`) — the check lives only in the UI. Low today (no HTTP route), Medium if a route is added — **GAP-17** | +| W-8 | E | Desktop app reachable by a non-admin | Pages default to `[Authorize]` (`src/AgentOs.Web/Components/_Imports.razor:33`); RBAC v2 (E1.2): `DesktopApp.Requires` hides an app from roles without its permission, `WindowHost` refuses to render it, and gated pages + Board/Workflow handlers re-check through `PermissionMatrix`; Settings is admin-gated in the component (see [DEPLOYMENT.md](../DEPLOYMENT.md#per-tenant-llm-keys)); tenant purge checks platform-admin + typed confirmation in `DataApp.razor:119-121` | `TenantDataService.PurgeAsync` has **no authorization of its own** (`src/AgentOs.Modules.Tenants/Data/TenantDataService.cs:88`) — the check lives only in the UI. Low today (no HTTP route), Medium if a route is added — **GAP-17** | | W-9 | S / I | Forwarded headers spoofed | Forwarded headers are processed so the ingress' scheme and client IP are seen | `KnownIPNetworks` / `KnownProxies` are **cleared** (`src/AgentOs.ServiceDefaults/Extensions.cs:37-42`): any peer can set `X-Forwarded-For/Proto`. The Api has `AllowedHosts: "*"` (`src/AgentOs.Api/appsettings.json:10`). Invitation and pairing URLs are built from `Request.Scheme/Host` (`src/AgentOs.Modules.Tenants/Endpoints/TenantEndpoints.cs:153-154`; `src/AgentOs.Modules.Sessions/Endpoints/PairingEndpoints.cs:89`) → host-header link poisoning, spoofable IP rate-limit partition and audit IPs. High — **GAP-05** | ## 4. TB2 — Web / Api ↔ Keycloak diff --git a/infra/hooks/postdeploy.ps1 b/infra/hooks/postdeploy.ps1 index ecdb0d0d..2922d72e 100644 --- a/infra/hooks/postdeploy.ps1 +++ b/infra/hooks/postdeploy.ps1 @@ -74,6 +74,25 @@ try { else { Write-Warning "Could not ensure realm role platform-admin: $($_.Exception.Message)" } } +# 2c. RBAC v2 realm roles (E1.2): viewer / developer / approver / auditor. Same reason as 2b (no re-import); the hosts +# also create a missing one on first assignment, this just makes them visible in Keycloak from day one. +$rbacRoles = [ordered]@{ + viewer = "Read-only access to the tenant's work" + developer = 'Runs agents and works tickets' + approver = 'Decides design checks and approvals' + auditor = 'Read-only audit log and evidence' +} +foreach ($role in $rbacRoles.GetEnumerator()) { + try { + Invoke-RestMethod -Method Post -Headers $headers -Uri "$kcUrl/admin/realms/$realm/roles" -ContentType 'application/json' ` + -Body (@{ name = $role.Key; description = $role.Value } | ConvertTo-Json) | Out-Null + Write-Host "Realm role $($role.Key) created." + } catch { + if ($_.Exception.Response -and [int]$_.Exception.Response.StatusCode -eq 409) { Write-Host "Realm role $($role.Key) already present." } + else { Write-Warning "Could not ensure realm role $($role.Key): $($_.Exception.Message)" } + } +} + # 3. Seed users: rotate imported placeholder passwords function Rotate-SeedUser([string]$username, [string]$newPass) { if (-not $newPass) { diff --git a/infra/hooks/postdeploy.sh b/infra/hooks/postdeploy.sh index e9fe2de7..6ec00bfc 100644 --- a/infra/hooks/postdeploy.sh +++ b/infra/hooks/postdeploy.sh @@ -67,6 +67,23 @@ case "$code" in *) echo "WARN: Could not ensure realm role platform-admin (HTTP $code)." ;; esac +# 2c. RBAC v2 realm roles (E1.2): viewer / developer / approver / auditor. Same reason as 2b (no re-import); the hosts +# also create a missing one on first assignment, this just makes them visible in Keycloak from day one. +ensure_role() { + local name="$1" desc="$2" rc + rc=$(curl -s -o /dev/null -w "%{http_code}" -X POST "${auth[@]}" "$KC_URL/admin/realms/$REALM/roles" \ + -d "$(jq -n --arg n "$name" --arg d "$desc" '{name:$n,description:$d}')") + case "$rc" in + 201) echo "Realm role $name created." ;; + 409) echo "Realm role $name already present." ;; + *) echo "WARN: Could not ensure realm role $name (HTTP $rc)." ;; + esac +} +ensure_role viewer "Read-only access to the tenant's work" +ensure_role developer "Runs agents and works tickets" +ensure_role approver "Decides design checks and approvals" +ensure_role auditor "Read-only audit log and evidence" + # 3. Seed users: rotate imported placeholder passwords rotate_user() { local username="$1" newpass="$2" diff --git a/infra/keycloak/agentic-realm.json b/infra/keycloak/agentic-realm.json index 6a339793..b7bf31b5 100644 --- a/infra/keycloak/agentic-realm.json +++ b/infra/keycloak/agentic-realm.json @@ -41,7 +41,11 @@ "roles": { "realm": [ { "name": "admin", "description": "Tenant administrator" }, - { "name": "member", "description": "Tenant member" }, + { "name": "viewer", "description": "Read-only access to the tenant's work" }, + { "name": "developer", "description": "Runs agents and works tickets" }, + { "name": "approver", "description": "Decides design checks and approvals" }, + { "name": "auditor", "description": "Read-only audit log and evidence" }, + { "name": "member", "description": "Legacy tenant member - developer + approver + connect boards (RBAC v2)" }, { "name": "platform-admin", "description": "Platform administrator - platform-wide settings for every tenant" } ] }, diff --git a/infra/lab/lab.ps1 b/infra/lab/lab.ps1 index bbc0cf69..b0042eda 100644 --- a/infra/lab/lab.ps1 +++ b/infra/lab/lab.ps1 @@ -157,6 +157,19 @@ function Sync-LabRealm { "$kcAdmin/admin/realms/agentic/clients/$($client.id)" -Body ($client | ConvertTo-Json -Depth 20) | Out-Null Write-Host "Realm: agentic-web now accepts $WebUrl" } + # RBAC v2 (E1.2) realm roles — an existing lab realm never got them from the import. + $existing = @((Invoke-RestMethod -SkipCertificateCheck -Headers $headers "$kcAdmin/admin/realms/agentic/roles").name) + $rbacRoles = [ordered]@{ + viewer = "Read-only access to the tenant's work" + developer = 'Runs agents and works tickets' + approver = 'Decides design checks and approvals' + auditor = 'Read-only audit log and evidence' + } + foreach ($role in $rbacRoles.GetEnumerator() | Where-Object { $existing -notcontains $_.Key }) { + Invoke-RestMethod -SkipCertificateCheck -Method Post -Headers $headers -ContentType 'application/json' ` + "$kcAdmin/admin/realms/agentic/roles" -Body (@{ name = $role.Key; description = $role.Value } | ConvertTo-Json) | Out-Null + Write-Host "Realm: role $($role.Key) created" + } } catch { Write-Warning "Could not sync the lab realm ($($_.Exception.Message)). Sign-in may fail until it is synced." } diff --git a/src/AgentOs.Api/Program.cs b/src/AgentOs.Api/Program.cs index 62eec863..c6b4e7a5 100644 --- a/src/AgentOs.Api/Program.cs +++ b/src/AgentOs.Api/Program.cs @@ -236,7 +236,7 @@ // Epic E4 — MCP HTTP endpoint at /mcp. Streamable HTTP per spec. RequireAuthorization so an // anonymous caller can't drive the full 5-agent LLM pipeline (uncapped spend) or read another // tenant's runs — every sibling REST route is gated, this one must be too. -app.MapMcp("/mcp").RequireAuthorization(); +app.MapMcp("/mcp").RequirePermission(Permission.RunAgents); // Settings "Test" — probe one provider (?provider=, from the Model keys cards; allow-listed by LlmProbe) or, with // none named, the Orchestrator's configured provider, with a minimal call. @@ -311,6 +311,6 @@ .WithName("LlmTest") .WithSummary("Probe the configured LLM provider with a minimal call") .WithTags("Settings") - .RequireAuthorization(); + .RequirePermission(Permission.ManageSettings); app.Run(); diff --git a/src/AgentOs.Modules.AppConfig/Endpoints/SettingsEndpoints.cs b/src/AgentOs.Modules.AppConfig/Endpoints/SettingsEndpoints.cs index 480f1dd6..11531b68 100644 --- a/src/AgentOs.Modules.AppConfig/Endpoints/SettingsEndpoints.cs +++ b/src/AgentOs.Modules.AppConfig/Endpoints/SettingsEndpoints.cs @@ -29,13 +29,13 @@ public static IEndpointRouteBuilder MapSettingsEndpoints(this IEndpointRouteBuil .WithName("SettingsList") .WithSummary("Read every key beneath a prefix (Llm, Github); secret values are masked") .WithTags("Settings") - .RequireAuthorization("Admin"); + .RequirePermission(Permission.ManageSettings); app.MapPost("/settings/Github/test", TestGitHubAsync) .WithName("SettingsGithubTest") .WithSummary("Probe GitHub with the saved (or a just-typed) Pipeline auto-PR token; never returns the token") .WithTags("Settings") - .RequireAuthorization("Admin"); + .RequirePermission(Permission.ManageSettings); app.MapPost("/settings", async (SetEntryRequest? body, IAppConfigStore store, CancellationToken ct) => { @@ -66,7 +66,7 @@ public static IEndpointRouteBuilder MapSettingsEndpoints(this IEndpointRouteBuil .WithName("SettingsSet") .WithSummary("Set a single key (overwrite if present)") .WithTags("Settings") - .RequireAuthorization("Admin"); + .RequirePermission(Permission.ManageSettings); app.MapDelete("/settings/{key}", async (string key, IAppConfigStore store, CancellationToken ct) => { @@ -82,7 +82,7 @@ public static IEndpointRouteBuilder MapSettingsEndpoints(this IEndpointRouteBuil .WithName("SettingsDelete") .WithSummary("Delete a key") .WithTags("Settings") - .RequireAuthorization("Admin"); + .RequirePermission(Permission.ManageSettings); return app; } diff --git a/src/AgentOs.Modules.Identity/Authorization/RbacServiceCollectionExtensions.cs b/src/AgentOs.Modules.Identity/Authorization/RbacServiceCollectionExtensions.cs new file mode 100644 index 00000000..9ef7bc35 --- /dev/null +++ b/src/AgentOs.Modules.Identity/Authorization/RbacServiceCollectionExtensions.cs @@ -0,0 +1,129 @@ +// RBAC v2 (E1.2) — wires the permission matrix into ASP.NET Core authorization: one "perm:" policy per +// Permission (PermissionMatrix.Policy), a handler that evaluates the matrix against the caller's role claims, and the +// claims transformation that runs the IRoleClaimMapper hook (legacy roles today, IdP groups with E1.1). +// Kept out of IdentityModule.cs so that file stays a two-line call site. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; +using AgentOs.SharedKernel.Identity; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authorization; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace AgentOs.Modules.Identity.Authorization; + +/// Registration of the RBAC v2 policies, handler and claim-mapping hook. +public static class RbacServiceCollectionExtensions +{ + /// Register one policy per (named ). + public static AuthorizationOptions AddPermissionPolicies(this AuthorizationOptions options) + { + ArgumentNullException.ThrowIfNull(options); + foreach (var permission in PermissionMatrix.Each) + { + options.AddPolicy(PermissionMatrix.Policy(permission), policy => policy + .RequireAuthenticatedUser() + .AddRequirements(new PermissionRequirement(permission))); + } + return options; + } + + /// Require on a policy (e.g. the legacy Member policy). + public static AuthorizationPolicyBuilder RequirePermission(this AuthorizationPolicyBuilder policy, Permission permission) + { + ArgumentNullException.ThrowIfNull(policy); + return policy.RequireAuthenticatedUser().AddRequirements(new PermissionRequirement(permission)); + } + + /// Register the permission handler + the role-claim mapping hook (with the legacy-role mapper). + public static IServiceCollection AddRbac(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddTransient(); + return services; + } +} + +/// Requires one permission from the matrix. +public sealed record PermissionRequirement(Permission Permission) : IAuthorizationRequirement; + +/// Succeeds when the caller's role claims grant the required permission (tenant scope). +public sealed class PermissionAuthorizationHandler : AuthorizationHandler +{ + /// + protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(requirement); + if (context.User.Can(requirement.Permission)) + { + context.Succeed(requirement); + } + return Task.CompletedTask; + } +} + +/// Adds the roles every returns as claims. +/// Runs on every authenticate (both hosts); idempotent — a role the principal already holds is not added +/// twice, and the original principal is never mutated (a fresh identity carries the mapped roles). +public sealed class RoleClaimsTransformation : IClaimsTransformation +{ + /// Authentication type of the identity that carries mapped roles. + public const string MappedIdentityType = "agentos-rbac"; + + private readonly IRoleClaimMapper[] _mappers; + + public RoleClaimsTransformation(IEnumerable mappers) + { + ArgumentNullException.ThrowIfNull(mappers); + _mappers = [.. mappers]; + } + + /// + public Task TransformAsync(ClaimsPrincipal principal) + { + ArgumentNullException.ThrowIfNull(principal); + if (_mappers.Length == 0 || principal.Identity?.IsAuthenticated != true) + { + return Task.FromResult(principal); + } + + HashSet? held = null; + List? added = null; + foreach (var role in _mappers.SelectMany(m => m.MapRoles(principal))) + { + if (!PermissionMatrix.Roles.ContainsKey(role)) { continue; } + held ??= principal.GetRoles().ToHashSet(StringComparer.Ordinal); + if (held.Add(role)) { (added ??= []).Add(role); } + } + if (added is null) + { + return Task.FromResult(principal); + } + + var clone = principal.Clone(); + clone.AddIdentity(new ClaimsIdentity( + added.Select(r => new Claim(ClaimTypes.Role, r)), MappedIdentityType, ClaimTypes.Name, ClaimTypes.Role)); + return Task.FromResult(clone); + } +} + +/// Maps the pre-E1.2 member role onto developer + approver, so role displays and +/// IsInRole("developer") agree with the matrix (which already treats member as that alias). +public sealed class LegacyRoleClaimMapper : IRoleClaimMapper +{ + private static readonly string[] MemberRoles = [UserRoles.Developer, UserRoles.Approver]; + + /// + public IEnumerable MapRoles(ClaimsPrincipal user) + { + ArgumentNullException.ThrowIfNull(user); + return user.IsInRole(UserRoles.LegacyMember) ? MemberRoles : []; + } +} diff --git a/src/AgentOs.Modules.Identity/IdentityModule.cs b/src/AgentOs.Modules.Identity/IdentityModule.cs index ea1e1feb..12041d17 100644 --- a/src/AgentOs.Modules.Identity/IdentityModule.cs +++ b/src/AgentOs.Modules.Identity/IdentityModule.cs @@ -3,6 +3,7 @@ // host wires cookie + OIDC explicitly. No DbContext; tenant state lives in JWT/cookie claims. using System; +using AgentOs.Modules.Identity.Authorization; using AgentOs.SharedKernel.Identity; using AgentOs.SharedKernel.Modularity; using Microsoft.Extensions.Configuration; @@ -21,8 +22,11 @@ public void AddServices(IServiceCollection services, IConfiguration configuratio services.AddAuthorization(options => { options.AddPolicy("Admin", policy => policy.RequireRole("admin")); - options.AddPolicy("Member", policy => policy.RequireRole("admin", "member")); + // RBAC v2 (E1.2): "Member" = any role of the tenant (ViewWork); writes use the "perm:*" policies. + options.AddPolicy("Member", policy => policy.RequirePermission(Permission.ViewWork)); options.AddPolicy("PlatformAdmin", policy => policy.RequireRole(ClaimNames.PlatformAdminRole)); + options.AddPermissionPolicies(); }); + services.AddRbac(); } } diff --git a/src/AgentOs.Modules.Mcp/McpModule.cs b/src/AgentOs.Modules.Mcp/McpModule.cs index 094d9341..eb81a28e 100644 --- a/src/AgentOs.Modules.Mcp/McpModule.cs +++ b/src/AgentOs.Modules.Mcp/McpModule.cs @@ -13,6 +13,7 @@ using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using AgentOs.SharedKernel.Identity; namespace AgentOs.Modules.Mcp; @@ -54,7 +55,7 @@ public void MapEndpoints(IEndpointRouteBuilder endpoints) .WithName("McpServers") .WithSummary("Configured upstream MCP servers + startup connection status") .WithTags("Mcp") - .RequireAuthorization("Admin"); + .RequirePermission(Permission.ManageSettings); } public async Task InitializeAsync(IServiceProvider services, CancellationToken ct) diff --git a/src/AgentOs.Modules.Pipeline/Endpoints/PipelineEndpoints.cs b/src/AgentOs.Modules.Pipeline/Endpoints/PipelineEndpoints.cs index e98c2868..b26b6c33 100644 --- a/src/AgentOs.Modules.Pipeline/Endpoints/PipelineEndpoints.cs +++ b/src/AgentOs.Modules.Pipeline/Endpoints/PipelineEndpoints.cs @@ -51,7 +51,7 @@ public static IEndpointRouteBuilder MapPipelineEndpoints(this IEndpointRouteBuil .Produces() .ProducesValidationProblem() .ProducesProblem(StatusCodes.Status402PaymentRequired) - .RequireAuthorization(); + .RequirePermission(Permission.RunAgents); app.MapPost("/code", async (CodeRequest? body, ICodingAgent agent, IBudgetGuard budget, ITenantContext tenant, CancellationToken ct) => { @@ -72,7 +72,7 @@ public static IEndpointRouteBuilder MapPipelineEndpoints(this IEndpointRouteBuil .Produces() .ProducesValidationProblem() .ProducesProblem(StatusCodes.Status402PaymentRequired) - .RequireAuthorization(); + .RequirePermission(Permission.RunAgents); app.MapPost("/test", async (TestRequest? body, ITestingAgent agent, IBudgetGuard budget, ITenantContext tenant, CancellationToken ct) => { @@ -93,7 +93,7 @@ public static IEndpointRouteBuilder MapPipelineEndpoints(this IEndpointRouteBuil .Produces() .ProducesValidationProblem() .ProducesProblem(StatusCodes.Status402PaymentRequired) - .RequireAuthorization(); + .RequirePermission(Permission.RunAgents); app.MapPost("/qa", async (QaRequest? body, IQaAgent agent, IBudgetGuard budget, ITenantContext tenant, CancellationToken ct) => { @@ -114,7 +114,7 @@ public static IEndpointRouteBuilder MapPipelineEndpoints(this IEndpointRouteBuil .Produces() .ProducesValidationProblem() .ProducesProblem(StatusCodes.Status402PaymentRequired) - .RequireAuthorization(); + .RequirePermission(Permission.RunAgents); app.MapPost("/pipeline", async (UserStory? body, IOrchestratorAgent orchestrator, CancellationToken ct) => { @@ -132,7 +132,7 @@ public static IEndpointRouteBuilder MapPipelineEndpoints(this IEndpointRouteBuil .Produces() .Produces(StatusCodes.Status500InternalServerError) .ProducesValidationProblem() - .RequireAuthorization(); + .RequirePermission(Permission.RunAgents); // Phase 8 — Server-Sent Events stream of progress + final result. // Wire shape per event: event: progress|result|error \n data: {json}\n\n @@ -167,7 +167,7 @@ public static IEndpointRouteBuilder MapPipelineEndpoints(this IEndpointRouteBuil .WithSummary("KC4 — Streamed pipeline run. SSE events: progress | result | error") .WithTags("Agents") .ProducesValidationProblem() - .RequireAuthorization(); + .RequirePermission(Permission.RunAgents); app.MapGet("/runs", async (IPipelineRunRepository repo, CancellationToken ct, int? limit, int? offset) => { @@ -180,7 +180,7 @@ public static IEndpointRouteBuilder MapPipelineEndpoints(this IEndpointRouteBuil .WithSummary("Pipeline run history (summaries, newest first). ?limit (≤500) and ?offset page through it.") .WithTags("History") .Produces>() - .RequireAuthorization(); + .RequirePermission(Permission.ViewWork); app.MapGet("/runs/{id:guid}", async (Guid id, IPipelineRunRepository repo, CancellationToken ct) => { @@ -194,7 +194,7 @@ public static IEndpointRouteBuilder MapPipelineEndpoints(this IEndpointRouteBuil .WithTags("History") .Produces() .Produces(StatusCodes.Status404NotFound) - .RequireAuthorization(); + .RequirePermission(Permission.ViewWork); return app; } diff --git a/src/AgentOs.Modules.Sessions/Endpoints/PairingEndpoints.cs b/src/AgentOs.Modules.Sessions/Endpoints/PairingEndpoints.cs index 92bbf92d..10efcc56 100644 --- a/src/AgentOs.Modules.Sessions/Endpoints/PairingEndpoints.cs +++ b/src/AgentOs.Modules.Sessions/Endpoints/PairingEndpoints.cs @@ -34,8 +34,8 @@ public static void MapPairingEndpoints(this IEndpointRouteBuilder endpoints) { ArgumentNullException.ThrowIfNull(endpoints); - endpoints.MapGet("/pair/vscode", ApprovePage).RequireAuthorization("Member"); - endpoints.MapPost("/pair/vscode", ApproveAsync).RequireAuthorization("Member").DisableAntiforgery(); + endpoints.MapGet("/pair/vscode", ApprovePage).RequirePermission(Permission.RunAgents); + endpoints.MapPost("/pair/vscode", ApproveAsync).RequirePermission(Permission.RunAgents).DisableAntiforgery(); // Anonymous — gated by the one-time code. A typed code is short (≈39 bits), so the host rate-limits this // route per client under ExchangeRateLimitPolicy (the Web registers it). endpoints.MapPost("/runner/pair/exchange", ExchangeAsync).RequireRateLimiting(ExchangeRateLimitPolicy); diff --git a/src/AgentOs.Modules.Sessions/Endpoints/SessionEndpoints.cs b/src/AgentOs.Modules.Sessions/Endpoints/SessionEndpoints.cs index 1857baec..512f4c16 100644 --- a/src/AgentOs.Modules.Sessions/Endpoints/SessionEndpoints.cs +++ b/src/AgentOs.Modules.Sessions/Endpoints/SessionEndpoints.cs @@ -1,5 +1,6 @@ // M3 — Sessions + Runners HTTP endpoints. Create a member × workspace session, list/get/close them; -// register a runner (a paired dev machine) and revoke it. Auth: Member policy; tenant + member resolved +// register a runner (a paired dev machine) and revoke it. Auth (RBAC v2): reads need ViewWork, writes RunAgents, +// and a restricted board's sessions follow its memberships (IWorkspaceAccess); tenant + member resolved // from the token by ITenantContext. // // Secret handling: a runner's pairing token is generated server-side, its salted hash is persisted on @@ -32,35 +33,46 @@ public static void MapSessionEndpoints(this IEndpointRouteBuilder endpoints) var sessions = endpoints.MapGroup("/sessions").RequireAuthorization("Member"); sessions.MapGet(string.Empty, ListSessionsAsync); sessions.MapGet("/{id:guid}", GetSessionAsync); - sessions.MapPost(string.Empty, CreateSessionAsync); - sessions.MapPost("/{id:guid}/close", CloseSessionAsync); + sessions.MapPost(string.Empty, CreateSessionAsync).RequirePermission(Permission.RunAgents); + sessions.MapPost("/{id:guid}/close", CloseSessionAsync).RequirePermission(Permission.RunAgents); var runners = endpoints.MapGroup("/runners").RequireAuthorization("Member"); runners.MapGet(string.Empty, ListRunnersAsync); - runners.MapPost(string.Empty, RegisterRunnerAsync); - runners.MapPost("/{id:guid}/revoke", RevokeRunnerAsync); + runners.MapPost(string.Empty, RegisterRunnerAsync).RequirePermission(Permission.RunAgents); + runners.MapPost("/{id:guid}/revoke", RevokeRunnerAsync).RequirePermission(Permission.RunAgents); } // ---- Sessions ---- - private static async Task ListSessionsAsync(ISessionRepository repo, CancellationToken ct, int? limit = null, int? offset = null) + private static async Task ListSessionsAsync( + ISessionRepository repo, ITenantContext tenant, System.Security.Claims.ClaimsPrincipal user, CancellationToken ct, + int? limit = null, int? offset = null, [Microsoft.AspNetCore.Mvc.FromServices] IWorkspaceAccess? access = null) { var rows = await repo.ListAsync(limit ?? Page.DefaultLimit, offset ?? 0, ct).ConfigureAwait(false); - return Results.Ok(rows.Select(SessionDto.From).ToList()); + // RBAC v2: a session on a restricted board is listed only to who may see that board. + var map = access is null ? null : await access.ForUserAsync(tenant.TenantId, user, ct).ConfigureAwait(false); + return Results.Ok(rows.Where(r => map?.CanSee(r.WorkspaceId) != false).Select(SessionDto.From).ToList()); } - private static async Task GetSessionAsync(Guid id, ISessionRepository repo, CancellationToken ct) + private static async Task GetSessionAsync( + Guid id, ISessionRepository repo, ITenantContext tenant, System.Security.Claims.ClaimsPrincipal user, CancellationToken ct, + [Microsoft.AspNetCore.Mvc.FromServices] IWorkspaceAccess? access = null) { var row = await repo.GetAsync(id, ct).ConfigureAwait(false); - return row is null ? Results.NotFound() : Results.Ok(SessionDto.From(row)); + if (row is null) { return Results.NotFound(); } + var map = access is null ? null : await access.ForUserAsync(tenant.TenantId, user, ct).ConfigureAwait(false); + // Not-found, not forbidden: a restricted board's sessions don't exist for an outsider. + return map?.CanSee(row.WorkspaceId) == false ? Results.NotFound() : Results.Ok(SessionDto.From(row)); } private static async Task CreateSessionAsync( CreateSessionRequest? request, ISessionRepository repo, ITenantContext tenant, + System.Security.Claims.ClaimsPrincipal user, TimeProvider clock, - CancellationToken ct) + CancellationToken ct, + [Microsoft.AspNetCore.Mvc.FromServices] IWorkspaceAccess? access = null) { if (request is null) { @@ -82,6 +94,12 @@ private static async Task CreateSessionAsync( { return Results.ValidationProblem(errors); } + // RBAC v2: the caller must be allowed to run agents ON THIS BOARD (a restricted board's membership decides). + if (access is not null + && !(await access.ForUserAsync(tenant.TenantId, user, ct).ConfigureAwait(false)).Can(request.WorkspaceId, Permission.RunAgents)) + { + return Results.Forbid(); + } var entity = new RemoteSessionEntity { diff --git a/src/AgentOs.Modules.Sessions/Endpoints/TicketFileEndpoints.cs b/src/AgentOs.Modules.Sessions/Endpoints/TicketFileEndpoints.cs index 1c8097fc..d6ce4521 100644 --- a/src/AgentOs.Modules.Sessions/Endpoints/TicketFileEndpoints.cs +++ b/src/AgentOs.Modules.Sessions/Endpoints/TicketFileEndpoints.cs @@ -29,11 +29,12 @@ internal static class TicketFileEndpoints public static void MapTicketFileEndpoints(this IEndpointRouteBuilder endpoints) { ArgumentNullException.ThrowIfNull(endpoints); - var files = endpoints.MapGroup(Route).RequireAuthorization("Member"); + var files = endpoints.MapGroup(Route).RequireAuthorization("Member") + .RequireWorkspacePermission("boardId", Permission.RunAgents); files.MapGet(string.Empty, ListAsync); files.MapGet("/{**path}", DownloadAsync); - files.MapPut("/{**path}", UploadAsync); - files.MapDelete("/{**path}", DeleteAsync); + files.MapPut("/{**path}", UploadAsync).RequirePermission(Permission.RunAgents); + files.MapDelete("/{**path}", DeleteAsync).RequirePermission(Permission.RunAgents); } /// A file as the API returns it (no content). diff --git a/src/AgentOs.Modules.Tenants/AgentOs.Modules.Tenants.csproj b/src/AgentOs.Modules.Tenants/AgentOs.Modules.Tenants.csproj index 80371cae..b3c1b114 100644 --- a/src/AgentOs.Modules.Tenants/AgentOs.Modules.Tenants.csproj +++ b/src/AgentOs.Modules.Tenants/AgentOs.Modules.Tenants.csproj @@ -9,6 +9,8 @@ + + diff --git a/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenService.cs b/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenService.cs index e7498751..d012388f 100644 --- a/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenService.cs +++ b/src/AgentOs.Modules.Tenants/ApiTokens/ApiTokenService.cs @@ -51,8 +51,10 @@ public static class ApiTokenFormat /// Every token starts with this. public const string Scheme = "aos_"; - /// Roles a token may hold. - public static IReadOnlyList Roles { get; } = ["member", "admin"]; + /// Roles a token may hold: the RBAC v2 roles (PermissionMatrix) plus the legacy member alias for + /// pre-E1.2 clients. Never platform-admin. + public static IReadOnlyList Roles { get; } = + [.. AgentOs.SharedKernel.Identity.UserRoles.Assignable, AgentOs.SharedKernel.Identity.UserRoles.LegacyMember]; private const string Base32 = "abcdefghijklmnopqrstuvwxyz234567"; diff --git a/src/AgentOs.Modules.Tenants/Endpoints/TenantEndpoints.cs b/src/AgentOs.Modules.Tenants/Endpoints/TenantEndpoints.cs index bebecce1..d7d8e17f 100644 --- a/src/AgentOs.Modules.Tenants/Endpoints/TenantEndpoints.cs +++ b/src/AgentOs.Modules.Tenants/Endpoints/TenantEndpoints.cs @@ -1,6 +1,7 @@ // Tenant identity + admin endpoints. /tenants/me is open to any authenticated user (returns the -// resolved context); /tenants list + create + member invite require the Admin policy and reach -// into Keycloak via IKeycloakAdminClient to provision realm users. +// resolved context + permissions); /tenants list + create need platform-admin; member management (invite, roles, +// board memberships) needs the ManageMembers permission and reaches into Keycloak via IKeycloakAdminClient; the +// audit trail needs ViewAudit (RBAC v2, E1.2 — see PermissionMatrix). using System; using System.Collections.Generic; @@ -9,6 +10,7 @@ using System.Threading.Tasks; using AgentOs.Modules.Tenants.Email; using AgentOs.Modules.Tenants.Keycloak; +using AgentOs.Modules.Workspaces.Access; using AgentOs.SharedKernel.Identity; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; @@ -28,7 +30,8 @@ public static IEndpointRouteBuilder MapTenantEndpoints(this IEndpointRouteBuilde tenant.UserName, tenant.Roles, tenant.IsAuthenticated, - tenant.IsAdmin))) + tenant.IsAdmin, + PermissionNames(tenant.IsAuthenticated ? PermissionMatrix.For(tenant.Roles) : Permission.None)))) .WithName("TenantMe") .WithSummary("Resolved tenant + user + roles for the current request") .WithTags("Tenants") @@ -147,10 +150,10 @@ public static IEndpointRouteBuilder MapTenantEndpoints(this IEndpointRouteBuilde { return Results.Forbid(); } - var role = string.IsNullOrWhiteSpace(body.Role) ? "member" : body.Role; - if (role is not ("admin" or "member")) + var role = string.IsNullOrWhiteSpace(body.Role) ? MemberRoles.DefaultRole : body.Role; + if (!MemberRoles.IsAllowed(role)) { - return Results.BadRequest(new { error = "role must be 'admin' or 'member'" }); + return Results.BadRequest(new { error = $"role must be one of: {string.Join(", ", UserRoles.Assignable)}" }); } var ttl = TimeSpan.FromHours(body.TtlHours is > 0 and <= 168 ? body.TtlHours.Value : 24); var minted = signup.CreateInvitation(tenantId, role, body.Email, ttl); @@ -193,7 +196,7 @@ await audit.WriteAsync(new AuditEntry( .WithName("TenantsCreateInvitation") .WithSummary("Mint a signup invitation URL for the tenant (admin only)") .WithTags("Tenants") - .RequireAuthorization("Admin"); + .RequirePermission(Permission.ManageMembers); // Public preview: decode an invitation token (no side effects). Lets the signup page show // the inviter's tenant + email before the user fills the form. @@ -228,7 +231,7 @@ await audit.WriteAsync(new AuditEntry( .WithName("TenantsListMembers") .WithSummary("List the members of the current tenant (tenant Admin only)") .WithTags("Tenants") - .RequireAuthorization("Admin"); + .RequirePermission(Permission.ManageMembers); // Change a member's roles (admin/member). Tenant-scoped: an Admin can only touch members of // their own tenant, and cannot strip their own last admin role (lock-out guard). @@ -246,18 +249,10 @@ await audit.WriteAsync(new AuditEntry( { return Results.Forbid(); } - var roles = (body.Roles ?? Array.Empty()) - .Where(r => r is "admin" or "member") - .Distinct(StringComparer.Ordinal) - .ToList(); - if (roles.Count == 0) - { - return Results.BadRequest(new { error = "roles must contain at least one of: admin, member" }); - } - // Lock-out guard: an Admin editing themselves must keep the admin role. - if (string.Equals(ctx.UserId, userId, StringComparison.Ordinal) && !roles.Contains("admin", StringComparer.Ordinal)) + var roles = MemberRoles.Sanitize(body.Roles); + if (MemberRoles.Check(ctx.UserId, userId, roles) is { } refused) { - return Results.BadRequest(new { error = "You cannot remove your own admin role." }); + return Results.BadRequest(new { error = refused }); } try { @@ -282,7 +277,7 @@ await audit.WriteAsync(new AuditEntry( .WithName("TenantsUpdateMemberRoles") .WithSummary("Change a member's roles (tenant Admin only)") .WithTags("Tenants") - .RequireAuthorization("Admin"); + .RequirePermission(Permission.ManageMembers); // Remove a member from the tenant (deletes the Keycloak user). Cannot remove yourself. Their paired computers are // revoked and disconnected too (GAP-04) — a departed member's runner must not keep taking (or answering) work. @@ -290,7 +285,7 @@ await audit.WriteAsync(new AuditEntry( .WithName("TenantsRemoveMember") .WithSummary("Remove a member from the tenant (tenant Admin only)") .WithTags("Tenants") - .RequireAuthorization("Admin"); + .RequirePermission(Permission.ManageMembers); // Trigger a password-reset action email for a member (Keycloak owns the new password). app.MapPost("/tenants/{tenantId}/members/{userId}/reset-password", async ( @@ -329,7 +324,7 @@ await audit.WriteAsync(new AuditEntry( .WithName("TenantsResetMemberPassword") .WithSummary("Send a member a password-reset email (tenant Admin only)") .WithTags("Tenants") - .RequireAuthorization("Admin"); + .RequirePermission(Permission.ManageMembers); app.MapGet("/tenants/{tenantId}/audit", async ( string tenantId, @@ -346,9 +341,9 @@ await audit.WriteAsync(new AuditEntry( return Results.Ok(rows); }) .WithName("TenantsAudit") - .WithSummary("Audit trail for the current tenant (tenant Admin only)") + .WithSummary("Audit trail for the current tenant (admin or auditor)") .WithTags("Tenants") - .RequireAuthorization("Admin"); + .RequirePermission(Permission.ViewAudit); app.MapPost("/tenants/{tenantId}/members", async ( string tenantId, @@ -373,9 +368,11 @@ await audit.WriteAsync(new AuditEntry( { return Results.NotFound(new { error = $"Tenant '{tenantId}' not found" }); } - var roles = body.Roles is { Count: > 0 } - ? body.Roles.Where(r => r is "admin" or "member").Distinct(StringComparer.Ordinal).ToList() - : new List { "member" }; + IReadOnlyList roles = body.Roles is { Count: > 0 } ? MemberRoles.Sanitize(body.Roles) : [MemberRoles.DefaultRole]; + if (roles.Count == 0) + { + return Results.BadRequest(new { error = $"roles must contain at least one of: {string.Join(", ", UserRoles.Assignable)}" }); + } try { var userId = await kc.CreateUserAsync( @@ -404,11 +401,84 @@ await audit.WriteAsync(new AuditEntry( .WithName("TenantsInviteMember") .WithSummary("Invite a member into a tenant (admin only)") .WithTags("Tenants") - .RequireAuthorization("Admin"); + .RequirePermission(Permission.ManageMembers); + MapBoardMemberEndpoints(app); return app; } + // RBAC v2 (E1.2): a member's role per board (workspace). The first membership makes a board restricted — only its + // members (and tenant-wide admins/auditors) see it. Tenant-scoped like every member route: {tenantId} must be the + // caller's own tenant, and the target user must belong to it. + private static void MapBoardMemberEndpoints(IEndpointRouteBuilder app) + { + app.MapGet("/tenants/{tenantId}/boards/{boardId:guid}/members", async ( + string tenantId, Guid boardId, [Microsoft.AspNetCore.Mvc.FromServices] IWorkspaceMembershipStore store, ITenantContext ctx, CancellationToken ct) => + { + if (!string.Equals(ctx.TenantId, tenantId, StringComparison.Ordinal)) { return Results.Forbid(); } + var rows = await store.ListAsync(tenantId, boardId, ct).ConfigureAwait(false); + return Results.Ok(rows); + }) + .WithName("TenantsListBoardMembers") + .WithSummary("List a board's members and their board roles (admin only)") + .WithTags("Tenants") + .RequirePermission(Permission.ManageMembers); + + app.MapPut("/tenants/{tenantId}/boards/{boardId:guid}/members/{userId}", async ( + string tenantId, Guid boardId, string userId, SetBoardRoleRequest body, [Microsoft.AspNetCore.Mvc.FromServices] IWorkspaceMembershipStore store, + IKeycloakAdminClient kc, IAuditLog audit, ITenantContext ctx, HttpContext http, CancellationToken ct) => + { + if (!string.Equals(ctx.TenantId, tenantId, StringComparison.Ordinal)) { return Results.Forbid(); } + if (!UserRoles.IsWorkspaceAssignable(body.Role)) + { + return Results.BadRequest(new { error = $"role must be one of: {string.Join(", ", UserRoles.WorkspaceAssignable)}" }); + } + try + { + if (!await UserInTenantAsync(kc, userId, tenantId, ct).ConfigureAwait(false)) { return Results.NotFound(); } + var row = await store.SetAsync(tenantId, boardId, userId, body.Role, ctx.UserId, ct).ConfigureAwait(false); + await audit.WriteAsync(new AuditEntry( + Guid.NewGuid(), tenantId, ctx.UserId, AuditActions.BoardRoleSet, + Target: $"board={boardId},user={userId},role={body.Role}", + IpAddress: http.Connection.RemoteIpAddress?.ToString(), + UserAgent: http.Request.Headers.UserAgent.ToString(), + TimestampUtc: DateTimeOffset.UtcNow), ct).ConfigureAwait(false); + return Results.Ok(row); + } + catch (KeyNotFoundException) + { + return Results.NotFound(); + } + catch (InvalidOperationException ex) + { + return Results.Problem(title: "Keycloak lookup failed", detail: ex.Message, statusCode: StatusCodes.Status502BadGateway); + } + }) + .WithName("TenantsSetBoardRole") + .WithSummary("Give a member a role on one board (admin only)") + .WithTags("Tenants") + .RequirePermission(Permission.ManageMembers); + + app.MapDelete("/tenants/{tenantId}/boards/{boardId:guid}/members/{userId}", async ( + string tenantId, Guid boardId, string userId, [Microsoft.AspNetCore.Mvc.FromServices] IWorkspaceMembershipStore store, IAuditLog audit, + ITenantContext ctx, HttpContext http, CancellationToken ct) => + { + if (!string.Equals(ctx.TenantId, tenantId, StringComparison.Ordinal)) { return Results.Forbid(); } + if (!await store.RemoveAsync(tenantId, boardId, userId, ct).ConfigureAwait(false)) { return Results.NotFound(); } + await audit.WriteAsync(new AuditEntry( + Guid.NewGuid(), tenantId, ctx.UserId, AuditActions.BoardRoleRemoved, + Target: $"board={boardId},user={userId}", + IpAddress: http.Connection.RemoteIpAddress?.ToString(), + UserAgent: http.Request.Headers.UserAgent.ToString(), + TimestampUtc: DateTimeOffset.UtcNow), ct).ConfigureAwait(false); + return Results.NoContent(); + }) + .WithName("TenantsRemoveBoardRole") + .WithSummary("Take a member off one board (admin only)") + .WithTags("Tenants") + .RequirePermission(Permission.ManageMembers); + } + private static readonly string[] AdminRole = new[] { "admin" }; /// DELETE /tenants/{tenantId}/members/{userId}: their paired computers are revoked FIRST, then the account @@ -467,6 +537,10 @@ internal static async Task RemoveMemberAsync( /// on an arbitrary user id — this confirms the target actually belongs to the caller's tenant before a /// re-role / delete / password-reset. Throws if Keycloak is /// unreachable (callers map it to 502, same as the mutating call). + /// The single permissions in , by name (RBAC v2 — what /tenants/me reports). + internal static IReadOnlyList PermissionNames(Permission granted) => + [.. PermissionMatrix.Each.Where(p => granted.Has(p)).Select(p => p.ToString())]; + private static async Task UserInTenantAsync( IKeycloakAdminClient kc, string userId, string tenantId, CancellationToken ct) { @@ -475,6 +549,9 @@ private static async Task UserInTenantAsync( } } +/// Body of PUT /tenants/{tenantId}/boards/{boardId}/members/{userId}. +public sealed record SetBoardRoleRequest(string Role); + /// Response shape for GET /tenants/me. public sealed record TenantMeResponse( string TenantId, @@ -482,7 +559,8 @@ public sealed record TenantMeResponse( string? UserName, IReadOnlyList Roles, bool IsAuthenticated, - bool IsAdmin); + bool IsAdmin, + IReadOnlyList Permissions); /// Body for POST /tenants. public sealed record CreateTenantRequest(string Id, string? Name, string AdminUsername, string? AdminEmail); diff --git a/src/AgentOs.Modules.Tenants/IAuditLog.cs b/src/AgentOs.Modules.Tenants/IAuditLog.cs index ad4b0ddc..4eb84d5a 100644 --- a/src/AgentOs.Modules.Tenants/IAuditLog.cs +++ b/src/AgentOs.Modules.Tenants/IAuditLog.cs @@ -38,6 +38,8 @@ public static class AuditActions public const string MemberInvited = "member.invited"; public const string MemberRoleChanged = "member.role_changed"; public const string MemberRemoved = "member.removed"; + public const string BoardRoleSet = "member.board_role_set"; + public const string BoardRoleRemoved = "member.board_role_removed"; public const string MemberPasswordReset = "member.password_reset"; public const string InvitationMinted = "invitation.minted"; public const string LoginFailed = "login.failed"; diff --git a/src/AgentOs.Modules.Tenants/Keycloak/IKeycloakAdminClient.cs b/src/AgentOs.Modules.Tenants/Keycloak/IKeycloakAdminClient.cs index aa12e430..815f40ee 100644 --- a/src/AgentOs.Modules.Tenants/Keycloak/IKeycloakAdminClient.cs +++ b/src/AgentOs.Modules.Tenants/Keycloak/IKeycloakAdminClient.cs @@ -32,8 +32,9 @@ Task CreateUserAsync( /// need a server-side search rewrite — call out the limit in the response if you display it. Task> ListUsersByTenantAsync(string tenantId, int max = 200, CancellationToken ct = default); - /// Set a member's realm roles to exactly (managed set: - /// admin + member). Diffs against the user's current mappings — grants the missing + /// Set a member's realm roles to exactly (managed set: the RBAC v2 roles + /// viewer/developer/approver/auditor/admin + the legacy member; a missing + /// managed realm role is created on first use). Diffs against the user's current mappings — grants the missing /// ones, revokes the managed ones no longer desired, leaves unrelated roles untouched. Throws /// on a non-success response. Task UpdateUserRolesAsync(string userId, IReadOnlyList roles, CancellationToken ct = default); diff --git a/src/AgentOs.Modules.Tenants/Keycloak/KeycloakAdminClient.cs b/src/AgentOs.Modules.Tenants/Keycloak/KeycloakAdminClient.cs index 3efc6074..112a4bf3 100644 --- a/src/AgentOs.Modules.Tenants/Keycloak/KeycloakAdminClient.cs +++ b/src/AgentOs.Modules.Tenants/Keycloak/KeycloakAdminClient.cs @@ -15,6 +15,7 @@ using AgentOs.SharedKernel.Logging; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using AgentOs.SharedKernel.Identity; namespace AgentOs.Modules.Tenants.Keycloak; @@ -107,14 +108,7 @@ public async Task CreateUserAsync( var roleMappings = new List(realmRoles.Count); foreach (var roleName in realmRoles) { - using var roleReq = BuildRequest(HttpMethod.Get, $"admin/realms/{_options.Realm}/roles/{Uri.EscapeDataString(roleName)}", token); - using var roleResp = await _http.SendAsync(roleReq, ct).ConfigureAwait(false); - if (!roleResp.IsSuccessStatusCode) - { - _logger.LogWarning("Keycloak role {Role} lookup failed: {Status}", LogSafe.Scrub(roleName), roleResp.StatusCode); - continue; - } - var roleJson = await roleResp.Content.ReadFromJsonAsync(ct).ConfigureAwait(false); + var roleJson = await ResolveRoleAsync(roleName, token, ct).ConfigureAwait(false); if (roleJson is null) { continue; @@ -256,14 +250,7 @@ public async Task UpdateUserRolesAsync(string userId, IReadOnlyList role var toAdd = new List(); foreach (var roleName in desired.Where(d => !currentNames.Contains(d))) { - using var roleReq = BuildRequest(HttpMethod.Get, $"admin/realms/{_options.Realm}/roles/{Uri.EscapeDataString(roleName)}", token); - using var roleResp = await _http.SendAsync(roleReq, ct).ConfigureAwait(false); - if (!roleResp.IsSuccessStatusCode) - { - _logger.LogWarning("Keycloak role {Role} lookup failed: {Status}", roleName, roleResp.StatusCode); - continue; - } - var dto = await roleResp.Content.ReadFromJsonAsync(ct).ConfigureAwait(false); + var dto = await ResolveRoleAsync(roleName, token, ct).ConfigureAwait(false); if (dto is not null) { toAdd.Add(new { id = dto.Id, name = dto.Name }); } } if (toAdd.Count > 0) @@ -279,6 +266,56 @@ public async Task UpdateUserRolesAsync(string userId, IReadOnlyList role } } + // A realm imported before RBAC v2 (E1.2) lacks viewer/developer/approver/auditor — an existing realm is never + // re-imported. Assigning one of OUR managed roles therefore creates it on first use (idempotent: 409 = a concurrent + // create won), so a lab / prod realm self-heals without a manual step. Any other missing role is only logged. + private async Task ResolveRoleAsync(string roleName, string token, CancellationToken ct) + { + var path = $"admin/realms/{_options.Realm}/roles/{Uri.EscapeDataString(roleName)}"; + using (var roleReq = BuildRequest(HttpMethod.Get, path, token)) + using (var roleResp = await _http.SendAsync(roleReq, ct).ConfigureAwait(false)) + { + if (roleResp.IsSuccessStatusCode) + { + return await roleResp.Content.ReadFromJsonAsync(ct).ConfigureAwait(false); + } + if (roleResp.StatusCode != System.Net.HttpStatusCode.NotFound || !ManagedRoles.Contains(roleName, StringComparer.Ordinal)) + { + _logger.LogWarning("Keycloak role {Role} lookup failed: {Status}", LogSafe.Scrub(roleName), roleResp.StatusCode); + return null; + } + } + + using (var create = BuildRequest(HttpMethod.Post, $"admin/realms/{_options.Realm}/roles", token, + new { name = roleName, description = RoleDescription(roleName) })) + using (var createResp = await _http.SendAsync(create, ct).ConfigureAwait(false)) + { + if (!createResp.IsSuccessStatusCode && createResp.StatusCode != System.Net.HttpStatusCode.Conflict) + { + _logger.LogWarning("Keycloak role {Role} could not be created: {Status}", LogSafe.Scrub(roleName), createResp.StatusCode); + return null; + } + } + _logger.LogInformation("Keycloak realm role {Role} created (RBAC v2)", LogSafe.Scrub(roleName)); + + using var again = BuildRequest(HttpMethod.Get, path, token); + using var againResp = await _http.SendAsync(again, ct).ConfigureAwait(false); + return againResp.IsSuccessStatusCode + ? await againResp.Content.ReadFromJsonAsync(ct).ConfigureAwait(false) + : null; + } + + // ASCII only: a non-ASCII description made the Keycloak admin API return 400 (CLAUDE.md). + internal static string RoleDescription(string role) => role switch + { + UserRoles.Viewer => "Read-only access to the tenant's work", + UserRoles.Developer => "Runs agents and works tickets", + UserRoles.Approver => "Decides design checks and approvals", + UserRoles.Auditor => "Read-only audit log and evidence", + UserRoles.Admin => "Tenant administrator", + _ => "AgentOS.NET role", + }; + /// public async Task SendPasswordResetEmailAsync(string userId, CancellationToken ct = default) { @@ -411,7 +448,8 @@ private static HttpRequestMessage BuildRequest(HttpMethod method, string path, s private static readonly string[] InviteActions = new[] { "UPDATE_PASSWORD", "VERIFY_EMAIL" }; private static readonly string[] VerifyOnlyActions = new[] { "VERIFY_EMAIL" }; private static readonly string[] VerifyOnlyResetActions = new[] { "UPDATE_PASSWORD" }; - private static readonly string[] ManagedRoles = new[] { "admin", "member" }; + // RBAC v2: the five roles + the legacy `member` alias — setting a user's roles revokes the managed ones not chosen. + private static readonly IReadOnlyList ManagedRoles = UserRoles.Managed; private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web) { diff --git a/src/AgentOs.Modules.Tenants/MemberRoles.cs b/src/AgentOs.Modules.Tenants/MemberRoles.cs new file mode 100644 index 00000000..b9ae9ba7 --- /dev/null +++ b/src/AgentOs.Modules.Tenants/MemberRoles.cs @@ -0,0 +1,55 @@ +// RBAC v2 (E1.2) — the role rules member management shares (HTTP endpoints AND the desktop Users app), so the two +// paths can't drift: which roles may be assigned, the lock-out guard, and which role a member "is" in the UI. + +using System; +using System.Collections.Generic; +using System.Linq; +using AgentOs.SharedKernel.Identity; + +namespace AgentOs.Modules.Tenants; + +/// Validation + display rules for a member's realm roles. +public static class MemberRoles +{ + /// The role a new member gets when none is given. + public const string DefaultRole = UserRoles.Developer; + + // Most to least privileged — the role a member is shown as in the Users list. + private static readonly string[] Precedence = + [UserRoles.Admin, UserRoles.Auditor, UserRoles.Approver, UserRoles.Developer, UserRoles.LegacyMember, UserRoles.Viewer]; + + /// True for a role an invitation / role change may carry (the five RBAC v2 roles, plus the legacy + /// member alias so pre-E1.2 API clients keep working). + public static bool IsAllowed(string? role) => UserRoles.IsAssignable(role) || role == UserRoles.LegacyMember; + + /// The allowed roles from , de-duplicated, in the given order. + public static IReadOnlyList Sanitize(IEnumerable? roles) => + roles is null ? [] : [.. roles.Where(IsAllowed).Distinct(StringComparer.Ordinal)]; + + /// Why a role change can't be applied, or null when it can. + /// The admin making the change. + /// The member whose roles change. + /// The sanitized new roles. + public static string? Check(string? actorUserId, string targetUserId, IReadOnlyList roles) + { + ArgumentNullException.ThrowIfNull(roles); + if (roles.Count == 0) + { + return $"roles must contain at least one of: {string.Join(", ", UserRoles.Assignable)}"; + } + // Lock-out guard: an admin editing themselves must keep the admin role. + if (string.Equals(actorUserId, targetUserId, StringComparison.Ordinal) && !roles.Contains(UserRoles.Admin, StringComparer.Ordinal)) + { + return "You cannot remove your own admin role."; + } + return null; + } + + /// The most privileged managed role the member holds (what the Users list shows), or null. + public static string? Primary(IEnumerable roles) + { + ArgumentNullException.ThrowIfNull(roles); + var held = roles as ICollection ?? [.. roles]; + return Array.Find(Precedence, held.Contains); + } +} diff --git a/src/AgentOs.Modules.Workspaces/Access/WorkspaceMemberships.cs b/src/AgentOs.Modules.Workspaces/Access/WorkspaceMemberships.cs new file mode 100644 index 00000000..27bcd1f9 --- /dev/null +++ b/src/AgentOs.Modules.Workspaces/Access/WorkspaceMemberships.cs @@ -0,0 +1,161 @@ +// RBAC v2 (E1.2) — per-board (workspace) membership. IWorkspaceMembershipStore persists who holds which role on which +// board; IWorkspaceAccess turns a user's realm roles + those rows into the permissions they hold on each board via the +// single matrix (PermissionMatrix.ForWorkspace). Every method is tenant-explicit (a Blazor circuit has no +// ITenantContext); the EF store adds an explicit TenantId predicate on top of the global filter, and RLS binds the +// connection to the ambient tenant as the second wall. + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using AgentOs.Modules.Workspaces.Persistence; +using AgentOs.Modules.Workspaces.Persistence.Entities; +using AgentOs.SharedKernel.Identity; +using Microsoft.EntityFrameworkCore; + +namespace AgentOs.Modules.Workspaces.Access; + +/// Persistence of board memberships, tenant-explicit. +public interface IWorkspaceMembershipStore +{ + /// Every membership in the tenant (all boards), for computing a user's access to many boards in one read. + Task> ListForTenantAsync(string tenantId, CancellationToken ct = default); + + /// The memberships of one board. + Task> ListAsync(string tenantId, Guid workspaceId, CancellationToken ct = default); + + /// Grant on a board (insert or replace). Throws for a + /// role a membership can't carry. + Task SetAsync(string tenantId, Guid workspaceId, string userId, string role, string? actorUserId, CancellationToken ct = default); + + /// Remove a membership. False when there was none. + Task RemoveAsync(string tenantId, Guid workspaceId, string userId, CancellationToken ct = default); +} + +internal sealed class WorkspaceAccess(IWorkspaceMembershipStore store) : IWorkspaceAccess +{ + public async Task ForUserAsync(string tenantId, IEnumerable roles, string? userId, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(roles); + var materialised = roles as IReadOnlyCollection ?? [.. roles]; + // An empty tenant (a token with no tenant claim) reads nothing; callers refuse an empty tenant before this. + var rows = string.IsNullOrWhiteSpace(tenantId) ? [] : await store.ListForTenantAsync(tenantId, ct).ConfigureAwait(false); + return WorkspaceAccessMap.Build(materialised, userId, rows); + } +} + +internal static class WorkspaceMemberMapping +{ + public static WorkspaceMember ToRecord(WorkspaceMemberEntity e) => new(e.WorkspaceId, e.UserId, e.Role, e.AddedByUserId, e.AddedAtUtc); + + public static void Validate(string tenantId, string userId, string role) + { + ArgumentException.ThrowIfNullOrWhiteSpace(tenantId); + ArgumentException.ThrowIfNullOrWhiteSpace(userId); + if (!UserRoles.IsWorkspaceAssignable(role)) + { + throw new ArgumentException( + $"A board role must be one of: {string.Join(", ", UserRoles.WorkspaceAssignable)}.", nameof(role)); + } + if (userId.Length > 64) { throw new ArgumentException("User id is too long.", nameof(userId)); } + } +} + +internal sealed class EfWorkspaceMembershipStore(WorkspacesDbContext db, TimeProvider clock) : IWorkspaceMembershipStore +{ + public async Task> ListForTenantAsync(string tenantId, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(tenantId); + var rows = await db.WorkspaceMembers.IgnoreQueryFilters().AsNoTracking() + .Where(x => x.TenantId == tenantId).ToListAsync(ct).ConfigureAwait(false); + return rows.Select(WorkspaceMemberMapping.ToRecord).ToList(); + } + + public async Task> ListAsync(string tenantId, Guid workspaceId, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(tenantId); + var rows = await db.WorkspaceMembers.IgnoreQueryFilters().AsNoTracking() + .Where(x => x.TenantId == tenantId && x.WorkspaceId == workspaceId) + .OrderBy(x => x.AddedAtUtc).ToListAsync(ct).ConfigureAwait(false); + return rows.Select(WorkspaceMemberMapping.ToRecord).ToList(); + } + + public async Task SetAsync(string tenantId, Guid workspaceId, string userId, string role, string? actorUserId, CancellationToken ct = default) + { + WorkspaceMemberMapping.Validate(tenantId, userId, role); + // The board must exist IN THIS TENANT — never attach a membership to another tenant's board id. + var boardExists = await db.Workspaces.IgnoreQueryFilters().AsNoTracking() + .AnyAsync(w => w.TenantId == tenantId && w.Id == workspaceId, ct).ConfigureAwait(false); + if (!boardExists) { throw new KeyNotFoundException("No such board in this workspace."); } + + var row = await db.WorkspaceMembers.IgnoreQueryFilters() + .FirstOrDefaultAsync(x => x.TenantId == tenantId && x.WorkspaceId == workspaceId && x.UserId == userId, ct) + .ConfigureAwait(false); + if (row is null) + { + var now = clock.GetUtcNow(); + row = new WorkspaceMemberEntity + { + Id = Guid.CreateVersion7(now), TenantId = tenantId, WorkspaceId = workspaceId, UserId = userId, + Role = role, AddedByUserId = actorUserId is { Length: <= 64 } ? actorUserId : null, AddedAtUtc = now, + }; + db.WorkspaceMembers.Add(row); + } + else + { + row.Role = role; + } + await db.SaveChangesAsync(ct).ConfigureAwait(false); + return WorkspaceMemberMapping.ToRecord(row); + } + + public async Task RemoveAsync(string tenantId, Guid workspaceId, string userId, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(tenantId); + var row = await db.WorkspaceMembers.IgnoreQueryFilters() + .FirstOrDefaultAsync(x => x.TenantId == tenantId && x.WorkspaceId == workspaceId && x.UserId == userId, ct) + .ConfigureAwait(false); + if (row is null) { return false; } + db.WorkspaceMembers.Remove(row); + await db.SaveChangesAsync(ct).ConfigureAwait(false); + return true; + } +} + +/// Process-local store for the stateless standalone Web (no connection string) — same semantics. +internal sealed class InMemoryWorkspaceMembershipStore(TimeProvider clock) : IWorkspaceMembershipStore +{ + private readonly ConcurrentDictionary<(string Tenant, Guid Board, string User), WorkspaceMember> _rows = new(); + + public Task> ListForTenantAsync(string tenantId, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(tenantId); + IReadOnlyList rows = [.. _rows.Where(kv => kv.Key.Tenant == tenantId).Select(kv => kv.Value)]; + return Task.FromResult(rows); + } + + public Task> ListAsync(string tenantId, Guid workspaceId, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(tenantId); + IReadOnlyList rows = + [.. _rows.Where(kv => kv.Key.Tenant == tenantId && kv.Key.Board == workspaceId).Select(kv => kv.Value).OrderBy(m => m.AddedAtUtc)]; + return Task.FromResult(rows); + } + + public Task SetAsync(string tenantId, Guid workspaceId, string userId, string role, string? actorUserId, CancellationToken ct = default) + { + WorkspaceMemberMapping.Validate(tenantId, userId, role); + var row = _rows.AddOrUpdate((tenantId, workspaceId, userId), + _ => new WorkspaceMember(workspaceId, userId, role, actorUserId, clock.GetUtcNow()), + (_, existing) => existing with { Role = role }); + return Task.FromResult(row); + } + + public Task RemoveAsync(string tenantId, Guid workspaceId, string userId, CancellationToken ct = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(tenantId); + return Task.FromResult(_rows.TryRemove((tenantId, workspaceId, userId), out _)); + } +} diff --git a/src/AgentOs.Modules.Workspaces/Endpoints/WorkspaceEndpoints.cs b/src/AgentOs.Modules.Workspaces/Endpoints/WorkspaceEndpoints.cs index 3e906fa2..8b1e1cd8 100644 --- a/src/AgentOs.Modules.Workspaces/Endpoints/WorkspaceEndpoints.cs +++ b/src/AgentOs.Modules.Workspaces/Endpoints/WorkspaceEndpoints.cs @@ -1,7 +1,7 @@ // M2 / board reshape — Workspaces HTTP endpoints. Connect a GitHub Projects v2 board (or, later, an // ADO board) as a workspace, list/get/remove boards, manage the repos under a board, list connectable -// repos/boards for a token, and read a repo's context to ground the Requirement agent. Auth: Member -// policy; tenant resolved from the token by ITenantContext. +// repos/boards for a token, and read a repo's context to ground the Requirement agent. Auth: RBAC v2 permissions +// (ViewWork to read, ManageWorkspaces to change) + per-board memberships; tenant resolved by ITenantContext. // // Secret handling: the access token is validated, then stored ONLY in the encrypted AppConfig store // under the board's CredentialRef. It is never written to a row and never returned in any DTO. @@ -30,24 +30,30 @@ public static void MapWorkspaceEndpoints(this IEndpointRouteBuilder endpoints) { ArgumentNullException.ThrowIfNull(endpoints); - var group = endpoints.MapGroup("/workspaces").RequireAuthorization("Member"); + // RBAC v2 (E1.2): reads need ViewWork, changing boards/repos ManageWorkspaces; every {id} route is re-checked + // against that board's memberships (a restricted board is 404 to an outsider). + var group = endpoints.MapGroup("/workspaces").RequireAuthorization("Member") + .RequireWorkspacePermission("id", Permission.ManageWorkspaces); group.MapGet(string.Empty, ListAsync); group.MapGet("/{id:guid}", GetAsync); - group.MapPost(string.Empty, ConnectAsync); - group.MapDelete("/{id:guid}", RemoveAsync); - group.MapPost("/repos", ListReposForTokenAsync); - group.MapPost("/boards", ListBoardsForTokenAsync); + group.MapPost(string.Empty, ConnectAsync).RequirePermission(Permission.ManageWorkspaces); + group.MapDelete("/{id:guid}", RemoveAsync).RequirePermission(Permission.ManageWorkspaces); + group.MapPost("/repos", ListReposForTokenAsync).RequirePermission(Permission.ManageWorkspaces); + group.MapPost("/boards", ListBoardsForTokenAsync).RequirePermission(Permission.ManageWorkspaces); group.MapGet("/{id:guid}/repos", ListBoardReposAsync); - group.MapPost("/{id:guid}/repos", AddRepoAsync); - group.MapDelete("/{id:guid}/repos/{repoId:guid}", RemoveRepoAsync); + group.MapPost("/{id:guid}/repos", AddRepoAsync).RequirePermission(Permission.ManageWorkspaces); + group.MapDelete("/{id:guid}/repos/{repoId:guid}", RemoveRepoAsync).RequirePermission(Permission.ManageWorkspaces); group.MapGet("/{id:guid}/context", ContextAsync); } - private static async Task ListAsync(IWorkspaceRepository repo, CancellationToken ct, int? limit = null, int? offset = null) + private static async Task ListAsync( + IWorkspaceRepository repo, IWorkspaceAccess access, ITenantContext tenant, System.Security.Claims.ClaimsPrincipal user, + CancellationToken ct, int? limit = null, int? offset = null) { var rows = await repo.ListAsync(limit ?? Page.DefaultLimit, offset ?? 0, ct).ConfigureAwait(false); - return Results.Ok(rows.Select(WorkspaceDto.From).ToList()); + var map = await access.ForUserAsync(tenant.TenantId, user, ct).ConfigureAwait(false); + return Results.Ok(rows.Where(r => map.CanSee(r.Id)).Select(WorkspaceDto.From).ToList()); } private static async Task GetAsync(Guid id, IWorkspaceRepository repo, CancellationToken ct) diff --git a/src/AgentOs.Modules.Workspaces/Persistence/Entities/WorkspaceMemberEntity.cs b/src/AgentOs.Modules.Workspaces/Persistence/Entities/WorkspaceMemberEntity.cs new file mode 100644 index 00000000..31d19546 --- /dev/null +++ b/src/AgentOs.Modules.Workspaces/Persistence/Entities/WorkspaceMemberEntity.cs @@ -0,0 +1,23 @@ +// RBAC v2 (E1.2) — a member's role on one board (workspace). A board with no rows here is open (tenant roles apply); +// the first row makes it restricted (see PermissionMatrix.ForWorkspace). One row per (tenant, board, user). + +using System; + +namespace AgentOs.Modules.Workspaces.Persistence.Entities; + +/// A user's role on one board (workspace). Tenant-stamped; one row per (tenant, board, user). +public sealed class WorkspaceMemberEntity +{ + public Guid Id { get; set; } + public string TenantId { get; set; } = string.Empty; + public Guid WorkspaceId { get; set; } + + /// The member's stable user id (token sub). + public string UserId { get; set; } = string.Empty; + + /// A workspace-assignable role (viewer, developer, approver). + public string Role { get; set; } = string.Empty; + + public string? AddedByUserId { get; set; } + public DateTimeOffset AddedAtUtc { get; set; } +} diff --git a/src/AgentOs.Modules.Workspaces/Persistence/Migrations/20261103133324_AddWorkspaceMembers.Designer.cs b/src/AgentOs.Modules.Workspaces/Persistence/Migrations/20261103133324_AddWorkspaceMembers.Designer.cs new file mode 100644 index 00000000..5c5fcd42 --- /dev/null +++ b/src/AgentOs.Modules.Workspaces/Persistence/Migrations/20261103133324_AddWorkspaceMembers.Designer.cs @@ -0,0 +1,308 @@ +// +using System; +using AgentOs.Modules.Workspaces.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace AgentOs.Modules.Workspaces.Persistence.Migrations +{ + [DbContext(typeof(WorkspacesDbContext))] + [Migration("20261103133324_AddWorkspaceMembers")] + partial class AddWorkspaceMembers + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasDefaultSchema("workspaces") + .HasAnnotation("ProductVersion", "10.0.14") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("AgentOs.Modules.Workspaces.Persistence.Entities.AutopilotEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("BoardId") + .HasColumnType("uuid"); + + b.Property("TenantId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.HasKey("Id"); + + b.HasIndex("TenantId", "BoardId", "AtUtc"); + + b.ToTable("autopilot_events", "workspaces"); + }); + + modelBuilder.Entity("AgentOs.Modules.Workspaces.Persistence.Entities.TicketFlowVersionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BoardId") + .HasColumnType("uuid"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByName") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("CreatedByUserId") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("DefinitionJson") + .HasMaxLength(64000) + .HasColumnType("character varying(64000)"); + + b.Property("Note") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("TenantId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("TenantId", "Version") + .IsUnique(); + + b.HasIndex("TenantId", "BoardId", "Version"); + + b.ToTable("ticket_flows", "workspaces"); + }); + + modelBuilder.Entity("AgentOs.Modules.Workspaces.Persistence.Entities.WorkspaceEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Autopilot") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(16) + .HasColumnType("character varying(16)") + .HasDefaultValue("Off"); + + b.Property("AutopilotUserId") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByUserId") + .HasColumnType("text"); + + b.Property("CredentialRef") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("DefaultBranch") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Owner") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Project") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ProjectNodeId") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ProjectNumber") + .HasColumnType("integer"); + + b.Property("ProjectOwner") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ProjectScope") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("RemoteUrl") + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("Repo") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("TenantId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("Autopilot"); + + b.HasIndex("TenantId", "CreatedAtUtc"); + + b.ToTable("workspaces", "workspaces"); + }); + + modelBuilder.Entity("AgentOs.Modules.Workspaces.Persistence.Entities.WorkspaceMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AddedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("AddedByUserId") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("TenantId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("WorkspaceId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("WorkspaceId"); + + b.HasIndex("TenantId", "UserId"); + + b.HasIndex("TenantId", "WorkspaceId", "UserId") + .IsUnique(); + + b.ToTable("workspace_members", "workspaces"); + }); + + modelBuilder.Entity("AgentOs.Modules.Workspaces.Persistence.Entities.WorkspaceRepoEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AddedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("DefaultBranch") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Owner") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Private") + .HasColumnType("boolean"); + + b.Property("RemoteUrl") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("character varying(2048)"); + + b.Property("Repo") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("TenantId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("WorkspaceId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("WorkspaceId"); + + b.HasIndex("TenantId", "WorkspaceId"); + + b.ToTable("workspace_repos", "workspaces"); + }); + + modelBuilder.Entity("AgentOs.Modules.Workspaces.Persistence.Entities.WorkspaceMemberEntity", b => + { + b.HasOne("AgentOs.Modules.Workspaces.Persistence.Entities.WorkspaceEntity", null) + .WithMany() + .HasForeignKey("WorkspaceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AgentOs.Modules.Workspaces.Persistence.Entities.WorkspaceRepoEntity", b => + { + b.HasOne("AgentOs.Modules.Workspaces.Persistence.Entities.WorkspaceEntity", null) + .WithMany() + .HasForeignKey("WorkspaceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/AgentOs.Modules.Workspaces/Persistence/Migrations/20261103133324_AddWorkspaceMembers.cs b/src/AgentOs.Modules.Workspaces/Persistence/Migrations/20261103133324_AddWorkspaceMembers.cs new file mode 100644 index 00000000..1b5562fa --- /dev/null +++ b/src/AgentOs.Modules.Workspaces/Persistence/Migrations/20261103133324_AddWorkspaceMembers.cs @@ -0,0 +1,67 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace AgentOs.Modules.Workspaces.Persistence.Migrations +{ + /// + public partial class AddWorkspaceMembers : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "workspace_members", + schema: "workspaces", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + TenantId = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + WorkspaceId = table.Column(type: "uuid", nullable: false), + UserId = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Role = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + AddedByUserId = table.Column(type: "character varying(64)", maxLength: 64, nullable: true), + AddedAtUtc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_workspace_members", x => x.Id); + table.ForeignKey( + name: "FK_workspace_members_workspaces_WorkspaceId", + column: x => x.WorkspaceId, + principalSchema: "workspaces", + principalTable: "workspaces", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_workspace_members_TenantId_UserId", + schema: "workspaces", + table: "workspace_members", + columns: new[] { "TenantId", "UserId" }); + + migrationBuilder.CreateIndex( + name: "IX_workspace_members_TenantId_WorkspaceId_UserId", + schema: "workspaces", + table: "workspace_members", + columns: new[] { "TenantId", "WorkspaceId", "UserId" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_workspace_members_WorkspaceId", + schema: "workspaces", + table: "workspace_members", + column: "WorkspaceId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "workspace_members", + schema: "workspaces"); + } + } +} diff --git a/src/AgentOs.Modules.Workspaces/Persistence/Migrations/WorkspacesDbContextModelSnapshot.cs b/src/AgentOs.Modules.Workspaces/Persistence/Migrations/WorkspacesDbContextModelSnapshot.cs index fa7edab2..db2f7be4 100644 --- a/src/AgentOs.Modules.Workspaces/Persistence/Migrations/WorkspacesDbContextModelSnapshot.cs +++ b/src/AgentOs.Modules.Workspaces/Persistence/Migrations/WorkspacesDbContextModelSnapshot.cs @@ -18,7 +18,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) #pragma warning disable 612, 618 modelBuilder .HasDefaultSchema("workspaces") - .HasAnnotation("ProductVersion", "10.0.13") + .HasAnnotation("ProductVersion", "10.0.14") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); @@ -190,6 +190,49 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("workspaces", "workspaces"); }); + modelBuilder.Entity("AgentOs.Modules.Workspaces.Persistence.Entities.WorkspaceMemberEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AddedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("AddedByUserId") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("TenantId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("UserId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("WorkspaceId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("WorkspaceId"); + + b.HasIndex("TenantId", "UserId"); + + b.HasIndex("TenantId", "WorkspaceId", "UserId") + .IsUnique(); + + b.ToTable("workspace_members", "workspaces"); + }); + modelBuilder.Entity("AgentOs.Modules.Workspaces.Persistence.Entities.WorkspaceRepoEntity", b => { b.Property("Id") @@ -239,6 +282,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("workspace_repos", "workspaces"); }); + modelBuilder.Entity("AgentOs.Modules.Workspaces.Persistence.Entities.WorkspaceMemberEntity", b => + { + b.HasOne("AgentOs.Modules.Workspaces.Persistence.Entities.WorkspaceEntity", null) + .WithMany() + .HasForeignKey("WorkspaceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("AgentOs.Modules.Workspaces.Persistence.Entities.WorkspaceRepoEntity", b => { b.HasOne("AgentOs.Modules.Workspaces.Persistence.Entities.WorkspaceEntity", null) diff --git a/src/AgentOs.Modules.Workspaces/Persistence/WorkspacesDbContext.cs b/src/AgentOs.Modules.Workspaces/Persistence/WorkspacesDbContext.cs index 7d8481cd..1a6e7a2c 100644 --- a/src/AgentOs.Modules.Workspaces/Persistence/WorkspacesDbContext.cs +++ b/src/AgentOs.Modules.Workspaces/Persistence/WorkspacesDbContext.cs @@ -32,11 +32,33 @@ public WorkspacesDbContext(DbContextOptions options, ITenan public DbSet TicketFlows => Set(); + public DbSet WorkspaceMembers => Set(); + protected override void OnModelCreating(ModelBuilder modelBuilder) { ArgumentNullException.ThrowIfNull(modelBuilder); modelBuilder.HasDefaultSchema("workspaces"); + // RBAC v2 (E1.2): a member's role per board. Rows cascade with their board. + modelBuilder.Entity(e => + { + e.ToTable("workspace_members"); + e.HasKey(x => x.Id); + e.Property(x => x.TenantId).IsRequired().HasMaxLength(64); + e.Property(x => x.WorkspaceId).IsRequired(); + e.Property(x => x.UserId).IsRequired().HasMaxLength(64); + e.Property(x => x.Role).IsRequired().HasMaxLength(32); + e.Property(x => x.AddedByUserId).HasMaxLength(64); + e.Property(x => x.AddedAtUtc).IsRequired(); + e.HasIndex(x => new { x.TenantId, x.WorkspaceId, x.UserId }).IsUnique(); + e.HasIndex(x => new { x.TenantId, x.UserId }); + e.HasQueryFilter(x => x.TenantId == (_tenant != null ? _tenant.TenantId : null)); + e.HasOne() + .WithMany() + .HasForeignKey(x => x.WorkspaceId) + .OnDelete(DeleteBehavior.Cascade); + }); + // Ticket flows (ADR-0014): append-only versions; BoardId = Guid.Empty is the tenant's default flow. modelBuilder.Entity(e => { diff --git a/src/AgentOs.Modules.Workspaces/WorkspacesModule.cs b/src/AgentOs.Modules.Workspaces/WorkspacesModule.cs index 79dc95bc..7fcdfa8e 100644 --- a/src/AgentOs.Modules.Workspaces/WorkspacesModule.cs +++ b/src/AgentOs.Modules.Workspaces/WorkspacesModule.cs @@ -38,6 +38,8 @@ public void AddServices(IServiceCollection services, IConfiguration configuratio services.AddScoped(); // A board's repositories for agents that see the whole board (the Autopilot lead reads their practices). services.AddScoped(); + // RBAC v2 (E1.2): a user's permissions per board (realm roles + board memberships through PermissionMatrix). + services.AddScoped(); var connectionString = configuration.GetConnectionString("DefaultConnection"); if (!string.IsNullOrWhiteSpace(connectionString)) @@ -49,6 +51,7 @@ public void AddServices(IServiceCollection services, IConfiguration configuratio services.AddNpgsqlConnectionFactory(connectionString); services.AddScoped(); services.AddScoped(); + services.AddScoped(); } else { @@ -63,6 +66,8 @@ public void AddServices(IServiceCollection services, IConfiguration configuratio services.AddSingleton(); // The standalone Web keeps ticket flows in memory, so the Workflow › Ticket flow editor saves and reverts. services.AddSingleton(); + // Board memberships (RBAC v2) likewise live in memory, so Users › Board access works standalone. + services.AddSingleton(); } } diff --git a/src/AgentOs.SharedKernel/Identity/IRoleClaimMapper.cs b/src/AgentOs.SharedKernel/Identity/IRoleClaimMapper.cs new file mode 100644 index 00000000..837ae9fe --- /dev/null +++ b/src/AgentOs.SharedKernel/Identity/IRoleClaimMapper.cs @@ -0,0 +1,18 @@ +// RBAC v2 (E1.2) — the group / claim → role mapping hook. Every authenticated request runs the registered mappers +// (Identity module's RoleClaimsTransformation) and adds the roles they return as ClaimTypes.Role claims, so the +// permission matrix sees them like realm roles. E1.1 (corporate SSO) registers a mapper that turns IdP groups +// (Entra ID / Okta group claims) into AgentOS.NET roles; nothing else in the RBAC stack has to change. + +using System.Collections.Generic; +using System.Security.Claims; + +namespace AgentOs.SharedKernel.Identity; + +/// Maps claims on a signed-in principal (IdP groups, legacy roles) onto AgentOS.NET roles. +/// Implementations are singletons and run on every authenticated request: keep them allocation-light and +/// side-effect free. Return only canonical role names (); unknown names grant nothing. +public interface IRoleClaimMapper +{ + /// The extra roles should hold. May return roles it already holds. + IEnumerable MapRoles(ClaimsPrincipal user); +} diff --git a/src/AgentOs.SharedKernel/Identity/Permission.cs b/src/AgentOs.SharedKernel/Identity/Permission.cs new file mode 100644 index 00000000..7b5599b8 --- /dev/null +++ b/src/AgentOs.SharedKernel/Identity/Permission.cs @@ -0,0 +1,45 @@ +// RBAC v2 (E1.2) — the permissions AgentOS.NET checks. A [Flags] set so a user's effective grant is one +// long: the role → permission lookup is a FrozenDictionary hit per role claim, the check is a single AND. +// The matrix that maps roles onto these lives in exactly one place: PermissionMatrix. + +using System; + +namespace AgentOs.SharedKernel.Identity; + +/// A capability an endpoint or a desktop app requires. Roles grant sets of these +/// (); a user's grant is the union over their roles. +[Flags] +[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix", + Justification = "Permission is the domain term (RBAC); not a System.Security permission type.")] +public enum Permission : long +{ + /// No permission. + None = 0, + + /// Read boards, tickets, tasks, runs, insights, files and the run log. + ViewWork = 1L << 0, + + /// Start and stop agent runs, create and edit tickets and tasks, pair a runner, upload ticket files. + RunAgents = 1L << 1, + + /// Decide human gates: design checks, review steps, plan / diff / PR approvals (E1.5 policies). + ApproveWork = 1L << 2, + + /// Connect and remove boards and their repositories, switch Autopilot, edit ticket flows. + ManageWorkspaces = 1L << 3, + + /// Invite and remove members, change their roles and their board (workspace) memberships. + ManageMembers = 1L << 4, + + /// Tenant settings: model keys, agent profiles, prompts, tool policy, MCP servers. + ManageSettings = 1L << 5, + + /// Create and revoke API tokens (service accounts). + ManageApiTokens = 1L << 6, + + /// Read the audit log and the tool-invocation evidence trail (and export the audit CSV). + ViewAudit = 1L << 7, + + /// Export the tenant's data (Settings → Data) and the cost CSV. + ExportData = 1L << 8, +} diff --git a/src/AgentOs.SharedKernel/Identity/PermissionEndpointExtensions.cs b/src/AgentOs.SharedKernel/Identity/PermissionEndpointExtensions.cs new file mode 100644 index 00000000..1523cf89 --- /dev/null +++ b/src/AgentOs.SharedKernel/Identity/PermissionEndpointExtensions.cs @@ -0,0 +1,20 @@ +// RBAC v2 (E1.2) — endpoint convention: `.RequirePermission(Permission.RunAgents)` attaches the "perm:" +// policy the Identity module registers. Lives in SharedKernel so a module can gate its routes without referencing the +// Identity module. + +using System; +using Microsoft.AspNetCore.Builder; + +namespace AgentOs.SharedKernel.Identity; + +/// Attach a permission policy from to endpoints. +public static class PermissionEndpointExtensions +{ + /// Require (tenant scope) for the endpoint(s). + public static TBuilder RequirePermission(this TBuilder builder, Permission permission) + where TBuilder : IEndpointConventionBuilder + { + ArgumentNullException.ThrowIfNull(builder); + return builder.RequireAuthorization(PermissionMatrix.Policy(permission)); + } +} diff --git a/src/AgentOs.SharedKernel/Identity/PermissionMatrix.cs b/src/AgentOs.SharedKernel/Identity/PermissionMatrix.cs new file mode 100644 index 00000000..e8aa1f4b --- /dev/null +++ b/src/AgentOs.SharedKernel/Identity/PermissionMatrix.cs @@ -0,0 +1,215 @@ +// RBAC v2 (E1.2) — THE permission matrix. One place maps every role onto its permissions; endpoints (via the +// "perm:" authorization policies), desktop apps (AppCatalog / WindowHost / in-app buttons) and services +// (re-checks below the UI, GAP-17) all ask this class, never a role name. Changing what a role may do is a one-line +// edit here, covered by the every-role × every-permission test (PermissionMatrixTests). +// +// Roles (Keycloak realm roles): +// viewer — read-only +// developer — viewer + run agents +// approver — viewer + decide human gates (separate from developer: who writes a change is not who approves it) +// auditor — viewer + audit log + evidence (read-only compliance) +// admin — everything in the tenant +// Roles are additive: a user holding developer + approver gets both sets. +// +// Legacy (pre-E1.2) role kept as an alias so existing users keep working with no migration: +// member → developer + approver + ManageWorkspaces — everything a member could do before: run agents, decide design +// checks on their own tasks, and connect boards (the old "Member" policy covered POST /workspaces). Reassigning a +// legacy member to one of the five roles drops what that role doesn't grant. +// admin keeps its name. platform-admin is orthogonal (platform-wide settings) and grants nothing tenant-scoped. +// +// Workspace (board) scope: viewer / developer / approver are WORKSPACE-SCOPABLE. A board with no memberships is open — +// tenant roles apply. Once a board has at least one membership it is restricted: a non-admin's workspace-scopable +// roles are replaced there by their membership role (none → no access). admin and auditor are TENANT-WIDE and apply +// on every board. + +using System; +using System.Collections.Frozen; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Security.Claims; + +namespace AgentOs.SharedKernel.Identity; + +/// Canonical RBAC v2 role names (Keycloak realm roles). +public static class UserRoles +{ + /// Read-only access to the tenant's work. + public const string Viewer = "viewer"; + + /// Runs agents and works tickets. + public const string Developer = "developer"; + + /// Decides human gates (design checks, approvals). + public const string Approver = "approver"; + + /// Read-only compliance: audit log + evidence. + public const string Auditor = "auditor"; + + /// Tenant administrator (same realm role name as before E1.2). + public const string Admin = ClaimNames.AdminRole; + + /// Pre-E1.2 role; an alias for + + managing boards. + public const string LegacyMember = ClaimNames.MemberRole; + + /// The roles an admin can assign, least to most privileged (UI order). + public static IReadOnlyList Assignable { get; } = [Viewer, Developer, Approver, Auditor, Admin]; + + /// The roles a board (workspace) membership can carry. + public static IReadOnlyList WorkspaceAssignable { get; } = [Viewer, Developer, Approver]; + + /// Every role AgentOS.NET manages on a user (assignable + the legacy alias it replaces). Setting a user's + /// roles revokes the managed ones not chosen and leaves every other realm role (platform-admin, defaults) alone. + public static IReadOnlyList Managed { get; } = [Viewer, Developer, Approver, Auditor, Admin, LegacyMember]; + + /// True for a role an admin may assign. + public static bool IsAssignable([NotNullWhen(true)] string? role) => role is not null && PermissionMatrix.AssignableSet.Contains(role); + + /// True for a role a board membership may carry. + public static bool IsWorkspaceAssignable([NotNullWhen(true)] string? role) => role is not null && PermissionMatrix.WorkspaceSet.Contains(role); + + /// Short UI label for a role. + public static string Label(string role) => role switch + { + Viewer => "Viewer", + Developer => "Developer", + Approver => "Approver", + Auditor => "Auditor", + Admin => "Admin", + LegacyMember => "Member (legacy)", + _ => role, + }; + + /// One-line UI description of what a role may do. + public static string Describe(string role) => role switch + { + Viewer => "Read boards, tasks, runs and insights", + Developer => "Viewer + run agents, work tickets, pair a computer", + Approver => "Viewer + decide design checks and approvals", + Auditor => "Viewer + audit log and evidence (read-only)", + Admin => "Everything in this workspace: members, settings, tokens, data", + LegacyMember => "Pre-RBAC role: Developer + Approver + connect boards", + _ => string.Empty, + }; +} + +/// The single role → permission matrix and the evaluation rules (tenant + workspace scope). +public static class PermissionMatrix +{ + /// Every defined permission combined. + public const Permission All = + Permission.ViewWork | Permission.RunAgents | Permission.ApproveWork | Permission.ManageWorkspaces + | Permission.ManageMembers | Permission.ManageSettings | Permission.ManageApiTokens | Permission.ViewAudit + | Permission.ExportData; + + private const Permission Viewer = Permission.ViewWork; + private const Permission Developer = Viewer | Permission.RunAgents; + private const Permission Approver = Viewer | Permission.ApproveWork; + private const Permission Auditor = Viewer | Permission.ViewAudit; + + /// Role → permissions. Ordinal role names (Keycloak role names are case-sensitive). + public static FrozenDictionary Roles { get; } = new Dictionary(StringComparer.Ordinal) + { + [UserRoles.Viewer] = Viewer, + [UserRoles.Developer] = Developer, + [UserRoles.Approver] = Approver, + [UserRoles.Auditor] = Auditor, + [UserRoles.Admin] = All, + [UserRoles.LegacyMember] = Developer | Approver | Permission.ManageWorkspaces, + }.ToFrozenDictionary(StringComparer.Ordinal); + + /// Roles whose grant applies on every board regardless of board memberships. + public static FrozenSet TenantWideRoles { get; } = + new[] { UserRoles.Admin, UserRoles.Auditor }.ToFrozenSet(StringComparer.Ordinal); + + internal static FrozenSet AssignableSet { get; } = UserRoles.Assignable.ToFrozenSet(StringComparer.Ordinal); + + internal static FrozenSet WorkspaceSet { get; } = UserRoles.WorkspaceAssignable.ToFrozenSet(StringComparer.Ordinal); + + /// Every single permission flag (no , no combinations), in declaration order. + public static IReadOnlyList Each { get; } = + [ + Permission.ViewWork, Permission.RunAgents, Permission.ApproveWork, Permission.ManageWorkspaces, + Permission.ManageMembers, Permission.ManageSettings, Permission.ManageApiTokens, Permission.ViewAudit, + Permission.ExportData, + ]; + + /// The permissions one role grants; unknown roles grant nothing. + public static Permission For(string? role) => + role is not null && Roles.TryGetValue(role, out var p) ? p : Permission.None; + + /// The union of the permissions the given roles grant (tenant scope). + public static Permission For(IEnumerable roles) + { + ArgumentNullException.ThrowIfNull(roles); + var granted = Permission.None; + foreach (var role in roles) + { + granted |= For(role); + } + return granted; + } + + /// True when includes every flag of . + public static bool Has(this Permission granted, Permission required) => + required != Permission.None && (granted & required) == required; + + /// The roles that apply on one board (workspace): tenant-wide roles always; the workspace-scopable roles + /// from the realm on an open board, or the membership role on a restricted one. + /// The user's tenant (realm) roles. + /// True when the board has at least one membership. + /// The user's membership role on the board, or null. + public static IEnumerable EffectiveRoles(IEnumerable roles, bool restricted, string? membershipRole) + { + ArgumentNullException.ThrowIfNull(roles); + foreach (var role in roles) + { + if (!restricted || TenantWideRoles.Contains(role)) + { + yield return role; + } + } + // A membership row may only carry a workspace-assignable role — anything else grants nothing. + if (restricted && UserRoles.IsWorkspaceAssignable(membershipRole)) + { + yield return membershipRole; + } + } + + /// The effective permissions on one board (workspace) — over + /// . + /// The user's tenant (realm) roles. + /// True when the board has at least one membership. + /// The user's membership role on the board, or null. + public static Permission ForWorkspace(IEnumerable roles, bool restricted, string? membershipRole) => + For(EffectiveRoles(roles, restricted, membershipRole)); + + /// The authorization policy name enforcing (registered by the Identity module). + public static string Policy(Permission permission) => PolicyPrefix + permission.ToString(); + + /// Prefix of every permission policy name. + public const string PolicyPrefix = "perm:"; +} + +/// Permission checks on a signed-in principal — the call sites' only way to ask "may this user …". +public static class PermissionPrincipalExtensions +{ + /// The realm roles on the principal (every identity's claims). + public static IEnumerable GetRoles(this ClaimsPrincipal user) + { + ArgumentNullException.ThrowIfNull(user); + foreach (var claim in user.FindAll(ClaimTypes.Role)) + { + yield return claim.Value; + } + } + + /// The tenant-scope permissions the principal's roles grant (none when anonymous). + public static Permission GetPermissions(this ClaimsPrincipal user) + { + ArgumentNullException.ThrowIfNull(user); + return user.Identity?.IsAuthenticated == true ? PermissionMatrix.For(user.GetRoles()) : Permission.None; + } + + /// True when the signed-in principal holds at tenant scope. + public static bool Can(this ClaimsPrincipal user, Permission permission) => user.GetPermissions().Has(permission); +} diff --git a/src/AgentOs.SharedKernel/Identity/WorkspaceAccess.cs b/src/AgentOs.SharedKernel/Identity/WorkspaceAccess.cs new file mode 100644 index 00000000..965dae54 --- /dev/null +++ b/src/AgentOs.SharedKernel/Identity/WorkspaceAccess.cs @@ -0,0 +1,93 @@ +// RBAC v2 (E1.2) — board (workspace) scope of the permission matrix, shared by every module that gates per board +// (Workspaces owns the memberships; Sessions, Pipeline and the Web desktop only ask). WorkspaceAccessMap is built once +// per request/circuit from one read of the tenant's memberships, then answers per board in O(1) via frozen lookups. + +using System; +using System.Collections.Frozen; +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading; +using System.Threading.Tasks; + +namespace AgentOs.SharedKernel.Identity; + +/// One user's role on one board. +public sealed record WorkspaceMember(Guid WorkspaceId, string UserId, string Role, string? AddedByUserId, DateTimeOffset AddedAtUtc); + +/// A user's effective permissions on every board of a tenant, computed once from one read. +public sealed class WorkspaceAccessMap +{ + private readonly string[] _roles; + private readonly FrozenSet _restricted; + private readonly FrozenDictionary _mine; + + private WorkspaceAccessMap(string[] roles, FrozenSet restricted, FrozenDictionary mine) + { + _roles = roles; + _restricted = restricted; + _mine = mine; + TenantPermissions = PermissionMatrix.For(roles); + } + + /// The user's tenant-scope permissions (realm roles only). + public Permission TenantPermissions { get; } + + /// Build the map for one user from the tenant's memberships (single pass). + public static WorkspaceAccessMap Build(IEnumerable roles, string? userId, IEnumerable memberships) + { + ArgumentNullException.ThrowIfNull(roles); + ArgumentNullException.ThrowIfNull(memberships); + var restricted = new HashSet(); + var mine = new Dictionary(); + foreach (var m in memberships) + { + restricted.Add(m.WorkspaceId); + if (userId is not null && string.Equals(m.UserId, userId, StringComparison.Ordinal)) + { + mine[m.WorkspaceId] = m.Role; + } + } + return new WorkspaceAccessMap([.. roles], restricted.ToFrozenSet(), mine.ToFrozenDictionary()); + } + + /// True when the board has at least one membership (only its members and tenant-wide roles get in). + public bool IsRestricted(Guid workspaceId) => _restricted.Contains(workspaceId); + + /// The user's own membership role on the board, or null. + public string? MembershipRole(Guid workspaceId) => _mine.GetValueOrDefault(workspaceId); + + /// The roles that apply to the user on one board (see ). + public IEnumerable RolesOn(Guid workspaceId) => + PermissionMatrix.EffectiveRoles(_roles, _restricted.Contains(workspaceId), _mine.GetValueOrDefault(workspaceId)); + + /// The user's effective permissions on one board. + public Permission For(Guid workspaceId) => + PermissionMatrix.ForWorkspace(_roles, _restricted.Contains(workspaceId), _mine.GetValueOrDefault(workspaceId)); + + /// True when the user holds on the board. + public bool Can(Guid workspaceId, Permission permission) => For(workspaceId).Has(permission); + + /// True when the user may see the board at all (holds there). + public bool CanSee(Guid workspaceId) => Can(workspaceId, Permission.ViewWork); +} + +/// Resolves a user's permissions per board. +public interface IWorkspaceAccess +{ + /// The user's access to every board of the tenant (one read). + Task ForUserAsync(string tenantId, IEnumerable roles, string? userId, CancellationToken ct = default); +} + +/// Convenience overloads over a signed-in principal. +public static class WorkspaceAccessExtensions +{ + /// The principal's access to every board of . + public static Task ForUserAsync(this IWorkspaceAccess access, string tenantId, ClaimsPrincipal user, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(access); + ArgumentNullException.ThrowIfNull(user); + var roles = user.Identity?.IsAuthenticated == true ? user.GetRoles() : []; + return access.ForUserAsync(tenantId, roles, user.GetUserId(), ct); + } +} + diff --git a/src/AgentOs.SharedKernel/Identity/WorkspaceScopeFilter.cs b/src/AgentOs.SharedKernel/Identity/WorkspaceScopeFilter.cs new file mode 100644 index 00000000..397763d2 --- /dev/null +++ b/src/AgentOs.SharedKernel/Identity/WorkspaceScopeFilter.cs @@ -0,0 +1,49 @@ +// RBAC v2 (E1.2) — endpoint filter for routes that carry a board id: the tenant-scope policy already passed, this +// re-checks the permission ON THAT BOARD (a restricted board's memberships decide). Reads → 404 when the caller +// can't see the board (it doesn't exist for them); writes → 403. + +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; + +namespace AgentOs.SharedKernel.Identity; + +/// Board-scope permission checks for routes with a board id in the path. +public static class WorkspaceScopeFilter +{ + /// Require ViewWork on the route's board for GET/HEAD and otherwise. + /// The endpoint (group) builder. + /// The route value holding the board id (e.g. boardId). + /// The permission non-read methods need on the board. + public static TBuilder RequireWorkspacePermission(this TBuilder builder, string routeKey, Permission write) + where TBuilder : IEndpointConventionBuilder + { + ArgumentNullException.ThrowIfNull(builder); + ArgumentException.ThrowIfNullOrWhiteSpace(routeKey); + builder.AddEndpointFilter(async (ctx, next) => + { + var http = ctx.HttpContext; + if (http.GetRouteValue(routeKey) is not { } raw || !Guid.TryParse(raw.ToString(), out var boardId)) + { + return await next(ctx).ConfigureAwait(false); + } + var access = http.RequestServices.GetService(); + var tenant = http.RequestServices.GetService(); + if (access is null || tenant is null) + { + return await next(ctx).ConfigureAwait(false); + } + var map = await access.ForUserAsync(tenant.TenantId, http.User, http.RequestAborted).ConfigureAwait(false); + if (!map.CanSee(boardId)) + { + return Results.NotFound(); + } + var isRead = HttpMethods.IsGet(http.Request.Method) || HttpMethods.IsHead(http.Request.Method); + return isRead || map.Can(boardId, write) ? await next(ctx).ConfigureAwait(false) : Results.Forbid(); + }); + return builder; + } +} diff --git a/src/AgentOs.SharedKernel/Persistence/RowLevelSecurity.cs b/src/AgentOs.SharedKernel/Persistence/RowLevelSecurity.cs index a778ef0e..2b8e138b 100644 --- a/src/AgentOs.SharedKernel/Persistence/RowLevelSecurity.cs +++ b/src/AgentOs.SharedKernel/Persistence/RowLevelSecurity.cs @@ -43,6 +43,7 @@ public static partial class RowLevelSecurity ("sessions", "design_reviews"), ("tools", "tool_invocations"), ("workspaces", "workspaces"), ("workspaces", "workspace_repos"), ("workspaces", "autopilot_events"), ("workspaces", "ticket_flows"), + ("workspaces", "workspace_members"), ("memory", "nodes"), ("memory", "edges"), ]; diff --git a/src/AgentOs.Web.Shell/Services/DesktopApp.cs b/src/AgentOs.Web.Shell/Services/DesktopApp.cs index dc7164bf..80bdc913 100644 --- a/src/AgentOs.Web.Shell/Services/DesktopApp.cs +++ b/src/AgentOs.Web.Shell/Services/DesktopApp.cs @@ -3,6 +3,8 @@ // and render a desktop app. The host owns the actual catalog (built-in component types + plugin apps) and // exposes it through IAppRegistry; the shell only needs this record shape. +using AgentOs.SharedKernel.Identity; + namespace AgentOs.Web.Shell.Services; /// A launchable desktop application. @@ -14,9 +16,13 @@ namespace AgentOs.Web.Shell.Services; /// Default window width. /// Default window height. /// Whether the app appears in the dock + pinned grid. -/// When true the app is only shown to users holding the tenant admin role. +/// When true the app is only shown to tenant admins (kept for plugins; built-ins use +/// ). Treated as requiring . /// The Blazor component the (app-agnostic) WindowHost renders via /// DynamicComponent — set for every app, built-in and plugin alike. The shell never names an app. +/// Launcher tile colour. +/// RBAC v2: the permission (PermissionMatrix) a user needs to see and open the app; +/// = every signed-in user. public sealed record DesktopApp( string Key, string Title, @@ -28,4 +34,12 @@ public sealed record DesktopApp( bool Pinned = true, bool AdminOnly = false, System.Type? ComponentType = null, - string Color = "#3584e4"); + string Color = "#3584e4", + Permission Requires = Permission.None) +{ + /// The permission this app needs, folding the legacy flag in. + public Permission Required => Requires != Permission.None ? Requires : AdminOnly ? Permission.ManageSettings : Permission.None; + + /// True when a user granted may see and open the app. + public bool IsVisibleTo(Permission granted) => Required == Permission.None || granted.Has(Required); +} diff --git a/src/AgentOs.Web.Shell/Services/IAppRegistry.cs b/src/AgentOs.Web.Shell/Services/IAppRegistry.cs index 02a02b37..0ce77871 100644 --- a/src/AgentOs.Web.Shell/Services/IAppRegistry.cs +++ b/src/AgentOs.Web.Shell/Services/IAppRegistry.cs @@ -19,6 +19,6 @@ public interface IAppRegistry /// Apps that appear in the dock and the pinned grid. System.Collections.Generic.IReadOnlyList Pinned { get; } - /// Pinned apps visible to a user with the given admin status (filters out admin-only apps). - System.Collections.Generic.IReadOnlyList VisiblePinned(bool isAdmin); + /// Pinned apps visible to a user granted (RBAC v2 — see ). + System.Collections.Generic.IReadOnlyList VisiblePinned(AgentOs.SharedKernel.Identity.Permission granted); } diff --git a/src/AgentOs.Web.Shell/UI/Taskbar.razor b/src/AgentOs.Web.Shell/UI/Taskbar.razor index 77438d46..98dc56c2 100644 --- a/src/AgentOs.Web.Shell/UI/Taskbar.razor +++ b/src/AgentOs.Web.Shell/UI/Taskbar.razor @@ -9,7 +9,7 @@ @* ===== Dock (floating bottom-center pill) ===== *@ } @* Every app this user may open, grouped by category (pinned first within each group). *@ - @foreach (var group in AppCatalog.VisibleAll(_isAdmin).GroupBy(a => a.Category)) + @foreach (var group in AppCatalog.VisibleAll(_granted).GroupBy(a => a.Category)) {
@group.Key @@ -239,7 +239,7 @@ private string _query = ""; private int _searchGeneration; // bump to get an empty search box (the input is uncontrolled) private string? _user; - private bool _isAdmin; + private Permission _granted; private ElementReference _searchRef; private bool _focusOnRender; @@ -249,7 +249,7 @@ if (AuthState is not null) { var state = await AuthState; - _isAdmin = state.User.IsAdmin(); + _granted = state.User.GetPermissions(); _isPlatformAdmin = state.User.IsPlatformAdmin(); } } @@ -356,7 +356,7 @@ var q = _query.Trim(); _results = string.IsNullOrEmpty(q) ? new() - : AppCatalog.VisibleAll(_isAdmin) + : AppCatalog.VisibleAll(_granted) .Where(a => a.Title.Contains(q, StringComparison.OrdinalIgnoreCase) || a.Caption.Contains(q, StringComparison.OrdinalIgnoreCase) || a.Category.Contains(q, StringComparison.OrdinalIgnoreCase)) @@ -365,8 +365,8 @@ var catalog = Services.GetService(); _settingHits = string.IsNullOrEmpty(q) ? [] - : SettingsSearch.Find(q, catalog?.All ?? [], _isAdmin, _isPlatformAdmin); - _actionHits = string.IsNullOrEmpty(q) ? [] : ShellActions.Find(q, _isAdmin); + : SettingsSearch.Find(q, catalog?.All ?? [], _granted, _isPlatformAdmin); + _actionHits = string.IsNullOrEmpty(q) ? [] : ShellActions.Find(q, _granted); } private void OnSearchKey(KeyboardEventArgs e) @@ -374,7 +374,7 @@ if (e.Key == "Escape") { CloseStart(); } else if (e.Key == "Enter") { - var first = !string.IsNullOrWhiteSpace(_query) ? _results.FirstOrDefault() : AppCatalog.VisiblePinned(_isAdmin).FirstOrDefault(); + var first = !string.IsNullOrWhiteSpace(_query) ? _results.FirstOrDefault() : AppCatalog.VisiblePinned(_granted).FirstOrDefault(); if (first is not null) { Launch(first); } else if (!string.IsNullOrWhiteSpace(_query) && _actionHits.Count > 0) { _ = RunActionAsync(_actionHits[0]); } else if (!string.IsNullOrWhiteSpace(_query) && _settingHits.Count > 0) { OpenSetting(_settingHits[0]); } diff --git a/src/AgentOs.Web/Components/Pages/AgentProfilesApp.razor b/src/AgentOs.Web/Components/Pages/AgentProfilesApp.razor index 905f2272..e72e8139 100644 --- a/src/AgentOs.Web/Components/Pages/AgentProfilesApp.razor +++ b/src/AgentOs.Web/Components/Pages/AgentProfilesApp.razor @@ -200,7 +200,7 @@ else if (AuthState is not null) { var state = await AuthState; - _isAdmin = state.User.IsAdmin(); + _isAdmin = state.User.Can(Permission.ManageSettings); // RBAC v2 re-check (PermissionMatrix) _tenantId = state.User.GetTenantId() ?? string.Empty; _actor = state.User.Identity?.Name ?? "admin"; } diff --git a/src/AgentOs.Web/Components/Pages/ApiTokensApp.razor b/src/AgentOs.Web/Components/Pages/ApiTokensApp.razor index 22f1c984..e21b0966 100644 --- a/src/AgentOs.Web/Components/Pages/ApiTokensApp.razor +++ b/src/AgentOs.Web/Components/Pages/ApiTokensApp.razor @@ -33,8 +33,10 @@ else @@ -107,7 +109,7 @@ else private string _tenantId = "default"; private string _actor = "admin"; private string _name = string.Empty; - private string _role = "member"; + private string _role = UserRoles.Developer; private int _days = 90; private string? _newToken; private IReadOnlyList? _rows; @@ -117,7 +119,7 @@ else if (AuthState is not null) { var state = await AuthState; - _isAdmin = state.User.IsAdmin(); + _isAdmin = state.User.Can(Permission.ManageApiTokens); // RBAC v2 re-check (PermissionMatrix) _tenantId = state.User.GetTenantId() ?? "default"; _actor = state.User.Identity?.Name ?? "admin"; } diff --git a/src/AgentOs.Web/Components/Pages/AuditLogApp.razor b/src/AgentOs.Web/Components/Pages/AuditLogApp.razor index ca6b0426..f0ac825d 100644 --- a/src/AgentOs.Web/Components/Pages/AuditLogApp.razor +++ b/src/AgentOs.Web/Components/Pages/AuditLogApp.razor @@ -11,9 +11,9 @@ { } -else if (!_isAdmin) +else if (!_canView) { - + } else { @@ -80,7 +80,7 @@ else private const int Max = 500; private bool _resolved; - private bool _isAdmin; + private bool _canView; private bool _isPlatformAdmin; private bool _platformScope; private bool _loading; @@ -97,12 +97,12 @@ else if (AuthState is not null) { var state = await AuthState; - _isAdmin = state.User.IsAdmin(); + _canView = state.User.Can(Permission.ViewAudit); // RBAC v2 re-check (PermissionMatrix) _isPlatformAdmin = state.User.IsPlatformAdmin(); _tenantId = state.User.GetTenantId() ?? "default"; } _resolved = true; - if (_isAdmin) { await LoadAsync(); } + if (_canView) { await LoadAsync(); } } private async Task LoadAsync() diff --git a/src/AgentOs.Web/Components/Pages/AutopilotSettingsApp.razor b/src/AgentOs.Web/Components/Pages/AutopilotSettingsApp.razor index fef64795..0869876c 100644 --- a/src/AgentOs.Web/Components/Pages/AutopilotSettingsApp.razor +++ b/src/AgentOs.Web/Components/Pages/AutopilotSettingsApp.razor @@ -109,7 +109,7 @@ else if (AuthState is not null) { var user = (await AuthState).User; - _isAdmin = user.IsAdmin(); + _isAdmin = user.Can(Permission.ManageSettings); // RBAC v2 re-check (PermissionMatrix) _tenantId = user.GetTenantId() ?? string.Empty; _actor = user.GetUserId() ?? user.Identity?.Name ?? _actor; } diff --git a/src/AgentOs.Web/Components/Pages/BoardApp.razor b/src/AgentOs.Web/Components/Pages/BoardApp.razor index 043a79a8..84ec5294 100644 --- a/src/AgentOs.Web/Components/Pages/BoardApp.razor +++ b/src/AgentOs.Web/Components/Pages/BoardApp.razor @@ -23,6 +23,7 @@ @using AgentOs.Domain.Files @inject IWorkspaceRepository Workspaces @inject IWorkspaceConnector Connector +@inject IWorkspaceAccess Access @inject IRunnerRepository Runners @inject ISessionRepository Sessions @inject IRunnerPairingService Pairing @@ -150,10 +151,10 @@ else if (_tab == Tab.Boards)
+ Disabled="@(_busy || _findingBoards || _wsKind != SourceProviderKind.GitHub || !Can(Permission.ManageWorkspaces))"> @(_findingBoards ? "Finding…" : "Find boards") - + @(_busy ? "Connecting…" : "Connect")
@@ -239,7 +240,7 @@ else if (_tab == Tab.Boards)
- + @(_busy ? "Adding…" : "Add repository")
@@ -259,16 +260,16 @@ else if (_tab == Tab.Boards) @{ var preview = Previews.Get(_tenantId, r.Id); } @(_previewBusy == r.Id ? "Checking…" : "Try the app") + OnClick="@(() => SeedLabels(r))" Disabled="@(_busyId == r.Id || !CanOnBoard(Permission.ManageWorkspaces))"> Seed labels + OnClick="@(() => RemoveRepo(r))" Disabled="@(_busyId == r.Id || !CanOnBoard(Permission.ManageWorkspaces))"> Remove @@ -343,7 +344,7 @@ else if (_tab == Tab.Boards) @if (readyCount > 0) {
- + Start approved tickets (@readyCount)
@@ -400,7 +401,7 @@ else if (_tab == Tab.Boards) + Disabled="@(_busy || ticket.Kind == BoardTicketKind.DraftIssue || ticket.RepoOwner is null || !CanOnBoard(Permission.RunAgents))"> Work on this @@ -457,7 +458,7 @@ else if (_tab == Tab.Idea) Note="Every ticket created from this idea gets them." /> @if (_ideaError is not null) { }
- + @(_ideaBusy ? "Generating…" : "Generate spec + tickets")
@@ -475,7 +476,7 @@ else if (_tab == Tab.Idea) The AI couldn't split this into tickets this time. These are rough drafts, one per requirement line — try again (your computer may have been busy), or edit and remove rows below.
- + @(_ideaBusy ? "Trying…" : "Try again")
@@ -526,10 +527,10 @@ else if (_tab == Tab.Idea) @WhereToWork
Back - + @(_ideaBusy ? "Working…" : "Create & run all ready") - + Create only
@@ -568,7 +569,7 @@ else if (_tab == Tab.Runners)
- + @(_busy ? "Connecting…" : "Connect this computer")
@@ -608,7 +609,7 @@ REMOTE_AGENT_TOKEN=@_newRunner.Value.Token steps — each keeps a live pairing secret, and its helper needs a new code to come back. *@
+ OnClick="@(() => DisconnectOffline(offline))" Disabled="@(_busy || !Can(Permission.RunAgents))"> @(_confirmOffline ? $"Click again to disconnect {offline.Count} offline computers" : $"Disconnect offline computers ({offline.Count})")
@@ -640,7 +641,7 @@ REMOTE_AGENT_TOKEN=@_newRunner.Value.Token @(Broker.IsConnected(r.Id) ? "now" : Ago(r.LastSeenUtc ?? r.CreatedAtUtc)) + OnClick="@(() => RevokeRunner(r))" Disabled="@(_busyId == r.Id || r.Status == "Revoked" || !Can(Permission.RunAgents))"> Disconnect @@ -685,16 +686,19 @@ else if (_tab == Tab.Autopilot)
@@ -713,7 +717,7 @@ else if (_tab == Tab.Autopilot)
}
- + Check now @@ -758,15 +762,16 @@ else if (_tab == Tab.Sessions) @if (_sessions is null) { } else { - - + + - @if (_isAdmin) { } + @if (TeamView) { } @@ -825,7 +830,7 @@ else if (_tab == Tab.Sessions) — } - @if (_isAdmin) { } + @if (TeamView) { } @@ -877,7 +882,7 @@ else if (_tab == Tab.Sessions) @if (s.Status == "Running" && CurrentStep(s.Id) is var step && step >= 0) { - - - @@ -922,16 +927,16 @@ else if (_tab == Tab.Sessions) @if (_designFor == s.Id) { - } @if (_activity.TryGetValue(s.Id, out var feed) && feed.Count > 0) { - } } - @if (_sessions.Count == 0) { } + @if (_sessions.Count == 0) { }
Title Project CodeMemberMemberStatus Started Actions@MemberLabel(s.MemberUserId)@MemberLabel(s.MemberUserId)@PlainStatus(s.Status) @Ago(s.CreatedAtUtc) @@ -836,7 +841,7 @@ else if (_tab == Tab.Sessions) { + Disabled="@(_busyId == s.Id || !Can(s.WorkspaceId, Permission.RunAgents))"> @(s.Status == "Failed" ? "Try again" : "Run") } @@ -849,7 +854,7 @@ else if (_tab == Tab.Sessions) } @if (s.Status is "Done" or "Failed" or "Blocked" && HasOpenChange(s.Id)) { - Test it @@ -869,7 +874,7 @@ else if (_tab == Tab.Sessions) } + Disabled="@(_busyId == s.Id || s.Status is "Closed" or "Running" || !Can(s.WorkspaceId, Permission.RunAgents))"> Close
+ @* Live progress in plain steps (reported by the computer doing the work). Static — no looping motion. *@
    @for (var i = 0; i < AgentOs.Domain.Sessions.TaskSteps.All.Count; i++) @@ -892,7 +897,7 @@ else if (_tab == Tab.Sessions) @if (_changesFor == s.Id) {
+ @* Review in words: what to change on the open proposed change. The AI continues on the same branch and pull request; "Fix the failing checks" fills this from the CI log. *@
@@ -901,8 +906,8 @@ else if (_tab == Tab.Sessions) placeholder="e.g. The second test is wrong: reload the page before checking the duplicate email.">
Send to the AI - + Disabled="@(_busyId == s.Id || string.IsNullOrWhiteSpace(_changesText) || !Can(s.WorkspaceId, Permission.RunAgents))">Send to the AI + @(_loadingChecks ? "Reading the checks…" : "Fix the failing checks")
@@ -913,7 +918,7 @@ else if (_tab == Tab.Sessions) @if (_filesFor == s.Id) {
+
+ + CanDecide="@CanDecide(s)" DecidedBy="@_userLabel" />
+
@foreach (var ev in feed.TakeLast(8)) { @@ -940,7 +945,7 @@ else if (_tab == Tab.Sessions) @ev.Message
} - @if (_isAdmin) + @if (Can(Permission.ViewAudit)) { @* Governance: every tool the agent used on a member's computer is evidence (Settings › Activity log). *@
@@ -955,7 +960,7 @@ else if (_tab == Tab.Sessions)
No tasks yet. Open a project and pick "Work on this" on a ticket.
No tasks yet. Open a project and pick "Work on this" on a ticket.
@@ -1035,6 +1040,11 @@ else if (_tab == Tab.Sessions) // The task whose "Files for the AI" are open. private Guid? _filesFor; private bool _isAdmin; + // RBAC v2 (E1.2): tenant permissions + per-board access (PermissionMatrix). Every mutating handler re-checks with + // Demand/BoardDemand before acting (GAP-17: never UI-only); the markup only hides what the role can't do. + private Permission _perms; + private string[] _roles = []; + private WorkspaceAccessMap? _access; // ── Data ──────────────────────────────────────────────────────────────────────────────── private IReadOnlyList? _boards; @@ -1107,6 +1117,7 @@ else if (_tab == Tab.Sessions) private async Task DisconnectOffline(IReadOnlyList offline) { + if (!Demand(Permission.RunAgents, "disconnect computers")) { return; } if (!_confirmOffline) { _confirmOffline = true; return; } _confirmOffline = false; _busy = true; @@ -1267,6 +1278,8 @@ else if (_tab == Tab.Sessions) _userId = user.GetUserId() ?? ""; _userLabel = string.IsNullOrWhiteSpace(user.Identity?.Name) ? _userId : user.Identity!.Name!; _isAdmin = user.IsAdmin(); + _perms = user.GetPermissions(); + _roles = [.. user.GetRoles()]; } _resolved = true; // Deep-link from the Home app's "Start from idea": prefill the wizard's idea + open the Idea tab. @@ -1316,18 +1329,66 @@ else if (_tab == Tab.Sessions) } } + /// True when the signed-in user holds on + /// (tenant scope until the board access map has loaded). + private bool Can(Guid boardId, Permission permission) => + _access is null ? _perms.Has(permission) : _access.Can(boardId, permission); + + /// Tenant-scope check (computers, connecting boards, ideas). + private bool Can(Permission permission) => _perms.Has(permission); + + /// Check on the open board (tenant scope when none is open). + private bool CanOnBoard(Permission permission) => + _selectedBoard is { } b ? Can(b.Id, permission) : Can(permission); + + private bool Demand(Permission permission, string what) => Refuse(Can(permission), what); + + private bool Demand(Guid boardId, Permission permission, string what) => Refuse(Can(boardId, permission), what); + + private bool BoardDemand(Permission permission, string what) => Refuse(CanOnBoard(permission), what); + + // Who sees whose tasks: admins every task; viewers, approvers and auditors the tasks of every board they can see + // (reading and approving others' work is their job); developers (and legacy members) their own, as before E1.2. + private static readonly System.Collections.Frozen.FrozenSet TeamRoles = + System.Collections.Frozen.FrozenSet.ToFrozenSet(new[] { UserRoles.Viewer, UserRoles.Approver, UserRoles.Auditor }, StringComparer.Ordinal); + + private bool TeamView => _isAdmin || _roles.Any(TeamRoles.Contains) || (_access is not null && (_boards ?? []).Any(b => _access.RolesOn(b.Id).Any(TeamRoles.Contains))); + + private bool TaskVisible(RemoteSessionEntity s) => + _isAdmin || s.MemberUserId == _userId + || (_access is { } map && map.CanSee(s.WorkspaceId) && map.RolesOn(s.WorkspaceId).Any(TeamRoles.Contains)); + + // Design decisions (ADR-0016) need ApproveWork on the task's board. An approver decides anyone's task on it; a + // holder of ApproveWork without the approver role (legacy member) only their own — exactly as before E1.2. + private bool CanDecide(RemoteSessionEntity s) => + Can(s.WorkspaceId, Permission.ApproveWork) + && (_isAdmin || s.MemberUserId == _userId || IsApproverOn(s.WorkspaceId)); + + private bool IsApproverOn(Guid boardId) => + (_access?.RolesOn(boardId) ?? _roles).Contains(UserRoles.Approver, StringComparer.Ordinal); + + private bool CanDecideFor(Guid sessionId) => + (_sessions ?? []).FirstOrDefault(x => x.Id == sessionId) is { } s && CanDecide(s); + + private bool Refuse(bool allowed, string what) + { + if (!allowed) { Toasts.Show("Board", $"Your role can't {what}. Ask an admin for a role that allows it.", ToastKind.Warn); } + return allowed; + } + private async Task ReloadAll() { _loading = true; try { - _boards = await Workspaces.ListForTenantAsync(_tenantId); + _access = await Access.ForUserAsync(_tenantId, _roles, _userId); + _boards = [.. (await Workspaces.ListForTenantAsync(_tenantId)).Where(b => _access.CanSee(b.Id))]; var allRunners = await Runners.ListForTenantAsync(_tenantId); _runners = _isAdmin ? allRunners : allRunners.Where(r => r.OwnerUserId == _userId).ToList(); var allSessions = await Sessions.ListForTenantAsync(_tenantId); - _sessions = _isAdmin ? allSessions : allSessions.Where(s => s.MemberUserId == _userId).ToList(); + _sessions = [.. allSessions.Where(TaskVisible)]; _sessionRepos = await Sessions.ListAllReposForTenantAsync(_tenantId); _ = SyncMergedAsync(); } @@ -1349,7 +1410,7 @@ else if (_tab == Tab.Sessions) try { var all = await Sessions.ListForTenantAsync(_tenantId); - _sessions = _isAdmin ? all : all.Where(s => s.MemberUserId == _userId).ToList(); + _sessions = [.. all.Where(TaskVisible)]; _sessionRepos = await Sessions.ListAllReposForTenantAsync(_tenantId); StateHasChanged(); if (_sessions.All(s => s.Status != "Running")) @@ -1425,7 +1486,7 @@ else if (_tab == Tab.Sessions) try { var all = await Sessions.ListForTenantAsync(_tenantId); - _sessions = _isAdmin ? all : all.Where(s => s.MemberUserId == _userId).ToList(); + _sessions = [.. all.Where(TaskVisible)]; _sessionRepos = await Sessions.ListAllReposForTenantAsync(_tenantId); } // Best-effort; the next event or poll retries. @@ -1525,6 +1586,7 @@ else if (_tab == Tab.Sessions) private async Task AddRepo() { + if (!BoardDemand(Permission.ManageWorkspaces, "change this board's repositories")) { return; } if (_busy || _selectedBoard is null) { return; } if (string.IsNullOrWhiteSpace(_addRepoOwner) || string.IsNullOrWhiteSpace(_addRepoName)) { @@ -1560,6 +1622,7 @@ else if (_tab == Tab.Sessions) private async Task RemoveRepo(WorkspaceRepoEntity repo) { + if (!BoardDemand(Permission.ManageWorkspaces, "change this board's repositories")) { return; } if (_selectedBoard is null) { return; } _busyId = repo.Id; try @@ -1582,6 +1645,7 @@ else if (_tab == Tab.Sessions) // labels are skipped. Writes to real GitHub, so it surfaces scope/credential errors as toasts. private async Task SeedLabels(WorkspaceRepoEntity repo) { + if (!BoardDemand(Permission.ManageWorkspaces, "change this board's repositories")) { return; } if (_selectedBoard is null) { return; } _busyId = repo.Id; try @@ -1636,6 +1700,7 @@ else if (_tab == Tab.Sessions) // constructs an LLM client and crashes the circuit (the documented eager-DI landmine). private async Task GenerateIdea() { + if (!Demand(Permission.RunAgents, "turn ideas into tickets")) { return; } if (_ideaBusy) { return; } if (string.IsNullOrWhiteSpace(_ideaText)) { @@ -1708,6 +1773,7 @@ else if (_tab == Tab.Sessions) // this is the autonomous idea→PRs path. private async Task CreateTickets(bool runReady) { + if (!Demand(Permission.RunAgents, "turn ideas into tickets")) { return; } if (_ideaBusy) { return; } var board = IdeaBoards().FirstOrDefault(b => b.Id.ToString() == _ideaBoardId); var repo = (_ideaRepos ?? Array.Empty()).FirstOrDefault(r => r.Id.ToString() == _ideaRepoId); @@ -1840,6 +1906,7 @@ else if (_tab == Tab.Sessions) // pre-selecting the ticket's repo. private void OpenWorkDialog(BoardTicket ticket) { + if (!BoardDemand(Permission.RunAgents, "start work on a ticket")) { return; } if (ticket.RepoOwner is null || ticket.RepoName is null) { return; } _workTicket = ticket; _workRepoOptions.Clear(); @@ -1898,6 +1965,7 @@ else if (_tab == Tab.Sessions) private async Task ConfirmWorkSession() { + if (!BoardDemand(Permission.RunAgents, "start work on a ticket")) { return; } if (_busy || _selectedBoard is null || _workTicket is null) { return; } if (NeedsPerson(_workTicket) && !_confirmPersonTicket) { return; } var selected = _workRepoOptions.Where(o => o.Selected).ToList(); @@ -2002,6 +2070,7 @@ else if (_tab == Tab.Sessions) // path, unattended). Shares PersistSessionAsync + RunSession with the single-ticket flow. private async Task RunAllReady() { + if (!BoardDemand(Permission.RunAgents, "start work on tickets")) { return; } if (_busy || _selectedBoard is null) { return; } var candidates = ReadyTickets(); if (candidates.Count == 0) @@ -2112,7 +2181,7 @@ else if (_tab == Tab.Sessions) } if (!changed) { return; } var all = await Sessions.ListForTenantAsync(_tenantId); - _sessions = _isAdmin ? all : all.Where(s => s.MemberUserId == _userId).ToList(); + _sessions = [.. all.Where(TaskVisible)]; _sessionRepos = await Sessions.ListAllReposForTenantAsync(_tenantId); await InvokeAsync(StateHasChanged); } @@ -2180,6 +2249,7 @@ else if (_tab == Tab.Sessions) private async Task RunSession(RemoteSessionEntity session, string? changeRequest = null) { + if (!Demand(session.WorkspaceId, Permission.RunAgents, "run this task")) { return; } if (_busyId == session.Id) { return; } _busyId = session.Id; try @@ -2191,7 +2261,7 @@ else if (_tab == Tab.Sessions) case AgentOs.Web.Services.BoardTasks.TaskStart.Started: _sessionRepos = await Sessions.ListAllReposForTenantAsync(_tenantId); var all = await Sessions.ListForTenantAsync(_tenantId); - _sessions = _isAdmin ? all : all.Where(s => s.MemberUserId == _userId).ToList(); + _sessions = [.. all.Where(TaskVisible)]; Toasts.Show("Board", $"Task #{session.IssueNumber} started — the AI is working on it. You can close this window.", ToastKind.Ok); StartPolling(); break; @@ -2231,6 +2301,7 @@ else if (_tab == Tab.Sessions) private async Task RegisterRunner() { + if (!Demand(Permission.RunAgents, "connect a computer")) { return; } if (_busy) { return; } if (string.IsNullOrWhiteSpace(_runnerLabel)) { @@ -2274,6 +2345,7 @@ else if (_tab == Tab.Sessions) private async Task RevokeRunner(RunnerEntity r) { + if (!Demand(Permission.RunAgents, "disconnect a computer")) { return; } _busyId = r.Id; try { @@ -2299,6 +2371,7 @@ else if (_tab == Tab.Sessions) // The failure card's one button. private async Task OnFailureAction(RemoteSessionEntity s, AgentOs.Web.Services.TaskFailureAction action) { + if (!Demand(s.WorkspaceId, Permission.RunAgents, "act on this task")) { return; } switch (action) { case AgentOs.Web.Services.TaskFailureAction.ConnectAiAccount: @@ -2356,6 +2429,7 @@ else if (_tab == Tab.Sessions) private async Task SendChanges(RemoteSessionEntity s) { + if (!Demand(s.WorkspaceId, Permission.RunAgents, "ask for changes on this task")) { return; } var text = _changesText; if (string.IsNullOrWhiteSpace(text)) { return; } _changesFor = null; @@ -2366,6 +2440,7 @@ else if (_tab == Tab.Sessions) // The checks of each open pull request of this task that failed, with the tail of their logs, as the request. private async Task FixFailingChecks(RemoteSessionEntity s) { + if (!Demand(s.WorkspaceId, Permission.RunAgents, "fix this task's checks")) { return; } var board = _boards?.FirstOrDefault(b => b.Id == s.WorkspaceId); if (board is null) { return; } _loadingChecks = true; @@ -2414,6 +2489,7 @@ else if (_tab == Tab.Sessions) private async Task TryTheApp(WorkspaceRepoEntity r) { + if (!BoardDemand(Permission.RunAgents, "run the app preview")) { return; } if (_selectedBoard is null) { return; } _previewBusy = r.Id; try { _previewAsk[r.Id] = await Previews.ReadRecipeAsync(_tenantId, _selectedBoard, r); } @@ -2422,6 +2498,7 @@ else if (_tab == Tab.Sessions) private async Task RunPreview(WorkspaceRepoEntity r, AgentOs.Domain.Preview.PreviewRecipe recipe) { + if (!BoardDemand(Permission.RunAgents, "run the app preview")) { return; } if (_selectedBoard is null) { return; } _previewAsk.Remove(r.Id); if (await Previews.StartAsync(_tenantId, _userId, _selectedBoard.Id, r, recipe) == AgentOs.Web.Services.Preview.PreviewStartResult.NoComputer) @@ -2432,6 +2509,7 @@ else if (_tab == Tab.Sessions) private async Task AskForRecipe(WorkspaceRepoEntity r) { + if (!BoardDemand(Permission.RunAgents, "run the app preview")) { return; } if (_selectedBoard is null) { return; } _previewBusy = r.Id; try @@ -2584,6 +2662,7 @@ else if (_tab == Tab.Sessions) } private async Task SetAutopilot(WorkspaceEntity board, string mode) { + if (!Demand(board.Id, Permission.ManageWorkspaces, "switch Autopilot")) { return; } if (!await Workspaces.SetAutopilotForTenantAsync(_tenantId, board.Id, mode, _userId)) { Toasts.Show("Board", "Couldn't change Autopilot — reload and try again.", ToastKind.Err); @@ -2602,6 +2681,7 @@ else if (_tab == Tab.Sessions) private async Task AutopilotNow(WorkspaceEntity board) { + if (!Demand(board.Id, Permission.ManageWorkspaces, "run Autopilot")) { return; } _busy = true; try { @@ -2619,6 +2699,7 @@ else if (_tab == Tab.Sessions) // Agentic Testing on demand: the Testing agent checks the open change against the ticket's criteria on your computer. private async Task TestTask(RemoteSessionEntity s) { + if (!Demand(s.WorkspaceId, Permission.RunAgents, "test this task")) { return; } _busyId = s.Id; try { @@ -2637,6 +2718,7 @@ else if (_tab == Tab.Sessions) private void StopSession(RemoteSessionEntity s) { + if (!Demand(s.WorkspaceId, Permission.RunAgents, "stop this task")) { return; } Toasts.Show("Board", StopRegistry.Stop(_tenantId, s.Id) ? $"Stopping task #{s.IssueNumber}… the AI finishes its current step and stops." : $"Task #{s.IssueNumber} isn't running here any more — refresh to see where it ended.", @@ -2645,13 +2727,14 @@ else if (_tab == Tab.Sessions) private async Task CloseSession(RemoteSessionEntity s) { + if (!Demand(s.WorkspaceId, Permission.RunAgents, "close this task")) { return; } _busyId = s.Id; try { await Sessions.CloseForTenantAsync(_tenantId, s.Id, DateTimeOffset.UtcNow); Toasts.Show("Board", $"Closed '{s.Title}'.", ToastKind.Ok); var s0 = await Sessions.ListForTenantAsync(_tenantId); - _sessions = _isAdmin ? s0 : s0.Where(s => s.MemberUserId == _userId).ToList(); + _sessions = [.. s0.Where(TaskVisible)]; } catch (System.Net.Http.HttpRequestException ex) { Toasts.Show("Board", $"Close failed: {ex.Message}", ToastKind.Err); } catch (InvalidOperationException ex) { Toasts.Show("Board", $"Close failed: {ex.Message}", ToastKind.Err); } @@ -2667,6 +2750,7 @@ else if (_tab == Tab.Sessions) private async Task FindBoards() { + if (!Demand(Permission.ManageWorkspaces, "connect a board")) { return; } if (_findingBoards) { return; } if (string.IsNullOrWhiteSpace(_wsProjectOwner) || string.IsNullOrWhiteSpace(_wsToken)) { @@ -2712,6 +2796,7 @@ else if (_tab == Tab.Sessions) private async Task ConnectBoard() { + if (!Demand(Permission.ManageWorkspaces, "connect a board")) { return; } if (_busy) { return; } if (string.IsNullOrWhiteSpace(_wsName) || string.IsNullOrWhiteSpace(_wsProjectOwner) || string.IsNullOrWhiteSpace(_wsToken)) @@ -2744,7 +2829,8 @@ else if (_tab == Tab.Sessions) Toasts.Show("Board", $"Connected '{_wsName.Trim()}'.", ToastKind.Ok); _wsName = _wsProjectOwner = _wsNumberText = _wsProject = _wsToken = ""; _foundBoards = null; - _boards = await Workspaces.ListForTenantAsync(_tenantId); + _access = await Access.ForUserAsync(_tenantId, _roles, _userId); + _boards = [.. (await Workspaces.ListForTenantAsync(_tenantId)).Where(b => _access.CanSee(b.Id))]; } else { diff --git a/src/AgentOs.Web/Components/Pages/DataApp.razor b/src/AgentOs.Web/Components/Pages/DataApp.razor index fab7949e..1a6f427f 100644 --- a/src/AgentOs.Web/Components/Pages/DataApp.razor +++ b/src/AgentOs.Web/Components/Pages/DataApp.razor @@ -107,7 +107,7 @@ else if (AuthState is not null) { var state = await AuthState; - _isAdmin = state.User.IsAdmin(); + _isAdmin = state.User.Can(Permission.ExportData); // RBAC v2 re-check (PermissionMatrix) _isPlatformAdmin = state.User.IsPlatformAdmin(); _tenantId = state.User.GetTenantId() ?? "default"; _actor = state.User.Identity?.Name ?? "admin"; diff --git a/src/AgentOs.Web/Components/Pages/EvidenceApp.razor b/src/AgentOs.Web/Components/Pages/EvidenceApp.razor index e648eb02..566f8cce 100644 --- a/src/AgentOs.Web/Components/Pages/EvidenceApp.razor +++ b/src/AgentOs.Web/Components/Pages/EvidenceApp.razor @@ -17,9 +17,9 @@ { } -else if (!_isAdmin) +else if (!_canView) { - + } else { @@ -105,7 +105,7 @@ else private (string?, string?) _appliedParameters; private bool OnComputer => _origin == ToolEvidenceOrigins.MemberComputer; private bool _resolved; - private bool _isAdmin; + private bool _canView; private bool _loading; private string _tenantId = "default"; private IReadOnlyList? _rows; @@ -129,11 +129,11 @@ else if (AuthState is not null) { var state = await AuthState; - _isAdmin = state.User.IsAdmin(); + _canView = state.User.Can(Permission.ViewAudit); // RBAC v2 re-check (PermissionMatrix) _tenantId = state.User.GetTenantId() ?? string.Empty; } _resolved = true; - if (_isAdmin && _tenantId.Length > 0) { await LoadAsync(); } + if (_canView && _tenantId.Length > 0) { await LoadAsync(); } } // A deep link (a task's activity panel) arrives as new parameters — also while this view is already open. @@ -143,7 +143,7 @@ else _appliedParameters = (Origin, SessionId); _origin = Origin == ToolEvidenceOrigins.MemberComputer ? Origin : null; _sessionId = string.IsNullOrWhiteSpace(SessionId) ? null : SessionId; - if (_resolved && _isAdmin && _tenantId.Length > 0) { await LoadAsync(); } + if (_resolved && _canView && _tenantId.Length > 0) { await LoadAsync(); } } private async Task SetOrigin(string? origin) diff --git a/src/AgentOs.Web/Components/Pages/HomeApp.razor b/src/AgentOs.Web/Components/Pages/HomeApp.razor index a0f6e86a..d1f7e574 100644 --- a/src/AgentOs.Web/Components/Pages/HomeApp.razor +++ b/src/AgentOs.Web/Components/Pages/HomeApp.razor @@ -41,8 +41,8 @@

}
- Run now - Plan as tickets + Run now + Plan as tickets @if (_isAdmin) { @@ -194,6 +194,8 @@ private string _story = string.Empty; private string _tenantId = string.Empty; private bool _isAdmin; + // RBAC v2: Run now / Plan as tickets need RunAgents; Workflow and Board re-check before anything runs. + private bool _canRun; private string _actor = "admin"; // Schedule form. @@ -220,6 +222,7 @@ { var user = (await AuthState).User; _isAdmin = user.IsAdmin(); + _canRun = user.Can(Permission.RunAgents); _actor = user.Identity?.Name ?? "admin"; _tenantId = user.GetTenantId() ?? string.Empty; } @@ -261,7 +264,7 @@ // Run now = the Workflow app, prefilled with the story and told to start (one click to a running pipeline). private void RunNow() { - if (string.IsNullOrWhiteSpace(_story)) { return; } + if (string.IsNullOrWhiteSpace(_story) || !_canRun) { return; } WM.RequestLaunchPayload("workflow", _story.Trim()); WM.RequestLaunchTab("workflow", WorkflowAutoRun); Open("workflow"); diff --git a/src/AgentOs.Web/Components/Pages/OrchestrationStudio.razor b/src/AgentOs.Web/Components/Pages/OrchestrationStudio.razor index 318a957d..04409017 100644 --- a/src/AgentOs.Web/Components/Pages/OrchestrationStudio.razor +++ b/src/AgentOs.Web/Components/Pages/OrchestrationStudio.razor @@ -70,7 +70,7 @@ Live · @ActiveProvider } - +
@@ -403,6 +403,8 @@ private const int DefaultQaCap = 3; private bool _isAdmin; + // RBAC v2: running the pipeline needs RunAgents (viewers, approvers and auditors read only); Run() re-checks. + private bool _canRun; private string? _userName; // The studio's two views. "ticket-flow" (optionally "ticket-flow:") is also the launch tab Board › @@ -622,6 +624,7 @@ _userId = user.GetUserId(); _userName = user.Identity?.Name; _isAdmin = user.IsAdmin(); + _canRun = user.Can(Permission.RunAgents); return user.GetTenantId() ?? string.Empty; } @@ -875,7 +878,7 @@ /// node types are refused (painted Skipped) before any agent runs; the QA gate's fail edge loops. private async Task Run() { - if (_running) + if (_running || !_canRun) { return; } diff --git a/src/AgentOs.Web/Components/Pages/PolicyApp.razor b/src/AgentOs.Web/Components/Pages/PolicyApp.razor index 29b90a8d..36a32efd 100644 --- a/src/AgentOs.Web/Components/Pages/PolicyApp.razor +++ b/src/AgentOs.Web/Components/Pages/PolicyApp.razor @@ -79,7 +79,7 @@ else if (AuthState is not null) { var state = await AuthState; - _isAdmin = state.User.IsAdmin(); + _isAdmin = state.User.Can(Permission.ManageSettings); // RBAC v2 re-check (PermissionMatrix) _tenantId = state.User.GetTenantId() ?? string.Empty; } _resolved = true; diff --git a/src/AgentOs.Web/Components/Pages/PromptsApp.razor b/src/AgentOs.Web/Components/Pages/PromptsApp.razor index 5d74b22c..f7af7e8b 100644 --- a/src/AgentOs.Web/Components/Pages/PromptsApp.razor +++ b/src/AgentOs.Web/Components/Pages/PromptsApp.razor @@ -114,7 +114,7 @@ else if (AuthState is not null) { var state = await AuthState; - _isAdmin = state.User.IsAdmin(); + _isAdmin = state.User.Can(Permission.ManageSettings); // RBAC v2 re-check (PermissionMatrix) _tenantId = state.User.GetTenantId() ?? string.Empty; _actor = state.User.Identity?.Name ?? "admin"; } diff --git a/src/AgentOs.Web/Components/Pages/Settings.razor b/src/AgentOs.Web/Components/Pages/Settings.razor index 5493416d..2ce2e44e 100644 --- a/src/AgentOs.Web/Components/Pages/Settings.razor +++ b/src/AgentOs.Web/Components/Pages/Settings.razor @@ -259,7 +259,7 @@ dotnet user-secrets set "Llm:AzureOpenAi:Endpoint" "https://your-resource.openai if (AuthState is not null) { var user = (await AuthState).User; - _isAdmin = user.IsAdmin(); + _isAdmin = user.Can(Permission.ManageSettings); // RBAC v2 re-check (PermissionMatrix) _tenantId = user.GetTenantId() ?? string.Empty; _userId = user.GetUserId(); } diff --git a/src/AgentOs.Web/Components/Pages/SettingsHub.razor b/src/AgentOs.Web/Components/Pages/SettingsHub.razor index f06e35bc..bd86c287 100644 --- a/src/AgentOs.Web/Components/Pages/SettingsHub.razor +++ b/src/AgentOs.Web/Components/Pages/SettingsHub.razor @@ -62,6 +62,7 @@ private bool _isAdmin; private bool _isPlatformAdmin; + private Permission _granted; private string _tab = "general"; // The tool-call view's filter from a deep link (SettingsLinks.MemberComputerToolCalls). private string? _evidenceOrigin; @@ -69,36 +70,34 @@ private string _filter = string.Empty; private int _filterGeneration; - private enum Access { Everyone, Admin, Platform } - // Rail order, grouped. "Host" pages are components with their own padded .prefs-content (Settings, System). // "Hidden" pages stay routable (deep links, search) but have no rail entry of their own. - private sealed record Item(string Key, string Group, string Label, string Icon, Access Access, bool Host = false, bool Hidden = false); + private sealed record Item(string Key, string Group, string Label, string Icon, Gate Gate, bool Host = false, bool Hidden = false); private static readonly Item[] Items = [ - new("keys", "AI", "Model keys", "key", Access.Admin, Host: true), - new("routing", "AI", "Routing", "lightning", Access.Admin, Host: true), - new("agents", "AI", "Agent profiles", "diamond", Access.Admin), - new("prompts", "AI", "Prompts", "file", Access.Admin), - new("autopilot", "AI", "Autopilot", "play", Access.Admin), - new("github", "Connections", "GitHub", "git-pull-request", Access.Admin, Host: true), - new("mcp", "Connections", "MCP servers", "arrow-square-out", Access.Admin), - new("plugins", "Connections", "Plugins", "squares-stack", Access.Everyone), - new("policy", "Governance", "Tool policy", "shield", Access.Admin), - new("audit", "Governance", "Activity log", "clock-counter", Access.Admin), - new("evidence", "Governance", "Tool calls", "scroll", Access.Admin, Hidden: true), // a view of Activity log - new("users", "People & data", "Users", "user", Access.Admin), - new("tokens", "People & data", "API tokens", "tag", Access.Admin), - new("data", "People & data", "Data", "floppy-disk", Access.Admin), - new("general", "Personal", "General", "gear", Access.Everyone, Host: true), - new("appearance", "Personal", "Appearance", "palette", Access.Everyone, Host: true), - new("datetime", "Personal", "Date & time", "clock", Access.Everyone, Host: true), - new("notifs", "Personal", "Notifications", "bell", Access.Everyone, Host: true), - new("session", "Personal", "Session", "power", Access.Everyone, Host: true), - new("about", "System", "About", "info", Access.Everyone, Host: true), - new("diagnostics", "System", "Diagnostics", "circle-fill", Access.Admin, Host: true), - new("platform", "System", "Platform", "server", Access.Platform), + new("keys", "AI", "Model keys", "key", Gate.Of(Permission.ManageSettings), Host: true), + new("routing", "AI", "Routing", "lightning", Gate.Of(Permission.ManageSettings), Host: true), + new("agents", "AI", "Agent profiles", "diamond", Gate.Of(Permission.ManageSettings)), + new("prompts", "AI", "Prompts", "file", Gate.Of(Permission.ManageSettings)), + new("autopilot", "AI", "Autopilot", "play", Gate.Of(Permission.ManageSettings)), + new("github", "Connections", "GitHub", "git-pull-request", Gate.Of(Permission.ManageSettings), Host: true), + new("mcp", "Connections", "MCP servers", "arrow-square-out", Gate.Of(Permission.ManageSettings)), + new("plugins", "Connections", "Plugins", "squares-stack", Gate.Everyone), + new("policy", "Governance", "Tool policy", "shield", Gate.Of(Permission.ManageSettings)), + new("audit", "Governance", "Activity log", "clock-counter", Gate.Of(Permission.ViewAudit)), + new("evidence", "Governance", "Tool calls", "scroll", Gate.Of(Permission.ViewAudit), Hidden: true), // a view of Activity log + new("users", "People & data", "Users", "user", Gate.Of(Permission.ManageMembers)), + new("tokens", "People & data", "API tokens", "tag", Gate.Of(Permission.ManageApiTokens)), + new("data", "People & data", "Data", "floppy-disk", Gate.Of(Permission.ExportData)), + new("general", "Personal", "General", "gear", Gate.Everyone, Host: true), + new("appearance", "Personal", "Appearance", "palette", Gate.Everyone, Host: true), + new("datetime", "Personal", "Date & time", "clock", Gate.Everyone, Host: true), + new("notifs", "Personal", "Notifications", "bell", Gate.Everyone, Host: true), + new("session", "Personal", "Session", "power", Gate.Everyone, Host: true), + new("about", "System", "About", "info", Gate.Everyone, Host: true), + new("diagnostics", "System", "Diagnostics", "circle-fill", Gate.Of(Permission.ManageSettings), Host: true), + new("platform", "System", "Platform", "server", Gate.Platform), ]; protected override async Task OnInitializedAsync() @@ -108,9 +107,11 @@ var state = await AuthState; _isAdmin = state.User.IsAdmin(); _isPlatformAdmin = state.User.IsPlatformAdmin(); + _granted = state.User.GetPermissions(); } - // Admins land on Model keys (the first thing a new workspace needs); members on their own preferences. - _tab = _isAdmin ? "keys" : "general"; + // Admins land on Model keys (the first thing a new workspace needs); auditors on the Activity log; everyone + // else on their own preferences. + _tab = _isAdmin ? "keys" : _granted.Has(Permission.ViewAudit) ? "audit" : "general"; Apply(WM.ConsumeLaunchTab(SettingsLinks.AppKey)); WM.Changed += OnWindowsChanged; } @@ -135,12 +136,8 @@ public void Dispose() => WM.Changed -= OnWindowsChanged; - private IEnumerable Allowed() => Items.Where(i => i.Access switch - { - Access.Admin => _isAdmin, - Access.Platform => _isPlatformAdmin, - _ => true, - }); + // RBAC v2: a page shows only to who holds its permission (PermissionMatrix) — the page re-checks on its own too. + private IEnumerable Allowed() => Items.Where(i => i.Gate.Allows(_granted, _isPlatformAdmin)); // The rail filter matches a page's label, or any setting / keyword SettingsSearch maps to that page. private IEnumerable VisibleItems() @@ -148,7 +145,7 @@ var q = _filter.Trim(); if (q.Length == 0) { return Allowed().Where(i => !i.Hidden); } var catalog = Services.GetService(); - var targets = SettingsSearch.Find(q, catalog?.All ?? [], _isAdmin, _isPlatformAdmin, max: 50) + var targets = SettingsSearch.Find(q, catalog?.All ?? [], _granted, _isPlatformAdmin, max: 50) .Select(h => h.Target).ToHashSet(StringComparer.Ordinal); return Allowed().Where(i => !i.Hidden && (targets.Contains(i.Key) || i.Label.Contains(q, StringComparison.OrdinalIgnoreCase) || (i.Key == "audit" && targets.Contains("evidence")))); diff --git a/src/AgentOs.Web/Components/Pages/UsersApp.razor b/src/AgentOs.Web/Components/Pages/UsersApp.razor index d60ce95f..55a7cc99 100644 --- a/src/AgentOs.Web/Components/Pages/UsersApp.razor +++ b/src/AgentOs.Web/Components/Pages/UsersApp.razor @@ -1,14 +1,18 @@ @* UsersApp — tenant-admin member management desktop window (Windows Server "Users" / GNOME - Users vibe). Lists the current tenant's Keycloak members and lets an Admin change roles, send a - password-reset email, remove a member, or mint an invitation URL. Admin-gated: the app is - AdminOnly in AppCatalog, and the page itself re-checks the admin role (defence in depth). Tenant - + role are read from the circuit's AuthenticationState — HttpContext is null in interactive - Server, so ITenantContext can't be used in a component. *@ + Users vibe). Lists the current tenant's Keycloak members and lets an Admin change roles (RBAC v2: viewer · + developer · approver · auditor · admin, see PermissionMatrix), send a password-reset email, remove a member, + mint an invitation URL, and give members a role on one board (Board access — the first membership restricts the + board to its members). Gated on ManageMembers: AppCatalog hides the app, WindowHost refuses it, and the page + re-checks (defence in depth); every change is audited. Tenant + role are read from the circuit's + AuthenticationState — HttpContext is null in interactive Server, so ITenantContext can't be used in a component. *@ @using System.Security.Claims @using Microsoft.AspNetCore.Components.Authorization @using AgentOs.Modules.Tenants @using AgentOs.Modules.Tenants.Keycloak +@using AgentOs.Modules.Workspaces.Access +@using AgentOs.Modules.Workspaces.Persistence +@using AgentOs.Modules.Workspaces.Persistence.Entities @inject AgentOs.Modules.Tenants.Keycloak.IKeycloakAdminClient Kc @inject AgentOs.Modules.Tenants.ITenantSignupService Signup @inject AgentOs.Modules.Tenants.Email.IEmailSender Email @@ -35,7 +39,7 @@ else

Users · @_tenantId

-

@(_members?.Count ?? 0) member(s) · roles + lifecycle managed via Keycloak

+

@(_members?.Count ?? 0) member(s) · roles + lifecycle managed via Keycloak · roles are additive; admin and auditor apply on every board

Refresh @@ -71,10 +75,16 @@ else @m.Username @(isSelf ? "(you)" : "") @(m.Email ?? "—") - @@ -110,8 +120,10 @@ else @@ -136,6 +148,97 @@ else } + + + @if (_boards is null) + { + + } + else if (_boards.Count == 0) + { +

No boards connected yet. Once a board is connected (Board app), give members a role on it here.

+ } + else + { +
+ + + +
+

+ @if (_boardMembers.Count == 0) + { + Open — everyone in @_tenantId works on this board with their workspace role. Add a member to restrict it. + } + else + { + Restricted — only the @_boardMembers.Count member(s) below, admins and auditors can see this board. + } +

+ + + + + + @foreach (var bm in _boardMembers) + { + + + + + + } + @if (_boardMembers.Count == 0) + { + + } + +
MemberBoard roleActions
@MemberName(bm.UserId) + + + + Remove + +
No board members — the board is open to the whole workspace.
+
+ + + + + + +
+
+ + Add to board + +
+ } +
} } @@ -170,7 +273,14 @@ else private bool _removing; private string _inviteEmail = ""; - private string _inviteRole = "member"; + private string _inviteRole = MemberRoles.DefaultRole; + + // Board access (RBAC v2 per-board memberships). + private IReadOnlyList? _boards; + private Guid? _boardId; + private IReadOnlyList _boardMembers = []; + private string _addUserId = ""; + private string _addRole = UserRoles.Developer; private int _inviteTtl = 24; private bool _busy; private string? _inviteUrl; @@ -183,7 +293,7 @@ else { var state = await AuthState; var user = state.User; - _isAdmin = user.IsAdmin(); + _isAdmin = user.Can(Permission.ManageMembers); // RBAC v2 re-check (PermissionMatrix) // No silent `default`: a signed-in principal with no tenant claim is a malformed token, not a // licence to manage the default tenant's members. Empty → the admin gate below blocks the UI. _tenantId = user.GetTenantId() ?? string.Empty; @@ -194,11 +304,88 @@ else if (_isAdmin && _tenantId.Length > 0) { await LoadMembersAsync(); + await LoadBoardsAsync(); } } - private static string PrimaryRole(KeycloakUser m) => - m.Roles.Contains("admin", StringComparer.Ordinal) ? "admin" : "member"; + private static string PrimaryRole(KeycloakUser m) => MemberRoles.Primary(m.Roles) ?? UserRoles.Viewer; + + private string MemberName(string userId) => + _members?.FirstOrDefault(m => m.Id == userId)?.Username ?? userId; + + // Each operation gets its own scope (its own DbContext), never the circuit's long-lived one. + private async Task LoadBoardsAsync() + { + await CircuitSafe.RunAsync( + async () => + { + await using var scope = Scopes.CreateAsyncScope(); + _boards = await scope.ServiceProvider.GetRequiredService().ListForTenantAsync(_tenantId); + _boardId ??= _boards.FirstOrDefault()?.Id; + await LoadBoardMembersAsync(scope.ServiceProvider); + }, + ex => { _boards = []; Toasts.Show("Users", $"Could not load boards: {ex.Message}", ToastKind.Err); }); + } + + private async Task LoadBoardMembersAsync(IServiceProvider services) + { + _boardMembers = _boardId is { } id + ? await services.GetRequiredService().ListAsync(_tenantId, id) + : []; + } + + private async Task OnBoardChanged(ChangeEventArgs e) + { + _boardId = Guid.TryParse(e.Value?.ToString(), out var id) ? id : null; + await using var scope = Scopes.CreateAsyncScope(); + await CircuitSafe.RunAsync(() => LoadBoardMembersAsync(scope.ServiceProvider), + ex => Toasts.Show("Users", $"Could not load the board's members: {ex.Message}", ToastKind.Err)); + } + + private Task AddBoardMember() => SetBoardRole(_addUserId, _addRole); + + private async Task SetBoardRole(string? userId, string? role) + { + // Server-side re-check (GAP-17): the handler, not only the hidden UI, refuses a caller without ManageMembers. + if (!_isAdmin || _boardId is not { } boardId || string.IsNullOrEmpty(userId) || !UserRoles.IsWorkspaceAssignable(role)) { return; } + if (_members?.Any(m => m.Id == userId) != true) { return; } // only members of THIS tenant + _busyId = userId; + await CircuitSafe.RunAsync( + async () => + { + await using var scope = Scopes.CreateAsyncScope(); + var services = scope.ServiceProvider; + await services.GetRequiredService().SetAsync(_tenantId, boardId, userId, role, _myUserId); + await services.GetRequiredService().WriteAsync(new AuditEntry(Guid.NewGuid(), _tenantId, _myUserId, + AuditActions.BoardRoleSet, $"board={boardId},user={userId},role={role}", null, null, DateTimeOffset.UtcNow)); + Toasts.Show("Users", $"{MemberName(userId)} is a {UserRoles.Label(role)} on this board.", ToastKind.Ok); + _addUserId = ""; + await LoadBoardMembersAsync(services); + }, + ex => Toasts.Show("Users", $"Board role change failed: {ex.Message}", ToastKind.Err)); + _busyId = null; + } + + private async Task RemoveBoardRole(string userId) + { + if (!_isAdmin || _boardId is not { } boardId) { return; } + _busyId = userId; + await CircuitSafe.RunAsync( + async () => + { + await using var scope = Scopes.CreateAsyncScope(); + var services = scope.ServiceProvider; + if (await services.GetRequiredService().RemoveAsync(_tenantId, boardId, userId)) + { + await services.GetRequiredService().WriteAsync(new AuditEntry(Guid.NewGuid(), _tenantId, _myUserId, + AuditActions.BoardRoleRemoved, $"board={boardId},user={userId}", null, null, DateTimeOffset.UtcNow)); + Toasts.Show("Users", $"{MemberName(userId)} was taken off this board.", ToastKind.Ok); + } + await LoadBoardMembersAsync(services); + }, + ex => Toasts.Show("Users", $"Remove failed: {ex.Message}", ToastKind.Err)); + _busyId = null; + } private async Task LoadMembersAsync() { @@ -216,15 +403,25 @@ else private async Task ChangeRole(KeycloakUser m, ChangeEventArgs e) { - var role = e.Value?.ToString() ?? "member"; - if (string.Equals(PrimaryRole(m), role, StringComparison.Ordinal)) { return; } + var role = e.Value?.ToString() ?? MemberRoles.DefaultRole; + if (!_isAdmin || string.Equals(PrimaryRole(m), role, StringComparison.Ordinal)) { return; } + // Same rules as PATCH /tenants/{id}/members/{userId}: allowed roles only, never strip your own admin role. + var roles = MemberRoles.Sanitize([role]); + if (MemberRoles.Check(_myUserId, m.Id, roles) is { } refused) + { + Toasts.Show("Users", refused, ToastKind.Err); + return; + } _busyId = m.Id; // Keycloak transport/Polly faults must surface as a toast, never tear down the circuit. await CircuitSafe.RunAsync( async () => { - await Kc.UpdateUserRolesAsync(m.Id, new[] { role }); - Toasts.Show("Users", $"{m.Username} is now {role}.", ToastKind.Ok); + await Kc.UpdateUserRolesAsync(m.Id, roles); + await using var scope = Scopes.CreateAsyncScope(); + await scope.ServiceProvider.GetRequiredService().WriteAsync(new AuditEntry(Guid.NewGuid(), _tenantId, _myUserId, + AuditActions.MemberRoleChanged, $"user={m.Id},roles={string.Join('+', roles)}", null, null, DateTimeOffset.UtcNow)); + Toasts.Show("Users", $"{m.Username} is now {UserRoles.Label(role)}.", ToastKind.Ok); await LoadMembersAsync(); }, ex => Toasts.Show("Users", $"Role change failed: {ex.Message}", ToastKind.Err)); @@ -308,6 +505,12 @@ else return; } + if (!MemberRoles.IsAllowed(_inviteRole)) + { + _inviteError = "Pick a role for the invitee."; + return; + } + _busy = true; try { diff --git a/src/AgentOs.Web/Components/UI/DesignChecks.razor b/src/AgentOs.Web/Components/UI/DesignChecks.razor index 97fd571a..c2ede5e8 100644 --- a/src/AgentOs.Web/Components/UI/DesignChecks.razor +++ b/src/AgentOs.Web/Components/UI/DesignChecks.razor @@ -26,7 +26,7 @@
@if (open) { - } } @@ -47,6 +47,10 @@ /// Who decides (recorded with the decision). [Parameter] public string DecidedBy { get; set; } = string.Empty; + /// RBAC v2: whether the signed-in person may decide the check of a task (ApproveWork on its board); + /// null = may decide every listed check. + [Parameter] public Func? CanDecideFor { get; set; } + /// How many checks to list. [Parameter] public int Max { get; set; } = 10; diff --git a/src/AgentOs.Web/Components/UI/DesignPanel.razor b/src/AgentOs.Web/Components/UI/DesignPanel.razor index 3f6a71bb..2b57fc02 100644 --- a/src/AgentOs.Web/Components/UI/DesignPanel.razor +++ b/src/AgentOs.Web/Components/UI/DesignPanel.razor @@ -268,6 +268,7 @@ // Autopilot's automatic re-runs. The owner's decision, if any, stands. private async Task CheckAgainAsync() { + if (!CanDecide) { return; } // RBAC v2 re-check in the handler, not only the hidden button (GAP-17) _busy = true; try { @@ -299,6 +300,7 @@ private async Task DecideAsync(DesignDecision decision, string? note) { + if (!CanDecide) { return; } // RBAC v2 re-check in the handler, not only the hidden button (GAP-17) _busy = true; try { diff --git a/src/AgentOs.Web/Components/UI/TopBar.razor b/src/AgentOs.Web/Components/UI/TopBar.razor index ed8ff4e4..10f505ed 100644 --- a/src/AgentOs.Web/Components/UI/TopBar.razor +++ b/src/AgentOs.Web/Components/UI/TopBar.razor @@ -69,9 +69,13 @@ @if (Dev.DevAutoLogin) {
- - - + @* RBAC v2: preview the desktop as each role (PermissionMatrix) without a second Keycloak user. *@ + @foreach (var role in UserRoles.Assignable) + { + + } + + }
diff --git a/src/AgentOs.Web/Program.cs b/src/AgentOs.Web/Program.cs index 54164430..38758cfa 100644 --- a/src/AgentOs.Web/Program.cs +++ b/src/AgentOs.Web/Program.cs @@ -425,7 +425,7 @@ // Tenant comes from the OIDC 'tenant' claim; admin-gated; `days` (0/absent = all time) sets the cutoff. app.MapGet("/cost/export", async (HttpContext http, AgentOs.Modules.Pipeline.Persistence.IPipelineRunRepository runs, int? days) => { - if (!http.User.IsAdmin()) + if (!http.User.Can(Permission.ExportData)) { return Results.Forbid(); } @@ -443,7 +443,7 @@ app.MapGet("/tenant/export", async (HttpContext http, AgentOs.Modules.Tenants.Data.ITenantDataService data, AgentOs.Modules.Tenants.IAuditLog audit, ILoggerFactory loggers, string? tenant) => { - if (!http.User.IsAdmin()) { return Results.Forbid(); } + if (!http.User.Can(Permission.ExportData)) { return Results.Forbid(); } var own = http.User.GetTenantId() ?? "default"; var target = string.IsNullOrWhiteSpace(tenant) ? own : tenant; if (!string.Equals(target, own, StringComparison.Ordinal) && !http.User.IsPlatformAdmin()) { return Results.Forbid(); } @@ -471,11 +471,11 @@ await audit.WriteAsync(new AgentOs.Modules.Tenants.AuditEntry(Guid.NewGuid(), ta }).RequireAuthorization(); // Audit CSV export (Settings → Audit log). Same-origin cookie-authed download like /cost/export. A tenant admin -// exports their own tenant; scope=platform (platform settings changes) needs platform-admin. +// exports their own tenant (ViewAudit: admin or auditor); scope=platform (platform settings changes) needs platform-admin. app.MapGet("/audit/export", async (HttpContext http, AgentOs.Modules.Tenants.IAuditLog audit, string? scope) => { var platform = string.Equals(scope, "platform", StringComparison.Ordinal); - if (!http.User.IsAdmin() || (platform && !http.User.IsPlatformAdmin())) + if (!http.User.Can(Permission.ViewAudit) || (platform && !http.User.IsPlatformAdmin())) { return Results.Forbid(); } @@ -520,12 +520,12 @@ static string SafeLocalReturn(string? url) => Results.Redirect(SafeLocalReturn(returnUrl))); app.MapGet("/account/logout", () => Results.Redirect("/")); - // Dev-only "View as": narrow the auto-login principal's roles to preview the member (or admin) + // Dev-only "View as": narrow the auto-login principal's roles to preview one RBAC v2 role (or the legacy member) // desktop without standing up a second Keycloak user. Writes the cookie DevAutoAuthHandler reads, // then reloads so the new principal takes effect. Available only because devAutoLogin is on. app.MapGet("/dev/view-as", (HttpContext ctx, string? role) => { - if (role is "admin" or "member") + if (AgentOs.SharedKernel.Identity.UserRoles.IsAssignable(role) || role is "member") { ctx.Response.Cookies.Append(DevAutoAuthHandler.ViewAsCookie, role, new Microsoft.AspNetCore.Http.CookieOptions diff --git a/src/AgentOs.Web/Services/AppCatalog.cs b/src/AgentOs.Web/Services/AppCatalog.cs index d0e1b22e..59b885a5 100644 --- a/src/AgentOs.Web/Services/AppCatalog.cs +++ b/src/AgentOs.Web/Services/AppCatalog.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; +using AgentOs.SharedKernel.Identity; using AgentOs.Web.Components.Pages; using AgentOs.Web.Shell.Services; @@ -32,16 +33,16 @@ public static class AppCatalog new("files", "Files", "folder", "Browse a connected repo's files (read-only)", "Agents", 880, 600, Pinned: false, ComponentType: typeof(FilesApp), Color: "#4a86d8"), // ── unpinned: reachable via the Settings hub, Activities search, or in-app deep links ── // (Workspaces + Sessions were standalone admin windows fully subsumed by Board → deleted.) - new("users", "Users", "user", "Manage tenant members + roles", "Admin", 880, 600, Pinned: false, AdminOnly: true, ComponentType: typeof(UsersApp), Color: "#e5a50a"), - new("evidence", "Evidence", "scroll", "Tool-invocation audit trail", "Admin", 960, 620, Pinned: false, AdminOnly: true, ComponentType: typeof(EvidenceApp), Color: "#c01c28"), - new("tokens", "API tokens", "tag", "Service-account tokens for CI, scripts and MCP clients", "Admin", 980, 620, Pinned: false, AdminOnly: true, ComponentType: typeof(ApiTokensApp), Color: "#1c71d8"), - new("data", "Data", "floppy-disk", "Export this workspace; platform admins purge tenants", "Admin", 900, 600, Pinned: false, AdminOnly: true, ComponentType: typeof(DataApp), Color: "#26a269"), - new("audit", "Audit log", "clock-counter", "Who changed what — settings, members, sign-in", "Admin", 980, 640, Pinned: false, AdminOnly: true, ComponentType: typeof(AuditLogApp), Color: "#865e3c"), - new("policy", "Policy", "shield", "Per-tenant tool allowlist", "Admin", 900, 620, Pinned: false, AdminOnly: true, ComponentType: typeof(PolicyApp), Color: "#613583"), - new("prompts", "Prompts", "lightning", "Tune the agents' prompts", "Admin", 1000, 680, Pinned: false, AdminOnly: true, ComponentType: typeof(PromptsApp), Color: "#c061cb"), - new("agents", "Agent profiles", "diamond", "Model + limits per agent", "Admin", 1100, 620, Pinned: false, AdminOnly: true, ComponentType: typeof(AgentProfilesApp), Color: "#1c71d8"), + new("users", "Users", "user", "Manage tenant members + roles", "Admin", 880, 600, Pinned: false, ComponentType: typeof(UsersApp), Color: "#e5a50a", Requires: Permission.ManageMembers), + new("evidence", "Evidence", "scroll", "Tool-invocation audit trail", "Admin", 960, 620, Pinned: false, ComponentType: typeof(EvidenceApp), Color: "#c01c28", Requires: Permission.ViewAudit), + new("tokens", "API tokens", "tag", "Service-account tokens for CI, scripts and MCP clients", "Admin", 980, 620, Pinned: false, ComponentType: typeof(ApiTokensApp), Color: "#1c71d8", Requires: Permission.ManageApiTokens), + new("data", "Data", "floppy-disk", "Export this workspace; platform admins purge tenants", "Admin", 900, 600, Pinned: false, ComponentType: typeof(DataApp), Color: "#26a269", Requires: Permission.ExportData), + new("audit", "Audit log", "clock-counter", "Who changed what — settings, members, sign-in", "Admin", 980, 640, Pinned: false, ComponentType: typeof(AuditLogApp), Color: "#865e3c", Requires: Permission.ViewAudit), + new("policy", "Policy", "shield", "Per-tenant tool allowlist", "Admin", 900, 620, Pinned: false, ComponentType: typeof(PolicyApp), Color: "#613583", Requires: Permission.ManageSettings), + new("prompts", "Prompts", "lightning", "Tune the agents' prompts", "Admin", 1000, 680, Pinned: false, ComponentType: typeof(PromptsApp), Color: "#c061cb", Requires: Permission.ManageSettings), + new("agents", "Agent profiles", "diamond", "Model + limits per agent", "Admin", 1100, 620, Pinned: false, ComponentType: typeof(AgentProfilesApp), Color: "#1c71d8", Requires: Permission.ManageSettings), new("plugins", "Plugins", "squares-stack", "Installed extensions", "System", 860, 600, Pinned: false, ComponentType: typeof(PluginsApp), Color: "#5e5c64"), - new("mcp", "MCP", "arrow-square-out", "Upstream MCP tool servers", "System", 860, 600, Pinned: false, AdminOnly: true, ComponentType: typeof(McpApp), Color: "#1a5fb4"), + new("mcp", "MCP", "arrow-square-out", "Upstream MCP tool servers", "System", 860, 600, Pinned: false, ComponentType: typeof(McpApp), Color: "#1a5fb4", Requires: Permission.ManageSettings), new("system", "System", "wrench","OS appearance, themes, about", "System", 760, 600, Pinned: false, ComponentType: typeof(SystemApp), Color: "#3d3846"), }; @@ -68,11 +69,11 @@ public static void RegisterPluginApps(IEnumerable apps) public static DesktopApp? Find(string key) => All.FirstOrDefault(a => a.Key == key); - /// All apps visible to a user with the given admin status (filters out ). - public static IEnumerable VisibleAll(bool isAdmin) => - All.Where(a => isAdmin || !a.AdminOnly); + /// All apps a user granted may see (RBAC v2: each app's ). + public static IEnumerable VisibleAll(Permission granted) => + All.Where(a => a.IsVisibleTo(granted)); - /// Pinned apps visible to a user with the given admin status. - public static IEnumerable VisiblePinned(bool isAdmin) => - Pinned.Where(a => isAdmin || !a.AdminOnly); + /// Pinned apps a user granted may see. + public static IEnumerable VisiblePinned(Permission granted) => + Pinned.Where(a => a.IsVisibleTo(granted)); } diff --git a/src/AgentOs.Web/Services/AppCatalogRegistry.cs b/src/AgentOs.Web/Services/AppCatalogRegistry.cs index 34ef463f..baee0652 100644 --- a/src/AgentOs.Web/Services/AppCatalogRegistry.cs +++ b/src/AgentOs.Web/Services/AppCatalogRegistry.cs @@ -17,5 +17,5 @@ internal sealed class AppCatalogRegistry : IAppRegistry public IReadOnlyList Pinned => AppCatalog.Pinned; - public IReadOnlyList VisiblePinned(bool isAdmin) => AppCatalog.VisiblePinned(isAdmin).ToList(); + public IReadOnlyList VisiblePinned(AgentOs.SharedKernel.Identity.Permission granted) => AppCatalog.VisiblePinned(granted).ToList(); } diff --git a/src/AgentOs.Web/Services/SettingsSearch.cs b/src/AgentOs.Web/Services/SettingsSearch.cs index 345d1808..1affbf5f 100644 --- a/src/AgentOs.Web/Services/SettingsSearch.cs +++ b/src/AgentOs.Web/Services/SettingsSearch.cs @@ -2,13 +2,15 @@ // Before, search matched app names only, so "gemini key" or "dark mode" found nothing and users had to know which // of ~22 nested settings screens held a field. This index has every Settings page (with the words people use // for it) plus every setting descriptor's label, each mapped to the page that edits it. A hit deep-links to -// the page through SettingsLinks. Role-gated: members never see admin pages, only platform admins see Platform. +// the page through SettingsLinks. Permission-gated (RBAC v2 matrix): a page shows only to who holds its permission +// (e.g. Activity log → ViewAudit, so auditors find it), only platform admins see Platform. using System; using System.Collections.Generic; using System.Linq; using AgentOs.Domain.Configuration; using AgentOs.Modules.Llm; +using AgentOs.SharedKernel.Identity; namespace AgentOs.Web.Services; @@ -22,9 +24,7 @@ public sealed record SettingsHit(string Title, string Path, string Target, strin /// Search over Settings pages + setting descriptors. public static class SettingsSearch { - private enum Access { Everyone, Admin, Platform } - - private sealed record Page(string Target, string Title, string Path, string Icon, string Keywords, Access Access); + private sealed record Page(string Target, string Title, string Path, string Icon, string Keywords, Gate Gate); private const string Ai = "Settings › AI"; private const string Conn = "Settings › Connections"; @@ -36,28 +36,28 @@ private sealed record Page(string Target, string Title, string Path, string Icon // Rail order (SettingsHub.Items). Keywords are the words people type for the page, not only the words on it. private static readonly Page[] Pages = [ - new("keys", "Model keys", Ai, "key", "api key apikey secret byok anthropic claude azure openai gpt gemini google xai grok endpoint", Access.Admin), - new("routing", "Routing", Ai, "lightning", "force provider default provider routing test connection offline fallback remoteagent remote agent paired tool output budget tokens", Access.Admin), - new("agents", "Agent profiles", Ai, "diamond", "agent model per agent temperature max tokens output qa loop iterations cap profile coding testing requirement orchestrator", Access.Admin), - new("prompts", "Prompts", Ai, "file", "prompt system prompt workspace rules instructions version history rollback", Access.Admin), - new("autopilot", "Autopilot", Ai, "play", "autopilot orchestrator decided by rules maf workflow step by step tasks at once parallel acceptance tests fix rounds retries checks timeout poll merge plan limit files attachments ticket files upload size comments discussion maintainer decisions", Access.Admin), - new("github", "GitHub", Conn, "git-pull-request", "github token pat pull request repo owner pipeline", Access.Admin), - new("mcp", "MCP servers", Conn, "arrow-square-out", "mcp model context protocol tool servers upstream", Access.Admin), - new("plugins", "Plugins", Conn, "squares-stack", "plugins extensions add-ons", Access.Everyone), - new("policy", "Tool policy", Gov, "shield", "tool allowlist policy permissions governance", Access.Admin), - new("evidence", "Tool calls", Gov + " › Activity log", "scroll", "evidence tool calls invocations trail governance", Access.Admin), - new("audit", "Activity log", Gov, "clock-counter", "audit log activity who changed history sign-in login members csv", Access.Admin), - new("users", "Users", People, "user", "users members invite invitation roles people team", Access.Admin), - new("tokens", "API tokens", People, "tag", "api token service account ci pipeline script machine bearer mcp client", Access.Admin), - new("data", "Data", People, "floppy-disk", "export purge delete tenant workspace data download gdpr", Access.Admin), - new("general", "General", Personal, "gear", "general preferences", Access.Everyone), - new("appearance", "Appearance", Personal, "palette", "appearance theme dark light mode wallpaper accent glass motion animation", Access.Everyone), - new("datetime", "Date & time", Personal, "clock", "date time clock time zone 24-hour", Access.Everyone), - new("notifs", "Notifications", Personal, "bell", "notifications toasts alerts", Access.Everyone), - new("session", "Session", Personal, "power", "session sign out logout", Access.Everyone), - new("about", "About", Sys, "info", "about version build health services status", Access.Everyone), - new("diagnostics", "Diagnostics", Sys, "circle-fill", "status diagnostics effective configuration which provider storage persistence database postgres stateless", Access.Admin), - new("platform", "Platform", Sys, "server", "platform safety run limits concurrency sandbox docker openai-compatible self-hosted ollama vllm foundry", Access.Platform), + new("keys", "Model keys", Ai, "key", "api key apikey secret byok anthropic claude azure openai gpt gemini google xai grok endpoint", Gate.Of(Permission.ManageSettings)), + new("routing", "Routing", Ai, "lightning", "force provider default provider routing test connection offline fallback remoteagent remote agent paired tool output budget tokens", Gate.Of(Permission.ManageSettings)), + new("agents", "Agent profiles", Ai, "diamond", "agent model per agent temperature max tokens output qa loop iterations cap profile coding testing requirement orchestrator", Gate.Of(Permission.ManageSettings)), + new("prompts", "Prompts", Ai, "file", "prompt system prompt workspace rules instructions version history rollback", Gate.Of(Permission.ManageSettings)), + new("autopilot", "Autopilot", Ai, "play", "autopilot orchestrator decided by rules maf workflow step by step tasks at once parallel acceptance tests fix rounds retries checks timeout poll merge plan limit files attachments ticket files upload size comments discussion maintainer decisions", Gate.Of(Permission.ManageSettings)), + new("github", "GitHub", Conn, "git-pull-request", "github token pat pull request repo owner pipeline", Gate.Of(Permission.ManageSettings)), + new("mcp", "MCP servers", Conn, "arrow-square-out", "mcp model context protocol tool servers upstream", Gate.Of(Permission.ManageSettings)), + new("plugins", "Plugins", Conn, "squares-stack", "plugins extensions add-ons", Gate.Everyone), + new("policy", "Tool policy", Gov, "shield", "tool allowlist policy permissions governance", Gate.Of(Permission.ManageSettings)), + new("evidence", "Tool calls", Gov + " › Activity log", "scroll", "evidence tool calls invocations trail governance", Gate.Of(Permission.ViewAudit)), + new("audit", "Activity log", Gov, "clock-counter", "audit log activity who changed history sign-in login members csv", Gate.Of(Permission.ViewAudit)), + new("users", "Users", People, "user", "users members invite invitation roles people team", Gate.Of(Permission.ManageMembers)), + new("tokens", "API tokens", People, "tag", "api token service account ci pipeline script machine bearer mcp client", Gate.Of(Permission.ManageApiTokens)), + new("data", "Data", People, "floppy-disk", "export purge delete tenant workspace data download gdpr", Gate.Of(Permission.ExportData)), + new("general", "General", Personal, "gear", "general preferences", Gate.Everyone), + new("appearance", "Appearance", Personal, "palette", "appearance theme dark light mode wallpaper accent glass motion animation", Gate.Everyone), + new("datetime", "Date & time", Personal, "clock", "date time clock time zone 24-hour", Gate.Everyone), + new("notifs", "Notifications", Personal, "bell", "notifications toasts alerts", Gate.Everyone), + new("session", "Session", Personal, "power", "session sign out logout", Gate.Everyone), + new("about", "About", Sys, "info", "about version build health services status", Gate.Everyone), + new("diagnostics", "Diagnostics", Sys, "circle-fill", "status diagnostics effective configuration which provider storage persistence database postgres stateless", Gate.Of(Permission.ManageSettings)), + new("platform", "Platform", Sys, "server", "platform safety run limits concurrency sandbox docker openai-compatible self-hosted ollama vllm foundry", Gate.Platform), ]; private static readonly Dictionary ByTarget = Pages.ToDictionary(p => p.Target, StringComparer.Ordinal); @@ -85,18 +85,20 @@ _ when NoEditor.Contains(d.Key) => null, _ => null, }; - /// Pages first (best match first), then individual settings; at most . + /// for an admin (every + /// tenant permission) or a non-admin ( only). public static IReadOnlyList Find( string query, IEnumerable descriptors, bool isAdmin, bool isPlatformAdmin, int max = 6) + => Find(query, descriptors, isAdmin ? PermissionMatrix.All : Permission.ViewWork, isPlatformAdmin, max); + + /// Pages first (best match first), then individual settings; at most . A page is + /// offered only when holds its permission (RBAC v2) — the same gate the hub uses. + public static IReadOnlyList Find( + string query, IEnumerable descriptors, Permission granted, bool isPlatformAdmin, int max = 6) { var terms = query.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (terms.Length == 0) { return []; } - bool Allowed(Page p) => p.Access switch - { - Access.Admin => isAdmin, - Access.Platform => isPlatformAdmin, - _ => true, - }; + bool Allowed(Page p) => p.Gate.Allows(granted, isPlatformAdmin); // Every term must appear in one of the fields. Terms never contain a space, so matching each field on its own // equals matching "first second" — without building that string per page and per descriptor on every keystroke. bool Matches(string first, string? second = null) @@ -129,3 +131,22 @@ bool Matches(string first, string? second = null) return hits.Count > max ? hits.GetRange(0, max) : hits; } } + +/// Who may open a Settings page: everyone, holders of one permission (RBAC v2), or platform admins. +/// The permission the page needs; = everyone. +/// Only platform admins (platform-wide settings). +public readonly record struct Gate(Permission Requires, bool PlatformOnly = false) +{ + /// Open to every signed-in user. + public static Gate Everyone => default; + + /// Platform admins only. + public static Gate Platform => new(Permission.None, PlatformOnly: true); + + /// Holders of . + public static Gate Of(Permission permission) => new(permission); + + /// True when a user with (and platform-admin status) may open the page. + public bool Allows(Permission granted, bool isPlatformAdmin) => + PlatformOnly ? isPlatformAdmin : Requires == Permission.None || granted.Has(Requires); +} diff --git a/src/AgentOs.Web/Services/ShellActions.cs b/src/AgentOs.Web/Services/ShellActions.cs index 325bc74f..0c5a02a7 100644 --- a/src/AgentOs.Web/Services/ShellActions.cs +++ b/src/AgentOs.Web/Services/ShellActions.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Linq; +using AgentOs.SharedKernel.Identity; namespace AgentOs.Web.Services; @@ -17,7 +18,8 @@ namespace AgentOs.Web.Services; public sealed record ShellAction(string Id, string Title, string Caption, string Icon) { internal string Keywords { get; init; } = string.Empty; - internal bool AdminOnly { get; init; } + /// RBAC v2: the permission the action needs ( = everyone). + internal Permission Requires { get; init; } } /// The action catalogue + search. @@ -44,21 +46,26 @@ public static class ShellActions [ new(Run, "Run the agent pipeline", "Home · describe a change, the 5 agents build it", "play") { Keywords = "run start execute pipeline workflow agents build story" }, new(Idea, "Start from an idea", "Board · turn an idea into a plan and tasks", "git-pull-request") { Keywords = "new idea ticket story issue plan board decompose" }, - new(AddKey, "Connect an AI account", "Settings › AI › Model keys", "key") { Keywords = "add model key api connect account llm provider anthropic openai gemini xai azure", AdminOnly = true }, - new(Invite, "Invite a member", "Settings › People & data › Users", "user") { Keywords = "invite add user member people team", AdminOnly = true }, - new(Token, "Create an API token", "Settings › People & data › API tokens", "tag") { Keywords = "create new api token service account ci machine", AdminOnly = true }, - new(Export, "Export workspace data", "Settings › People & data › Data", "floppy-disk") { Keywords = "export download backup data workspace", AdminOnly = true }, + new(AddKey, "Connect an AI account", "Settings › AI › Model keys", "key") { Keywords = "add model key api connect account llm provider anthropic openai gemini xai azure", Requires = Permission.ManageSettings }, + new(Invite, "Invite a member", "Settings › People & data › Users", "user") { Keywords = "invite add user member people team", Requires = Permission.ManageMembers }, + new(Token, "Create an API token", "Settings › People & data › API tokens", "tag") { Keywords = "create new api token service account ci machine", Requires = Permission.ManageApiTokens }, + new(Export, "Export workspace data", "Settings › People & data › Data", "floppy-disk") { Keywords = "export download backup data workspace", Requires = Permission.ExportData }, new(Theme, "Switch light / dark theme", "Appearance", "moon") { Keywords = "theme dark light mode toggle switch appearance night" }, new(SignOut, "Sign out", "End this session", "power") { Keywords = "sign out log out logout exit leave" }, ]; /// Actions whose title or keywords contain every query term; title-prefix matches first. public static IReadOnlyList Find(string query, bool isAdmin, int max = 4) + => Find(query, isAdmin ? PermissionMatrix.All : Permission.ViewWork, max); + + /// Actions the user granted may run whose title or keywords contain every query + /// term; title-prefix matches first. + public static IReadOnlyList Find(string query, Permission granted, int max = 4) { var terms = query.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (terms.Length == 0) { return []; } return All - .Where(a => (isAdmin || !a.AdminOnly) && terms.All(t => (a.Title + " " + a.Keywords).Contains(t, StringComparison.OrdinalIgnoreCase))) + .Where(a => (a.Requires == Permission.None || granted.Has(a.Requires)) && terms.All(t => (a.Title + " " + a.Keywords).Contains(t, StringComparison.OrdinalIgnoreCase))) .OrderBy(a => a.Title.StartsWith(terms[0], StringComparison.OrdinalIgnoreCase) ? 0 : 1) .Take(max) .ToList(); diff --git a/tests/AgentOs.E2E.Tests/AgentOsUi/RowLevelSecurityRealDbTests.cs b/tests/AgentOs.E2E.Tests/AgentOsUi/RowLevelSecurityRealDbTests.cs index 5999ac00..2fe18928 100644 --- a/tests/AgentOs.E2E.Tests/AgentOsUi/RowLevelSecurityRealDbTests.cs +++ b/tests/AgentOs.E2E.Tests/AgentOsUi/RowLevelSecurityRealDbTests.cs @@ -21,6 +21,7 @@ public sealed class RowLevelSecurityRealDbTests "pipeline.pipeline_runs", "pipeline.run_metrics", "pipeline.orchestrations", "sessions.sessions", "sessions.session_repos", "sessions.runners", "sessions.ticket_files", "tools.tool_invocations", "workspaces.workspaces", "workspaces.workspace_repos", "workspaces.ticket_flows", + "workspaces.workspace_members", ]; private static string? Conn => diff --git a/tests/AgentOs.Tests/AgentOs.Tests.csproj b/tests/AgentOs.Tests/AgentOs.Tests.csproj index 675e80a6..9136e786 100644 --- a/tests/AgentOs.Tests/AgentOs.Tests.csproj +++ b/tests/AgentOs.Tests/AgentOs.Tests.csproj @@ -46,6 +46,8 @@ + +