diff --git a/CHANGELOG.md b/CHANGELOG.md index 8941863a..24c3a361 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,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). @@ -128,5 +131,8 @@ Everything on `main` before the first tagged release. AgentOS.NET has not shippe [docs/CONFIG.md](docs/CONFIG.md#set-at-deploy-bootstrap). - The `approver` realm role (E1.5) is created by the azd post-deploy hook and the Helm realm job; a local realm imported before it needs the role added through the Keycloak admin API, or its volume dropped. +- 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 + manage boards); new invitations default + to `developer`. Existing Keycloak realms get the new roles (incl. E1.5's `approver`) from the azd post-deploy hook, the Helm realm job, `lab.ps1`, or on first assignment. [Unreleased]: https://github.com/hoangsnowy/AgentOS.NET/commits/main diff --git a/README.md b/README.md index 65322064..488d79a3 100644 --- a/README.md +++ b/README.md @@ -477,7 +477,7 @@ The most used routes: | `POST` | `/llm/test` | signed in | Probe the configured provider with a minimal call | | — | `/mcp` | signed in | AgentOS.NET as an MCP server | | `GET` | `/health` · `/alive` | none | Readiness, liveness | -| `GET` | `/health/llm` | signed in | Provider-key readiness | +| `GET` | `/health/llm` | admin (`ManageSettings`) | Provider-key readiness | ## Extending diff --git a/SECURITY.md b/SECURITY.md index 243a69f5..e9ae78d7 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 60244402..1f5aba39 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 and approver realm roles (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 @@ -140,6 +141,20 @@ else echo " role approver 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 de09be5c..c3c221b3 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -314,7 +314,8 @@ product setting); project skills may not pre-approve tools (`allowed-tools` / `h Approval policies: which steps a person must approve before AgentOS.NET takes them, per tenant and per project. Declared by the Integration module (`ApprovalSettings`), shown in their own *Approvals* panel on Settings › Autopilot, read on every pass / call. Approvers are people with the **Approver** or **Admin** role (Settings › Users; the `approver` realm role — -an approver is also a member). They decide on **Board › Tasks › Approvals** — *Approve*, or *Reject* with a reason — and +under RBAC v2 an approver reads everything but does not run agents; see +[Roles and permissions](#roles-and-permissions-rbac-v2)). They decide on **Board › Tasks › Approvals** — *Approve*, or *Reject* with a reason — and every decision is stored with who and when (`sessions.approvals`) and audited (`approval.decided`). | Key | Default | Values | What it holds | @@ -432,6 +433,53 @@ as one fixed dev user, so production-sized per-user buckets would throttle a UI - **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` — approval-policy gates (E1.5: plan, diff, PR, merge) and design checks on anyone's task. A task's owner (with `RunAgents`) still decides their own design check (ADR-0016) | | | ✓ | | ✓ | +| `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` + `ManageWorkspaces` — exactly what a member could do before (run agents, decide design checks on their own tasks, connect boards — including an Azure DevOps / Jira tracker, E1.8). E1.5's approval gates never accepted a member, so the alias approves nothing. Choosing one of the five roles for that user in Users replaces it. | +| `approver` (E1.5) | `approver` (same realm role). E1.5 assigned `approver` + `member` together; such a user keeps both until an admin picks one role in Users. New approvers get `approver` alone. | +| `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 97594bce..11f5e6ae 100644 --- a/docs/plans/enterprise-readiness.md +++ b/docs/plans/enterprise-readiness.md @@ -74,7 +74,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 | 🟡 4 roles (admin · approver · member · platform-admin) | `IdentityModule.cs`; `TenantRoles.cs` | **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 2edfade0..0cec4237 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`) | ~~Web paths fall back to `"default"` when the claim is missing~~ — **Fixed (GAP-17)**: the export routes return 403 (`src/AgentOs.Web/Endpoints/ExportEndpoints.cs`) and API tokens / Audit log / Data show `TenantClaim.MissingMessage` instead of loading anything; a guard test forbids the fallback in `src/AgentOs.Web`. None known | | 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~~ — **Fixed (GAP-02):** the Api's limiter moved to `ServiceDefaults` (`RequestRateLimiting.cs`) and runs on both hosts: per-tenant + per-user token buckets (anonymous: per IP), limits in Settings › Platform › Request limits, 429 + `Retry-After`. Opening a circuit (`/_blazor/negotiate`) counts; the live circuit's transport, health and static assets don't. Residual: circuit options left at defaults; in-memory buckets are per replica. Low | -| 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~~ — **Fixed (GAP-17)**: it takes the caller's `ClaimsPrincipal` and refuses (`TenantPurgeDeniedException`) unless platform-admin and not their own tenant, before any connection opens. None known | +| 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 | ~~Forwarded headers from any peer; `AllowedHosts: "*"`; links built from the request Host~~ — **Fixed (GAP-05)**: forwarded headers only from loopback + `Hosting:TrustedNetworks`/`TrustedProxies` (a PostConfigure `ASPNETCORE_FORWARDEDHEADERS_ENABLED` can't widen); a host filter allows `AllowedHosts` or the public base URL's host (+ loopback, probes exempt); invitation, pairing and hub links come from `Hosting:PublicBaseUrl`, required outside Development (`src/AgentOs.ServiceDefaults/HostingSecurity.cs`, `src/AgentOs.SharedKernel/Hosting/PublicOrigin.cs`). Residual: the default trusted ranges are broad (every private range on azd/Helm) until an operator narrows them. Low | ## 4. TB2 — Web / Api ↔ Keycloak diff --git a/infra/hooks/postdeploy.ps1 b/infra/hooks/postdeploy.ps1 index de29a921..55cb96b4 100644 --- a/infra/hooks/postdeploy.ps1 +++ b/infra/hooks/postdeploy.ps1 @@ -74,14 +74,23 @@ try { else { Write-Warning "Could not ensure realm role platform-admin: $($_.Exception.Message)" } } -# 2c. Realm role approver (E1.5 approval policies): approves or rejects the steps a policy holds. Same idempotent ensure. -try { - Invoke-RestMethod -Method Post -Headers $headers -Uri "$kcUrl/admin/realms/$realm/roles" -ContentType 'application/json' ` - -Body (@{ name = 'approver'; description = 'Tenant approver - approves or rejects plan, diff, pull request and merge steps' } | ConvertTo-Json) | Out-Null - Write-Host "Realm role approver created." -} catch { - if ($_.Exception.Response -and [int]$_.Exception.Response.StatusCode -eq 409) { Write-Host "Realm role approver already present." } - else { Write-Warning "Could not ensure realm role approver: $($_.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 = 'Approves plan, diff, pull request and merge steps; decides design checks' + 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 diff --git a/infra/hooks/postdeploy.sh b/infra/hooks/postdeploy.sh index 1b5fa92c..5861c262 100644 --- a/infra/hooks/postdeploy.sh +++ b/infra/hooks/postdeploy.sh @@ -67,13 +67,22 @@ case "$code" in *) echo "WARN: Could not ensure realm role platform-admin (HTTP $code)." ;; esac -# 2c. Realm role approver (E1.5 approval policies): approves or rejects the steps a policy holds. Same idempotent ensure. -code=$(curl -s -o /dev/null -w "%{http_code}" -X POST "${auth[@]}" "$KC_URL/admin/realms/$REALM/roles" -d '{"name":"approver","description":"Tenant approver - approves or rejects plan, diff, pull request and merge steps"}') -case "$code" in - 201) echo "Realm role approver created." ;; - 409) echo "Realm role approver already present." ;; - *) echo "WARN: Could not ensure realm role approver (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 "Approves plan, diff, pull request and merge steps; decides design checks" +ensure_role auditor "Read-only audit log and evidence" # 3. Seed users: rotate imported placeholder passwords rotate_user() { diff --git a/infra/keycloak/agentic-realm.json b/infra/keycloak/agentic-realm.json index ecfc9808..6c744d0c 100644 --- a/infra/keycloak/agentic-realm.json +++ b/infra/keycloak/agentic-realm.json @@ -41,8 +41,11 @@ "roles": { "realm": [ { "name": "admin", "description": "Tenant administrator" }, - { "name": "member", "description": "Tenant member" }, - { "name": "approver", "description": "Tenant approver - approves or rejects plan, diff, pull request and merge steps" }, + { "name": "viewer", "description": "Read-only access to the tenant's work" }, + { "name": "developer", "description": "Runs agents and works tickets" }, + { "name": "approver", "description": "Approves plan, diff, pull request and merge steps; decides design checks" }, + { "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 5aedfa69..3eba5b4d 100644 --- a/src/AgentOs.Api/Program.cs +++ b/src/AgentOs.Api/Program.cs @@ -222,14 +222,14 @@ .WithName("HealthLlm") .WithSummary("LLM provider configuration readiness (not a pod-recycle signal)") .WithTags("Meta") - .RequireAuthorization(); + .RequirePermission(Permission.ManageSettings); // RBAC v2: provider configuration is a settings read app.MapModuleEndpoints(); // 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. @@ -304,6 +304,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..a8d189b3 --- /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, so role displays and IsInRole("developer") +/// agree with the matrix (which already treats member as developer + managing boards). +public sealed class LegacyRoleClaimMapper : IRoleClaimMapper +{ + private static readonly string[] MemberRoles = [UserRoles.Developer]; + + /// + 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 d17ae678..f07a1493 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.AspNetCore.Authorization; @@ -29,10 +30,13 @@ public void AddServices(IServiceCollection services, IConfiguration configuratio // static assets) opt out with an explicit AllowAnonymous — a new route can no longer be public by omission. options.FallbackPolicy = FallbackPolicy; 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)); // E1.5: approve or reject a step an approval policy holds (an admin may too). options.AddPolicy("Approver", policy => policy.RequireRole(ClaimNames.ApproverRole, ClaimNames.AdminRole)); + 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 26b01c5f..20ba8aa6 100644 --- a/src/AgentOs.Modules.Sessions/Endpoints/PairingEndpoints.cs +++ b/src/AgentOs.Modules.Sessions/Endpoints/PairingEndpoints.cs @@ -39,10 +39,10 @@ public static void MapPairingEndpoints(this IEndpointRouteBuilder endpoints) { ArgumentNullException.ThrowIfNull(endpoints); - endpoints.MapGet("/pair/vscode", ApprovePage).RequireAuthorization("Member"); + endpoints.MapGet("/pair/vscode", ApprovePage).RequirePermission(Permission.RunAgents); // GAP-19: the approve form carries an antiforgery token (ApprovePage) and the POST validates it — a cross-site // form can no longer provision a runner for the signed-in member (SameSite=Lax was the only defence). - endpoints.MapPost("/pair/vscode", ApproveAsync).RequireAuthorization("Member"); + endpoints.MapPost("/pair/vscode", ApproveAsync).RequirePermission(Permission.RunAgents); // 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).AllowAnonymous().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/Approvals/KeycloakApproverDirectory.cs b/src/AgentOs.Modules.Tenants/Approvals/KeycloakApproverDirectory.cs index 15268e7f..cc0d8a69 100644 --- a/src/AgentOs.Modules.Tenants/Approvals/KeycloakApproverDirectory.cs +++ b/src/AgentOs.Modules.Tenants/Approvals/KeycloakApproverDirectory.cs @@ -35,7 +35,7 @@ internal sealed class KeycloakApproverDirectory(IServiceScopeFactory scopes, Tim try { var users = await keycloak.ListUsersByTenantAsync(tenantId, ct: ct).ConfigureAwait(false); - var count = users.Count(u => u.Enabled && u.Roles.Any(r => r is ClaimNames.ApproverRole or ClaimNames.AdminRole)); + var count = users.Count(u => u.Enabled && PermissionMatrix.For(u.Roles).Has(Permission.ApproveWork)); _cache[tenantId] = (now, count); return count; } diff --git a/src/AgentOs.Modules.Tenants/Endpoints/TenantEndpoints.cs b/src/AgentOs.Modules.Tenants/Endpoints/TenantEndpoints.cs index fc98366f..25ba59d1 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.Hosting; using AgentOs.SharedKernel.Identity; using Microsoft.AspNetCore.Builder; @@ -29,7 +31,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") @@ -149,10 +152,10 @@ public static IEndpointRouteBuilder MapTenantEndpoints(this IEndpointRouteBuilde { return Results.Forbid(); } - var role = string.IsNullOrWhiteSpace(body.Role) ? "member" : body.Role; - if (!TenantRoles.IsKnown(role)) + var role = string.IsNullOrWhiteSpace(body.Role) ? MemberRoles.DefaultRole : body.Role; + if (!MemberRoles.IsAllowed(role)) { - return Results.BadRequest(new { error = "role must be 'admin', 'approver' 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); @@ -196,7 +199,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. @@ -231,7 +234,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). @@ -249,16 +252,10 @@ await audit.WriteAsync(new AuditEntry( { return Results.Forbid(); } - // An approver is a member too (TenantRoles.Expand); unknown roles are dropped. - var roles = TenantRoles.Expand(body.Roles).ToList(); - if (roles.Count == 0) - { - return Results.BadRequest(new { error = "roles must contain at least one of: admin, approver, 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 { @@ -283,7 +280,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. @@ -291,7 +288,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 ( @@ -330,7 +327,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, @@ -347,9 +344,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, @@ -374,9 +371,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( @@ -405,11 +404,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 @@ -468,6 +540,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) { @@ -476,6 +552,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, @@ -483,7 +562,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 47fc150a..465912c9 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 227eaf6c..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", "approver" }; + // 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.Tenants/TenantRoles.cs b/src/AgentOs.Modules.Tenants/TenantRoles.cs deleted file mode 100644 index 0b1590d3..00000000 --- a/src/AgentOs.Modules.Tenants/TenantRoles.cs +++ /dev/null @@ -1,39 +0,0 @@ -// The roles a tenant member can be given, and what each grants in Keycloak realm roles. "Approver" (E1.5) is a member -// who may also approve or reject the steps an approval policy holds — so it carries the member role with it: an approver -// alone would otherwise fail every Member-policy check. - -using System; -using System.Collections.Generic; -using System.Linq; -using AgentOs.SharedKernel.Identity; - -namespace AgentOs.Modules.Tenants; - -/// Tenant roles (admin, approver, member) and their realm-role sets. -public static class TenantRoles -{ - /// The roles a person can be given, most rights first. - public static IReadOnlyList All { get; } = [ClaimNames.AdminRole, ClaimNames.ApproverRole, ClaimNames.MemberRole]; - - /// True for a role a tenant admin may grant. - public static bool IsKnown(string? role) => role is not null && All.Contains(role, StringComparer.Ordinal); - - /// The realm roles amount to: unknown roles dropped, an approver also a member. - public static IReadOnlyList Expand(IEnumerable? roles) - { - var set = (roles ?? []).Where(IsKnown).ToList(); - if (set.Contains(ClaimNames.ApproverRole, StringComparer.Ordinal) && !set.Contains(ClaimNames.AdminRole, StringComparer.Ordinal)) - { - set.Add(ClaimNames.MemberRole); - } - return set.Distinct(StringComparer.Ordinal).OrderBy(r => All.ToList().IndexOf(r)).ToList(); - } - - /// The one role a person is shown with: admin over approver over member. - public static string Primary(IEnumerable realmRoles) - { - ArgumentNullException.ThrowIfNull(realmRoles); - var set = realmRoles.ToHashSet(StringComparer.Ordinal); - return All.FirstOrDefault(set.Contains) ?? ClaimNames.MemberRole; - } -} diff --git a/src/AgentOs.Modules.Tenants/TenantSignupService.cs b/src/AgentOs.Modules.Tenants/TenantSignupService.cs index 3c02140f..15875925 100644 --- a/src/AgentOs.Modules.Tenants/TenantSignupService.cs +++ b/src/AgentOs.Modules.Tenants/TenantSignupService.cs @@ -123,8 +123,9 @@ public async Task SignupAsync(TenantSignupRequest request, createTenantRow = true; } - // An invited approver is a member too (TenantRoles.Expand). - var roles = TenantRoles.Expand([role]).ToArray(); + // RBAC v2: the invitation's role as-is (MemberRoles); an approver is NOT also made a member — approver alone + // already passes every read (Member policy = ViewWork) and must not gain RunAgents/ManageWorkspaces. + var roles = MemberRoles.Sanitize([role]) is { Count: > 0 } allowed ? allowed.ToArray() : [MemberRoles.DefaultRole]; var sendVerify = !string.IsNullOrWhiteSpace(request.Email); string kcUserId = await _kc.CreateUserAsync( 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 c211b072..b72aa116 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 6060f602..c6e042be 100644 --- a/src/AgentOs.Modules.Workspaces/Persistence/Migrations/WorkspacesDbContextModelSnapshot.cs +++ b/src/AgentOs.Modules.Workspaces/Persistence/Migrations/WorkspacesDbContextModelSnapshot.cs @@ -194,6 +194,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") @@ -243,6 +286,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 aea4f3de..18db06d9 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 165b2bad..c56dadc8 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(); // E1.8 — a board's external ticket tracker (Azure DevOps Boards / Jira), read by the source-provider routing. services.AddScoped(); @@ -51,6 +53,7 @@ public void AddServices(IServiceCollection services, IConfiguration configuratio services.AddNpgsqlConnectionFactory(connectionString); services.AddScoped(); services.AddScoped(); + services.AddScoped(); } else { @@ -65,6 +68,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/ClaimsPrincipalExtensions.cs b/src/AgentOs.SharedKernel/Identity/ClaimsPrincipalExtensions.cs index f4503fdd..f8c26574 100644 --- a/src/AgentOs.SharedKernel/Identity/ClaimsPrincipalExtensions.cs +++ b/src/AgentOs.SharedKernel/Identity/ClaimsPrincipalExtensions.cs @@ -60,7 +60,7 @@ public static bool IsPlatformAdmin(this ClaimsPrincipal user) /// True when the user may approve or reject a step held by an approval policy: the approver or the /// admin realm role (E1.5). public static bool CanApprove(this ClaimsPrincipal user) - => user.IsInRole(ClaimNames.ApproverRole) || user.IsInRole(ClaimNames.AdminRole); + => user.Can(Permission.ApproveWork); // RBAC v2: PermissionMatrix decides (approver, admin) } /// GAP-17 — a signed-in principal without a tenant claim is a misconfigured token, never "the shared 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..d166b06b --- /dev/null +++ b/src/AgentOs.SharedKernel/Identity/Permission.cs @@ -0,0 +1,46 @@ +// 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, + + /// Approve or reject what an approval policy holds (E1.5: plan, diff, pull request, merge) and decide the design + /// check of anyone's task. Approvers and admins; board-scoped like every permission. + 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..e65b9ee6 --- /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 + ManageWorkspaces — everything a member could do before: run agents, decide design checks on +// their own tasks (the task owner's call — ADR-0016 — which every developer keeps), and connect boards (the old +// "Member" policy covered POST /workspaces). No ApproveWork: E1.5's approval gates never accepted a member. +// 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.Linq; +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"; + + /// Holds : decides E1.5's approval-policy gates (plan, diff, pull + /// request, merge) and design checks on anyone's task. The same realm role E1.5 introduced. + public const string Approver = ClaimNames.ApproverRole; + + /// 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 + 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 | 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.Where(r => !restricted || TenantWideRoles.Contains(r))) + { + 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}"; + + /// 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 f5f2c16b..cc7cc535 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"), ("sessions", "approvals"), ("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) ===== *@ private static string[] RolesFor(string? viewAs) => viewAs switch { - "admin" => ["admin"], "member" => ["member"], + { } role when AgentOs.SharedKernel.Identity.UserRoles.IsAssignable(role) => [role], _ => ["admin", "member", "platform-admin"], }; } diff --git a/src/AgentOs.Web/Components/Layout/AppShellLayout.razor b/src/AgentOs.Web/Components/Layout/AppShellLayout.razor index 82360b43..b7beed6a 100644 --- a/src/AgentOs.Web/Components/Layout/AppShellLayout.razor +++ b/src/AgentOs.Web/Components/Layout/AppShellLayout.razor @@ -87,7 +87,7 @@ } @* 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 746458de..59dd424b 100644 --- a/src/AgentOs.Web/Components/Pages/ApiTokensApp.razor +++ b/src/AgentOs.Web/Components/Pages/ApiTokensApp.razor @@ -37,8 +37,10 @@ else @@ -112,7 +114,7 @@ else private string? _tenantId; 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; @@ -122,7 +124,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(); _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 5d8bc0bf..8719609c 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 if (_tenantId is null) { @@ -84,7 +84,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; @@ -102,12 +102,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(); } _resolved = true; - if (_isAdmin && _tenantId is not null) { await LoadAsync(); } + if (_canView && _tenantId is not null) { 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 903a6658..329b86e6 100644 --- a/src/AgentOs.Web/Components/Pages/AutopilotSettingsApp.razor +++ b/src/AgentOs.Web/Components/Pages/AutopilotSettingsApp.razor @@ -117,7 +117,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 fa5698bd..04cb196c 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 @@ -226,11 +227,11 @@ else if (_tab == Tab.Boards) @if (_wsTicketsFrom == TicketsFrom.GitHubProjects) { + Disabled="@(_busy || _findingBoards || _wsKind != SourceProviderKind.GitHub || !Can(Permission.ManageWorkspaces))"> @(_findingBoards ? "Finding…" : "Find boards") } - + @(_busy ? "Connecting…" : "Connect")
@@ -334,7 +335,7 @@ else if (_tab == Tab.Boards)
- + @(_busy ? "Adding…" : "Add repository")
@@ -354,16 +355,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 @@ -438,7 +439,7 @@ else if (_tab == Tab.Boards) @if (readyCount > 0) {
- + Start approved tickets (@readyCount)
@@ -499,7 +500,7 @@ else if (_tab == Tab.Boards) + Disabled="@(_busy || ticket.Kind == BoardTicketKind.DraftIssue || ticket.RepoOwner is null || !CanOnBoard(Permission.RunAgents))"> Work on this @@ -556,7 +557,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")
@@ -574,7 +575,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")
@@ -625,10 +626,10 @@ else if (_tab == Tab.Idea) @WhereToWork
Back - + @(_ideaBusy ? "Working…" : "Create & run all ready") - + Create only
@@ -667,7 +668,7 @@ else if (_tab == Tab.Runners)
- + @(_busy ? "Connecting…" : "Connect this computer")
@@ -707,7 +708,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})")
@@ -739,7 +740,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 @@ -784,16 +785,19 @@ else if (_tab == Tab.Autopilot)
@@ -812,7 +816,7 @@ else if (_tab == Tab.Autopilot)
}
- + Check now @@ -859,16 +863,18 @@ else if (_tab == Tab.Sessions) { @* E1.5: the steps the approval policy holds (plan, pull request, change, merge) — Approve / Reject, audited. *@ - - + Actor="@(new AgentOs.Web.Services.Approvals.ApprovalActor(_userId, _userLabel, CanApproveAnywhere))" + CanDecideFor="@ApprovalDecidable" /> + + - @if (_isAdmin) { } + @if (TeamView) { } @@ -927,7 +933,7 @@ else if (_tab == Tab.Sessions) — } - @if (_isAdmin) { } + @if (TeamView) { } @@ -979,7 +985,7 @@ else if (_tab == Tab.Sessions) @if (s.Status == "Running" && CurrentStep(s.Id) is var step && step >= 0) { - - - @@ -1024,16 +1030,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) @@ -938,7 +944,7 @@ else if (_tab == Tab.Sessions) { + Disabled="@(_busyId == s.Id || !Can(s.WorkspaceId, Permission.RunAgents))"> @(s.Status == "Failed" ? "Try again" : "Run") } @@ -951,7 +957,7 @@ else if (_tab == Tab.Sessions) } @if (s.Status is "Done" or "Failed" or "Blocked" && HasOpenChange(s.Id)) { - Test it @@ -971,7 +977,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++) @@ -994,7 +1000,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. *@
@@ -1003,8 +1009,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")
@@ -1015,7 +1021,7 @@ else if (_tab == Tab.Sessions) @if (_filesFor == s.Id) {
+
+ + CanDecide="@CanDecide(s)" DecidedBy="@_userLabel" />
+
@foreach (var ev in feed.TakeLast(8)) { @@ -1042,7 +1048,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). *@
@@ -1057,7 +1063,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.
@@ -1140,8 +1146,11 @@ else if (_tab == Tab.Sessions) // The task whose "Files for the AI" are open. private Guid? _filesFor; private bool _isAdmin; - // Holds the approver or admin role: may approve or reject what the approval policy holds (E1.5). - private bool _canApprove; + // 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; @@ -1214,6 +1223,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; @@ -1388,7 +1398,8 @@ else if (_tab == Tab.Sessions) _userId = user.GetUserId() ?? ""; _userLabel = string.IsNullOrWhiteSpace(user.Identity?.Name) ? _userId : user.Identity!.Name!; _isAdmin = user.IsAdmin(); - _canApprove = user.CanApprove(); + _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. @@ -1438,18 +1449,72 @@ 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): the task's owner decides their own check (with RunAgents on its board, as before + // E1.2); approvers and admins (ApproveWork on the board) decide anyone's. + private bool CanDecide(RemoteSessionEntity s) => + Can(s.WorkspaceId, Permission.ApproveWork) + || (s.MemberUserId == _userId && Can(s.WorkspaceId, Permission.RunAgents)); + + // E1.5 approval gates (RBAC v2): ApproveWork on the task's board — approvers and admins, board memberships included. + private bool CanApproveAnywhere => + _perms.Has(Permission.ApproveWork) || (_access is { } map && (_boards ?? []).Any(b => map.Can(b.Id, Permission.ApproveWork))); + + private bool ApprovalDecidable(Guid sessionId) => + (_sessions ?? []).FirstOrDefault(x => x.Id == sessionId) is { } s ? Can(s.WorkspaceId, Permission.ApproveWork) : _isAdmin; + + // A check whose task isn't in this person's task list (only admins see those — DesignChecks lists a non-admin + // only their visible tasks' checks; the standalone desktop's seeded sample has no task at all) is an admin's call. + private bool CanDecideFor(Guid sessionId) => + (_sessions ?? []).FirstOrDefault(x => x.Id == sessionId) is { } s ? CanDecide(s) : _isAdmin; + + 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(); } @@ -1471,7 +1536,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")) @@ -1547,7 +1612,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. @@ -1647,6 +1712,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)) { @@ -1682,6 +1748,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 @@ -1704,6 +1771,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 @@ -1758,6 +1826,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)) { @@ -1830,6 +1899,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); @@ -1962,6 +2032,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(); @@ -2020,6 +2091,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(); @@ -2124,6 +2196,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) @@ -2234,7 +2307,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); } @@ -2304,6 +2377,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 @@ -2315,7 +2389,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; @@ -2355,6 +2429,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)) { @@ -2398,6 +2473,7 @@ else if (_tab == Tab.Sessions) private async Task RevokeRunner(RunnerEntity r) { + if (!Demand(Permission.RunAgents, "disconnect a computer")) { return; } _busyId = r.Id; try { @@ -2423,6 +2499,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: @@ -2480,6 +2557,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; @@ -2490,6 +2568,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; @@ -2538,6 +2617,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); } @@ -2546,6 +2626,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) @@ -2556,6 +2637,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 @@ -2708,6 +2790,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); @@ -2726,6 +2809,7 @@ else if (_tab == Tab.Sessions) private async Task AutopilotNow(WorkspaceEntity board) { + if (!Demand(board.Id, Permission.ManageWorkspaces, "run Autopilot")) { return; } _busy = true; try { @@ -2743,6 +2827,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 { @@ -2761,6 +2846,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.", @@ -2769,13 +2855,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); } @@ -2791,6 +2878,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)) { @@ -2877,6 +2965,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)) @@ -2910,7 +2999,8 @@ else if (_tab == Tab.Sessions) _wsName = _wsProjectOwner = _wsNumberText = _wsProject = _wsToken = ""; _trSite = _trProject = _trArea = _trIteration = _trStates = _trTags = _trJql = _trAccount = _trToken = ""; _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 f2227a96..060a7184 100644 --- a/src/AgentOs.Web/Components/Pages/DataApp.razor +++ b/src/AgentOs.Web/Components/Pages/DataApp.razor @@ -112,7 +112,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(); _user = state.User; 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 f05bf5ba..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,11 +75,16 @@ else @m.Username @(isSelf ? "(you)" : "") @(m.Email ?? "—") - @@ -111,9 +120,10 @@ else @@ -138,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 + +
+ } +
} } @@ -172,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; @@ -185,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; @@ -196,11 +304,88 @@ else if (_isAdmin && _tenantId.Length > 0) { await LoadMembersAsync(); + await LoadBoardsAsync(); } } - // Admin over approver over member (an approver is a member who may also approve the steps an approval policy holds). - private static string PrimaryRole(KeycloakUser m) => AgentOs.Modules.Tenants.TenantRoles.Primary(m.Roles); + 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() { @@ -218,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, AgentOs.Modules.Tenants.TenantRoles.Expand([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)); @@ -310,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/ApprovalsPanel.razor b/src/AgentOs.Web/Components/UI/ApprovalsPanel.razor index b282041b..0a8a4e76 100644 --- a/src/AgentOs.Web/Components/UI/ApprovalsPanel.razor +++ b/src/AgentOs.Web/Components/UI/ApprovalsPanel.razor @@ -49,7 +49,7 @@ } @if (r.Status == ApprovalStatus.Pending) { - @if (Actor.CanApprove) + @if (MayDecide(r)) {
Most decided requests listed under the waiting ones. [Parameter] public int MaxDecided { get; set; } = 5; + /// RBAC v2: whether the person may decide the approval of a task (ApproveWork on its board); + /// null = alone. + [Parameter] public Func? CanDecideFor { get; set; } + + private bool MayDecide(ApprovalRequest r) => Actor.CanApprove && (CanDecideFor?.Invoke(r.SessionId) ?? true); + private List _requests = []; private string? _loadedFor; private Guid? _busy; @@ -138,7 +144,9 @@ if (scope.ServiceProvider.GetService() is not { } store) { _requests = []; return; } var visible = VisibleTasks as ISet ?? VisibleTasks.ToHashSet(); var all = (await store.ListRecentAsync(TenantId, 100)) - .Where(r => IsAdmin || Actor.CanApprove || visible.Contains(r.SessionId)) + // RBAC v2: the approvals of the tasks this person sees (an approver sees every task of the boards they can + // see — Board's team view); a restricted board's approvals stay with its members. + .Where(r => IsAdmin || visible.Contains(r.SessionId)) .ToList(); _requests = all.Where(r => r.Status == ApprovalStatus.Pending).OrderBy(r => r.RequestedAtUtc) .Concat(all.Where(r => r.Status != ApprovalStatus.Pending).OrderByDescending(r => r.DecidedAtUtc).Take(MaxDecided)) @@ -161,7 +169,9 @@ _busy = request.Id; try { - var outcome = await Approvals.DecideAsync(TenantId, request.Id, approve, approve ? null : _note, Actor); + // Re-check in the handler (GAP-17): a hidden button is not the gate. + var actor = Actor with { CanApprove = MayDecide(request) }; + var outcome = await Approvals.DecideAsync(TenantId, request.Id, approve, approve ? null : _note, actor); if (outcome.Request is { } stored) { var i = _requests.FindIndex(r => r.Id == stored.Id); 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 fdbdb633..fbddb95c 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/Endpoints/ExportEndpoints.cs b/src/AgentOs.Web/Endpoints/ExportEndpoints.cs index 186ba808..0c20ef65 100644 --- a/src/AgentOs.Web/Endpoints/ExportEndpoints.cs +++ b/src/AgentOs.Web/Endpoints/ExportEndpoints.cs @@ -21,7 +21,8 @@ namespace AgentOs.Web.Endpoints; /// Maps /cost/export, /tenant/export and /audit/export. public static class ExportEndpoints { - /// Map the export routes (each requires an authenticated admin with a tenant claim). + /// Map the export routes (RBAC v2: cost + tenant export need ExportData, the audit CSV ViewAudit — admin or + /// auditor; each also needs a tenant claim). public static IEndpointRouteBuilder MapExportEndpoints(this IEndpointRouteBuilder app) { ArgumentNullException.ThrowIfNull(app); @@ -29,7 +30,7 @@ public static IEndpointRouteBuilder MapExportEndpoints(this IEndpointRouteBuilde // Cost CSV export for the admin Cost app; `days` (0/absent = all time) sets the cutoff. app.MapGet("/cost/export", async (HttpContext http, IPipelineRunRepository runs, int? days) => { - if (!http.User.IsAdmin() || http.User.GetTenantId() is not { } tenant) + if (!http.User.Can(Permission.ExportData) || http.User.GetTenantId() is not { } tenant) { return Results.Forbid(); } @@ -37,14 +38,14 @@ public static IEndpointRouteBuilder MapExportEndpoints(this IEndpointRouteBuilde var summary = await runs.GetCostSummaryForTenantAsync(tenant, since); var bytes = System.Text.Encoding.UTF8.GetBytes(AgentOs.Modules.Pipeline.Cost.CostCsv.ToCsv(summary)); return Results.File(bytes, "text/csv", "agentos-cost.csv"); - }).RequireAuthorization(); + }).RequirePermission(Permission.ExportData); // Tenant data export (Settings → Data, E1.4): one JSON document of every row the tenant owns, secrets excluded, // streamed. A tenant admin exports their own tenant; ?tenant= another one needs platform-admin. Audited only once // the export has been written — a refused export (a secret column it can't safely redact) is a 409. app.MapGet("/tenant/export", async (HttpContext http, ITenantDataService data, IAuditLog audit, ILoggerFactory loggers, string? tenant) => { - if (!http.User.IsAdmin() || http.User.GetTenantId() is not { } own) { return Results.Forbid(); } + if (!http.User.Can(Permission.ExportData) || http.User.GetTenantId() is not { } own) { return Results.Forbid(); } var target = string.IsNullOrWhiteSpace(tenant) ? own : tenant; if (!string.Equals(target, own, StringComparison.Ordinal) && !http.User.IsPlatformAdmin()) { return Results.Forbid(); } if (!data.IsAvailable) { return Results.NotFound("No database in this run — nothing to export."); } @@ -68,14 +69,14 @@ public static IEndpointRouteBuilder MapExportEndpoints(this IEndpointRouteBuilde await audit.WriteAsync(new AuditEntry(Guid.NewGuid(), target, http.User.Identity?.Name, AuditActions.TenantExported, $"export of {target}", null, null, DateTimeOffset.UtcNow), CancellationToken.None); return Results.Empty; - }).RequireAuthorization(); + }).RequirePermission(Permission.ExportData); // Audit CSV export (Settings → Audit log). A tenant admin exports their own tenant; scope=platform (platform // settings changes) needs platform-admin. app.MapGet("/audit/export", async (HttpContext http, 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(); } @@ -87,7 +88,7 @@ await audit.WriteAsync(new AuditEntry(Guid.NewGuid(), target, http.User.Identity var rows = await audit.ListAsync(tenant, 10_000); var bytes = System.Text.Encoding.UTF8.GetBytes(AuditCsv.ToCsv(rows)); return Results.File(bytes, "text/csv", platform ? "agentos-audit-platform.csv" : $"agentos-audit-{tenant}.csv"); - }).RequireAuthorization(); + }).RequirePermission(Permission.ViewAudit); return app; } 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 c3f4fc7b..393abc62 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 approvals approve approver plan diff pull request draft merge policy branch protection codeowners", 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 request rate limit 429 throttle 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 approvals approve approver plan diff pull request draft merge policy branch protection codeowners", 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 request rate limit 429 throttle 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/Governance/ApprovalDecisionTests.cs b/tests/AgentOs.Tests/Governance/ApprovalDecisionTests.cs index 8d60e7d7..091aff52 100644 --- a/tests/AgentOs.Tests/Governance/ApprovalDecisionTests.cs +++ b/tests/AgentOs.Tests/Governance/ApprovalDecisionTests.cs @@ -241,14 +241,16 @@ public void Settings_AreDeclared_WithSafeDefaults_AndAValidator() // ── Roles and who can approve ── [Fact] - public void TenantRoles_AnApproverIsAMemberToo() + public void MemberRoles_AnApproverStaysAnApprover_UnderRbacV2() { - TenantRoles.Expand(["approver"]).ShouldBe(["approver", "member"]); - TenantRoles.Expand(["admin", "approver"]).ShouldBe(["admin", "approver"]); - TenantRoles.Expand(["root", "member"]).ShouldBe(["member"]); - TenantRoles.Primary(["member", "approver"]).ShouldBe("approver"); - TenantRoles.Primary(["admin", "approver", "member"]).ShouldBe("admin"); - TenantRoles.Primary([]).ShouldBe("member"); + // RBAC v2 (E1.2): approver alone already reads everything (Member policy = ViewWork) — it is no longer expanded + // into member, which would hand it RunAgents + ManageWorkspaces (separation of duties). + MemberRoles.Sanitize(["approver"]).ShouldBe(["approver"]); + MemberRoles.Sanitize(["admin", "approver"]).ShouldBe(["admin", "approver"]); + MemberRoles.Sanitize(["root", "member"]).ShouldBe(["member"]); + MemberRoles.Primary(["member", "approver"]).ShouldBe("approver"); + MemberRoles.Primary(["admin", "approver", "member"]).ShouldBe("admin"); + MemberRoles.Primary([]).ShouldBeNull(); } private static IApproverDirectory Directory(IKeycloakAdminClient keycloak) diff --git a/tests/AgentOs.Tests/Identity/EndpointAuthorizationByRoleTests.cs b/tests/AgentOs.Tests/Identity/EndpointAuthorizationByRoleTests.cs new file mode 100644 index 00000000..2d70fb44 --- /dev/null +++ b/tests/AgentOs.Tests/Identity/EndpointAuthorizationByRoleTests.cs @@ -0,0 +1,317 @@ +// RBAC v2 (E1.2) — endpoint authorization per role, over real HTTP. An in-process TestServer hosts the real module +// endpoints (Tenants, Workspaces, Sessions, Settings) with the Identity module's real policies + handler, and a test +// authentication scheme that signs the caller in with the roles named in a header. Every case asserts the status the +// matrix implies: 401 anonymous, 403 when the role lacks the permission, anything else when it has it (the stubbed +// services behind an allowed call may still answer 400/404 — authorization already passed). Per-board isolation runs +// through the real WorkspaceAccess over the in-memory membership store. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Security.Claims; +using System.Text.Encodings.Web; +using System.Threading; +using System.Threading.Tasks; +using AgentOs.Domain.Configuration; +using AgentOs.Domain.Sessions; +using AgentOs.Domain.Workspaces; +using AgentOs.Modules.AppConfig; +using AgentOs.Modules.AppConfig.Endpoints; +using AgentOs.Modules.Identity; +using AgentOs.Modules.Sessions.Endpoints; +using AgentOs.Modules.Sessions.Pairing; +using AgentOs.Modules.Sessions.Persistence; +using AgentOs.Modules.Sessions.Persistence.Entities; +using AgentOs.Modules.Tenants; +using AgentOs.Modules.Tenants.Email; +using AgentOs.Modules.Tenants.Endpoints; +using AgentOs.Modules.Tenants.Keycloak; +using AgentOs.Modules.Workspaces; +using AgentOs.Modules.Workspaces.Access; +using AgentOs.Modules.Workspaces.Endpoints; +using AgentOs.Modules.Workspaces.Persistence; +using AgentOs.Modules.Workspaces.Persistence.Entities; +using AgentOs.Modules.Workspaces.Security; +using AgentOs.SharedKernel.Identity; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NSubstitute; +using Shouldly; +using Xunit; + +namespace AgentOs.Tests.Identity; + +public sealed class EndpointAuthorizationByRoleTests : IAsyncLifetime +{ + private const string Tenant = "acme"; + private static readonly Guid OpenBoard = Guid.Parse("00000000-0000-0000-0000-0000000000a1"); + private static readonly Guid RestrictedBoard = Guid.Parse("00000000-0000-0000-0000-0000000000b2"); + + private static readonly string[] ViewerOnly = ["viewer"]; + + private WebApplication? _app; + private HttpClient? _client; + private readonly InMemoryWorkspaceMembershipStore _memberships = new(TimeProvider.System); + private readonly ISessionRepository _sessions = Substitute.For(); + + public async ValueTask InitializeAsync() + { + var builder = WebApplication.CreateSlimBuilder(); + builder.WebHost.UseTestServer(); + builder.Logging.ClearProviders(); + builder.Services.AddRouting(); + builder.Services.AddAuthentication(HeaderAuth.SchemeName) + .AddScheme(HeaderAuth.SchemeName, _ => { }); + // The real policies, permission handler and claim-mapping hook. + new IdentityModule().AddServices(builder.Services, new ConfigurationBuilder().Build()); + + // Tenants + builder.Services.AddSingleton(Substitute.For()); + var kc = Substitute.For(); + kc.GetUserTenantAsync(Arg.Any(), Arg.Any()).Returns(Tenant); + kc.ListUsersByTenantAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns([]); + builder.Services.AddSingleton(kc); + builder.Services.AddSingleton(Substitute.For()); + builder.Services.AddSingleton(Substitute.For()); + builder.Services.AddSingleton(Substitute.For()); + builder.Services.AddSingleton(_memberships); + builder.Services.AddSingleton(new AgentOs.SharedKernel.Hosting.PublicOrigin("https://agentos.example.com", allowRequestFallback: false)); + // Workspaces + var boards = Substitute.For(); + boards.ListAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns( + [ + new WorkspaceEntity { Id = OpenBoard, TenantId = Tenant, Name = "open" }, + new WorkspaceEntity { Id = RestrictedBoard, TenantId = Tenant, Name = "restricted" }, + ]); + boards.GetAsync(Arg.Any(), Arg.Any()) + .Returns(ci => new WorkspaceEntity { Id = ci.Arg(), TenantId = Tenant, Name = "board" }); + builder.Services.AddSingleton(boards); + builder.Services.AddSingleton(Substitute.For()); + builder.Services.AddSingleton(Substitute.For()); + builder.Services.AddSingleton(Substitute.For()); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(new WorkspaceAccess(_memberships)); + // Sessions + builder.Services.AddSingleton(_sessions); + builder.Services.AddSingleton(Substitute.For()); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(TimeProvider.System); + // Settings + builder.Services.AddSingleton(Substitute.For()); + + _app = builder.Build(); + // A stub answering with defaults may throw behind an ALLOWED call — that is a 500, not an authorization result. + _app.Use(async (ctx, next) => + { + try { await next(ctx); } + catch (Exception ex) when (ex is NullReferenceException or InvalidOperationException or ArgumentException) + { + ctx.Response.StatusCode = StatusCodes.Status500InternalServerError; + } + }); + _app.UseAuthentication(); + _app.UseAuthorization(); + _app.MapTenantEndpoints(); + _app.MapWorkspaceEndpoints(); + _app.MapSessionEndpoints(); + _app.MapSettingsEndpoints(); + await _app.StartAsync(); + _client = _app.GetTestClient(); + + // The restricted board has one member: u-dev as a developer. + await _memberships.SetAsync(Tenant, RestrictedBoard, "u-dev", "developer", "admin"); + } + + public async ValueTask DisposeAsync() + { + _client?.Dispose(); + if (_app is not null) { await _app.DisposeAsync(); } + } + + private async Task SendAsync(string? roles, HttpMethod method, string path, object? body = null, string user = "u1") + { + using var request = new HttpRequestMessage(method, path); + if (roles is not null) + { + request.Headers.Add(HeaderAuth.RolesHeader, roles); + request.Headers.Add(HeaderAuth.UserHeader, user); + } + if (body is not null) { request.Content = JsonContent.Create(body); } + using var response = await _client!.SendAsync(request, TestContext.Current.CancellationToken); + return response.StatusCode; + } + + // (method, route, the permission the matrix requires) + private static readonly (string Method, string Path, Permission Required)[] RouteTable = + [ + ("GET", $"/tenants/{Tenant}/members", Permission.ManageMembers), + ("PATCH", $"/tenants/{Tenant}/members/u2", Permission.ManageMembers), + ("POST", $"/tenants/{Tenant}/invitations", Permission.ManageMembers), + ("GET", $"/tenants/{Tenant}/audit", Permission.ViewAudit), + ("GET", $"/tenants/{Tenant}/boards/{OpenBoard}/members", Permission.ManageMembers), + ("PUT", $"/tenants/{Tenant}/boards/{OpenBoard}/members/u2", Permission.ManageMembers), + ("GET", "/workspaces", Permission.ViewWork), + ("GET", $"/workspaces/{OpenBoard}", Permission.ViewWork), + ("POST", "/workspaces", Permission.ManageWorkspaces), + ("DELETE", $"/workspaces/{OpenBoard}", Permission.ManageWorkspaces), + ("POST", $"/workspaces/{OpenBoard}/repos", Permission.ManageWorkspaces), + ("GET", "/sessions", Permission.ViewWork), + ("POST", "/sessions", Permission.RunAgents), + ("POST", "/runners", Permission.RunAgents), + ("GET", "/settings/Llm", Permission.ManageSettings), + ("POST", "/settings", Permission.ManageSettings), + ]; + + public static TheoryData Routes() + { + var data = new TheoryData(); + foreach (var (method, path, required) in RouteTable) { data.Add(method, path, required); } + return data; + } + + private static object? BodyFor(string method, string path) => (method, path) switch + { + ("PATCH", _) => new { roles = ViewerOnly }, + ("PUT", _) => new { role = "viewer" }, + ("POST", var p) when p.EndsWith("/invitations", StringComparison.Ordinal) => new { role = "viewer" }, + ("POST", "/sessions") => new { workspaceId = OpenBoard, title = "t" }, + ("POST", "/runners") => new { label = "laptop" }, + ("POST", "/settings") => new { key = "Llm:ForceProvider", value = "Claude" }, + ("POST", "/workspaces") => new { name = "b", projectOwner = "o", projectScope = "user", accessToken = "x" }, + ("POST", _) => new { owner = "o", repo = "r" }, + _ => null, + }; + + [Theory] + [MemberData(nameof(Routes))] + public async Task Route_Anonymous_IsUnauthorized(string method, string path, Permission required) + { + _ = required; + (await SendAsync(null, new HttpMethod(method), path, BodyFor(method, path))).ShouldBe(HttpStatusCode.Unauthorized); + } + + public static TheoryData RoutesByRole() + { + var data = new TheoryData(); + foreach (var role in UserRoles.Assignable.Append(UserRoles.LegacyMember).Append("platform-admin")) + { + foreach (var (method, path, required) in RouteTable) + { + data.Add(role, method, path, required); + } + } + return data; + } + + [Theory] + [MemberData(nameof(RoutesByRole))] + public async Task Route_EveryRole_GetsExactlyWhatTheMatrixGrants(string role, string method, string path, Permission required) + { + var status = await SendAsync(role, new HttpMethod(method), path, BodyFor(method, path)); + if (PermissionMatrix.For(role).Has(required)) + { + status.ShouldNotBe(HttpStatusCode.Forbidden, $"{role} {method} {path}"); + status.ShouldNotBe(HttpStatusCode.Unauthorized, $"{role} {method} {path}"); + } + else + { + status.ShouldBe(HttpStatusCode.Forbidden, $"{role} {method} {path}"); + } + } + + // ── Per-board (workspace) membership isolation ────────────────────────────────────────────── + + [Fact] + public async Task RestrictedBoard_IsNotFound_ForATenantDeveloperWhoIsNotAMember() + => (await SendAsync("developer", HttpMethod.Get, $"/workspaces/{RestrictedBoard}", user: "u-other")) + .ShouldBe(HttpStatusCode.NotFound); + + [Fact] + public async Task RestrictedBoard_IsVisible_ToItsMember_AndToTenantWideRoles() + { + (await SendAsync("viewer", HttpMethod.Get, $"/workspaces/{RestrictedBoard}", user: "u-dev")).ShouldBe(HttpStatusCode.OK); + (await SendAsync("auditor", HttpMethod.Get, $"/workspaces/{RestrictedBoard}", user: "u-other")).ShouldBe(HttpStatusCode.OK); + (await SendAsync("admin", HttpMethod.Get, $"/workspaces/{RestrictedBoard}", user: "u-other")).ShouldBe(HttpStatusCode.OK); + } + + [Fact] + public async Task BoardList_LeavesOutRestrictedBoards_TheCallerIsNotOn() + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/workspaces"); + request.Headers.Add(HeaderAuth.RolesHeader, "developer"); + request.Headers.Add(HeaderAuth.UserHeader, "u-other"); + using var response = await _client!.SendAsync(request, TestContext.Current.CancellationToken); + var rows = await response.Content.ReadFromJsonAsync>(TestContext.Current.CancellationToken); + rows!.Select(r => r.Id).ShouldBe([OpenBoard]); + } + + [Fact] + public async Task CreateSession_OnARestrictedBoard_FollowsTheMembershipRole() + { + _sessions.AddAsync(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); + var body = new { workspaceId = RestrictedBoard, title = "t" }; + // u-dev is the board's developer member: allowed. + (await SendAsync("developer", HttpMethod.Post, "/sessions", body, user: "u-dev")).ShouldBe(HttpStatusCode.Created); + // A tenant developer who is not on the restricted board may not start work there. + (await SendAsync("developer", HttpMethod.Post, "/sessions", body, user: "u-other")).ShouldBe(HttpStatusCode.Forbidden); + } + + [Fact] + public async Task BoardMembership_ForAnotherTenant_IsForbidden() + => (await SendAsync("admin", HttpMethod.Get, $"/tenants/other/boards/{OpenBoard}/members")).ShouldBe(HttpStatusCode.Forbidden); + + [Fact] + public async Task BoardMembership_RejectsARoleABoardCannotCarry() + => (await SendAsync("admin", HttpMethod.Put, $"/tenants/{Tenant}/boards/{OpenBoard}/members/u2", new { role = "admin" })) + .ShouldBe(HttpStatusCode.BadRequest); + + [Fact] + public async Task MemberRoles_LockOutGuard_StillHolds() + => (await SendAsync("admin", HttpMethod.Patch, $"/tenants/{Tenant}/members/u1", new { roles = ViewerOnly }, user: "u1")) + .ShouldBe(HttpStatusCode.BadRequest); + + private sealed record BoardRow(Guid Id); + + private sealed class AllowAllHosts : IWorkspaceHostPolicy + { + public bool IsAllowed(string? host) => true; + } + + private sealed class NoProvisioning : IRunnerProvisioningService + { + public Task ProvisionAsync(string tenantId, string userId, string label, CancellationToken ct = default) + => throw new InvalidOperationException("not under test"); + } + + /// Signs the caller in with the roles in (comma-separated) for tenant "acme". + private sealed class HeaderAuth(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder) + : AuthenticationHandler(options, logger, encoder) + { + public const string SchemeName = "header"; + public const string RolesHeader = "X-Test-Roles"; + public const string UserHeader = "X-Test-User"; + + protected override Task HandleAuthenticateAsync() + { + if (!Request.Headers.TryGetValue(RolesHeader, out var roles)) { return Task.FromResult(AuthenticateResult.NoResult()); } + var claims = new List + { + new(ClaimNames.Subject, Request.Headers[UserHeader].ToString()), + new(ClaimNames.Tenant, Tenant), + }; + claims.AddRange(roles.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries).Select(r => new Claim(ClaimTypes.Role, r))); + var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, SchemeName, ClaimTypes.Name, ClaimTypes.Role)); + return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, SchemeName))); + } + } +} diff --git a/tests/AgentOs.Tests/Identity/PermissionMatrixTests.cs b/tests/AgentOs.Tests/Identity/PermissionMatrixTests.cs new file mode 100644 index 00000000..8270a43f --- /dev/null +++ b/tests/AgentOs.Tests/Identity/PermissionMatrixTests.cs @@ -0,0 +1,216 @@ +// RBAC v2 (E1.2) — the permission matrix, cell by cell. The expected table below is the spec: every role × every +// permission is asserted, so a change to what a role may do is a deliberate edit here AND in PermissionMatrix. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using AgentOs.SharedKernel.Identity; +using Shouldly; +using Xunit; + +namespace AgentOs.Tests.Identity; + +public sealed class PermissionMatrixTests +{ + private const Permission V = Permission.ViewWork; + private const Permission R = Permission.RunAgents; + private const Permission A = Permission.ApproveWork; + private const Permission W = Permission.ManageWorkspaces; + private const Permission M = Permission.ManageMembers; + private const Permission S = Permission.ManageSettings; + private const Permission T = Permission.ManageApiTokens; + private const Permission Au = Permission.ViewAudit; + private const Permission X = Permission.ExportData; + + // The spec. Rows = roles, values = exactly the permissions the role grants. + private static readonly Dictionary Expected = new(StringComparer.Ordinal) + { + ["viewer"] = [V], + ["developer"] = [V, R], + ["approver"] = [V, A], + ["auditor"] = [V, Au], + ["admin"] = [V, R, A, W, M, S, T, Au, X], + ["member"] = [V, R, W], // legacy alias: everything a pre-E1.2 member could do (no E1.5 approvals) + ["platform-admin"] = [], // orthogonal: platform-wide settings, nothing tenant-scoped + ["unknown-role"] = [], + }; + + public static TheoryData EveryCell() + { + var data = new TheoryData(); + foreach (var (role, granted) in Expected) + { + foreach (var permission in PermissionMatrix.Each) + { + data.Add(role, permission, granted.Contains(permission)); + } + } + return data; + } + + [Theory] + [MemberData(nameof(EveryCell))] + public void For_EveryRoleAndPermission_MatchesTheSpec(string role, Permission permission, bool expected) + => PermissionMatrix.For(role).Has(permission).ShouldBe(expected, $"{role} × {permission}"); + + [Fact] + public void Each_ListsEveryDefinedPermissionOnce_AndAllIsTheirUnion() + { + var defined = Enum.GetValues().Where(p => p != Permission.None).ToArray(); + PermissionMatrix.Each.ShouldBe(defined, ignoreOrder: true); + PermissionMatrix.Each.Distinct().Count().ShouldBe(PermissionMatrix.Each.Count); + PermissionMatrix.Each.Aggregate(Permission.None, (acc, p) => acc | p).ShouldBe(PermissionMatrix.All); + // Single flags only — a combined value in Each would make "has X" checks ambiguous. + PermissionMatrix.Each.ShouldAllBe(p => ((long)p & ((long)p - 1)) == 0); + } + + [Fact] + public void Matrix_CoversExactlyTheManagedRoles() + => PermissionMatrix.Roles.Keys.ShouldBe(UserRoles.Managed, ignoreOrder: true); + + [Fact] + public void Has_NoneIsNeverGranted_AndCombinationsNeedEveryFlag() + { + PermissionMatrix.All.Has(Permission.None).ShouldBeFalse(); + PermissionMatrix.For("developer").Has(R | V).ShouldBeTrue(); + PermissionMatrix.For("developer").Has(R | A).ShouldBeFalse(); + } + + [Fact] + public void For_RolesAreAdditive() + { + var both = PermissionMatrix.For(["developer", "approver"]); + both.ShouldBe(V | R | A); + PermissionMatrix.For(["viewer", "auditor", "nonsense"]).ShouldBe(V | Au); + PermissionMatrix.For(Array.Empty()).ShouldBe(Permission.None); + } + + [Fact] + public void For_IsCaseSensitive_LikeKeycloakRoleNames() + => PermissionMatrix.For("Admin").ShouldBe(Permission.None); + + [Fact] + public void LegacyMember_KeepsEverythingADeveloperHas_ButApprovesNothing() + { + var member = PermissionMatrix.For("member"); + member.Has(PermissionMatrix.For("developer")).ShouldBeTrue(); + member.Has(Permission.ManageWorkspaces).ShouldBeTrue(); + member.Has(Permission.ApproveWork).ShouldBeFalse(); + member.Has(Permission.ManageMembers).ShouldBeFalse(); + } + + // ── Workspace (board) scope ────────────────────────────────────────────────────────────────── + + [Fact] + public void ForWorkspace_OpenBoard_TenantRolesApply() + => PermissionMatrix.ForWorkspace(["developer"], restricted: false, membershipRole: null).ShouldBe(V | R); + + [Fact] + public void ForWorkspace_RestrictedBoard_WithoutMembership_GrantsNothingToWorkspaceRoles() + { + PermissionMatrix.ForWorkspace(["developer", "approver", "viewer", "member"], restricted: true, membershipRole: null) + .ShouldBe(Permission.None); + } + + [Fact] + public void ForWorkspace_RestrictedBoard_MembershipRoleReplacesTenantRole() + { + // Tenant developer, viewer on this board → read only here. + PermissionMatrix.ForWorkspace(["developer"], restricted: true, membershipRole: "viewer").ShouldBe(V); + // Tenant viewer, developer on this board → may run agents here. + PermissionMatrix.ForWorkspace(["viewer"], restricted: true, membershipRole: "developer").ShouldBe(V | R); + } + + [Theory] + [InlineData("admin")] + [InlineData("auditor")] + public void ForWorkspace_TenantWideRoles_ApplyOnEveryBoard(string role) + => PermissionMatrix.ForWorkspace([role], restricted: true, membershipRole: null).ShouldBe(PermissionMatrix.For(role)); + + [Theory] + [InlineData("admin")] + [InlineData("auditor")] + [InlineData("member")] + [InlineData("platform-admin")] + public void ForWorkspace_AMembershipCanOnlyCarryAWorkspaceRole(string role) + => PermissionMatrix.ForWorkspace(["viewer"], restricted: true, membershipRole: role).ShouldBe(Permission.None); + + [Fact] + public void WorkspaceAccessMap_AnswersPerBoard() + { + var open = Guid.NewGuid(); + var mine = Guid.NewGuid(); + var theirs = Guid.NewGuid(); + var rows = new[] + { + new WorkspaceMember(mine, "u1", "developer", null, DateTimeOffset.UnixEpoch), + new WorkspaceMember(theirs, "u2", "approver", null, DateTimeOffset.UnixEpoch), + }; + var map = WorkspaceAccessMap.Build(["viewer"], "u1", rows); + + map.TenantPermissions.ShouldBe(V); + map.CanSee(open).ShouldBeTrue(); // open board → tenant viewer reads + map.Can(open, R).ShouldBeFalse(); + map.Can(mine, R).ShouldBeTrue(); // membership elevates on that board only + map.CanSee(theirs).ShouldBeFalse(); // restricted, not a member + map.IsRestricted(open).ShouldBeFalse(); + map.IsRestricted(theirs).ShouldBeTrue(); + map.MembershipRole(mine).ShouldBe("developer"); + map.RolesOn(mine).ShouldBe(["developer"]); + } + + [Fact] + public void WorkspaceAccessMap_AnonymousUserIdMatchesNoMembership() + { + var board = Guid.NewGuid(); + var map = WorkspaceAccessMap.Build([], null, [new WorkspaceMember(board, "u1", "viewer", null, DateTimeOffset.UnixEpoch)]); + map.CanSee(board).ShouldBeFalse(); + } + + // ── Names, policies, principals ────────────────────────────────────────────────────────────── + + [Fact] + public void Policy_NamesAreUniqueAndPrefixed() + { + var names = PermissionMatrix.Each.Select(PermissionMatrix.Policy).ToArray(); + names.Distinct(StringComparer.Ordinal).Count().ShouldBe(names.Length); + names.ShouldAllBe(n => n.StartsWith(PermissionMatrix.PolicyPrefix, StringComparison.Ordinal)); + PermissionMatrix.Policy(Permission.RunAgents).ShouldBe("perm:RunAgents"); + } + + [Fact] + public void Assignable_IsTheFiveRoles_LeastToMostPrivileged() + { + UserRoles.Assignable.ShouldBe(["viewer", "developer", "approver", "auditor", "admin"]); + UserRoles.WorkspaceAssignable.ShouldBe(["viewer", "developer", "approver"]); + UserRoles.IsAssignable("member").ShouldBeFalse(); + UserRoles.IsAssignable(null).ShouldBeFalse(); + UserRoles.Assignable.ShouldAllBe(r => UserRoles.Label(r).Length > 0 && UserRoles.Describe(r).Length > 0); + } + + [Fact] + public void CanApprove_IsTheMatrixApproveWork_ForE15Gates() + { + static ClaimsPrincipal As(string role) => new(new ClaimsIdentity([new Claim(ClaimTypes.Role, role)], "test")); + As("approver").CanApprove().ShouldBeTrue(); + As("admin").CanApprove().ShouldBeTrue(); + foreach (var role in new[] { "viewer", "developer", "auditor", "member", "platform-admin" }) + { + As(role).CanApprove().ShouldBeFalse(role); + } + } + + [Fact] + public void Can_ReadsTheRoleClaims_AndAnonymousHoldsNothing() + { + var user = new ClaimsPrincipal(new ClaimsIdentity( + [new Claim(ClaimTypes.Role, "developer"), new Claim(ClaimTypes.Role, "auditor")], "test")); + user.GetPermissions().ShouldBe(V | R | Au); + user.Can(Permission.RunAgents).ShouldBeTrue(); + user.Can(Permission.ManageMembers).ShouldBeFalse(); + + var anonymous = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.Role, "admin")])); + anonymous.GetPermissions().ShouldBe(Permission.None); + } +} diff --git a/tests/AgentOs.Tests/Identity/RbacAuthorizationTests.cs b/tests/AgentOs.Tests/Identity/RbacAuthorizationTests.cs new file mode 100644 index 00000000..2a1fe666 --- /dev/null +++ b/tests/AgentOs.Tests/Identity/RbacAuthorizationTests.cs @@ -0,0 +1,134 @@ +// RBAC v2 (E1.2) — the ASP.NET Core side of the matrix: the "perm:*" policies the Identity module registers, the +// permission handler, the legacy "Member" policy, and the role-claim mapping hook (legacy roles today, IdP groups +// with E1.1 SSO). + +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; +using AgentOs.Modules.Identity; +using AgentOs.Modules.Identity.Authorization; +using AgentOs.SharedKernel.Identity; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authorization; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Xunit; + +namespace AgentOs.Tests.Identity; + +public sealed class RbacAuthorizationTests +{ + private static ServiceProvider Services(params IRoleClaimMapper[] mappers) + { + var services = new ServiceCollection(); + services.AddLogging(); + foreach (var m in mappers) { services.AddSingleton(m); } + new IdentityModule().AddServices(services, new ConfigurationBuilder().Build()); + return services.BuildServiceProvider(); + } + + private static ClaimsPrincipal User(params string[] roles) => new(new ClaimsIdentity( + roles.Select(r => new Claim(ClaimTypes.Role, r)).Append(new Claim(ClaimNames.Subject, "u1")), + "test", ClaimTypes.Name, ClaimTypes.Role)); + + public static TheoryData RoleByPermission() + { + var data = new TheoryData(); + foreach (var role in UserRoles.Managed) + { + foreach (var p in PermissionMatrix.Each) { data.Add(role, p); } + } + return data; + } + + [Theory] + [MemberData(nameof(RoleByPermission))] + public async Task PermissionPolicy_AgreesWithTheMatrix(string role, Permission permission) + { + await using var sp = Services(); + var auth = sp.GetRequiredService(); + var result = await auth.AuthorizeAsync(User(role), PermissionMatrix.Policy(permission)); + result.Succeeded.ShouldBe(PermissionMatrix.For(role).Has(permission), $"{role} × {permission}"); + } + + [Fact] + public async Task PermissionPolicy_AnonymousIsRefused_EvenWithARoleClaim() + { + await using var sp = Services(); + var anonymous = new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.Role, "admin")])); + (await sp.GetRequiredService().AuthorizeAsync(anonymous, PermissionMatrix.Policy(Permission.ViewWork))) + .Succeeded.ShouldBeFalse(); + } + + [Theory] + [InlineData("viewer", true)] + [InlineData("auditor", true)] + [InlineData("member", true)] + [InlineData("admin", true)] + [InlineData("platform-admin", false)] + public async Task MemberPolicy_IsAnyTenantRole(string role, bool expected) + { + await using var sp = Services(); + (await sp.GetRequiredService().AuthorizeAsync(User(role), "Member")).Succeeded.ShouldBe(expected); + } + + [Fact] + public async Task Transformation_MapsLegacyMember_OntoDeveloper() + { + await using var sp = Services(); + var transformed = await sp.GetRequiredService().TransformAsync(User("member")); + transformed.IsInRole("developer").ShouldBeTrue(); + transformed.IsInRole("approver").ShouldBeFalse(); // E1.5's gates never accepted a member + transformed.CanApprove().ShouldBeFalse(); + transformed.IsInRole("member").ShouldBeTrue(); + } + + [Fact] + public async Task Transformation_IsIdempotent_AndLeavesOtherUsersAlone() + { + await using var sp = Services(); + var t = sp.GetRequiredService(); + var once = await t.TransformAsync(User("member")); + var twice = await t.TransformAsync(once); + twice.FindAll(ClaimTypes.Role).Count(c => c.Value == "developer").ShouldBe(1); + + var viewer = User("viewer"); + (await t.TransformAsync(viewer)).ShouldBeSameAs(viewer); + } + + [Fact] + public async Task Transformation_RunsRegisteredMappers_TheE11GroupHook() + { + // What E1.1 SSO will register: IdP group claims → AgentOS.NET roles. Unknown role names are dropped. + await using var sp = Services(new GroupMapper()); + var user = User(); + ((ClaimsIdentity)user.Identity!).AddClaim(new Claim("groups", "eng-approvers")); + var transformed = await sp.GetRequiredService().TransformAsync(user); + transformed.IsInRole("approver").ShouldBeTrue(); + transformed.IsInRole("superuser").ShouldBeFalse(); + transformed.Can(Permission.ApproveWork).ShouldBeTrue(); + user.IsInRole("approver").ShouldBeFalse(); // the original principal is never mutated + } + + [Fact] + public async Task Transformation_SkipsAnonymous() + { + await using var sp = Services(new GroupMapper()); + var anonymous = new ClaimsPrincipal(new ClaimsIdentity([new Claim("groups", "eng-approvers")])); + (await sp.GetRequiredService().TransformAsync(anonymous)).ShouldBeSameAs(anonymous); + } + + private sealed class GroupMapper : IRoleClaimMapper + { + private static readonly string[] ApproverGroup = ["approver", "superuser"]; + + public IEnumerable MapRoles(ClaimsPrincipal user) => + user.FindAll("groups").SelectMany(g => g.Value switch + { + "eng-approvers" => ApproverGroup, + _ => [], + }); + } +} diff --git a/tests/AgentOs.Tests/Persistence/RowLevelSecurityTests.cs b/tests/AgentOs.Tests/Persistence/RowLevelSecurityTests.cs index 37d1388a..14a7e29f 100644 --- a/tests/AgentOs.Tests/Persistence/RowLevelSecurityTests.cs +++ b/tests/AgentOs.Tests/Persistence/RowLevelSecurityTests.cs @@ -38,12 +38,13 @@ public void StageOne_LeavesPlatformScopedTablesToStageTwo() { // app_config and audit_events hold platform-scope rows (__platform / _platform) read by every tenant. RowLevelSecurity.Tables.ShouldNotContain(t => t.Table == "app_config" || t.Table == "audit_events"); - RowLevelSecurity.Tables.Count.ShouldBe(17); // + pipeline.scheduled_runs, memory.nodes, memory.edges, workspaces.autopilot_events, workspaces.ticket_flows, sessions.ticket_files, sessions.design_reviews, sessions.approvals + RowLevelSecurity.Tables.Count.ShouldBe(18); // + pipeline.scheduled_runs, memory.nodes, memory.edges, workspaces.autopilot_events, workspaces.ticket_flows, sessions.ticket_files, sessions.design_reviews, sessions.approvals, workspaces.workspace_members RowLevelSecurity.Tables.ShouldContain(("sessions", "design_reviews")); RowLevelSecurity.Tables.ShouldContain(("sessions", "approvals")); RowLevelSecurity.Tables.ShouldContain(("pipeline", "scheduled_runs")); RowLevelSecurity.Tables.ShouldContain(("sessions", "ticket_files")); RowLevelSecurity.Tables.ShouldContain(("workspaces", "ticket_flows")); + RowLevelSecurity.Tables.ShouldContain(("workspaces", "workspace_members")); RowLevelSecurity.Tables.ShouldContain(("memory", "nodes")); } diff --git a/tests/AgentOs.Tests/Security/HostSecurityTests.cs b/tests/AgentOs.Tests/Security/HostSecurityTests.cs index b35c5b84..2d1553dc 100644 --- a/tests/AgentOs.Tests/Security/HostSecurityTests.cs +++ b/tests/AgentOs.Tests/Security/HostSecurityTests.cs @@ -103,6 +103,32 @@ .. services.GetRequiredService().Endpoints.OfTypeEndpoints that state NO authorization of their own — neither an explicit AllowAnonymous nor a named + /// policy / role (RBAC v2's perm:* policies, Admin, PlatformAdmin, …). They are protected only by #331's fallback + /// (any signed-in caller), i.e. by omission: a viewer could call them. Each "method route" is listed. + private static string[] ImplicitlyAuthorizedRoutes(IServiceProvider services) => + [ + .. services.GetRequiredService().Endpoints.OfType() + .Where(e => e.Metadata.GetMetadata() is null) + .Where(e => !e.Metadata.GetOrderedMetadata().Any(a => a.Policy is { Length: > 0 } || a.Roles is { Length: > 0 })) + .Where(e => !IsStaticFile(e.RoutePattern.RawText ?? string.Empty)) + .Select(e => $"{string.Join('|', e.Metadata.GetMetadata()?.HttpMethods ?? ["*"])} {e.RoutePattern.RawText}") + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal), + ]; + // MapStaticAssets maps one endpoint per file (and per fingerprinted / compressed variant): a file name has an extension. private static bool IsStaticFile(string raw) => raw.Contains('.', StringComparison.Ordinal) && !raw.Contains('{', StringComparison.Ordinal); @@ -169,6 +195,15 @@ public async Task Web_AccountLogin_IsAnonymousAndChallenges() response.Headers.Location!.ToString().ShouldStartWith(WebHostFactory.Authority); } + [Fact] + public async Task Web_EveryEndpoint_NamesItsAuthorization_OrIsExplicitlyAnonymous() + { + // RBAC v2 x GAP-13: the fallback catches a forgotten route, but a route that relies on it lets every role in. + await using var factory = new WebHostFactory(); + _ = factory.Server; // build the host + ImplicitlyAuthorizedRoutes(factory.Services).ShouldBe(WebAuthenticatedOnly); + } + [Fact] public async Task Web_AnonymousEndpointInventory_IsTheReviewedList() { @@ -359,6 +394,14 @@ public async Task Api_ExplicitAnonymousRoutes_StillAnswer() } } + [Fact] + public async Task Api_EveryEndpoint_NamesItsAuthorization_OrIsExplicitlyAnonymous() + { + await using var factory = new ApiHostFactory(); + _ = factory.Server; // build the host + ImplicitlyAuthorizedRoutes(factory.Services).ShouldBe(ApiAuthenticatedOnly); + } + [Fact] public async Task Api_AnonymousEndpointInventory_IsTheReviewedList() { diff --git a/tests/AgentOs.Tests/Security/PublicLinkTests.cs b/tests/AgentOs.Tests/Security/PublicLinkTests.cs index 98df4b85..f0e49524 100644 --- a/tests/AgentOs.Tests/Security/PublicLinkTests.cs +++ b/tests/AgentOs.Tests/Security/PublicLinkTests.cs @@ -80,7 +80,7 @@ public async Task Invitation_UrlPointsAtThePublicBaseUrl_NotTheRequestHost() await using var app = await StartAsync(services => { var signup = Substitute.For(); - signup.CreateInvitation("acme", "member", null, Arg.Any()) + signup.CreateInvitation("acme", MemberRoles.DefaultRole, null, Arg.Any()) // RBAC v2 default: developer .Returns(new InvitationToken("tok/1", DateTimeOffset.UtcNow.AddHours(1))); services.AddSingleton(signup); services.AddSingleton(Substitute.For()); diff --git a/tests/AgentOs.Tests/Security/TestHosting.cs b/tests/AgentOs.Tests/Security/TestHosting.cs index 84b05cf0..ac2e519b 100644 --- a/tests/AgentOs.Tests/Security/TestHosting.cs +++ b/tests/AgentOs.Tests/Security/TestHosting.cs @@ -17,6 +17,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using AgentOs.Modules.Identity.Authorization; namespace AgentOs.Tests.Security; @@ -54,12 +55,15 @@ public static SignOutRecorder AddTestAuth(this IServiceCollection services) .AddScheme(TestAuthHandler.SchemeName, _ => { }) .AddScheme("Cookies", _ => { }) .AddScheme("OpenIdConnect", _ => { }); + // The production policy set (IdentityModule): the named policies + RBAC v2's "perm:*" permission policies. services.AddAuthorization(o => { o.AddPolicy("Admin", p => p.RequireRole("admin")); - o.AddPolicy("Member", p => p.RequireRole("admin", "member")); + o.AddPolicy("Member", p => p.RequirePermission(AgentOs.SharedKernel.Identity.Permission.ViewWork)); o.AddPolicy("PlatformAdmin", p => p.RequireRole("platform-admin")); + o.AddPermissionPolicies(); }); + services.AddRbac(); return recorder; } } diff --git a/tests/AgentOs.Tests/Tenants/TenantEndpointAuthorizationTests.cs b/tests/AgentOs.Tests/Tenants/TenantEndpointAuthorizationTests.cs index cbf883ae..a485fefa 100644 --- a/tests/AgentOs.Tests/Tenants/TenantEndpointAuthorizationTests.cs +++ b/tests/AgentOs.Tests/Tenants/TenantEndpointAuthorizationTests.cs @@ -29,6 +29,7 @@ private static RouteEndpoint[] Endpoints() builder.Services.AddSingleton(Substitute.For()); builder.Services.AddSingleton(Substitute.For()); builder.Services.AddSingleton(Substitute.For()); + builder.Services.AddSingleton(Substitute.For()); builder.Services.AddSingleton(new AgentOs.SharedKernel.Hosting.PublicOrigin("https://agentos.example.com", allowRequestFallback: false)); var app = builder.Build(); app.MapTenantEndpoints(); @@ -45,18 +46,36 @@ public void CrossTenantEndpoints_RequirePlatformAdmin(string name) var endpoint = Endpoints().Single(e => e.Metadata.GetMetadata()?.EndpointName == name); Policies(endpoint).ShouldContain("PlatformAdmin"); Policies(endpoint).ShouldNotContain("Admin"); + Policies(endpoint).ShouldNotContain(PermissionMatrix.Policy(Permission.ManageMembers)); } [Fact] public void EveryTenantScopedAdminRoute_CarriesTheTenantInItsPath() { - // Routes a TENANT admin may call must be scoped by {tenantId} (checked against the caller's claim in the - // handler); an Admin-policy route without it would act across tenants. + // Routes a TENANT admin (or auditor) may call must be scoped by {tenantId} (checked against the caller's claim in + // the handler); a tenant-permission route without it would act across tenants. RBAC v2: those are the "perm:*" + // policies (and the legacy "Admin" one). var offenders = Endpoints() - .Where(e => Policies(e).Contains("Admin")) + .Where(e => Policies(e).Any(p => p == "Admin" || p?.StartsWith(PermissionMatrix.PolicyPrefix, System.StringComparison.Ordinal) == true)) .Where(e => !e.RoutePattern.RawText!.Contains("{tenantId}", System.StringComparison.Ordinal)) .Select(e => e.RoutePattern.RawText) .ToArray(); offenders.ShouldBeEmpty(); } + + [Theory] + [InlineData("TenantsListMembers", Permission.ManageMembers)] + [InlineData("TenantsUpdateMemberRoles", Permission.ManageMembers)] + [InlineData("TenantsRemoveMember", Permission.ManageMembers)] + [InlineData("TenantsInviteMember", Permission.ManageMembers)] + [InlineData("TenantsCreateInvitation", Permission.ManageMembers)] + [InlineData("TenantsSetBoardRole", Permission.ManageMembers)] + [InlineData("TenantsRemoveBoardRole", Permission.ManageMembers)] + [InlineData("TenantsListBoardMembers", Permission.ManageMembers)] + [InlineData("TenantsAudit", Permission.ViewAudit)] + public void MemberManagementRoutes_RequireTheirPermission(string name, Permission permission) + { + var endpoint = Endpoints().Single(e => e.Metadata.GetMetadata()?.EndpointName == name); + Policies(endpoint).ShouldContain(PermissionMatrix.Policy(permission)); + } } diff --git a/tests/AgentOs.Tests/Web/DesktopGatingTests.cs b/tests/AgentOs.Tests/Web/DesktopGatingTests.cs new file mode 100644 index 00000000..58cfcabc --- /dev/null +++ b/tests/AgentOs.Tests/Web/DesktopGatingTests.cs @@ -0,0 +1,122 @@ +// RBAC v2 (E1.2) — desktop app gating per role. The dock, Activities, Settings hub/search and the shell actions all +// filter through the same matrix; WindowHost refuses an app the role can't open. These pin what each role sees, so a +// gate can't silently drift from the endpoints it fronts. + +using System.Linq; +using AgentOs.Modules.Tenants; +using AgentOs.SharedKernel.Identity; +using AgentOs.Web.Services; +using AgentOs.Web.Shell.Services; +using Shouldly; +using Xunit; + +namespace AgentOs.Tests.Web; + +public sealed class DesktopGatingTests +{ + private static string[] AppsFor(string role) => + [.. AppCatalog.VisibleAll(PermissionMatrix.For(role)).Select(a => a.Key)]; + + private static readonly string[] AdminApps = ["users", "evidence", "tokens", "data", "audit", "policy", "prompts", "agents", "mcp"]; + private static readonly string[] EveryoneApps = ["home", "workflow", "board", "insights", "settings", "terminal", "files", "plugins", "system"]; + + [Theory] + [InlineData("viewer")] + [InlineData("developer")] + [InlineData("approver")] + [InlineData("auditor")] + [InlineData("admin")] + [InlineData("member")] + public void EveryRole_SeesTheWorkApps(string role) + => EveryoneApps.ShouldBeSubsetOf(AppsFor(role)); + + [Fact] + public void Admin_SeesEveryApp() + => AppsFor("admin").ShouldBe(AppCatalog.All.Select(a => a.Key), ignoreOrder: true); + + [Theory] + [InlineData("viewer")] + [InlineData("developer")] + [InlineData("approver")] + [InlineData("member")] + public void NonAdminRoles_SeeNoAdminApp(string role) + => AppsFor(role).Intersect(AdminApps).ShouldBeEmpty(); + + [Fact] + public void Auditor_SeesTheAuditApps_AndNothingElseAdmin() + => AppsFor("auditor").Intersect(AdminApps).ShouldBe(["evidence", "audit"], ignoreOrder: true); + + [Fact] + public void EveryAdminApp_DeclaresTheMatrixPermissionItNeeds() + { + foreach (var key in AdminApps) + { + AppCatalog.Find(key)!.Required.ShouldNotBe(Permission.None, key); + } + } + + [Fact] + public void PluginAdminOnlyFlag_StillMeansAdmin() + { + var plugin = new DesktopApp("p", "P", "x", "c", "Plugins", AdminOnly: true); + plugin.IsVisibleTo(PermissionMatrix.For("developer")).ShouldBeFalse(); + plugin.IsVisibleTo(PermissionMatrix.For("admin")).ShouldBeTrue(); + new DesktopApp("q", "Q", "x", "c", "Plugins").IsVisibleTo(Permission.None).ShouldBeTrue(); + } + + [Fact] + public void Pinned_FollowsTheSameGate() + => new AppCatalogRegistry().VisiblePinned(PermissionMatrix.For("viewer")).ShouldAllBe(a => a.IsVisibleTo(PermissionMatrix.For("viewer"))); + + [Theory] + [InlineData("invite", "admin", true)] + [InlineData("invite", "auditor", false)] + [InlineData("api token", "developer", false)] + [InlineData("export", "admin", true)] + [InlineData("export", "auditor", false)] + [InlineData("add model key", "approver", false)] + public void ShellActions_AreGatedByPermission(string query, string role, bool offered) + => ShellActions.Find(query, PermissionMatrix.For(role)).Any().ShouldBe(offered); + + [Theory] + [InlineData("audit log", "auditor", true)] + [InlineData("audit log", "developer", false)] + [InlineData("tool calls", "auditor", true)] + [InlineData("invite", "auditor", false)] + [InlineData("api token", "admin", true)] + [InlineData("theme", "viewer", true)] + public void SettingsSearch_OffersAPageOnlyToWhoHoldsItsPermission(string query, string role, bool offered) + => SettingsSearch.Find(query, [], PermissionMatrix.For(role), isPlatformAdmin: false).Any().ShouldBe(offered); + + [Fact] + public void Gate_PlatformPagesNeedPlatformAdmin_RegardlessOfTenantPermissions() + { + Gate.Platform.Allows(PermissionMatrix.All, isPlatformAdmin: false).ShouldBeFalse(); + Gate.Platform.Allows(Permission.None, isPlatformAdmin: true).ShouldBeTrue(); + Gate.Everyone.Allows(Permission.None, isPlatformAdmin: false).ShouldBeTrue(); + } + + // ── Member management rules (shared by the Users app and the HTTP endpoints) ────────────────── + + [Theory] + [InlineData(new[] { "admin", "member" }, "admin")] + [InlineData(new[] { "member" }, "member")] + [InlineData(new[] { "viewer", "approver" }, "approver")] + [InlineData(new[] { "developer", "auditor" }, "auditor")] + [InlineData(new[] { "platform-admin", "default-roles-agentic" }, null)] + public void MemberRoles_Primary_IsTheMostPrivilegedManagedRole(string[] roles, string? expected) + => MemberRoles.Primary(roles).ShouldBe(expected); + + [Fact] + public void MemberRoles_Sanitize_KeepsAllowedRolesOnly() + => MemberRoles.Sanitize(["viewer", "platform-admin", "viewer", "member", "root"]).ShouldBe(["viewer", "member"]); + + [Fact] + public void MemberRoles_Check_RefusesEmptyAndSelfDemotion() + { + MemberRoles.Check("me", "you", []).ShouldNotBeNull(); + MemberRoles.Check("me", "me", ["viewer"]).ShouldBe("You cannot remove your own admin role."); + MemberRoles.Check("me", "me", ["admin"]).ShouldBeNull(); + MemberRoles.Check("me", "you", ["auditor"]).ShouldBeNull(); + } +} diff --git a/tests/AgentOs.Tests/Workspaces/WorkspaceMembershipTests.cs b/tests/AgentOs.Tests/Workspaces/WorkspaceMembershipTests.cs new file mode 100644 index 00000000..b35c9d1d --- /dev/null +++ b/tests/AgentOs.Tests/Workspaces/WorkspaceMembershipTests.cs @@ -0,0 +1,115 @@ +// RBAC v2 (E1.2) — per-board (workspace) membership storage + isolation. Both stores (EF, the stateless standalone's +// in-memory one) must agree: tenant-explicit, one row per (tenant, board, user), only workspace roles, never attach to +// another tenant's board, and a user's access map only ever reads their own tenant's rows. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using AgentOs.Modules.Workspaces.Access; +using AgentOs.Modules.Workspaces.Persistence; +using AgentOs.Modules.Workspaces.Persistence.Entities; +using AgentOs.SharedKernel.Identity; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; + +namespace AgentOs.Tests.Workspaces; + +public sealed class WorkspaceMembershipTests +{ + private static readonly Guid BoardA = Guid.NewGuid(); + private static readonly Guid BoardB = Guid.NewGuid(); + + public static TheoryData Stores() => ["ef", "memory"]; + + private static async Task StoreAsync(string kind) + { + if (kind == "memory") { return new InMemoryWorkspaceMembershipStore(TimeProvider.System); } + var options = new DbContextOptionsBuilder().UseInMemoryDatabase($"ws-members-{Guid.NewGuid()}").Options; + var db = new WorkspacesDbContext(options); + db.Workspaces.AddRange( + new WorkspaceEntity { Id = BoardA, TenantId = "acme", Name = "a", CredentialRef = "c" }, + new WorkspaceEntity { Id = BoardB, TenantId = "globex", Name = "b", CredentialRef = "c" }); + await db.SaveChangesAsync(TestContext.Current.CancellationToken); + return new EfWorkspaceMembershipStore(db, TimeProvider.System); + } + + [Theory] + [MemberData(nameof(Stores))] + public async Task Set_InsertsThenReplaces_OneRowPerUser(string kind) + { + var store = await StoreAsync(kind); + await store.SetAsync("acme", BoardA, "u1", "viewer", "admin-1", TestContext.Current.CancellationToken); + await store.SetAsync("acme", BoardA, "u1", "developer", "admin-1", TestContext.Current.CancellationToken); + + var rows = await store.ListAsync("acme", BoardA, TestContext.Current.CancellationToken); + rows.ShouldHaveSingleItem().Role.ShouldBe("developer"); + rows[0].AddedByUserId.ShouldBe("admin-1"); + } + + [Theory] + [MemberData(nameof(Stores))] + public async Task Set_RefusesRolesABoardCannotCarry(string kind) + { + var store = await StoreAsync(kind); + foreach (var role in new[] { "admin", "auditor", "member", "platform-admin", "" }) + { + await Should.ThrowAsync(() => store.SetAsync("acme", BoardA, "u1", role, null, TestContext.Current.CancellationToken)); + } + } + + [Fact] + public async Task Set_EfStore_RefusesABoardOfAnotherTenant() + { + var store = await StoreAsync("ef"); + await Should.ThrowAsync(() => store.SetAsync("acme", BoardB, "u1", "viewer", null, TestContext.Current.CancellationToken)); + (await store.ListForTenantAsync("globex", TestContext.Current.CancellationToken)).ShouldBeEmpty(); + } + + [Theory] + [MemberData(nameof(Stores))] + public async Task Reads_AreTenantScoped(string kind) + { + var store = await StoreAsync(kind); + await store.SetAsync("acme", BoardA, "u1", "viewer", null, TestContext.Current.CancellationToken); + + (await store.ListForTenantAsync("acme", TestContext.Current.CancellationToken)).Count.ShouldBe(1); + (await store.ListForTenantAsync("globex", TestContext.Current.CancellationToken)).ShouldBeEmpty(); + (await store.ListAsync("globex", BoardA, TestContext.Current.CancellationToken)).ShouldBeEmpty(); + (await store.RemoveAsync("globex", BoardA, "u1", TestContext.Current.CancellationToken)).ShouldBeFalse(); + (await store.ListAsync("acme", BoardA, TestContext.Current.CancellationToken)).Count.ShouldBe(1); + } + + [Theory] + [MemberData(nameof(Stores))] + public async Task Remove_DeletesOnlyThatMembership(string kind) + { + var store = await StoreAsync(kind); + await store.SetAsync("acme", BoardA, "u1", "viewer", null, TestContext.Current.CancellationToken); + await store.SetAsync("acme", BoardA, "u2", "approver", null, TestContext.Current.CancellationToken); + + (await store.RemoveAsync("acme", BoardA, "u1", TestContext.Current.CancellationToken)).ShouldBeTrue(); + (await store.RemoveAsync("acme", BoardA, "u1", TestContext.Current.CancellationToken)).ShouldBeFalse(); + (await store.ListAsync("acme", BoardA, TestContext.Current.CancellationToken)).Select(m => m.UserId).ShouldBe(["u2"]); + } + + [Theory] + [MemberData(nameof(Stores))] + public async Task Access_ComesFromTheCallersTenantOnly(string kind) + { + var store = await StoreAsync(kind); + await store.SetAsync("acme", BoardA, "u1", "developer", null, TestContext.Current.CancellationToken); + var access = new WorkspaceAccess(store); + + // In acme the board is restricted: u1 (member) may run agents there, u2 (tenant developer, no membership) can't see it. + (await access.ForUserAsync("acme", ["viewer"], "u1", TestContext.Current.CancellationToken)).Can(BoardA, Permission.RunAgents).ShouldBeTrue(); + (await access.ForUserAsync("acme", ["developer"], "u2", TestContext.Current.CancellationToken)).CanSee(BoardA).ShouldBeFalse(); + // The same user id in another tenant inherits nothing from acme's memberships. + var other = await access.ForUserAsync("globex", ["viewer"], "u1", TestContext.Current.CancellationToken); + other.IsRestricted(BoardA).ShouldBeFalse(); + other.Can(BoardA, Permission.RunAgents).ShouldBeFalse(); + // A malformed sign-in (no tenant) reads nothing. + (await access.ForUserAsync("", ["admin"], "u1", TestContext.Current.CancellationToken)).IsRestricted(BoardA).ShouldBeFalse(); + } +}