Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

fix(security)!: scope every role grant to the granter (GHSA-pm3f-h6gc-rvgp) (#1068)

Beenu Arora079fdb694bea
diff --git a/.github/workflows/isolation.yml b/.github/workflows/isolation.yml
index acf3f37bf..8115baf77 100644
--- a/.github/workflows/isolation.yml
+++ b/.github/workflows/isolation.yml
@@ -33,6 +33,7 @@ on:
- "scripts/check_runtime_db_role.py"
- "scripts/check_rls_policy_shape.py"
- "scripts/check_scim_contract.py"
+ - "scripts/check_role_grant_scope.py"
- "scripts/check_whitelabel_metering.py"
- "docker-compose.yml"
- "infra/**"
@@ -56,6 +57,7 @@ on:
- "scripts/check_runtime_db_role.py"
- "scripts/check_rls_policy_shape.py"
- "scripts/check_scim_contract.py"
+ - "scripts/check_role_grant_scope.py"
- "scripts/check_whitelabel_metering.py"
- "docker-compose.yml"
- "infra/**"
@@ -235,6 +237,19 @@ jobs:
- name: The SCIM surface matches what it advertises, audits and grants
run: python scripts/check_scim_contract.py
+ # A role string from a request body is an authorization decision the
+ # client made. `POST /tenants/me/users` persisted one with no allow-list
+ # and no grant scope, and because `platform_admin` is declared `["*"]` a
+ # `tenant_admin` could mint total authority (GHSA-pm3f-h6gc-rvgp). Five
+ # sibling routes had the same defect, which is why this gate asks the
+ # question of every handler that binds an authority field rather than of
+ # the one the report named.
+ - name: Role-grant gate self-test (six injected drifts)
+ run: python scripts/check_role_grant_scope.py --self-test
+
+ - name: No route confers authority its caller does not hold
+ run: python scripts/check_role_grant_scope.py
+
# An uploaded logo renders in the console and inside PDF reports other
# people open, so the SVG allowlist is a security control under steady
# pressure to widen. And a meter added later with its tenant formatted
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a588e0e54..8bbeaef92 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,45 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+## [14.0.0] - 2026-09-29
+
+### BREAKING
+
+- **No route will confer a role, scope or organisation membership beyond the caller's own authority, and `platform_admin` and `admin` are now unreachable from every API route.** If you script any of the following, it stops working and the remedy is below.
+
+ | Route | What used to be accepted | What happens now |
+ |---|---|---|
+ | `POST /api/v1/tenants/me/users` | any `role` string, including `platform_admin` and `admin` | `403` for a role above the caller; `422` for a role outside `ROLE_PERMISSIONS` |
+ | `PATCH /api/v1/tenants/me/users/{id}` | promotion to any role; re-roling a wildcard principal | `403` on both |
+ | `POST /api/v1/api-keys` | `scopes: ["*"]` from `tenant_admin`; any scope from any `users:write` holder | `403` unless every scope is one the minter holds |
+ | `PATCH /api/v1/api-keys/{id}` | the same widening on an existing key | `403`, and the name and expiry in the same request are not written either |
+ | `POST /api/v1/rbac/roles` and `PATCH /api/v1/rbac/roles/{id}` | any permission set | `403` if it exceeds the author's own |
+ | `POST /api/v1/rbac/users/{id}/roles` | attaching any tenant role | `403` if the role carries a permission the caller lacks |
+ | `POST /api/v1/mssp/delegations` | any `granted_role` string | `403` / `422` on the same rule |
+ | `PUT /api/v1/mssp/organizations/current/members` | an `admin` appointing or demoting an `owner` | `403` on both |
+
+ **The remedy.** A `tenant_admin` can still create, promote to and mint keys for every role and scope it holds itself, `tenant_admin` included — nothing narrowed there. What it can no longer do is create something above itself. To create a wildcard principal, run `python -m app.scripts.bootstrap_admin` against the database, which is now the only path and is deliberately not reachable over HTTP. Deployments that used the tenant API to provision their own `platform_admin` should move that step into their bootstrap.
+
+### Security
+
+- **GHSA-pm3f-h6gc-rvgp (HIGH, CVSS 8.1): a `tenant_admin` could mint a `platform_admin` and become it.** `create_user` in `services/api/app/api/v1/endpoints/tenants.py` took `role` from the request body and wrote it to `users.role` — the column `CurrentUser.require_permission` reads on every guarded request — with no allow-list and no grant scope. `ROLE_PERMISSIONS` declares `platform_admin` and `admin` as `["*"]` and `has_permission` returns `True` for everything when the list holds `"*"`, so the string a client chose became a blanket authorization bypass. Reproduced end to end against the shipped code on real Postgres: `tenant_admin` logs in, `POST /tenants/me/users` with `role: "platform_admin"` returns **201** and persists the row, the new account logs in with `role=platform_admin` in its JWT, and `GET /api/v1/rbac/permissions` answers **200** for it while answering **403** for the `tenant_admin` that created it.
+
+ **Fixed by scoping the grant to the granter rather than by allow-listing the route**, because the report's own root cause — the server trusting a client-supplied role string as the authorization decision — is not specific to one handler. `services/api/app/core/role_grants.py` is the single place a grant is decided, and the property is *no principal may confer authority it does not itself hold*: the granted role's permission set must be a subset of the caller's, computed from `scopes` for an API-key principal because that is the branch `require_permission` actually takes. Escalation is then impossible by construction instead of by enumeration, which matters because **five more routes had the same defect and the report named one**. Enumerating them first was the point; the list, with verdicts, is in the pull request.
+
+ **The wildcard is refused to everybody, including a caller that already holds it.** Every route that could mint one resolves its tenant from the caller's session, so a `platform_admin` created through one is a deployment-wide administrator made through a single tenant's door. That set is *derived* from `ROLE_PERMISSIONS` rather than listed, so a third role declared `["*"]` is un-grantable the moment it is declared — a listed set is the version of this rule that goes stale. `app/services/scim/roles.py` had reached the same conclusion for directory groups first and kept its own copy of the vocabulary; it now binds to the shared one, and `check_scim_contract.py` follows that indirection rather than reporting the vocabulary unreadable.
+
+ **Two of the six siblings were worse than the reported route, in different directions.** `POST /api/v1/api-keys` guarded only `"*"` and guarded it with `current_user.role not in ("platform_admin", "tenant_admin")` — so `tenant_admin`, a role that is scoped on purpose, could mint a wildcard key and reach total authority creating no user at all; and every non-wildcard scope was unguarded, so any `users:write` holder could mint a `plugins:admin` key (plugin import runs code) while being refused `POST /api/v1/plugins/discover` themselves. Both reproduced: the wildcard key answered **200** on `/rbac/permissions`, and the `plugins:admin` key answered **200** on `/plugins/discover` against its minter's **403**. `POST /api/v1/rbac/users/{id}/roles` is gated on `users:write` while role *authorship* is gated on `roles:write`, so a caller holding only the first could attach whatever the second had built — and those rows are a live authorization path, since `has_permission_db` prefers `user_roles` over the static map for any principal holding one.
+
+ Reported by [@a25370](https://github.com/a25370).
+
+### Added
+
+- **`scripts/check_role_grant_scope.py`**, wired into `isolation.yml`, asks of every handler binding a request model that declares `role`, `org_role`, `granted_role`, `scopes`, `role_id` or `permission_ids` whether it reaches `app.core.role_grants`. Three directions, because a one-directional gate passes while drift goes the way things actually change: forward (a handler that confers authority without deciding), reverse (a waiver that no longer covers a live handler), and vocabulary (a grantable role that acquires the wildcard, a role nobody classified, or SCIM going back to its own copy). Six injected drifts prove it fails, and **run against the tree before this fix it names all nine handlers** rather than only the reported one.
+
+ The first version of it read assignments instead of request models and produced eight false reports — `scopes=list(row.scopes)` in a response projection and `org_role=str(member.org_role)` in a member listing are indistinguishable from a grant at the syntax level and are not one. What distinguishes a grant is that a client chose the value, which is exactly what a request model says. The two remaining entries in its waiver list are name collisions rather than exemptions and are recorded with the reason: a connector's third-party OAuth scopes, and the free-text job title on the public waitlist row.
+
+ Regression coverage is `services/api/tests/test_role_grant_scope.py`, which asserts both directions on every call site — the escalating request is refused **and** nothing is written, and a legitimate grant still lands. It imports nothing the fix added, deliberately: a test that imports a new symbol fails on the old tree with `ImportError`, which proves the symbol is absent and says nothing about whether the escalation was possible. **16 of its 28 tests fail against the vulnerable tree and every one of them fails with `DID NOT RAISE HTTPException`** — the grant succeeding. The other 12 are the legitimate-grant direction and pass on both trees, which is the assertion that this is a closed hole and not a lost capability.
+
### Fixed
- **Two scanner jobs in `security.yml` could report success over a scan that failed, and that was the only thing keeping one of them off branch protection.** `Semgrep (ratcheted)` and `IaC scan (checkov, ratcheted)` each ran their scan under `continue-on-error: true` with no later step reading the outcome. `continue-on-error` is *defined* as rewriting a failed step's conclusion to `success`, so the Actions API shows a clean job and no amount of run history would have found it — which is why `scripts/check_required_check_substance.py` refuses the shape statically instead, and why it named both by name when they were considered for promotion alongside the three scanner checks that were required yesterday.
diff --git a/README.md b/README.md
index 358f0c979..1a0c0c4b7 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,7 @@
**An open-source, self-hostable AI Security Operations Center.** It ingests your security telemetry, detects and correlates threats, investigates them with AI agents whose reasoning is fully auditable, and proposes responses a human approves.
[![License: MIT](https://img.shields.io/badge/License-MIT-22c55e.svg?style=flat-square)](https://opensource.org/licenses/MIT)
-[![Version](https://img.shields.io/badge/version-13.0.1-f59e0b?style=flat-square)](CHANGELOG.md)
+[![Version](https://img.shields.io/badge/version-14.0.0-f59e0b?style=flat-square)](CHANGELOG.md)
[![CI](https://img.shields.io/github/actions/workflow/status/beenuar/AiSOC/ci.yml?branch=main&label=CI&style=flat-square)](https://github.com/beenuar/AiSOC/actions/workflows/ci.yml)
[![CodeQL](https://img.shields.io/github/actions/workflow/status/beenuar/AiSOC/codeql.yml?branch=main&label=CodeQL&style=flat-square)](https://github.com/beenuar/AiSOC/actions/workflows/codeql.yml)
[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/beenuar/AiSOC/badge)](https://securityscorecards.dev/viewer/?uri=github.com/beenuar/AiSOC)
diff --git a/RELEASES.md b/RELEASES.md
index b486ec941..2e545ab32 100644
--- a/RELEASES.md
+++ b/RELEASES.md
@@ -2,13 +2,22 @@
This file mirrors what used to live in the "What's new" section of [`README.md`](README.md). The complete, machine-readable inventory (with file paths, env-var diffs, and per-release test counts) lives in [`CHANGELOG.md`](CHANGELOG.md).
-> **TL;DR for first-time visitors:** AiSOC is on `v13.0.1`, released 2026-09-29. It is a patch that exists to **publish the corrected Helm chart**, because until it the only chart anybody could pull was the wrong one. v13.0.0 bumped the chart's `appVersion` and left its own `version` at `5.9.2`, so `helm push` — which replaces silently — republished a coordinate v12.3.2 already held, pointing at a different application. The fix landed on `main` after the tag, and the chart reaches GHCR from exactly one place: three steps in `release.yml` each gated `if: github.event_name == 'push'`. A dispatch therefore packages, lints, verifies against the registry and deliberately stops, so a fix that lands after a tag has no route to the registry except a new tag — which is this one. The chart publishes as **`6.0.1`**: the 5.x → 6.x boundary is what announces the v13.0.0 behavioural break to anyone upgrading off `5.9.2`, and that boundary is crossed whichever 6.x publishes first, while the step up from the never-published `6.0.0` is a patch because the only thing that moved inside the chart is `appVersion` — no template, no default, no `values.yaml` key added, removed or renamed. `6.0.0` is not reused: it is already declared on `main` against a different `appVersion`, and unpublished is not the same as free. Everything below describes **v13.0.0**, which this patch does not change. **It was a major because it breaks behaviour, not a schema:** 75 state-changing API routes now require a permission they did not require before, and unlike the two patches earlier the same day, some of them refuse roles other than `viewer` — several surfaces move to `settings:write`, which `soc_analyst`, `soc_lead` and `threat_hunter` do not hold, so operators who are not tenant administrators will meet HTTP 403 where they previously got 200. The `### BREAKING` section of [`CHANGELOG.md`](CHANGELOG.md) lists every affected route, the permission it now takes, the roles that lose it, and what to do; `docs/openapi.yaml` is unchanged apart from one corrected description, which is exactly why the break is announced rather than left to be inferred from the spec. What it fixes is the debt the previous two patches measured but did not work down: `scripts/check_route_authz.py` reported **103 of 246 state-changing routes in `services/api` authenticating the caller and then checking nothing** — 42% of the write surface — and that figure is now **28**, every remaining route carrying a recorded reason. The worst module was MSSP, where `_require_own_child` established whose child a tenant was and nothing established whether the caller could act on it, so a `viewer` in a managing tenant could push a rule pack into a customer, grant itself a role inside one, or delete a critical detection from one. `community.py` had the moderation step gated and the thing being moderated open. Every permission used already existed and was already withheld from `viewer`, so there is no migration and no new permission to define. Upgrading is `make up`. v12.3.2 earlier the same day was the second security patch of the day: eleven more write routes were found declaring a permission that never ran. `Annotated[Any, require_permission("users:write")]` carries no `Depends()`, and FastAPI honours only `Annotated` metadata that is a `Depends` or a `FieldInfo` — everything else is silently dropped, so the check never happened and `current_user` degraded into a required query parameter. The tell was the status code: a `viewer` hitting these routes got **422, not 403**, which reads as a malformed request rather than a refusal. v12.3.1 was a security patch on top of v12.3.0, and the reason it exists separately is that a fix living on `main` is not a fix anyone has. Two reported advisories: a **critical** SQL injection in the osquery allowlist, where a denylist scanning rendered SQL for `--`, `/*` and `;` had never listed `'`, so a value could close a quoted literal and replace the WHERE clause — and reproducing it showed all six query templates were injectable, not the one reported, because the numeric parameters were never coerced either. Each parameter now declares what it is and anything else is refused rather than escaped, because an escaped path still reaches the endpoint, matches nothing, and reads to an operator as a clean host. The second is a **high** missing-authorization hole where every remediation write route authenticated and none authorized, so a `viewer` could raise the tenant to autonomy L4 and pre-approve a high blast-radius verb; the permission it needed already existed and was simply never enforced, which is the third time on this repository. The gate that should have caught it passed throughout, because it asks whether a route authenticates — so a second gate now asks whether it authorizes, and measures 103 of 246 state-changing routes making no authorization decision, as a ceiling that can only fall. Upgrading is `make up`. v12.3.0 (same day) closed six lettered sub-phases; its notes are below. None of the eight first-party npm/PyPI packages has been uploaded — the registries return 404 for all eight — and that remains credential-blocked rather than done. The latest GitHub release with notes and downloads: <https://github.com/beenuar/AiSOC/releases/latest>.
+> **TL;DR for first-time visitors:** AiSOC is on `v14.0.0`, released 2026-09-29. It closes [GHSA-pm3f-h6gc-rvgp](https://github.com/beenuar/AiSOC/security/advisories/GHSA-pm3f-h6gc-rvgp) (HIGH, CVSS 8.1): `POST /api/v1/tenants/me/users` took a `role` string from the request body and wrote it to the column every permission check reads, with no allow-list and no comparison against the caller, so a `tenant_admin` could create a `platform_admin` — a role declared `["*"]` — sign in as it and hold every permission in the product. Reproduced end to end on real Postgres before the fix. **It is a major because the fix is a refusal**: no route will now confer a role, an API-key scope or an organisation membership beyond the caller's own authority, and `platform_admin` and `admin` are unreachable from every API route including for a caller that already holds `*` — the only way to mint one is `python -m app.scripts.bootstrap_admin` against the database. The narrow repair would have been an allow-list on the reported handler; **five more routes had the same defect**, including `POST /api/v1/api-keys`, whose guard named `tenant_admin` in a tuple and let it mint a wildcard key — total authority creating no user at all — and let any `users:write` holder mint a `plugins:admin` key they were themselves refused. The `### BREAKING` section of [`CHANGELOG.md`](CHANGELOG.md) tables every affected route, what it used to accept and what it answers now. `scripts/check_role_grant_scope.py` asks the question of every handler binding an authority field and, run against the tree before the fix, names all nine. Upgrading is `make up`. The chart publishes as **`7.0.0`**. v13.0.1 earlier the same day was a patch that existed to **publish the corrected Helm chart**, because until it the only chart anybody could pull was the wrong one. v13.0.0 bumped the chart's `appVersion` and left its own `version` at `5.9.2`, so `helm push` — which replaces silently — republished a coordinate v12.3.2 already held, pointing at a different application. The fix landed on `main` after the tag, and the chart reaches GHCR from exactly one place: three steps in `release.yml` each gated `if: github.event_name == 'push'`. A dispatch therefore packages, lints, verifies against the registry and deliberately stops, so a fix that lands after a tag has no route to the registry except a new tag — which is this one. The chart publishes as **`6.0.1`**: the 5.x → 6.x boundary is what announces the v13.0.0 behavioural break to anyone upgrading off `5.9.2`, and that boundary is crossed whichever 6.x publishes first, while the step up from the never-published `6.0.0` is a patch because the only thing that moved inside the chart is `appVersion` — no template, no default, no `values.yaml` key added, removed or renamed. `6.0.0` is not reused: it is already declared on `main` against a different `appVersion`, and unpublished is not the same as free. Everything below describes **v13.0.0**, which this patch does not change. **It was a major because it breaks behaviour, not a schema:** 75 state-changing API routes now require a permission they did not require before, and unlike the two patches earlier the same day, some of them refuse roles other than `viewer` — several surfaces move to `settings:write`, which `soc_analyst`, `soc_lead` and `threat_hunter` do not hold, so operators who are not tenant administrators will meet HTTP 403 where they previously got 200. The `### BREAKING` section of [`CHANGELOG.md`](CHANGELOG.md) lists every affected route, the permission it now takes, the roles that lose it, and what to do; `docs/openapi.yaml` is unchanged apart from one corrected description, which is exactly why the break is announced rather than left to be inferred from the spec. What it fixes is the debt the previous two patches measured but did not work down: `scripts/check_route_authz.py` reported **103 of 246 state-changing routes in `services/api` authenticating the caller and then checking nothing** — 42% of the write surface — and that figure is now **28**, every remaining route carrying a recorded reason. The worst module was MSSP, where `_require_own_child` established whose child a tenant was and nothing established whether the caller could act on it, so a `viewer` in a managing tenant could push a rule pack into a customer, grant itself a role inside one, or delete a critical detection from one. `community.py` had the moderation step gated and the thing being moderated open. Every permission used already existed and was already withheld from `viewer`, so there is no migration and no new permission to define. Upgrading is `make up`. v12.3.2 earlier the same day was the second security patch of the day: eleven more write routes were found declaring a permission that never ran. `Annotated[Any, require_permission("users:write")]` carries no `Depends()`, and FastAPI honours only `Annotated` metadata that is a `Depends` or a `FieldInfo` — everything else is silently dropped, so the check never happened and `current_user` degraded into a required query parameter. The tell was the status code: a `viewer` hitting these routes got **422, not 403**, which reads as a malformed request rather than a refusal. v12.3.1 was a security patch on top of v12.3.0, and the reason it exists separately is that a fix living on `main` is not a fix anyone has. Two reported advisories: a **critical** SQL injection in the osquery allowlist, where a denylist scanning rendered SQL for `--`, `/*` and `;` had never listed `'`, so a value could close a quoted literal and replace the WHERE clause — and reproducing it showed all six query templates were injectable, not the one reported, because the numeric parameters were never coerced either. Each parameter now declares what it is and anything else is refused rather than escaped, because an escaped path still reaches the endpoint, matches nothing, and reads to an operator as a clean host. The second is a **high** missing-authorization hole where every remediation write route authenticated and none authorized, so a `viewer` could raise the tenant to autonomy L4 and pre-approve a high blast-radius verb; the permission it needed already existed and was simply never enforced, which is the third time on this repository. The gate that should have caught it passed throughout, because it asks whether a route authenticates — so a second gate now asks whether it authorizes, and measures 103 of 246 state-changing routes making no authorization decision, as a ceiling that can only fall. Upgrading is `make up`. v12.3.0 (same day) closed six lettered sub-phases; its notes are below. None of the eight first-party npm/PyPI packages has been uploaded — the registries return 404 for all eight — and that remains credential-blocked rather than done. The latest GitHub release with notes and downloads: <https://github.com/beenuar/AiSOC/releases/latest>.
---
## What's new
-`VERSION` is `13.0.1`. The **v13.0.1** patch (2026-09-29) ships no application
+`VERSION` is `14.0.0`. The **v14.0.0** release (2026-09-29) closes a HIGH
+privilege-escalation advisory by scoping every grant to the granter: no
+principal may confer a role, an API-key scope or an organisation membership
+beyond what it holds itself, and the two wildcard roles are unreachable from
+any API route. Six routes accepted authority from a request body and only one
+was reported; `scripts/check_role_grant_scope.py` names all nine handlers when
+run against the tree before the fix. The `### BREAKING` section of
+[`CHANGELOG.md`](CHANGELOG.md) tables the change per route.
+
+`VERSION` was `13.0.1`. The **v13.0.1** patch (2026-09-29) shipped no application
change at all: it is the tag push that puts the corrected Helm chart into GHCR
as **`6.0.1`**, the first 6.x a user can actually pull. v13.0.0 left the
chart's own `version` at `5.9.2` while moving `appVersion`, and `helm push`
diff --git a/ROADMAP.md b/ROADMAP.md
index fcd3df9dc..16b894e57 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
-The claim-to-gate matrix stands at **240 rows — 240 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
+The claim-to-gate matrix stands at **241 rows — 241 GATED / 0 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test**, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
## v4.0 — Shipped
diff --git a/VERSION b/VERSION
index 5cb7d8566..4b964e965 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-13.0.1
+14.0.0
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index 7913efb06..dce0e95d5 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` |
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
-The last row is the one worth reading first. It is the honest index: 240 rows
+The last row is the one worth reading first. It is the honest index: 241 rows
`GATED`, 0 `PARTIAL`, and a ratchet that refuses to let a row sit at
`NO GATE`. Re-read the figure from the table rather than from here — a count
copied into prose goes stale in silence, which is why
diff --git a/apps/docs/docs/operations/security.md b/apps/docs/docs/operations/security.md
index 33214eed2..8540b2036 100644
--- a/apps/docs/docs/operations/security.md
+++ b/apps/docs/docs/operations/security.md
@@ -93,10 +93,30 @@ Defined in [`ROLE_PERMISSIONS`](https://github.com/beenuar/AiSOC/blob/main/servi
Wildcards are supported (`*` grants everything). For everything else, the check is exact string match — no implicit hierarchies, no inherited verbs. This is deliberate: it keeps the permission list auditable.
+### Role grants are scoped to the granter
+
+The table above is the whole reason this section exists. Two of those roles hold `*`, so a single role string decides whether an account has every permission in the product — and `POST /api/v1/tenants/me/users` used to take that string from the request body and store it with no allow-list and no comparison against the caller. A `tenant_admin`, which is scoped on purpose, could create a `platform_admin`, sign in as it, and reach `roles:write` and `plugins:admin` (GHSA-pm3f-h6gc-rvgp).
+
+[`app/core/role_grants.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/core/role_grants.py) is the one place that decides a grant, and the rule is about the granter rather than the route:
+
+**No principal may confer authority it does not itself hold.**
+
+Concretely, a grant is refused when the role is not in `ROLE_PERMISSIONS` at all (`422`), when it confers a permission the caller lacks (`403`), or when it is one of the roles nobody may confer from a request (`403`). Three consequences are worth stating outright:
+
+- **`platform_admin` and `admin` are unreachable from every API route**, including for a caller that already holds `*`. Every route that could mint one resolves its tenant from the caller's own session, so a wildcard principal created through one is a deployment-wide administrator made through a single tenant's door. The only way to create one is [`app/scripts/bootstrap_admin.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/scripts/bootstrap_admin.py), which runs out of band with database credentials.
+- That set is **derived** from `ROLE_PERMISSIONS`, not listed. A role declared `["*"]` tomorrow is un-grantable the moment it is declared.
+- A `tenant_admin` can still create and promote to every other role, including `tenant_admin`. What it can no longer do is create something above itself.
+
+The same rule covers authority that is not spelled "role": API-key scopes (a key is a bearer credential, so its scopes must be a subset of its minter's — the check this replaced named `("platform_admin", "tenant_admin")` in a tuple and covered only `*`, which let a `tenant_admin` mint a wildcard key and let anyone with `users:write` mint a `plugins:admin` key they were themselves refused), the database-backed RBAC roles below, MSSP delegations, and organisation membership, where an `admin` may neither appoint an `owner` nor demote the sitting one.
+
+[`scripts/check_role_grant_scope.py`](https://github.com/beenuar/AiSOC/blob/main/scripts/check_role_grant_scope.py) fails CI if a handler binds a request model declaring `role`, `org_role`, `granted_role`, `scopes`, `role_id` or `permission_ids` without reaching that module. Run against the tree before the fix it names all nine handlers, which is why it exists instead of an allow-list on the route the report happened to name.
+
### Custom roles
Custom roles can be defined by inserting rows into the `roles` table with the desired permission list. They are scoped per-tenant; one tenant's `compliance_auditor` does not bleed into another's.
+These rows are a live authorization path rather than documentation: `CurrentUser.has_permission_db` resolves `user_roles` → `role_permissions` → `permissions` and prefers it over `ROLE_PERMISSIONS` for any principal holding a row. So authoring a role, and attaching one to a user, are both grants and both go through the check above — a caller may not build or hand out a permission set larger than its own.
+
### Permission denied vs. not found
When a user hits an endpoint they don't have permission for, AiSOC returns `403 Forbidden` with the missing permission name in the body. It does **not** return `404` to hide existence — the resource ID is already in the URL the caller chose, so hiding it offers no real protection and complicates support.
diff --git a/apps/docs/static/data/scoreboard.json b/apps/docs/static/data/scoreboard.json
index 8d193eb7a..4085dd560 100644
--- a/apps/docs/static/data/scoreboard.json
+++ b/apps/docs/static/data/scoreboard.json
@@ -4,8 +4,8 @@
"rows": [
{
"date": "2026-09-29",
- "agent_version": "v13.0.1",
- "commit_sha": "821bf0d1",
+ "agent_version": "v14.0.0",
+ "commit_sha": "ebaa19a1",
"substrate": true,
"eval_mode": "substrate-only",
"mitre_accuracy": 0.97,
diff --git a/apps/docs/static/llms-full.txt b/apps/docs/static/llms-full.txt
index cebe41667..6c99458f3 100644
--- a/apps/docs/static/llms-full.txt
+++ b/apps/docs/static/llms-full.txt
@@ -3,7 +3,7 @@
<!-- Generated by scripts/generate_llms_txt.py. Do not edit by hand; run the script and commit the result. -->
> AiSOC is an open-source, self-hostable AI Security Operations Center, MIT
-> licensed and maintained by the AiSOC community. Version 13.0.1.
+> licensed and maintained by the AiSOC community. Version 14.0.0.
> Repository: https://github.com/beenuar/AiSOC. Documentation: https://beenuar.github.io/AiSOC/.
This file exists so an automated reader can answer questions about AiSOC
diff --git a/apps/docs/static/llms.txt b/apps/docs/static/llms.txt
index e4deeebf4..dc50661d1 100644
--- a/apps/docs/static/llms.txt
+++ b/apps/docs/static/llms.txt
@@ -6,7 +6,7 @@
> security telemetry from 84 first-party connectors, normalises it to OCSF,
> correlates it into alerts, and runs LLM agents that triage and investigate them.
> Every agent decision is written to an investigation ledger, so the reasoning
-> behind a verdict can be replayed step by step. MIT licensed. Current version 13.0.1.
+> behind a verdict can be replayed step by step. MIT licensed. Current version 14.0.0.
AiSOC is built and maintained by the AiSOC community. It is a complete SOC
platform rather than a single tool: ingestion, detection, correlation, agent
diff --git a/apps/web/package.json b/apps/web/package.json
index a6052400a..5e24695ea 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -1,6 +1,6 @@
{
"name": "@aisoc/web",
- "version": "13.0.1",
+ "version": "14.0.0",
"private": true,
"description": "AiSOC SOC Console - Next.js 14 Frontend",
"license": "MIT",
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 10def806d..1abe3d16e 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -222,6 +222,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| SCIM deprovisioning ends access rather than flagging a row | `plans/aisoc_gap_closure_plan.plan.md` (13.1); `docs/decisions/0008-scim-trust-boundary.md`; `apps/docs/docs/operations/scim.md` (What deprovisioning does) | `ci.yml` api job (`test_scim_provisioning.py::TestDeprovisioning` - a deactivation is asserted to revoke the principal's API keys by **count**, and to stamp `sessions_revoked_at`; `token_is_revoked` is asserted in all four directions including the fail-closed case of a token with no `iat`; minted tokens are asserted to carry `iat`, so the check has something to read; re-activation is asserted **not** to restore revoked API keys; the whole chain is repeated end to end through `DELETE /scim/v2/Users/{id}`) | GATED | DELETE deactivates rather than erasing, which RFC 7644 permits: erasing the row would take the principal's audit attribution and case history with it. A pre-existing fall-through that left a deactivated user's API key working under a generic role is closed in the same change |
| A directory group confers only a role AiSOC enforces, and an unrecognised group confers nothing | `plans/aisoc_gap_closure_plan.plan.md` (13.1); `apps/docs/docs/operations/scim.md` (Mapping groups to roles) | `isolation.yml` (`check_scim_contract.py` compares the group-to-role mapping against `ROLE_PERMISSIONS` in **both** directions, so a role renamed there cannot leave a mapping pointing at a string that grants nothing, and a *new* role must be classified as assignable or recorded as deliberately unreachable; proven able to fail by introducing an unclassified role) + `ci.yml` api job (`test_scim_provisioning.py::TestRoleMapping` - membership is asserted to write `users.role`, which is the column the permission check reads, and removal to take it back; an unmapped group is asserted to confer nothing; no group name resolves to a wildcard role) | GATED | Precedence is a total order, so a principal in several mapped groups holds the same role regardless of the order a provider syncs in |
| The SCIM surface serves what its discovery documents advertise, and audits every write | `plans/aisoc_gap_closure_plan.plan.md` (13.1); `apps/docs/docs/operations/scim.md` (What is implemented) | `isolation.yml` (`check_scim_contract.py` reads `ServiceProviderConfig` and the route table and compares them in both directions, so a capability advertised with no route **and** a route no document advertises both fail; asserts each of the eight mutating handlers still reaches the audit helper; asserts `main.py` includes the router, since a router nobody mounts serves nothing) + `ci.yml` api job (`test_scim_mounted.py` reads `app.openapi()` from the real application and refuses an empty inventory before asserting membership, because `include_router` does not populate `app.routes` on the pinned FastAPI) | GATED | Filtering implements one `attribute eq "value"` comparison and refuses the rest: a dropped filter would return every principal in the tenant, which a provider reads as "this user already exists" |
+| No principal can confer a role, scope or organisation membership beyond its own authority, and the wildcard roles are unreachable from any request | `apps/docs/docs/operations/security.md` (Role grants are scoped to the granter); GHSA-pm3f-h6gc-rvgp | `isolation.yml` (`check_role_grant_scope.py` asks of every handler binding a request model that declares `role`, `org_role`, `granted_role`, `scopes`, `role_id` or `permission_ids` whether it reaches `app.core.role_grants`, checks each waiver still covers a live handler, and derives the refused set from `ROLE_PERMISSIONS` so a role declared with the wildcard later is un-grantable the moment it is declared; six injected drifts prove it fails, and run against the pre-fix tree it names all nine handlers) + `ci.yml` api job (`test_role_grant_scope.py` calls the shipped handlers and asserts both directions per call site — the escalating request is refused and nothing is written, a legitimate grant still lands; 16 of its 28 tests fail against the vulnerable tree, every one of them for the grant succeeding rather than for a missing symbol) | GATED | Scoped to grants a *request* makes. `scripts/bootstrap_admin.py` still mints a wildcard role out of band with database credentials, which is deliberate: it is the only path left, and it is not reachable over HTTP |
| An uploaded brand asset cannot execute, and is never fetched from a third party | `plans/aisoc_gap_closure_plan.plan.md` (13.2); `apps/docs/docs/operations/white-label.md` (SVG uploads are sanitised) | `ci.yml` api job (`test_svg_sanitizer.py`, 29 cases written as attacks rather than round trips: `<script>`, a namespace-qualified `<svg:script>` that a bare-name comparison misses, event handlers, `<foreignObject>` in well-formed XML, `<animate attributeName="href">`, `<set>`, an external `<use xlink:href>`, a remote `<image>`, `@import`, a `fill="url(https://…)"` paint server, `javascript:` in an `<a>`, a billion-laughs DTD, an XXE entity and a bare DOCTYPE. A benign logo is asserted to survive **intact**, because a sanitiser that removes everything is safe and useless) + `isolation.yml` (`check_whitelabel_metering.py` refuses any script-capable element or `on*` attribute entering the allowlist, and refuses a remote scheme in the logo reference; proven able to fail by injecting each) | GATED | Allowlist rather than denylist: a denylist of `<script>` passes while `<foreignObject>` renders arbitrary HTML. DTD and entity declarations are refused on a byte scan before parsing, which removes the expansion class rather than bounding it |
| A white-labelled organisation's console and PDF report carry its branding | `plans/aisoc_gap_closure_plan.plan.md` (13.2, Done when); `apps/docs/docs/operations/white-label.md` | `ci.yml` api job (`test_branding.py` renders the digest HTML that becomes the PDF and asserts the product name, the palette and the logo are present **and** that the platform wordmark is gone, since a report showing both is co-branded by accident; a separate case asserts the rendered report contains **no** external URL at all) + `web` job (`SidebarBranding.test.tsx` renders the real console shell against a branded API response and reads the wordmark out of the DOM, mocking the API client rather than the hook so the wiring is inside the test) | GATED | The PDF is this HTML through WeasyPrint, so asserting on the HTML asserts on the PDF without requiring the native stack in CI. Email approvals and ChatOps read the same resolved `sender_name` and are **not** covered end to end; the doc says so rather than implying they are |
| Usage metering equals the rows it summarises | `plans/aisoc_gap_closure_plan.plan.md` (13.3, Done when); `apps/docs/docs/operations/usage-metering.md` (Checking the numbers) | `ci.yml` api job (`test_usage_metering.py`, 15 cases. Every assertion counts rows **independently in the test** and compares, rather than comparing a producer against a copy of itself, which is how two console figures in this repository were wrong on real data while passing. The daily series summed is asserted equal to one query over the whole window; an alert seeded at exactly midnight is asserted counted once; another tenant's rows sit inside the window and are asserted never counted; `triages_model` + `triages_deterministic` is asserted to equal `alerts` exactly, so no triage is unaccounted for or double-counted) | GATED | Computed from source tables on request rather than kept in a counter table. A counter can only be tested against itself; a query cannot drift from the rows because it is the rows. `GET /usage/reconciliation` exposes the same comparison so an operator can run it on their own data |
@@ -251,7 +252,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- GATED: 240
+- GATED: 241
- PARTIAL: 0
- NO GATE: 0 (**every claim is backed by a failing test, and none is now a named deferral either.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The last two PARTIAL rows closed with `scripts/check_live_agent_floor.py` and a floor derived from ten runs across two environments, not by relabelling. Recount with `scripts/check_claim_gate_matrix.py` rather than trusting these three numbers: they move weekly, and a count copied into prose goes stale in silence.)
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 23f3af2fb..980c3952a 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -2498,7 +2498,12 @@ paths:
tags:
- tenants
summary: Create User
- description: Create a new user in the current tenant.
+ description: 'Create a new user in the current tenant.
+
+
+ The role must be one the caller could hold itself. `platform_admin` and
+
+ `admin` cannot be assigned through the API at all.'
operationId: create_user_api_v1_tenants_me_users_post
requestBody:
content:
@@ -2526,7 +2531,12 @@ paths:
tags:
- tenants
summary: Update User
- description: Update a user.
+ description: 'Update a user.
+
+
+ A role change is bounded the same way creation is, and a principal
+
+ already holding `platform_admin` or `admin` cannot be re-roled here.'
operationId: update_user_api_v1_tenants_me_users__user_id__patch
security:
- HTTPBearer: []
diff --git a/infra/helm/aisoc/Chart.yaml b/infra/helm/aisoc/Chart.yaml
index 18e389724..5dc0a1838 100644
--- a/infra/helm/aisoc/Chart.yaml
+++ b/infra/helm/aisoc/Chart.yaml
@@ -12,20 +12,26 @@ type: application
# knows to read the notes, whatever the templates did or did not do.
#
# 6.0.0 itself never reached the registry — it landed on `main` after the
-# v13.0.0 tag, and only a tag push publishes — so the first pullable 6.x is
-# this one. A patch, because the only thing that moved inside this directory
-# is `appVersion` naming a patch release: no template, no default and no
-# values key added, removed or renamed, so no consumer's values file changes.
+# v13.0.0 tag, and only a tag push publishes — so the first pullable 6.x was
+# 6.0.1. A patch, because the only thing that moved inside this directory was
+# `appVersion` naming a patch release: no template, no default and no values
+# key added, removed or renamed, so no consumer's values file changed.
# 6.0.0 is not reused for it. It is already declared on `main` against
# appVersion v13.0.0, and a version that names two applications is the defect
# the 5.9.2 overwrite taught; unpublished is not the same as free.
-version: 6.0.1
+#
+# 7.0.0 for v14.0.0 on the same reasoning the 5.x → 6.x boundary used. No
+# template and no values key moved here either, but the application behind
+# the chart refuses grants it used to accept (see the v14.0.0 BREAKING
+# section), and the chart's major is the only coordinate a consumer pulling
+# `oci://ghcr.io/beenuar/charts/aisoc` sees before they install it.
+version: 7.0.0
# Used as the image tag wherever a `tag:` in values.yaml is left empty, so
# it has to be a tag the registry actually holds — it read "5.2.0", which
# exists for no image, so every pod of a default install would have gone to
# ImagePullBackOff. scripts/check_published_images.py resolves it the same
# way the templates do and fails when it names nothing.
-appVersion: "v13.0.1"
+appVersion: "v14.0.0"
keywords:
- security
diff --git a/scripts/check_role_grant_scope.py b/scripts/check_role_grant_scope.py
new file mode 100644
index 000000000..75775c675
--- /dev/null
+++ b/scripts/check_role_grant_scope.py
@@ -0,0 +1,434 @@
+#!/usr/bin/env python3
+"""Every route that confers authority must decide whether the caller may.
+
+Why this gate exists
+--------------------
+``POST /api/v1/tenants/me/users`` wrote a client-supplied ``role`` string into
+``users.role`` — the column every ``require_permission`` reads — with no
+allow-list and no comparison against the caller's own authority. Because
+``platform_admin`` and ``admin`` are declared ``["*"]``, a ``tenant_admin``
+could create an account holding every permission in the product
+(GHSA-pm3f-h6gc-rvgp).
+
+Five more routes had the same defect and the report named one, which is the
+shape this repository keeps finding: the fix is applied where the finding
+points and the siblings keep shipping. So the thing enforced here is not "this
+handler validates its input" but the property that makes enumeration
+unnecessary — **no principal confers authority it does not itself hold** —
+and the check is that every role-conferring write reaches the one place that
+decides it.
+
+Three directions, because a one-directional gate passes while drift goes the
+way things actually change:
+
+*forward*
+ A handler writes a role, scope or membership field from request data and
+ never reaches ``app.core.role_grants``. This is the defect itself.
+
+*reverse*
+ An allow-list entry names a handler that no longer writes a role. A
+ waiver covering nothing is a waiver nobody will notice is load-bearing
+ when the handler comes back.
+
+*vocabulary*
+ A role is added to ``ROLE_PERMISSIONS`` and nothing classifies it, or a
+ grantable role acquires the wildcard, or ``app/services/scim/roles.py``
+ goes back to keeping its own copy of the list. The last one matters
+ because SCIM had already refused wildcard roles from a directory group
+ while the tenant API shipped without the rule; two lists that agree today
+ are two lists that disagree later.
+
+Run: python3 scripts/check_role_grant_scope.py [--self-test]
+"""
+
+from __future__ import annotations
+
+import ast
+import shutil
+import sys
+import tempfile
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from gate_toolkit import SELF_TEST_FLAG, repo_root, self_test_main # noqa: E402
+
+REPO_ROOT = repo_root()
+
+ENDPOINTS = Path("services/api/app/api/v1/endpoints")
+SECURITY = Path("services/api/app/core/security.py")
+ROLE_GRANTS = Path("services/api/app/core/role_grants.py")
+SCIM_ROLES = Path("services/api/app/services/scim/roles.py")
+
+#: Fields whose value is authority rather than data. A request model that
+#: declares one of these lets the client choose what the resulting principal
+#: may do, whatever the column is called.
+#:
+#: ``role_id`` and ``permission_ids`` are here because the database-backed
+#: RBAC tables are a second authorization path, not documentation:
+#: ``CurrentUser.has_permission_db`` prefers ``user_roles`` over the static
+#: map for any principal holding a row in it.
+ROLE_FIELDS: frozenset[str] = frozenset(
+ {
+ "role",
+ "org_role",
+ "granted_role",
+ "mapped_role",
+ "scopes",
+ "role_id",
+ "permission_ids",
+ }
+)
+
+#: Names that mean the decision was made. The module-level helpers are listed
+#: alongside the chokepoint functions because a handler calling a helper that
+#: calls the chokepoint has made the decision just as much as one calling it
+#: directly — and reading only the chokepoint's own name would push every
+#: handler into inlining it.
+CHOKEPOINT_CALLS: frozenset[str] = frozenset(
+ {
+ "authorize_role_grant",
+ "authorize_role_change",
+ "authorize_permission_grant",
+ "_authorize_scopes",
+ "_authorize_permission_grant",
+ "_require_org_grant_scope",
+ }
+)
+
+#: Handlers that accept one of those field names and deliberately do not
+#: consult the chokepoint, with the reason. ``(module, function)``.
+#:
+#: Both entries are name collisions rather than exemptions: the field means
+#: something that is not authority *in this product*. Recorded here rather
+#: than excluded by a narrower field list, so the decision is visible and the
+#: reverse check below notices when it stops applying.
+ALLOWED: dict[tuple[str, str], str] = {
+ (
+ "oauth.py",
+ "upsert_oauth_app",
+ ): "scopes are the third-party provider's OAuth scopes for a connector, not AiSOC permissions; they confer nothing here",
+ (
+ "waitlist.py",
+ "signup",
+ ): "role is the free-text job title on a public marketing signup row and is never read as authority",
+}
+
+
+def _parse(path: Path) -> ast.Module:
+ return ast.parse(path.read_text(encoding="utf-8"))
+
+
+def _module_literal(tree: ast.Module, name: str) -> object | None:
+ """A module-level name bound to a literal, or ``None``."""
+ for node in ast.walk(tree):
+ target: ast.expr | None = None
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == name:
+ target = node.value
+ elif isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == name for t in node.targets):
+ target = node.value
+ if target is None:
+ continue
+ try:
+ return ast.literal_eval(target)
+ except (ValueError, TypeError, SyntaxError):
+ return None
+ return None
+
+
+def _binding(tree: ast.Module, name: str) -> ast.expr | None:
+ """The expression a module-level name is bound to, literal or not."""
+ for node in ast.walk(tree):
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == name:
+ return node.value
+ if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == name for t in node.targets):
+ return node.value
+ return None
+
+
+def _called_names(node: ast.AST) -> set[str]:
+ names: set[str] = set()
+ for inner in ast.walk(node):
+ if isinstance(inner, ast.Call):
+ func = inner.func
+ if isinstance(func, ast.Name):
+ names.add(func.id)
+ elif isinstance(func, ast.Attribute):
+ names.add(func.attr)
+ return names
+
+
+def _request_models(tree: ast.Module) -> dict[str, set[str]]:
+ """Module-level Pydantic models, mapped to the field names they declare.
+
+ Only ``BaseModel`` subclasses. A response projection that happens to carry
+ a ``role`` field is not the subject here — what matters is a shape the
+ *client* fills in, and that is the one FastAPI binds to a request body.
+ """
+ models: dict[str, set[str]] = {}
+ for node in tree.body:
+ if not isinstance(node, ast.ClassDef):
+ continue
+ bases = {b.id for b in node.bases if isinstance(b, ast.Name)} | {b.attr for b in node.bases if isinstance(b, ast.Attribute)}
+ if "BaseModel" not in bases and not (bases & set(models)):
+ continue
+ fields = {stmt.target.id for stmt in node.body if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name)}
+ inherited: set[str] = set()
+ for base in bases:
+ inherited |= models.get(base, set())
+ models[node.name] = fields | inherited
+ return models
+
+
+def _annotation_names(annotation: ast.expr | None) -> set[str]:
+ """Every bare name inside a parameter annotation, including ``Annotated``."""
+ if annotation is None:
+ return set()
+ if isinstance(annotation, ast.Constant) and isinstance(annotation.value, str):
+ # `from __future__ import annotations` makes these strings.
+ try:
+ annotation = ast.parse(annotation.value, mode="eval").body
+ except SyntaxError:
+ return set()
+ return {node.id for node in ast.walk(annotation) if isinstance(node, ast.Name)}
+
+
+def _granted_fields(func: ast.FunctionDef | ast.AsyncFunctionDef, models: dict[str, set[str]]) -> set[str]:
+ """Authority fields this handler accepts from a request body.
+
+ Derived from the *bound model*, not from the assignments in the body.
+ Reading assignments was the first version of this gate and it produced
+ eight false reports: `scopes=list(row.scopes)` in a response projection
+ and `org_role=str(member.org_role)` in a member listing look identical to
+ a grant at the syntax level and are not one. What distinguishes a grant is
+ that a client chose the value, which is exactly what a request model says.
+ """
+ granted: set[str] = set()
+ args = func.args
+ for arg in [*args.posonlyargs, *args.args, *args.kwonlyargs]:
+ for name in _annotation_names(arg.annotation):
+ granted |= models.get(name, set()) & ROLE_FIELDS
+ return granted
+
+
+def audit(root: Path) -> tuple[list[str], dict[str, int]]:
+ """Return ``(problems, counts)``. Counts prove the gate read something."""
+ problems: list[str] = []
+ counts = {"modules": 0, "handlers": 0, "writes": 0, "roles": 0}
+
+ endpoints = root / ENDPOINTS
+ security = root / SECURITY
+ role_grants = root / ROLE_GRANTS
+ scim_roles = root / SCIM_ROLES
+
+ if not endpoints.is_dir():
+ problems.append(f"{ENDPOINTS} is absent, so no route was examined")
+ return problems, counts
+ if not role_grants.is_file():
+ # Reported and then carried on with, deliberately. Returning here
+ # would answer "the chokepoint is missing" and hide *which* routes
+ # confer authority without one, which is the list an operator needs.
+ problems.append(f"{ROLE_GRANTS} is absent: there is no chokepoint for a role grant to reach")
+
+ # --- forward: every role-conferring write reaches the chokepoint -------
+ matched_waivers: set[tuple[str, str]] = set()
+ for module in sorted(endpoints.glob("*.py")):
+ counts["modules"] += 1
+ tree = _parse(module)
+ models = _request_models(tree)
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
+ continue
+ granted = _granted_fields(node, models)
+ if not granted:
+ continue
+ counts["handlers"] += 1
+ counts["writes"] += len(granted)
+ key = (module.name, node.name)
+ if key in ALLOWED:
+ matched_waivers.add(key)
+ continue
+ if not (_called_names(node) & CHOKEPOINT_CALLS):
+ problems.append(
+ f"{module.name}::{node.name} accepts {', '.join(sorted(granted))} from the request body and never reaches "
+ "app.core.role_grants, so the caller chooses the authority it confers"
+ )
+
+ # --- reverse: no waiver covers a handler that no longer grants ---------
+ for key, reason in sorted(ALLOWED.items()):
+ if key not in matched_waivers:
+ problems.append(
+ f"ALLOWED names {key[0]}::{key[1]} ({reason}) and that handler no longer accepts an authority field; remove the entry"
+ )
+
+ # --- vocabulary --------------------------------------------------------
+ if not security.is_file():
+ problems.append(f"{SECURITY} is absent, so the enforced role map could not be read")
+ return problems, counts
+
+ enforced = _module_literal(_parse(security), "ROLE_PERMISSIONS")
+ if isinstance(enforced, dict):
+ counts["roles"] = len(enforced)
+ if not role_grants.is_file():
+ return problems, counts
+
+ grants_tree = _parse(role_grants)
+ grantable = _module_literal(grants_tree, "GRANTABLE_ROLES")
+ explicit = _module_literal(grants_tree, "_NEVER_GRANTABLE_EXPLICIT")
+
+ if not isinstance(enforced, dict) or not isinstance(grantable, list | tuple) or not isinstance(explicit, dict):
+ problems.append("the role vocabulary is no longer a set of literals this gate can read")
+ return problems, counts
+
+ # counted above, before the early return
+ wildcard = {role for role, perms in enforced.items() if "*" in (perms or [])}
+ refused = wildcard | set(explicit)
+
+ for role in sorted(set(grantable) & wildcard):
+ problems.append(f"{role!r} is grantable and holds the wildcard: one unchecked string would confer every permission")
+ for role in sorted(set(grantable) - set(enforced)):
+ problems.append(f"GRANTABLE_ROLES names {role!r}, which ROLE_PERMISSIONS does not define; it grants nothing")
+ for role in sorted(set(enforced) - set(grantable) - refused):
+ problems.append(
+ f"ROLE_PERMISSIONS defines {role!r} and app/core/role_grants.py neither makes it grantable nor records why it is refused"
+ )
+
+ # --- vocabulary: SCIM shares it rather than copying it -----------------
+ if not scim_roles.is_file():
+ problems.append(f"{SCIM_ROLES} is absent")
+ return problems, counts
+
+ scim_tree = _parse(scim_roles)
+ precedence = _binding(scim_tree, "ROLE_PRECEDENCE")
+ unreachable = _binding(scim_tree, "UNREACHABLE_BY_GROUP")
+ if not (isinstance(precedence, ast.Name) and precedence.id == "GRANTABLE_ROLES"):
+ problems.append(
+ "app/services/scim/roles.py::ROLE_PRECEDENCE no longer *is* GRANTABLE_ROLES. SCIM refused wildcard roles "
+ "before the tenant API did and kept its own copy; a second list is how they diverge again"
+ )
+ if not (isinstance(unreachable, ast.Call) and getattr(unreachable.func, "id", "") == "never_grantable"):
+ problems.append(
+ "app/services/scim/roles.py::UNREACHABLE_BY_GROUP no longer calls never_grantable(), so a role declared "
+ "with the wildcard later would stay conferrable by a directory group name"
+ )
+
+ return problems, counts
+
+
+def _self_test_cases() -> list[tuple[str, bool]]:
+ """Prove the gate detects each drift it exists to catch.
+
+ Mutations are applied to a copy of the real tree rather than to a fixture,
+ because a gate proven against a fixture is proven against the fixture.
+ """
+ cases: list[tuple[str, bool]] = []
+ clean, counts = audit(REPO_ROOT)
+ cases.append(("the real tree passes", not clean))
+ cases.append(("the real tree has role-conferring writes to judge", counts["writes"] > 0))
+
+ read = (ENDPOINTS, SECURITY, ROLE_GRANTS, SCIM_ROLES)
+ mutations: list[tuple[str, Path, str, str]] = [
+ (
+ "a handler that stops consulting the chokepoint is reported",
+ Path("services/api/app/api/v1/endpoints/tenants.py"),
+ " granted_role = authorize_role_grant(",
+ " granted_role = request.role or _unchecked(",
+ ),
+ (
+ "an API-key handler that stops authorizing its scopes is reported",
+ Path("services/api/app/api/v1/endpoints/api_keys.py"),
+ " _authorize_scopes(body.scopes, current_user)\n\n raw_key",
+ "\n raw_key",
+ ),
+ (
+ "a grantable role that acquires the wildcard is reported",
+ SECURITY,
+ ' "tenant_admin": [\n "alerts:read",',
+ ' "tenant_admin": [\n "*",\n "alerts:read",',
+ ),
+ (
+ "a new role nobody classified is reported",
+ SECURITY,
+ 'ROLE_PERMISSIONS: dict[str, list[str]] = {\n "platform_admin": ["*"],',
+ 'ROLE_PERMISSIONS: dict[str, list[str]] = {\n "break_glass": ["alerts:read"],\n "platform_admin": ["*"],',
+ ),
+ (
+ "SCIM keeping its own copy of the vocabulary is reported",
+ SCIM_ROLES,
+ "ROLE_PRECEDENCE: Final[tuple[str, ...]] = GRANTABLE_ROLES",
+ 'ROLE_PRECEDENCE: Final[tuple[str, ...]] = ("viewer", "soc_analyst", "tenant_admin")',
+ ),
+ (
+ "a waiver that no longer covers anything is reported",
+ Path(__file__).relative_to(REPO_ROOT),
+ ' (\n "scim.py",\n "_apply_group_rename",\n ):',
+ ' (\n "scim.py",\n "gone_away",\n ):',
+ ),
+ ]
+
+ for description, target, old, new in mutations:
+ with tempfile.TemporaryDirectory() as tmp:
+ tree = Path(tmp) / "tree"
+ for rel in read:
+ source = REPO_ROOT / rel
+ destination = tree / rel
+ if source.is_dir():
+ shutil.copytree(source, destination)
+ else:
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(source, destination)
+ if target == Path(__file__).relative_to(REPO_ROOT):
+ # The waiver list lives in this file, so that case is proven by
+ # rewriting the constant in memory rather than on disk.
+ original = dict(ALLOWED)
+ ALLOWED.clear()
+ ALLOWED[("scim.py", "gone_away")] = "deliberately stale"
+ problems, _ = audit(tree)
+ ALLOWED.clear()
+ ALLOWED.update(original)
+ cases.append((description, bool(problems)))
+ continue
+ patched = tree / target
+ source_text = patched.read_text(encoding="utf-8")
+ if old not in source_text:
+ cases.append((f"{description} (self-test anchor missing; case did not run)", False))
+ continue
+ patched.write_text(source_text.replace(old, new, 1), encoding="utf-8")
+ problems, _ = audit(tree)
+ cases.append((description, bool(problems)))
+
+ return cases
+
+
+def main() -> int:
+ if SELF_TEST_FLAG in sys.argv[1:]:
+ return self_test_main(Path(__file__).name, extra=_self_test_cases())
+
+ problems, counts = audit(REPO_ROOT)
+
+ print(
+ f"check_role_grant_scope: read {counts['modules']} endpoint module(s), {counts['handlers']} handler(s) "
+ f"conferring authority across {counts['writes']} write(s), and {counts['roles']} enforced role(s)"
+ )
+
+ # "found nothing" and "scanned nothing" must not print the same word.
+ if counts["modules"] == 0 or counts["roles"] == 0 or counts["writes"] == 0:
+ print(
+ "\nFAIL: the endpoint surface or the role map read as empty. A clean result over nothing is "
+ "indistinguishable from a wrong root or a glob that stopped matching.",
+ file=sys.stderr,
+ )
+ return 2
+
+ if problems:
+ print(f"\nFAIL: {len(problems)} role-grant problem(s).", file=sys.stderr)
+ for problem in problems:
+ print(f" - {problem}", file=sys.stderr)
+ return 1
+
+ print("OK: every role-conferring route reaches app.core.role_grants, and the grantable vocabulary excludes the wildcard.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/check_scim_contract.py b/scripts/check_scim_contract.py
index d7552d1a5..fa35828d1 100644
--- a/scripts/check_scim_contract.py
+++ b/scripts/check_scim_contract.py
@@ -57,6 +57,13 @@ ROUTER = REPO_ROOT / "services/api/app/api/v1/endpoints/scim.py"
RESOURCES = REPO_ROOT / "services/api/app/services/scim/resources.py"
ROLES = REPO_ROOT / "services/api/app/services/scim/roles.py"
SECURITY = REPO_ROOT / "services/api/app/core/security.py"
+#: The grant vocabulary moved here when the tenant user API was found
+#: conferring wildcard roles from a request body (GHSA-pm3f-h6gc-rvgp), and
+#: ``roles.py`` now binds its two constants to this module rather than
+#: restating them. This gate follows that indirection instead of reporting
+#: the vocabulary unreadable, which is what it did the moment the two lists
+#: became one.
+ROLE_GRANTS = REPO_ROOT / "services/api/app/core/role_grants.py"
MAIN = REPO_ROOT / "services/api/app/main.py"
#: Operations RFC 7644 defines that this deployment intends to serve, mapped
@@ -244,6 +251,54 @@ def _assigned_names(tree: ast.Module, variable: str) -> set[str] | None:
return None
+def _shared_vocabulary(roles_tree: ast.Module, grants_tree: ast.Module, security_tree: ast.Module, variable: str) -> set[str] | None:
+ """Resolve a name ``roles.py`` binds to the shared grant vocabulary.
+
+ Handles exactly the two forms that module uses — a bare reference to
+ ``GRANTABLE_ROLES`` and a call to ``never_grantable()`` — rather than
+ anything general. A third form should fail this gate loudly, because it
+ would mean the vocabulary moved again without anyone saying where to.
+ """
+ for node in ast.walk(roles_tree):
+ value: ast.expr | None = None
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == variable:
+ value = node.value
+ elif isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == variable for t in node.targets):
+ value = node.value
+ if value is None:
+ continue
+ if isinstance(value, ast.Name):
+ resolved = _assigned_names(grants_tree, value.id)
+ return resolved
+ if isinstance(value, ast.Call) and getattr(value.func, "id", "") == "never_grantable":
+ explicit = _assigned_names(grants_tree, "_NEVER_GRANTABLE_EXPLICIT")
+ enforced_map = _dict_value(security_tree, "ROLE_PERMISSIONS")
+ if explicit is None or enforced_map is None:
+ return None
+ wildcard = {role for role, perms in enforced_map.items() if "*" in (perms or [])}
+ return wildcard | explicit
+ return _assigned_names(roles_tree, variable)
+ return None
+
+
+def _dict_value(tree: ast.Module, variable: str) -> dict | None:
+ """A module-level dict literal, values included."""
+ for node in ast.walk(tree):
+ value: ast.expr | None = None
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == variable:
+ value = node.value
+ elif isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == variable for t in node.targets):
+ value = node.value
+ if value is None:
+ continue
+ try:
+ resolved = ast.literal_eval(value)
+ except (ValueError, TypeError, SyntaxError):
+ return None
+ return resolved if isinstance(resolved, dict) else None
+ return None
+
+
def _group_rule_roles(tree: ast.Module) -> set[str]:
"""Roles the group-name rules can produce."""
for node in ast.walk(tree):
@@ -330,8 +385,10 @@ def audit(root: Path) -> tuple[list[str], dict[str, int]]:
# --- the role vocabulary agrees, in both directions -------------------
enforced = _assigned_names(security_tree, "ROLE_PERMISSIONS")
- precedence = _assigned_names(roles_tree, "ROLE_PRECEDENCE")
- unreachable = _assigned_names(roles_tree, "UNREACHABLE_BY_GROUP")
+ grants_path = root / ROLE_GRANTS.relative_to(REPO_ROOT)
+ grants_tree = _parse(grants_path) if grants_path.is_file() else ast.parse("")
+ precedence = _shared_vocabulary(roles_tree, grants_tree, security_tree, "ROLE_PRECEDENCE")
+ unreachable = _shared_vocabulary(roles_tree, grants_tree, security_tree, "UNREACHABLE_BY_GROUP")
rule_roles = _group_rule_roles(roles_tree)
if enforced is None or precedence is None or unreachable is None:
@@ -385,10 +442,15 @@ def _self_test_cases() -> list[tuple[str, bool]]:
'await _unrecorded(\n db,\n principal,\n request,\n action="scim:user:create",',
),
(
+ # Deliberately *not* a wildcard role. Since the vocabulary moved to
+ # `app/core/role_grants.py` a role declared `["*"]` is classified
+ # as unreachable the moment it is declared, so probing with one
+ # would assert the old behaviour and pass for the wrong reason.
+ # The role that still needs a human decision is an ordinary one.
"a role the mapping does not classify is reported",
SECURITY,
'ROLE_PERMISSIONS: dict[str, list[str]] = {\n "platform_admin": ["*"],',
- 'ROLE_PERMISSIONS: dict[str, list[str]] = {\n "brand_new_role": ["*"],\n "platform_admin": ["*"],',
+ 'ROLE_PERMISSIONS: dict[str, list[str]] = {\n "brand_new_role": ["alerts:read"],\n "platform_admin": ["*"],',
),
(
"a capability advertised with no route is reported",
@@ -402,7 +464,7 @@ def _self_test_cases() -> list[tuple[str, bool]]:
with tempfile.TemporaryDirectory() as tmp:
tree = Path(tmp) / "tree"
# Copy only what the gate reads, so the self-test stays fast.
- for source in {ROUTER, RESOURCES, ROLES, SECURITY, MAIN}:
+ for source in {ROUTER, RESOURCES, ROLES, SECURITY, ROLE_GRANTS, MAIN}:
destination = tree / source.relative_to(REPO_ROOT)
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
diff --git a/services/api/app/api/v1/endpoints/api_keys.py b/services/api/app/api/v1/endpoints/api_keys.py
index a81d33911..3bdedcb4b 100644
--- a/services/api/app/api/v1/endpoints/api_keys.py
+++ b/services/api/app/api/v1/endpoints/api_keys.py
@@ -33,6 +33,7 @@ from pydantic import BaseModel, Field
from sqlalchemy import select
from app.api.v1.deps import AuthUser, DBSession, require_permission
+from app.core.role_grants import RoleGrantDenied, authorize_permission_grant
from app.core.security import generate_api_key
from app.models.tenant import ApiKey
@@ -78,6 +79,30 @@ def _validate_scopes(scopes: list[str]) -> None:
)
+def _authorize_scopes(scopes: list[str], current_user: AuthUser) -> None:
+ """Refuse scopes the minter does not hold.
+
+ A key is a bearer credential, so its scopes are authority conferred on
+ whoever holds it. The check this replaced named two roles in a tuple —
+ ``("platform_admin", "tenant_admin")`` — and covered only ``"*"``, which
+ got both halves wrong. ``tenant_admin`` is a scoped role by design and
+ could mint a wildcard key, which is the same total escalation as
+ GHSA-pm3f-h6gc-rvgp by a door that creates no user at all; and every
+ non-wildcard scope was unguarded, so the same caller could mint a
+ ``plugins:admin`` key — plugin import runs code — while being refused
+ ``POST /api/v1/plugins/discover`` itself.
+ """
+ try:
+ authorize_permission_grant(
+ granter_role=current_user.role,
+ granter_scopes=current_user.scopes,
+ requested=scopes,
+ subject="API key scope(s)",
+ )
+ except RoleGrantDenied as exc:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=exc.reason) from exc
+
+
# ── Request / response schemas ────────────────────────────────────────────────
@@ -147,13 +172,7 @@ async def create_api_key(
The raw key value is returned **only once** in this response.
"""
_validate_scopes(body.scopes)
-
- # Only admins can issue wildcard keys
- if "*" in body.scopes and current_user.role not in ("platform_admin", "tenant_admin"):
- raise HTTPException(
- status_code=status.HTTP_403_FORBIDDEN,
- detail="Only admins can create wildcard (*) API keys",
- )
+ _authorize_scopes(body.scopes, current_user)
raw_key, prefix, hashed_key = generate_api_key()
@@ -220,6 +239,13 @@ async def update_api_key(
current_user: Annotated[AuthUser, Depends(require_permission("users:write"))],
) -> ApiKeyOut:
"""Update an API key's name, scopes, or expiry."""
+ # Authorized before the row is loaded, so a refused scope change leaves
+ # the name and expiry in the same request unwritten as well. `get_db`
+ # would roll back anyway; not depending on that is the point.
+ if body.scopes is not None:
+ _validate_scopes(body.scopes)
+ _authorize_scopes(body.scopes, current_user)
+
result = await db.execute(select(ApiKey).where(ApiKey.id == key_id, ApiKey.tenant_id == current_user.tenant_id))
ak = result.scalar_one_or_none()
if ak is None:
@@ -229,12 +255,6 @@ async def update_api_key(
ak.name = body.name
if body.scopes is not None:
- _validate_scopes(body.scopes)
- if "*" in body.scopes and current_user.role not in ("platform_admin", "tenant_admin"):
- raise HTTPException(
- status_code=status.HTTP_403_FORBIDDEN,
- detail="Only admins can grant wildcard (*) scope",
- )
ak.scopes = body.scopes
if body.expires_in_days is not None:
diff --git a/services/api/app/api/v1/endpoints/mssp.py b/services/api/app/api/v1/endpoints/mssp.py
index 32fec9f3d..fbb2acc1c 100644
--- a/services/api/app/api/v1/endpoints/mssp.py
+++ b/services/api/app/api/v1/endpoints/mssp.py
@@ -67,6 +67,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.deps import CurrentUser, require_permission
from app.api.v1.endpoints.auth import get_current_user
+from app.core.role_grants import RoleGrantDenied, authorize_role_grant
from app.db.database import get_db
from app.models.mssp import MSSPDelegation, MSSPTenantMetrics, MSSPTenantNote
from app.models.organization import (
@@ -284,11 +285,27 @@ async def create_delegation(
db: Annotated[AsyncSession, Depends(get_db)],
current_user: Annotated[CurrentUser, Depends(require_permission("users:write"))],
) -> MSSPDelegation:
+ # Ownership first, so a caller probing for tenants they do not manage
+ # still gets the same 404 whatever role string they send.
await _require_own_child(db, current_user, body.child_tenant_id)
+ # `granted_role` was an unvalidated string. Nothing resolves it into a
+ # session yet, so this was not exploitable — but it is a role name stored
+ # against a customer tenant, and the whole point of the column is that a
+ # future reader turns it into authority. Refusing an ungrantable value now
+ # means that reader cannot be the thing that makes it exploitable.
+ try:
+ granted_role = authorize_role_grant(
+ granter_role=current_user.role,
+ granter_scopes=current_user.scopes,
+ requested_role=body.granted_role,
+ )
+ except RoleGrantDenied as exc:
+ code = status.HTTP_422_UNPROCESSABLE_ENTITY if exc.unknown else status.HTTP_403_FORBIDDEN
+ raise HTTPException(status_code=code, detail=exc.reason) from exc
delegation = MSSPDelegation(
parent_tenant_id=current_user.tenant_id,
child_tenant_id=body.child_tenant_id,
- granted_role=body.granted_role,
+ granted_role=granted_role,
granted_by_user=current_user.user_id,
expires_at=body.expires_at,
)
@@ -817,6 +834,35 @@ async def _admin_scope(scope: PortfolioScope = Depends(_scope)) -> PortfolioScop
return scope
+def _require_org_grant_scope(granter: str | None, requested: str, *, current: str | None) -> None:
+ """Refuse an organisation role above the granter's own.
+
+ ``ORG_ROLES`` is ordered by authority, unlike the tenant roles, so this is
+ an index comparison rather than a permission-set comparison — but it is
+ the same property `app.core.role_grants` enforces there: nobody confers
+ what they do not hold. ``current`` covers the other half, since demoting
+ the sitting ``owner`` is how an ``admin`` would clear the way.
+
+ ``granter`` is ``str | None`` because ``PortfolioScope.org_role`` is.
+ ``_admin_scope`` has already refused a non-administering caller by the
+ time this runs, so ``None`` should be unreachable — an unrecognised or
+ absent role lands on a ceiling of -1 and confers nothing, which is the
+ direction to fail in if that ever stops being true.
+ """
+ rank = {role: index for index, role in enumerate(reversed(ORG_ROLES))}
+ ceiling = rank.get(granter or "", -1)
+ if rank.get(requested, len(ORG_ROLES)) > ceiling:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=f"Cannot grant organisation role '{requested}': it is above your own '{granter}'",
+ )
+ if current is not None and rank.get(current, len(ORG_ROLES)) > ceiling:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=f"Cannot change a member holding '{current}': it is above your own '{granter}'",
+ )
+
+
class LimitHeadroomOut(BaseModel):
key: str
label: str
@@ -1274,6 +1320,14 @@ async def upsert_member(
)
).scalar_one_or_none()
+ # `ORG_ROLES` is a vocabulary, not a grant scope. `_admin_scope` admits
+ # `owner` and `admin` alike, so without this an `admin` could appoint an
+ # `owner` — or demote the sitting one — which is the same shape as the
+ # tenant-role escalation in a second vocabulary. Checked after the member
+ # row is loaded because demotion needs the *current* role, and before any
+ # write.
+ _require_org_grant_scope(scope.org_role, body.org_role, current=None if member is None else str(member.org_role))
+
if member is None:
member = OrganizationMember(org_id=scope.org_id, user_id=body.user_id, org_role=body.org_role)
db.add(member)
diff --git a/services/api/app/api/v1/endpoints/rbac.py b/services/api/app/api/v1/endpoints/rbac.py
index c79e4b64d..be0c23609 100644
--- a/services/api/app/api/v1/endpoints/rbac.py
+++ b/services/api/app/api/v1/endpoints/rbac.py
@@ -18,6 +18,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.api.v1.deps import AuthUser, require_permission
+from app.core.role_grants import RoleGrantDenied, authorize_permission_grant
from app.db.rls import TenantDBSession
from app.models.rbac import Permission, Role, RolePermission, UserRole
from app.models.tenant import User
@@ -25,6 +26,27 @@ from app.models.tenant import User
router = APIRouter(prefix="/rbac", tags=["rbac"])
+def _authorize_permission_grant(permissions: list[Permission], current_user: AuthUser, *, subject: str) -> None:
+ """Refuse a database-backed role that confers more than its author holds.
+
+ These rows are a second authorization path, not documentation:
+ ``CurrentUser.has_permission_db`` resolves ``user_roles`` →
+ ``role_permissions`` → ``permissions`` and prefers it over the static
+ ``ROLE_PERMISSIONS`` map whenever the principal has any row at all. So a
+ role assembled here and attached below is exactly as load-bearing as
+ ``users.role``, and the same property has to hold for it.
+ """
+ try:
+ authorize_permission_grant(
+ granter_role=current_user.role,
+ granter_scopes=current_user.scopes,
+ requested=[p.name for p in permissions],
+ subject=subject,
+ )
+ except RoleGrantDenied as exc:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=exc.reason) from exc
+
+
# ──────────────────────────────────────────────
# Pydantic schemas
# ──────────────────────────────────────────────
@@ -140,6 +162,11 @@ async def create_role(
if existing.scalar_one_or_none() is not None:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Role '{body.name}' already exists")
+ # Resolved and authorized before the role row exists, so a refused
+ # permission set does not leave an empty role behind.
+ perms_to_attach = await _resolve_permissions(db, body.permission_ids)
+ _authorize_permission_grant(perms_to_attach, current_user, subject="permission(s)")
+
role = Role(
tenant_id=current_user.tenant_id,
name=body.name,
@@ -150,7 +177,6 @@ async def create_role(
await db.flush() # get role.id
# Attach permissions
- perms_to_attach = await _resolve_permissions(db, body.permission_ids)
for perm in perms_to_attach:
db.add(RolePermission(role_id=role.id, permission_id=perm.id))
@@ -197,6 +223,13 @@ async def update_role(
if role.is_system:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="System roles cannot be modified")
+ # Resolved and authorized before the DELETE below, which would otherwise
+ # strip the role's existing permissions on the way to a refusal.
+ perms: list[Permission] = []
+ if body.permission_ids is not None:
+ perms = await _resolve_permissions(db, body.permission_ids)
+ _authorize_permission_grant(perms, current_user, subject="permission(s)")
+
if body.name is not None:
role.name = body.name
if body.description is not None:
@@ -205,7 +238,6 @@ async def update_role(
if body.permission_ids is not None:
# Replace permissions
await db.execute(delete(RolePermission).where(RolePermission.role_id == role.id))
- perms = await _resolve_permissions(db, body.permission_ids)
for perm in perms:
db.add(RolePermission(role_id=role.id, permission_id=perm.id))
@@ -272,6 +304,16 @@ async def assign_role(
role = await _get_role_or_404(db, body.role_id, current_user.tenant_id)
+ # `users:write` is the gate on this route and `roles:write` is the gate on
+ # role *authorship*, so without this a caller holding only the former
+ # could attach whatever the latter had already built — including
+ # `roles:write` itself, from which the rest follows.
+ _authorize_permission_grant(
+ await _load_role_models(db, role.id),
+ current_user,
+ subject=f"permission(s) carried by role {role.name!r}",
+ )
+
# Ensure the target user belongs to this tenant
user_res = await db.execute(select(User).where(User.id == user_id, User.tenant_id == current_user.tenant_id))
if user_res.scalar_one_or_none() is None:
@@ -323,11 +365,15 @@ async def _resolve_permissions(db: AsyncSession, permission_ids: list[uuid.UUID]
return list(found)
-async def _load_role_permissions(db: AsyncSession, role_id: uuid.UUID) -> list[PermissionOut]:
+async def _load_role_models(db: AsyncSession, role_id: uuid.UUID) -> list[Permission]:
result = await db.execute(
select(Permission)
.join(RolePermission, RolePermission.permission_id == Permission.id)
.where(RolePermission.role_id == role_id)
.order_by(Permission.category, Permission.name)
)
- return [PermissionOut.model_validate(p) for p in result.scalars().all()]
+ return list(result.scalars().all())
+
+
+async def _load_role_permissions(db: AsyncSession, role_id: uuid.UUID) -> list[PermissionOut]:
+ return [PermissionOut.model_validate(p) for p in await _load_role_models(db, role_id)]
diff --git a/services/api/app/api/v1/endpoints/tenants.py b/services/api/app/api/v1/endpoints/tenants.py
index d7159fb13..87eff034e 100644
--- a/services/api/app/api/v1/endpoints/tenants.py
+++ b/services/api/app/api/v1/endpoints/tenants.py
@@ -9,6 +9,7 @@ from pydantic import BaseModel, EmailStr
from sqlalchemy import select, update
from app.api.v1.deps import AuthUser, DBSession, require_permission
+from app.core.role_grants import RoleGrantDenied, authorize_role_change, authorize_role_grant
from app.core.security import get_password_hash
from app.models.tenant import Tenant, User
from app.services.tenant_deletion import delete_tenant
@@ -16,6 +17,16 @@ from app.services.tenant_deletion import delete_tenant
router = APIRouter(prefix="/tenants", tags=["tenants"])
+def _refuse(exc: RoleGrantDenied) -> HTTPException:
+ """Map a refused grant onto a status code.
+
+ 422 when the role is not in the vocabulary at all (the request is
+ malformed), 403 when it exists and this caller may not confer it.
+ """
+ code = status.HTTP_422_UNPROCESSABLE_ENTITY if exc.unknown else status.HTTP_403_FORBIDDEN
+ return HTTPException(status_code=code, detail=exc.reason)
+
+
class TenantHeaderResponse(BaseModel):
"""Minimal tenant identity payload — safe for *any* authenticated user.
@@ -64,6 +75,10 @@ class CreateUserRequest(BaseModel):
email: EmailStr
username: str
password: str
+ #: Refused unless the caller already holds everything it confers, and
+ #: refused outright for the wildcard roles. See ``app.core.role_grants``.
+ #: Not a Literal: the enforced vocabulary lives in ``ROLE_PERMISSIONS``,
+ #: and a second copy in the schema would be a second thing to keep true.
role: str = "soc_analyst"
@@ -195,7 +210,22 @@ async def create_user(
current_user: Annotated[AuthUser, Depends(require_permission("users:write"))],
db: DBSession,
) -> UserResponse:
- """Create a new user in the current tenant."""
+ """Create a new user in the current tenant.
+
+ The role must be one the caller could hold itself. `platform_admin` and
+ `admin` cannot be assigned through the API at all.
+ """
+ # Authorized before anything is read or written, so a refused request
+ # touches no row and reveals nothing about which addresses exist.
+ try:
+ granted_role = authorize_role_grant(
+ granter_role=current_user.role,
+ granter_scopes=current_user.scopes,
+ requested_role=request.role,
+ )
+ except RoleGrantDenied as exc:
+ raise _refuse(exc) from exc
+
# Check email uniqueness
existing = await db.execute(select(User).where(User.email == request.email))
if existing.scalar_one_or_none() is not None:
@@ -209,7 +239,7 @@ async def create_user(
email=request.email,
username=request.username,
hashed_password=get_password_hash(request.password),
- role=request.role,
+ role=granted_role,
)
db.add(user)
await db.commit()
@@ -224,7 +254,15 @@ async def update_user(
current_user: Annotated[AuthUser, Depends(require_permission("users:write"))],
db: DBSession,
) -> UserResponse:
- """Update a user."""
+ """Update a user.
+
+ A role change is bounded the same way creation is, and a principal
+ already holding `platform_admin` or `admin` cannot be re-roled here.
+ """
+ # Promotion is the same grant as creation and goes through the same check.
+ # An allow-list on `create_user` alone would have left `role: "admin"`
+ # here as a one-request escalation. Rationale kept out of the docstring
+ # because FastAPI publishes that verbatim in docs/openapi.yaml.
result = await db.execute(select(User).where(User.id == user_id, User.tenant_id == current_user.tenant_id))
user = result.scalar_one_or_none()
if user is None:
@@ -236,6 +274,19 @@ async def update_user(
if val is not None:
updates[field] = val
+ if "role" in updates:
+ try:
+ updates["role"] = authorize_role_change(
+ granter_role=current_user.role,
+ granter_scopes=current_user.scopes,
+ current_role=str(user.role),
+ requested_role=updates["role"],
+ )
+ except RoleGrantDenied as exc:
+ # Raised before the UPDATE, so a refused promotion leaves the
+ # username and is_active fields in the same request unwritten too.
+ raise _refuse(exc) from exc
+
if updates:
updates["updated_at"] = datetime.now(UTC)
await db.execute(update(User).where(User.id == user_id).values(**updates))
diff --git a/services/api/app/core/role_grants.py b/services/api/app/core/role_grants.py
new file mode 100644
index 000000000..36f747d00
--- /dev/null
+++ b/services/api/app/core/role_grants.py
@@ -0,0 +1,274 @@
+"""The one place that decides whether a principal may confer authority.
+
+Why this module exists
+----------------------
+``POST /api/v1/tenants/me/users`` took a ``role`` string from the request body
+and wrote it to ``users.role`` — the column ``CurrentUser.require_permission``
+reads on every guarded request. ``ROLE_PERMISSIONS`` gives ``platform_admin``
+and ``admin`` the list ``["*"]``, and ``has_permission`` returns ``True`` for
+every permission when that list contains ``"*"``. So a ``tenant_admin``, whose
+whole point is that it is *scoped*, could create an account holding every
+permission in the product and sign in as it (GHSA-pm3f-h6gc-rvgp).
+
+The narrow repair is an allow-list on that one handler. It is the wrong
+repair, because the defect is not "this handler forgot to validate": it is
+that the server treated a client-supplied authority string as the
+authorization decision itself. Four other routes did the same thing, and an
+allow-list per route means the fifth one written next year is a new advisory.
+
+So the property enforced here is about the *granter*, not the call site:
+
+ no principal may confer authority it does not itself hold.
+
+Escalation is then impossible by construction rather than by enumeration, and
+a new route that writes a role gets the property by calling one function.
+
+Where the wildcard fits
+-----------------------
+A subset check alone would still let a wildcard principal confer a wildcard
+role, which is ordinarily unremarkable — administrators appoint
+administrators. It is not unremarkable *here*, because every route that could
+do it resolves its tenant from the caller's session, so a ``platform_admin``
+minted through one is a principal with ``"*"`` over every tenant created
+through a single tenant's door. :func:`never_grantable` therefore refuses the
+wildcard roles to everyone, including a caller that already holds ``"*"``.
+Minting one stays an out-of-band act with database credentials
+(``app/scripts/bootstrap_admin.py``).
+
+That set is *derived* from ``ROLE_PERMISSIONS`` rather than written down. A
+third wildcard role added later is un-grantable the moment it is declared,
+which is the only version of this rule that survives someone else editing the
+map.
+
+Relationship to the SCIM vocabulary
+-----------------------------------
+``app/services/scim/roles.py`` had already reached the same conclusion for
+directory groups and kept its own copy of the list. Two lists that agree today
+are two lists that disagree later, so it now imports :data:`GRANTABLE_ROLES`
+and :data:`NEVER_GRANTABLE` from here and the vocabularies are the same object.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Sequence
+from typing import Final
+
+from app.core.security import ROLE_PERMISSIONS
+
+#: The permission string that means "every permission".
+WILDCARD: Final[str] = "*"
+
+#: Roles a request may confer, least authority first.
+#:
+#: The order is declared rather than derived because permission sets are only
+#: *partially* ordered: ``threat_hunter`` holds ``rules:write`` and
+#: ``soc_analyst`` does not, while ``soc_analyst`` holds ``playbooks:execute``
+#: and ``threat_hunter`` does not. Neither contains the other, so no sort of
+#: the map produces this list. Callers that need authority comparison should
+#: use :func:`permissions_for` and compare sets; this order exists for the
+#: places that must pick a single winner, such as SCIM group precedence.
+GRANTABLE_ROLES: Final[tuple[str, ...]] = (
+ "viewer",
+ "soc_analyst",
+ "threat_hunter",
+ "soc_lead",
+ "tenant_admin",
+)
+
+#: Roles no request may confer, whatever the caller holds, with the reason.
+#:
+#: Only the non-wildcard entries are listed. The wildcard ones are computed in
+#: :func:`never_grantable` so that a role declared with ``["*"]`` tomorrow is
+#: covered without anyone remembering to add it here.
+_NEVER_GRANTABLE_EXPLICIT: Final[dict[str, str]] = {
+ "api_service": "the identity an API key resolves to, not a role a person can hold",
+}
+
+_WILDCARD_REASON: Final[str] = (
+ "holds '*' across every tenant; a tenant-scoped request must not be able to mint one. "
+ "Use app/scripts/bootstrap_admin.py, which runs out of band with database credentials."
+)
+
+
+class RoleGrantDenied(Exception):
+ """A grant was refused. ``unknown`` separates bad input from a real refusal.
+
+ Carries the reason as text because every caller surfaces it to an operator
+ who otherwise sees a bare 403 and has to read the source to learn which of
+ their own permissions was missing.
+ """
+
+ def __init__(self, reason: str, *, unknown: bool = False) -> None:
+ super().__init__(reason)
+ self.reason = reason
+ self.unknown = unknown
+
+
+def wildcard_roles() -> frozenset[str]:
+ """Roles whose declared permission list is the wildcard."""
+ return frozenset(role for role, perms in ROLE_PERMISSIONS.items() if WILDCARD in perms)
+
+
+def never_grantable() -> dict[str, str]:
+ """Every role a request may not confer, mapped to why."""
+ reasons = dict.fromkeys(wildcard_roles(), _WILDCARD_REASON)
+ reasons.update(_NEVER_GRANTABLE_EXPLICIT)
+ return reasons
+
+
+def permissions_for(role: str) -> frozenset[str]:
+ """The permissions a role confers. An unknown role confers nothing."""
+ return frozenset(ROLE_PERMISSIONS.get(role, []))
+
+
+def holds_wildcard(role: str) -> bool:
+ """Whether a role confers every permission."""
+ return WILDCARD in ROLE_PERMISSIONS.get(role, [])
+
+
+def _granter_permissions(granter_role: str, granter_scopes: Sequence[str] | None) -> frozenset[str]:
+ """What the caller actually holds.
+
+ An API-key principal's authority is its ``scopes`` list, not the role of
+ the user who minted it — ``CurrentUser.require_permission`` takes the
+ scopes branch whenever ``scopes`` is not ``None``. Reading the role here
+ would let a key with two read scopes, owned by a ``tenant_admin``, grant
+ everything ``tenant_admin`` holds.
+ """
+ if granter_scopes is not None:
+ return frozenset(granter_scopes)
+ return permissions_for(granter_role)
+
+
+def _covers(held: frozenset[str], wanted: str) -> bool:
+ """Whether a held permission set covers one wanted permission.
+
+ Mirrors ``has_permission`` and the API-key branch of
+ ``CurrentUser.require_permission``, including the ``resource:*`` form. A
+ subset check that did not understand ``alerts:*`` would refuse a grant the
+ caller can in fact make, which is the kind of false refusal that gets a
+ control removed.
+ """
+ if WILDCARD in held:
+ return True
+ if wanted in held:
+ return True
+ return f"{wanted.split(':')[0]}:{WILDCARD}" in held
+
+
+def missing_permissions(held: frozenset[str], wanted: Iterable[str]) -> list[str]:
+ """Which wanted permissions the held set does not cover, sorted."""
+ return sorted({perm for perm in wanted if not _covers(held, perm)})
+
+
+def authorize_role_grant(
+ *,
+ granter_role: str,
+ requested_role: str,
+ granter_scopes: Sequence[str] | None = None,
+) -> str:
+ """Return ``requested_role`` if this caller may confer it, else raise.
+
+ Raises :class:`RoleGrantDenied`. ``unknown`` is set when the role is not in
+ the enforced vocabulary at all, which callers map to 422 — a role outside
+ ``ROLE_PERMISSIONS`` is not a smaller privilege, it is a string in a column
+ that grants nothing while reading in a console as though it grants
+ something.
+ """
+ if requested_role not in ROLE_PERMISSIONS:
+ raise RoleGrantDenied(
+ f"Unknown role {requested_role!r}. Assignable roles: {', '.join(GRANTABLE_ROLES)}",
+ unknown=True,
+ )
+
+ blocked = never_grantable().get(requested_role)
+ if blocked is not None:
+ raise RoleGrantDenied(f"Role {requested_role!r} cannot be assigned through the API: {blocked}")
+
+ held = _granter_permissions(granter_role, granter_scopes)
+ missing = missing_permissions(held, permissions_for(requested_role))
+ if missing:
+ raise RoleGrantDenied(f"Cannot grant {requested_role!r}: it confers permissions you do not hold ({', '.join(missing)})")
+ return requested_role
+
+
+def authorize_permission_grant(
+ *,
+ granter_role: str,
+ requested: Sequence[str],
+ granter_scopes: Sequence[str] | None = None,
+ subject: str = "permissions",
+) -> list[str]:
+ """Return ``requested`` if this caller may confer every one of them, else raise.
+
+ The same property applied to a permission list rather than a role name,
+ for API-key scopes and for database-backed RBAC roles. The wildcard is
+ *not* special-cased away here, unlike :func:`authorize_role_grant`: a
+ caller holding ``"*"`` may mint a ``"*"`` key, because that confers no
+ authority the caller does not already have and does not create a principal
+ outside the caller's own tenant. What it stops is the case that shipped —
+ ``tenant_admin``, which is scoped on purpose, minting one.
+ """
+ held = _granter_permissions(granter_role, granter_scopes)
+ missing = missing_permissions(held, requested)
+ if missing:
+ raise RoleGrantDenied(f"Cannot grant {subject} you do not hold: {', '.join(missing)}")
+ return list(requested)
+
+
+def authorize_role_change(
+ *,
+ granter_role: str,
+ current_role: str,
+ requested_role: str,
+ granter_scopes: Sequence[str] | None = None,
+) -> str:
+ """Authorize re-roling an existing principal.
+
+ Two checks, because changing a role is two acts. Conferring the new role
+ is :func:`authorize_role_grant`. Taking away the old one matters
+ separately: without this, a ``tenant_admin`` could not *create* a
+ ``platform_admin`` but could demote the one that exists to ``viewer``,
+ ending the only principal able to undo it. So a principal currently
+ holding a never-grantable role is not re-roled from a tenant-scoped
+ request at all.
+ """
+ blocked = never_grantable().get(current_role)
+ if blocked is not None:
+ raise RoleGrantDenied(f"This account holds {current_role!r}, which cannot be changed through the API: {blocked}")
+ return authorize_role_grant(
+ granter_role=granter_role,
+ requested_role=requested_role,
+ granter_scopes=granter_scopes,
+ )
+
+
+def vocabulary_problems() -> list[str]:
+ """Disagreements between this module and the enforced permission map.
+
+ Returned rather than raised so a gate and a test can report all of them at
+ once. The last check is the ratchet that matters: a role added to
+ ``ROLE_PERMISSIONS`` that is neither grantable nor recorded as refused is
+ a role nobody decided about, and silence there defaults to "assignable"
+ in every reviewer's head and to "refused" in this module's.
+ """
+ problems: list[str] = []
+ refused = never_grantable()
+
+ for role in GRANTABLE_ROLES:
+ if role not in ROLE_PERMISSIONS:
+ problems.append(f"GRANTABLE_ROLES names {role!r}, which ROLE_PERMISSIONS does not define")
+ if role in refused:
+ problems.append(f"{role!r} is both grantable and refused: {refused[role]}")
+ if holds_wildcard(role):
+ problems.append(f"{role!r} is grantable and holds the wildcard — a single request would confer everything")
+
+ for role in _NEVER_GRANTABLE_EXPLICIT:
+ if role not in ROLE_PERMISSIONS:
+ problems.append(f"_NEVER_GRANTABLE_EXPLICIT names {role!r}, which ROLE_PERMISSIONS no longer defines")
+
+ undecided = set(ROLE_PERMISSIONS) - set(GRANTABLE_ROLES) - set(refused)
+ for role in sorted(undecided):
+ problems.append(f"ROLE_PERMISSIONS defines {role!r} and this module neither makes it grantable nor records why it is not")
+
+ return problems
diff --git a/services/api/app/services/scim/roles.py b/services/api/app/services/scim/roles.py
index 095eab91b..85ed6ea18 100644
--- a/services/api/app/services/scim/roles.py
+++ b/services/api/app/services/scim/roles.py
@@ -36,6 +36,7 @@ from __future__ import annotations
import re
from typing import Final
+from app.core.role_grants import GRANTABLE_ROLES, never_grantable
from app.core.security import ROLE_PERMISSIONS
#: The role a provisioned principal holds before any group confers one.
@@ -46,16 +47,12 @@ DEFAULT_PROVISIONED_ROLE: Final[str] = "viewer"
#: Total order, least authority first. A principal's role is the last entry
#: in this list that any of their mapped groups confers.
#:
-#: ``admin`` and ``platform_admin`` are both in ``ROLE_PERMISSIONS`` with
-#: ``["*"]`` and are deliberately **not** reachable from a directory group:
-#: see :data:`UNREACHABLE_BY_GROUP`.
-ROLE_PRECEDENCE: Final[tuple[str, ...]] = (
- "viewer",
- "soc_analyst",
- "threat_hunter",
- "soc_lead",
- "tenant_admin",
-)
+#: This *is* ``app.core.role_grants.GRANTABLE_ROLES``, not a copy of it. SCIM
+#: reached the conclusion that wildcard roles must not be conferrable by a
+#: client-supplied name first, and kept its own list; the tenant user API then
+#: shipped without the same rule (GHSA-pm3f-h6gc-rvgp). Two lists that agree
+#: today are two lists that disagree later, so there is now one.
+ROLE_PRECEDENCE: Final[tuple[str, ...]] = GRANTABLE_ROLES
#: Roles no directory group may confer, with the reason.
#:
@@ -65,11 +62,11 @@ ROLE_PRECEDENCE: Final[tuple[str, ...]] = (
#: than the platform's administrators, could mint a platform administrator by
#: choosing a group name. ``api_service`` is the identity an API key resolves
#: to and is not a human role at all.
-UNREACHABLE_BY_GROUP: Final[dict[str, str]] = {
- "platform_admin": "holds '*' across every tenant; a directory group name must not be able to mint one",
- "admin": "holds '*' across every tenant; a directory group name must not be able to mint one",
- "api_service": "the identity an API key resolves to, not a role a person can hold",
-}
+#:
+#: Shared with every other grant path, and the wildcard members are derived
+#: from ``ROLE_PERMISSIONS`` rather than named, so a third role declared with
+#: ``["*"]`` is unreachable from a group the moment it is declared.
+UNREACHABLE_BY_GROUP: Final[dict[str, str]] = never_grantable()
#: Group-name fragments that resolve to a role, most specific first.
#:
diff --git a/services/api/tests/test_role_grant_scope.py b/services/api/tests/test_role_grant_scope.py
new file mode 100644
index 000000000..7d9844f46
--- /dev/null
+++ b/services/api/tests/test_role_grant_scope.py
@@ -0,0 +1,549 @@
+"""GHSA-pm3f-h6gc-rvgp: a principal conferring authority it does not hold.
+
+`POST /api/v1/tenants/me/users` took a `role` string from the body and wrote
+it to `users.role`, the column `CurrentUser.require_permission` reads. With
+`platform_admin` and `admin` both declared `["*"]`, a `tenant_admin` could
+create an account holding every permission in the product and sign in as it.
+
+Five more routes had the same defect and the report named only the first, so
+the tests here are organised by call site rather than by advisory:
+
+* `PATCH /tenants/me/users/{id}` — the same grant, spelled as a promotion.
+* `POST /api-keys` and `PATCH /api-keys/{id}` — the check they *did* have read
+ `current_user.role not in ("platform_admin", "tenant_admin")` and covered
+ only `"*"`, so `tenant_admin` could mint a wildcard key (total escalation,
+ no user created) and anyone with `users:write` could mint a `plugins:admin`
+ key they were themselves refused.
+* `POST /rbac/users/{id}/roles` — `users:write` attaching a database-backed
+ role authored under `roles:write`, which `has_permission_db` then prefers
+ over the static map.
+* `POST /mssp/delegations` — an unvalidated role string stored against a
+ customer tenant.
+* `PUT /mssp/organizations/current/members` — `ORG_ROLES` is a vocabulary, not
+ a grant scope, and `_admin_scope` admits `admin` as well as `owner`.
+
+**Nothing here imports `app.core.role_grants`.** A test that imports a symbol
+added by the fix fails on the old tree with `ImportError`, which proves the
+symbol is absent and says nothing about whether the escalation was possible.
+These call the shipped handlers and assert on what they do, so against the
+pre-fix tree they fail because the grant *succeeded*.
+
+Every call site is asserted in both directions: the escalating request is
+refused **and no write is issued**, and a legitimate grant still lands.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from app.api.v1.deps import CurrentUser
+from app.api.v1.endpoints import api_keys as api_keys_mod
+from app.api.v1.endpoints import mssp as mssp_mod
+from app.api.v1.endpoints import rbac as rbac_mod
+from app.api.v1.endpoints import tenants as tenants_mod
+from fastapi import HTTPException
+
+TENANT = uuid.uuid4()
+
+pytestmark = pytest.mark.anyio
+
+
+def anyio_backend() -> str:
+ return "asyncio"
+
+
+def _principal(role: str, *, scopes: list[str] | None = None) -> CurrentUser:
+ return CurrentUser(
+ user_id=uuid.uuid4(),
+ tenant_id=TENANT,
+ role=role,
+ email=f"{role}@tenant-a.example",
+ scopes=scopes,
+ )
+
+
+def _db(*, found: Any = None) -> AsyncMock:
+ """An async session whose reads answer `found` and whose writes are visible."""
+ db = AsyncMock()
+ result = MagicMock()
+ result.scalar_one_or_none = MagicMock(return_value=found)
+ result.scalars = MagicMock(return_value=MagicMock(all=MagicMock(return_value=[])))
+ db.execute = AsyncMock(return_value=result)
+ db.add = MagicMock()
+ db.commit = AsyncMock()
+ db.flush = AsyncMock()
+
+ async def _refresh(obj: Any) -> None:
+ # Stand in for the flush that would populate server-side defaults, so
+ # a *successful* call can still build its response model and the
+ # positive direction is a real assertion rather than an xfail.
+ for field, value in (
+ ("id", uuid.uuid4()),
+ ("created_at", datetime.now(UTC)),
+ ("is_active", True),
+ ("last_login", None),
+ ("expires_at", None),
+ ("last_used_at", None),
+ ("scopes", getattr(obj, "scopes", None) or []),
+ ("revoked_at", None),
+ ("granted_by_user", None),
+ ):
+ if getattr(obj, field, None) is None:
+ try:
+ setattr(obj, field, value)
+ except (AttributeError, ValueError): # pragma: no cover - ORM guard
+ pass
+
+ db.refresh = AsyncMock(side_effect=_refresh)
+ return db
+
+
+def _wrote(db: AsyncMock) -> bool:
+ """Whether the handler issued any write at all."""
+ return bool(db.add.call_args_list) or bool(db.commit.call_args_list)
+
+
+# ---------------------------------------------------------------------------
+# POST /api/v1/tenants/me/users — the reported route
+# ---------------------------------------------------------------------------
+
+
+class TestCreateUser:
+ @pytest.mark.parametrize("role", ["platform_admin", "admin"])
+ async def test_a_tenant_admin_cannot_mint_a_wildcard_role(self, role: str) -> None:
+ db = _db()
+ body = tenants_mod.CreateUserRequest(
+ username="backdoor",
+ password="AnotherLongPassword2!",
+ role=role,
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await tenants_mod.create_user(request=body, current_user=_principal("tenant_admin"), db=db)
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db), "the refused request still wrote a row"
+
+ async def test_an_unknown_role_is_refused_rather_than_stored(self) -> None:
+ """A role outside `ROLE_PERMISSIONS` grants nothing and reads in a
+ console as though it grants something, which is worse than refusing."""
+ db = _db()
+ body = tenants_mod.CreateUserRequest(
+ username="ghost",
+ password="AnotherLongPassword2!",
+ role="superuser",
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await tenants_mod.create_user(request=body, current_user=_principal("tenant_admin"), db=db)
+
+ assert exc.value.status_code == 422
+ assert not _wrote(db)
+
+ async def test_an_api_key_is_bounded_by_its_scopes_not_its_owners_role(self) -> None:
+ """The authority of an API-key principal is its scope list.
+
+ `CurrentUser.require_permission` takes the scopes branch whenever
+ `scopes` is not None, so a narrow key owned by a `tenant_admin` must
+ not be able to grant everything `tenant_admin` holds.
+ """
+ db = _db()
+ body = tenants_mod.CreateUserRequest(
+ username="lateral",
+ password="AnotherLongPassword2!",
+ role="soc_lead",
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await tenants_mod.create_user(
+ request=body,
+ current_user=_principal("tenant_admin", scopes=["alerts:read", "cases:read"]),
+ db=db,
+ )
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db)
+
+ @pytest.mark.parametrize("role", ["viewer", "soc_analyst", "threat_hunter", "soc_lead", "tenant_admin"])
+ async def test_a_tenant_admin_can_still_create_every_ordinary_role(self, role: str) -> None:
+ db = _db()
+ body = tenants_mod.CreateUserRequest(
+ email=f"{role}@tenant-a.example",
+ username=role,
+ password="AnotherLongPassword2!",
+ role=role,
+ )
+
+ out = await tenants_mod.create_user(request=body, current_user=_principal("tenant_admin"), db=db)
+
+ assert out.role == role
+ assert db.add.call_args.args[0].role == role
+
+
+# ---------------------------------------------------------------------------
+# PATCH /api/v1/tenants/me/users/{id}
+# ---------------------------------------------------------------------------
+
+
+def _existing_user(role: str) -> Any:
+ user = MagicMock()
+ user.id = uuid.uuid4()
+ user.tenant_id = TENANT
+ user.email = "[email protected]"
+ user.username = "target"
+ user.role = role
+ user.is_active = True
+ user.last_login = None
+ user.created_at = datetime.now(UTC)
+ return user
+
+
+class TestUpdateUser:
+ @pytest.mark.parametrize("role", ["platform_admin", "admin"])
+ async def test_promotion_to_a_wildcard_role_is_refused(self, role: str) -> None:
+ target = _existing_user("viewer")
+ db = _db(found=target)
+
+ with pytest.raises(HTTPException) as exc:
+ await tenants_mod.update_user(
+ user_id=target.id,
+ request=tenants_mod.UpdateUserRequest(role=role),
+ current_user=_principal("tenant_admin"),
+ db=db,
+ )
+
+ assert exc.value.status_code == 403
+ assert not db.commit.call_args_list, "the refused promotion still committed"
+ assert target.role == "viewer"
+
+ async def test_a_wildcard_principal_cannot_be_re_roled_either(self) -> None:
+ """Otherwise the route that cannot create a `platform_admin` can still
+ demote the one that exists, ending the only principal able to undo it."""
+ target = _existing_user("platform_admin")
+ db = _db(found=target)
+
+ with pytest.raises(HTTPException) as exc:
+ await tenants_mod.update_user(
+ user_id=target.id,
+ request=tenants_mod.UpdateUserRequest(role="viewer"),
+ current_user=_principal("tenant_admin"),
+ db=db,
+ )
+
+ assert exc.value.status_code == 403
+ assert not db.commit.call_args_list
+
+ async def test_a_refused_role_does_not_write_the_other_fields_either(self) -> None:
+ target = _existing_user("viewer")
+ db = _db(found=target)
+
+ with pytest.raises(HTTPException):
+ await tenants_mod.update_user(
+ user_id=target.id,
+ request=tenants_mod.UpdateUserRequest(username="renamed", role="admin", is_active=False),
+ current_user=_principal("tenant_admin"),
+ db=db,
+ )
+
+ assert not db.commit.call_args_list
+ assert target.username == "target"
+
+ async def test_an_ordinary_promotion_still_succeeds(self) -> None:
+ target = _existing_user("viewer")
+ db = _db(found=target)
+
+ await tenants_mod.update_user(
+ user_id=target.id,
+ request=tenants_mod.UpdateUserRequest(role="soc_lead"),
+ current_user=_principal("tenant_admin"),
+ db=db,
+ )
+
+ assert db.commit.call_args_list, "a legitimate promotion was not committed"
+
+
+# ---------------------------------------------------------------------------
+# POST /api/v1/api-keys and PATCH /api/v1/api-keys/{id}
+# ---------------------------------------------------------------------------
+
+
+class TestApiKeyScopes:
+ async def test_a_tenant_admin_cannot_mint_a_wildcard_key(self) -> None:
+ """The escalation the advisory describes, with no user created at all.
+
+ A `*` key satisfies every `require_permission` on the API-key branch,
+ so this is the same total compromise by a quieter door.
+ """
+ db = _db()
+ body = api_keys_mod.CreateApiKeyRequest(name="backdoor-key", scopes=["*"])
+
+ with pytest.raises(HTTPException) as exc:
+ await api_keys_mod.create_api_key(body=body, db=db, current_user=_principal("tenant_admin"))
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db)
+
+ async def test_a_key_cannot_carry_a_scope_its_minter_is_refused(self) -> None:
+ """`plugins:admin` is held by no role in `ROLE_PERMISSIONS`, and
+ plugin import runs code. A `tenant_admin` gets 403 from
+ `POST /plugins/discover` and could mint a key that does not."""
+ db = _db()
+ body = api_keys_mod.CreateApiKeyRequest(name="plugin-key", scopes=["plugins:admin"])
+
+ with pytest.raises(HTTPException) as exc:
+ await api_keys_mod.create_api_key(body=body, db=db, current_user=_principal("tenant_admin"))
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db)
+
+ async def test_a_wildcard_principal_may_still_mint_a_wildcard_key(self) -> None:
+ """It confers nothing the caller does not already hold."""
+ db = _db()
+ body = api_keys_mod.CreateApiKeyRequest(name="ops-key", scopes=["*"])
+
+ out = await api_keys_mod.create_api_key(body=body, db=db, current_user=_principal("platform_admin"))
+
+ assert out.scopes == ["*"]
+
+ async def test_a_tenant_admin_may_still_mint_a_key_within_its_own_authority(self) -> None:
+ db = _db()
+ body = api_keys_mod.CreateApiKeyRequest(name="reporting-key", scopes=["alerts:read", "cases:write"])
+
+ out = await api_keys_mod.create_api_key(body=body, db=db, current_user=_principal("tenant_admin"))
+
+ assert sorted(out.scopes) == ["alerts:read", "cases:write"]
+
+ async def test_widening_an_existing_key_is_refused_and_writes_nothing(self) -> None:
+ key = MagicMock()
+ key.id = uuid.uuid4()
+ key.name = "reporting-key"
+ key.prefix = "aisoc_abc123"
+ key.key_prefix = "aisoc_abc123"
+ key.scopes = ["alerts:read"]
+ key.is_active = True
+ key.expires_at = None
+ key.last_used_at = None
+ key.created_at = datetime.now(UTC)
+ db = _db(found=key)
+
+ with pytest.raises(HTTPException) as exc:
+ await api_keys_mod.update_api_key(
+ key_id=key.id,
+ body=api_keys_mod.UpdateApiKeyRequest(name="renamed", scopes=["*"]),
+ db=db,
+ current_user=_principal("tenant_admin"),
+ )
+
+ assert exc.value.status_code == 403
+ assert key.scopes == ["alerts:read"]
+ assert key.name == "reporting-key", "the refused request still renamed the key"
+ assert not db.commit.call_args_list
+
+
+# ---------------------------------------------------------------------------
+# POST /api/v1/rbac/users/{id}/roles and POST /api/v1/rbac/roles
+# ---------------------------------------------------------------------------
+
+
+def _permission(name: str) -> Any:
+ perm = MagicMock()
+ perm.id = uuid.uuid4()
+ perm.name = name
+ perm.description = name
+ perm.category = name.split(":")[0]
+ return perm
+
+
+def _rbac_db(*, scalars_queue: list[Any], permissions: list[Any]) -> AsyncMock:
+ """A session where row reads are a queue and permission reads are not.
+
+ Deliberately not a fixed `side_effect` list. The fix inserts one extra
+ `SELECT` (the role's permissions) into these handlers, so a positional
+ list would make every test here fail on the pre-fix tree purely because
+ the call count moved — which looks exactly like a caught defect and is
+ not one. `scalar_one_or_none` pops; `scalars().all()` always answers the
+ permission set; both orderings work.
+ """
+ db = AsyncMock()
+ db.add = MagicMock()
+ db.commit = AsyncMock()
+ db.refresh = AsyncMock()
+ pending = list(scalars_queue)
+
+ async def _flush() -> None:
+ # Stands in for the server-side default on `roles.id`, so the pre-fix
+ # handler runs to completion and fails the assertion rather than
+ # tripping over an unpopulated primary key.
+ for call in db.add.call_args_list:
+ obj = call.args[0]
+ if getattr(obj, "id", None) is None:
+ obj.id = uuid.uuid4()
+
+ db.flush = AsyncMock(side_effect=_flush)
+
+ result = MagicMock()
+ result.scalar_one_or_none = MagicMock(side_effect=lambda: pending.pop(0) if pending else None)
+ result.scalars = MagicMock(return_value=MagicMock(all=MagicMock(return_value=permissions)))
+ db.execute = AsyncMock(return_value=result)
+ return db
+
+
+class TestRbacRoleAssignment:
+ async def test_users_write_cannot_attach_a_role_carrying_permissions_it_lacks(self) -> None:
+ """`user_roles` is a live authorization path: `has_permission_db`
+ prefers it over the static map for any principal holding a row."""
+ role = MagicMock(id=uuid.uuid4(), tenant_id=TENANT)
+ role.name = "shadow-admin" # `name=` on a MagicMock names the mock, not the attribute
+ target = MagicMock(id=uuid.uuid4(), tenant_id=TENANT)
+ db = _rbac_db(scalars_queue=[role, target, None], permissions=[_permission("roles:write")])
+
+ with pytest.raises(HTTPException) as exc:
+ await rbac_mod.assign_role(
+ user_id=target.id,
+ body=rbac_mod.UserRoleAssignment(user_id=target.id, role_id=role.id),
+ current_user=_principal("tenant_admin"),
+ db=db,
+ )
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db)
+
+ async def test_a_role_within_the_granters_authority_still_attaches(self) -> None:
+ role = MagicMock(id=uuid.uuid4(), tenant_id=TENANT)
+ role.name = "triage"
+ target = MagicMock(id=uuid.uuid4(), tenant_id=TENANT)
+ db = _rbac_db(scalars_queue=[role, target, None], permissions=[_permission("alerts:read")])
+
+ out = await rbac_mod.assign_role(
+ user_id=target.id,
+ body=rbac_mod.UserRoleAssignment(user_id=target.id, role_id=role.id),
+ current_user=_principal("tenant_admin"),
+ db=db,
+ )
+
+ assert out.role_name == "triage"
+ assert db.add.call_args_list
+
+ async def test_authoring_a_role_beyond_the_authors_authority_is_refused(self) -> None:
+ perm = _permission("plugins:admin")
+ db = _rbac_db(scalars_queue=[None], permissions=[perm])
+
+ with pytest.raises(HTTPException) as exc:
+ await rbac_mod.create_role(
+ body=rbac_mod.RoleIn(name="plugin-ops", permission_ids=[perm.id]),
+ current_user=_principal("tenant_admin"),
+ db=db,
+ )
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db), "the refused request still created the role row"
+
+
+# ---------------------------------------------------------------------------
+# POST /api/v1/mssp/delegations
+# ---------------------------------------------------------------------------
+
+
+class TestDelegationRole:
+ async def test_a_delegation_cannot_name_a_wildcard_role(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ child = uuid.uuid4()
+ db = _db()
+ monkeypatch.setattr(mssp_mod, "_require_own_child", AsyncMock())
+ body = MagicMock(child_tenant_id=child, granted_role="admin", expires_at=None)
+
+ with pytest.raises(HTTPException) as exc:
+ await mssp_mod.create_delegation(body=body, db=db, current_user=_principal("tenant_admin"))
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db)
+
+ async def test_an_ordinary_delegation_still_lands(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ child = uuid.uuid4()
+ db = _db()
+ monkeypatch.setattr(mssp_mod, "_require_own_child", AsyncMock())
+ body = MagicMock(child_tenant_id=child, granted_role="soc_analyst", expires_at=None)
+
+ await mssp_mod.create_delegation(body=body, db=db, current_user=_principal("tenant_admin"))
+
+ assert db.add.call_args.args[0].granted_role == "soc_analyst"
+
+
+# ---------------------------------------------------------------------------
+# PUT /api/v1/mssp/organizations/current/members
+# ---------------------------------------------------------------------------
+
+
+def _scope(org_role: str) -> Any:
+ scope = MagicMock()
+ scope.org_id = uuid.uuid4()
+ scope.org_role = org_role
+ return scope
+
+
+class TestOrganisationMemberRole:
+ async def test_an_org_admin_cannot_appoint_an_owner(self) -> None:
+ target = MagicMock(id=uuid.uuid4(), email="[email protected]")
+ db = _db(found=None)
+ db.get = AsyncMock(return_value=target)
+
+ with pytest.raises(HTTPException) as exc:
+ await mssp_mod.upsert_member(
+ body=mssp_mod.MemberUpsert(user_id=target.id, org_role="owner"),
+ scope=_scope("admin"),
+ db=db,
+ )
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db)
+
+ async def test_an_org_admin_cannot_demote_the_sitting_owner(self) -> None:
+ target = MagicMock(id=uuid.uuid4(), email="[email protected]")
+ member = MagicMock(org_role="owner")
+ db = _db(found=member)
+ db.get = AsyncMock(return_value=target)
+
+ with pytest.raises(HTTPException) as exc:
+ await mssp_mod.upsert_member(
+ body=mssp_mod.MemberUpsert(user_id=target.id, org_role="viewer"),
+ scope=_scope("admin"),
+ db=db,
+ )
+
+ assert exc.value.status_code == 403
+ assert member.org_role == "owner"
+ assert not _wrote(db)
+
+ async def test_an_org_admin_may_still_appoint_at_or_below_its_own_level(self) -> None:
+ target = MagicMock(id=uuid.uuid4(), email="[email protected]")
+ db = _db(found=None)
+ db.get = AsyncMock(return_value=target)
+
+ out = await mssp_mod.upsert_member(
+ body=mssp_mod.MemberUpsert(user_id=target.id, org_role="operator"),
+ scope=_scope("admin"),
+ db=db,
+ )
+
+ assert out.org_role == "operator"
+ assert db.add.call_args_list
+
+ async def test_an_owner_may_still_appoint_an_owner(self) -> None:
+ target = MagicMock(id=uuid.uuid4(), email="[email protected]")
+ db = _db(found=None)
+ db.get = AsyncMock(return_value=target)
+
+ out = await mssp_mod.upsert_member(
+ body=mssp_mod.MemberUpsert(user_id=target.id, org_role="owner"),
+ scope=_scope("owner"),
+ db=db,
+ )
+
+ assert out.org_role == "owner"
diff --git a/services/api/tests/test_role_grant_vocabulary.py b/services/api/tests/test_role_grant_vocabulary.py
new file mode 100644
index 000000000..086495b66
--- /dev/null
+++ b/services/api/tests/test_role_grant_vocabulary.py
@@ -0,0 +1,118 @@
+"""Unit tests for the grant-scope chokepoint itself.
+
+Separate from `test_role_grant_scope.py` on purpose. That file asserts what
+the shipped handlers do and imports nothing the fix added, so every failure
+there is a failure of the product. This file tests `app.core.role_grants`
+directly and therefore cannot run against a tree that predates it — which is
+fine for a unit test and would be worthless as a regression proof.
+
+The ratchet is `test_every_declared_role_has_a_decision`: a role added to
+`ROLE_PERMISSIONS` that is neither grantable nor recorded as refused fails
+here, because silence about a new role reads as "assignable" to a reviewer
+and as "refused" to the code.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.core.role_grants import (
+ GRANTABLE_ROLES,
+ RoleGrantDenied,
+ authorize_permission_grant,
+ authorize_role_change,
+ authorize_role_grant,
+ missing_permissions,
+ never_grantable,
+ permissions_for,
+ vocabulary_problems,
+ wildcard_roles,
+)
+from app.core.security import ROLE_PERMISSIONS
+from app.services.scim import roles as scim_roles
+
+
+class TestVocabulary:
+ def test_every_declared_role_has_a_decision(self) -> None:
+ assert vocabulary_problems() == []
+
+ def test_no_grantable_role_holds_the_wildcard(self) -> None:
+ """The whole finding in one assertion: a single unchecked string must
+ not be able to confer every permission in the product."""
+ assert not (set(GRANTABLE_ROLES) & wildcard_roles())
+
+ def test_the_wildcard_set_is_derived_not_listed(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """A third role declared `["*"]` must be refused without anyone
+ remembering to add it to a list."""
+ monkeypatch.setitem(ROLE_PERMISSIONS, "break_glass", ["*"])
+ assert "break_glass" in never_grantable()
+ with pytest.raises(RoleGrantDenied):
+ authorize_role_grant(granter_role="platform_admin", requested_role="break_glass")
+
+ def test_scim_shares_this_vocabulary_rather_than_copying_it(self) -> None:
+ assert scim_roles.ROLE_PRECEDENCE is GRANTABLE_ROLES
+ assert scim_roles.UNREACHABLE_BY_GROUP == never_grantable()
+ assert scim_roles.validate_vocabulary() == []
+
+
+class TestRoleGrant:
+ @pytest.mark.parametrize("role", sorted(never_grantable()))
+ def test_a_refused_role_is_refused_even_for_a_wildcard_caller(self, role: str) -> None:
+ with pytest.raises(RoleGrantDenied) as exc:
+ authorize_role_grant(granter_role="platform_admin", requested_role=role)
+ assert not exc.value.unknown
+
+ def test_an_unknown_role_is_flagged_as_unknown(self) -> None:
+ with pytest.raises(RoleGrantDenied) as exc:
+ authorize_role_grant(granter_role="platform_admin", requested_role="superuser")
+ assert exc.value.unknown
+
+ @pytest.mark.parametrize("role", GRANTABLE_ROLES)
+ def test_a_tenant_admin_covers_every_grantable_role(self, role: str) -> None:
+ """If this ever fails, the refusal below is a real capability loss and
+ not just a closed hole — which is the thing to notice before shipping."""
+ assert authorize_role_grant(granter_role="tenant_admin", requested_role=role) == role
+
+ def test_a_viewer_cannot_grant_an_analyst(self) -> None:
+ with pytest.raises(RoleGrantDenied) as exc:
+ authorize_role_grant(granter_role="viewer", requested_role="soc_analyst")
+ assert "alerts:write" in exc.value.reason
+
+ def test_the_two_hunter_and_analyst_roles_cannot_grant_each_other(self) -> None:
+ """Permission sets are only partially ordered, so `GRANTABLE_ROLES`
+ order is presentation and the subset check is the authority."""
+ with pytest.raises(RoleGrantDenied):
+ authorize_role_grant(granter_role="soc_analyst", requested_role="threat_hunter")
+ with pytest.raises(RoleGrantDenied):
+ authorize_role_grant(granter_role="threat_hunter", requested_role="soc_analyst")
+
+
+class TestPermissionGrant:
+ def test_a_resource_wildcard_covers_its_members(self) -> None:
+ assert missing_permissions(frozenset({"alerts:*"}), ["alerts:read", "alerts:delete"]) == []
+
+ def test_a_held_scope_list_bounds_an_api_key_principal(self) -> None:
+ with pytest.raises(RoleGrantDenied):
+ authorize_permission_grant(
+ granter_role="tenant_admin",
+ granter_scopes=["alerts:read"],
+ requested=["cases:write"],
+ )
+
+ def test_a_wildcard_holder_may_confer_the_wildcard(self) -> None:
+ assert authorize_permission_grant(granter_role="platform_admin", requested=["*"]) == ["*"]
+
+ def test_a_scoped_role_may_not(self) -> None:
+ with pytest.raises(RoleGrantDenied):
+ authorize_permission_grant(granter_role="tenant_admin", requested=["*"])
+
+
+class TestRoleChange:
+ def test_a_principal_holding_a_refused_role_cannot_be_re_roled(self) -> None:
+ with pytest.raises(RoleGrantDenied):
+ authorize_role_change(granter_role="tenant_admin", current_role="admin", requested_role="viewer")
+
+ def test_an_ordinary_change_is_allowed(self) -> None:
+ assert authorize_role_change(granter_role="tenant_admin", current_role="viewer", requested_role="soc_lead") == "soc_lead"
+
+ def test_permissions_for_an_unknown_role_is_empty(self) -> None:
+ assert permissions_for("superuser") == frozenset()