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): measure a grant against the authority its caller was admitted on (#1114)

Beenu Arorab1c6925ae5ac
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4da269441..cc65088da 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Security
+
+- **A grant was measured against the caller's static role rather than the
+ permissions it was admitted on (GHSA-4gx4-x7gm-4xq8).**
+
+ `CurrentUser` resolves authority in three tiers — an API key's `scopes`,
+ then the database-backed RBAC tables, then the static `ROLE_PERMISSIONS`
+ map — and `require_permission` implements all three. `_granter_permissions`,
+ which every grant route consults, implemented the first and the third.
+
+ So a principal admitted through the middle tier had its grant checked
+ against a different authority than the one that opened the door. A
+ `tenant_admin` deliberately narrowed to `users:write` in `user_roles` still
+ carried 28 permissions statically: it could assign itself a role conferring
+ any of the other 27 and resolve them on its next request, defeating the
+ restriction a tenant administrator had applied. Reported by
+ [HaiND](https://github.com/Haind03).
+
+ The report named `POST /api/v1/rbac/users/{user_id}/roles`. The resolver is
+ shared, so the same caller reached it through five more: authoring a role,
+ re-permissioning one, creating a user, delegating to a child tenant, and
+ minting an API key — that last needing no target user and yielding a
+ durable bearer credential. All six now pass the resolved set.
+
+ `scripts/check_role_grant_scope.py` gains a fourth direction: a call to one
+ of the three authorizers that omits `granter_permissions=` fails CI. The
+ existing directions could not catch this, because they asked whether a
+ route *reached* the chokepoint and all six did.
+
+- **Dependency advisories.** `serialize-javascript` to `>=7.1.2`
+ (GHSA-gfhx-hw2g-v5hg) and `http-cache-semantics` to `>=4.3.0`
+ (GHSA-ch52-4w7c-c8xp). The second was reported with no patched version
+ because the advisory carries a null `first_patched_version`; its vulnerable
+ range is `<= 4.2.0` and `4.3.0` is published, so the fix existed and the
+ metadata did not say so.
+
## [16.0.0] - 2026-10-03
### BREAKING
diff --git a/apps/docs/docs/operations/security.md b/apps/docs/docs/operations/security.md
index 1fb184fa1..abdb23337 100644
--- a/apps/docs/docs/operations/security.md
+++ b/apps/docs/docs/operations/security.md
@@ -138,8 +138,18 @@ Concretely, a grant is refused when the role is not in `ROLE_PERMISSIONS` at all
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.
+#### "Does not itself hold" means the permissions the caller was admitted on
+
+A principal's authority resolves in three tiers, in this order: an API key's `scopes`, then the database-backed RBAC tables, then the static `ROLE_PERMISSIONS` map. `require_permission` — the door on every route — implements all three. The grant check implemented the first and the third, so a caller admitted through the middle tier had its grant measured against a different authority than the one that let it in (GHSA-4gx4-x7gm-4xq8, reported by [HaiND](https://github.com/Haind03)).
+
+That gap is only reachable when a tenant uses database-backed roles, and it is exactly the configuration where it hurts: narrowing an account is what those tables are *for*. A `tenant_admin` restricted to `users:write` in `user_roles` still carried 28 permissions statically, so it could assign itself a role carrying any of the other 27 and resolve them on its next request. Six routes shared the defective resolver, not the one the report named — authoring a role, re-permissioning one, assigning one, creating a user, delegating to a child tenant, and minting an API key. The last needs no target user and yields a durable credential.
+
+The resolver now reads the same three tiers in the same order, so the authority that admits a caller is the authority that bounds what it confers. A tenant with no RBAC rows resolves nothing and keeps conferring exactly what its static role confers.
+
[`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.
+It also fails if a call to `authorize_role_grant`, `authorize_role_change` or `authorize_permission_grant` omits `granter_permissions=`. That direction exists because the first one passed on the vulnerable tree: it asked whether each route *reached* the chokepoint, and all six did. Reaching the right function while handing it the wrong authority is indistinguishable from a correct grant unless something checks the argument.
+
### 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.
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 8215e661a..894f7ea77 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -222,7 +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}`) | core | 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) | core | 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) | core | 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) | core | 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 |
+| No principal can confer a role, scope or organisation membership beyond the authority it was itself admitted on, 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; GHSA-4gx4-x7gm-4xq8 | `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; and asks of every call to `authorize_role_grant`, `authorize_role_change` or `authorize_permission_grant` whether it passes `granter_permissions=`, since reaching the chokepoint while handing it the caller's *static* role measures the grant against an authority the caller was not admitted on; seven injected drifts prove it fails, and run against the pre-fix tree it names all nine handlers and all six under-authorised call sites) + `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) + `ci.yml` api job (`test_role_grant_effective_permissions.py` drives the same handlers with a principal whose database permissions are narrower than its static role; 7 of its 10 tests fail against the pre-fix tree, each for the escalation landing, and the other 3 hold the positive direction so a tenant with no RBAC rows keeps conferring what its role confers) | core | 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) | core | 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) | core | 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) | core | 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 |
diff --git a/package.json b/package.json
index e2519f721..dfea939b9 100644
--- a/package.json
+++ b/package.json
@@ -90,7 +90,8 @@
"ip-address": ">=10.3.1 <11",
"js-yaml@3": ">=3.15.2 <4",
"js-yaml@4": ">=4.3.2 <5",
- "serialize-javascript": ">=7.0.3 <8",
+ "serialize-javascript": ">=7.1.2 <8",
+ "http-cache-semantics": ">=4.3.0 <5",
"sharp": ">=0.35.4",
"svgo@3": ">=3.3.5 <4",
"websocket-driver": ">=0.7.5",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d24004906..2425e3552 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -5,39 +5,40 @@ settings:
excludeLinksFromLockfile: false
overrides:
- axios: '>=1.20.0 <2'
- shell-quote: '>=1.8.4'
- form-data: '>=4.0.6'
- ws: '>=8.21.0'
- hono: '>=4.13.5'
+ '@babel/plugin-transform-modules-systemjs': '>=7.29.4 <8'
'@hono/node-server': '>=1.19.15 <2'
'@vitest/mocker': '>=4.1.11 <5'
- colord: '>=2.9.4'
- joi: '>=17.13.6 <18'
- qs: '>=6.16.0 <7'
+ axios: '>=1.20.0 <2'
body-parser: '>=2.3.0 <3'
- dompurify: '>=3.4.13 <4'
- postcss-selector-parser: '>=7.1.3 <8'
- http-proxy-middleware: '>=2.0.10 <4'
- launch-editor: '>=2.14.1 <3'
- uuid: '>=11.1.1 <12'
- webpack-dev-middleware: '>=7.4.6 <8'
- webpack-dev-server: '>=5.2.6 <6'
- '@babel/plugin-transform-modules-systemjs': '>=7.29.4 <8'
brace-expansion@1: '>=1.1.18 <2'
browserslist: '>=4.28.7 <5'
+ bundle-require>esbuild: ^0.28.1
+ colord: '>=2.9.4'
+ dompurify: '>=3.4.13 <4'
fast-uri: '>=3.1.6 <4'
+ form-data: '>=4.0.6'
+ hono: '>=4.13.5'
+ http-cache-semantics: '>=4.3.0 <5'
+ http-proxy-middleware: '>=2.0.10 <4'
image-size: '>=2.0.4 <3'
ip-address: '>=10.3.1 <11'
+ joi: '>=17.13.6 <18'
js-yaml@3: '>=3.15.2 <4'
js-yaml@4: '>=4.3.2 <5'
- serialize-javascript: '>=7.0.3 <8'
+ launch-editor: '>=2.14.1 <3'
+ postcss-selector-parser: '>=7.1.3 <8'
+ qs: '>=6.16.0 <7'
+ serialize-javascript: '>=7.1.2 <8'
sharp: '>=0.35.4'
+ shell-quote: '>=1.8.4'
svgo@3: '>=3.3.5 <4'
- websocket-driver: '>=0.7.5'
tsup>esbuild: ^0.28.1
+ uuid: '>=11.1.1 <12'
vite>esbuild: ^0.28.1
- bundle-require>esbuild: ^0.28.1
+ webpack-dev-middleware: '>=7.4.6 <8'
+ webpack-dev-server: '>=5.2.6 <6'
+ websocket-driver: '>=0.7.5'
+ ws: '>=8.21.0'
importers:
@@ -9542,7 +9543,7 @@ packages:
dependencies:
'@types/http-cache-semantics': 4.2.0
get-stream: 6.0.1
- http-cache-semantics: 4.2.0
+ http-cache-semantics: 4.3.0
keyv: 4.5.4
mimic-response: 4.0.0
normalize-url: 8.1.1
@@ -10052,7 +10053,7 @@ packages:
globby: 13.2.2
normalize-path: 3.0.0
schema-utils: 4.3.3
- serialize-javascript: 7.1.1
+ serialize-javascript: 7.1.2
dev: false
@@ -10206,7 +10207,7 @@ packages:
jest-worker: 29.7.0
postcss: 8.5.28
schema-utils: 4.3.3
- serialize-javascript: 7.1.1
+ serialize-javascript: 7.1.2
dev: false
@@ -12714,8 +12715,8 @@ packages:
entities: 4.5.0
dev: false
- resolution: {integrity: sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==}
+ resolution: {integrity: sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA==}
dev: false
@@ -18185,8 +18186,8 @@ packages:
- supports-color
dev: false
- resolution: {integrity: sha512-k3CMsaIvvdSwm8oLB4MXSl0wH2/cwlH7xGcnRd2DaeRmBkbzYmyT8j0tsX60DwD1eRwHTpNpH8ljKu9oUT1MeQ==}
+ resolution: {integrity: sha512-GL2BWwVa6JydKO6l/ljVgjAZF4QJ3S7dWDWi53s5GZT8PJzD2fNxi67HANQGKAqPrwEpL5ba7gUBGi0Ls/sEoQ==}
engines: {node: '>=20.0.0'}
dev: false
diff --git a/scripts/check_role_grant_scope.py b/scripts/check_role_grant_scope.py
index 75775c675..7227fd66a 100644
--- a/scripts/check_role_grant_scope.py
+++ b/scripts/check_role_grant_scope.py
@@ -96,6 +96,23 @@ CHOKEPOINT_CALLS: frozenset[str] = frozenset(
}
)
+#: The functions that decide a grant, as opposed to the helpers that reach
+#: them. Every call to one of these must say which authority to measure the
+#: grant against — see the ``authority`` direction in :func:`audit`.
+GRANT_DECIDERS: frozenset[str] = frozenset(
+ {
+ "authorize_role_grant",
+ "authorize_role_change",
+ "authorize_permission_grant",
+ }
+)
+
+#: The keyword that carries the caller's database-resolved permissions.
+#: ``CurrentUser`` resolves authority in three tiers and prefers this one over
+#: the static role whenever the principal has RBAC rows, so a call that omits
+#: it measures the grant against an authority the caller was not admitted on.
+EFFECTIVE_KEYWORD = "granter_permissions"
+
#: Handlers that accept one of those field names and deliberately do not
#: consult the chokepoint, with the reason. ``(module, function)``.
#:
@@ -214,7 +231,7 @@ def _granted_fields(func: ast.FunctionDef | ast.AsyncFunctionDef, models: dict[s
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}
+ counts = {"modules": 0, "handlers": 0, "writes": 0, "roles": 0, "decisions": 0}
endpoints = root / ENDPOINTS
security = root / SECURITY
@@ -254,6 +271,31 @@ def audit(root: Path) -> tuple[list[str], dict[str, int]]:
"app.core.role_grants, so the caller chooses the authority it confers"
)
+ # --- authority: the grant is measured against what admitted the caller -
+ #
+ # The forward direction above asks whether a handler *reaches* the
+ # chokepoint. It cannot ask whether it hands over the right authority,
+ # and GHSA-4gx4-x7gm-4xq8 was exactly that gap: six call sites reached
+ # `role_grants`, passed this gate, and compared the requested grant
+ # against the caller's static role while `require_permission` had
+ # admitted the caller on its narrower database permissions.
+ for module in sorted([*endpoints.glob("*.py"), role_grants]):
+ if not module.is_file():
+ continue
+ for node in ast.walk(_parse(module)):
+ if not isinstance(node, ast.Call):
+ continue
+ func = node.func
+ name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")
+ if name not in GRANT_DECIDERS:
+ continue
+ counts["decisions"] += 1
+ if not any(kw.arg == EFFECTIVE_KEYWORD for kw in node.keywords):
+ problems.append(
+ f"{module.name}:{node.lineno} calls {name}() without {EFFECTIVE_KEYWORD}=, so the grant is measured "
+ "against the caller's static role rather than the permissions it was admitted on"
+ )
+
# --- reverse: no waiver covers a handler that no longer grants ---------
for key, reason in sorted(ALLOWED.items()):
if key not in matched_waivers:
@@ -358,6 +400,12 @@ def _self_test_cases() -> list[tuple[str, bool]]:
"ROLE_PRECEDENCE: Final[tuple[str, ...]] = GRANTABLE_ROLES",
'ROLE_PRECEDENCE: Final[tuple[str, ...]] = ("viewer", "soc_analyst", "tenant_admin")',
),
+ (
+ "a grant measured against the static role instead of the resolved set is reported",
+ Path("services/api/app/api/v1/endpoints/rbac.py"),
+ " granter_permissions=current_user.resolved_permissions,\n",
+ "",
+ ),
(
"a waiver that no longer covers anything is reported",
Path(__file__).relative_to(REPO_ROOT),
@@ -408,11 +456,12 @@ def main() -> int:
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)"
+ f"conferring authority across {counts['writes']} write(s), {counts['decisions']} grant decision(s), "
+ f"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:
+ if counts["modules"] == 0 or counts["roles"] == 0 or counts["writes"] == 0 or counts["decisions"] == 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.",
@@ -426,7 +475,10 @@ def main() -> int:
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.")
+ print(
+ "OK: every role-conferring route reaches app.core.role_grants, every grant is measured against the "
+ "authority its caller was admitted on, and the grantable vocabulary excludes the wildcard."
+ )
return 0
diff --git a/services/api/app/api/v1/endpoints/api_keys.py b/services/api/app/api/v1/endpoints/api_keys.py
index 3bdedcb4b..997b4df03 100644
--- a/services/api/app/api/v1/endpoints/api_keys.py
+++ b/services/api/app/api/v1/endpoints/api_keys.py
@@ -96,6 +96,7 @@ def _authorize_scopes(scopes: list[str], current_user: AuthUser) -> None:
authorize_permission_grant(
granter_role=current_user.role,
granter_scopes=current_user.scopes,
+ granter_permissions=current_user.resolved_permissions,
requested=scopes,
subject="API key scope(s)",
)
diff --git a/services/api/app/api/v1/endpoints/mssp.py b/services/api/app/api/v1/endpoints/mssp.py
index a7bac7690..9c5cdbeb4 100644
--- a/services/api/app/api/v1/endpoints/mssp.py
+++ b/services/api/app/api/v1/endpoints/mssp.py
@@ -297,6 +297,7 @@ async def create_delegation(
granted_role = authorize_role_grant(
granter_role=current_user.role,
granter_scopes=current_user.scopes,
+ granter_permissions=current_user.resolved_permissions,
requested_role=body.granted_role,
)
except RoleGrantDenied as exc:
diff --git a/services/api/app/api/v1/endpoints/rbac.py b/services/api/app/api/v1/endpoints/rbac.py
index 669e5169b..797086db0 100644
--- a/services/api/app/api/v1/endpoints/rbac.py
+++ b/services/api/app/api/v1/endpoints/rbac.py
@@ -41,6 +41,7 @@ def _authorize_permission_grant(permissions: list[Permission], current_user: Aut
authorize_permission_grant(
granter_role=current_user.role,
granter_scopes=current_user.scopes,
+ granter_permissions=current_user.resolved_permissions,
requested=[p.name for p in permissions],
subject=subject,
)
diff --git a/services/api/app/api/v1/endpoints/sso_connections.py b/services/api/app/api/v1/endpoints/sso_connections.py
index d0a78150b..2e6c8742f 100644
--- a/services/api/app/api/v1/endpoints/sso_connections.py
+++ b/services/api/app/api/v1/endpoints/sso_connections.py
@@ -129,6 +129,7 @@ def _assert_roles_grantable(caller: AuthUser, body: SsoConnectionIn) -> None:
role_grants.authorize_role_grant(
granter_role=getattr(caller, "role", "viewer"),
granter_scopes=getattr(caller, "scopes", None),
+ granter_permissions=getattr(caller, "resolved_permissions", None),
requested_role=role,
)
except role_grants.RoleGrantDenied as denied:
diff --git a/services/api/app/api/v1/endpoints/tenants.py b/services/api/app/api/v1/endpoints/tenants.py
index 87eff034e..cd50d4553 100644
--- a/services/api/app/api/v1/endpoints/tenants.py
+++ b/services/api/app/api/v1/endpoints/tenants.py
@@ -221,6 +221,7 @@ async def create_user(
granted_role = authorize_role_grant(
granter_role=current_user.role,
granter_scopes=current_user.scopes,
+ granter_permissions=current_user.resolved_permissions,
requested_role=request.role,
)
except RoleGrantDenied as exc:
@@ -279,6 +280,7 @@ async def update_user(
updates["role"] = authorize_role_change(
granter_role=current_user.role,
granter_scopes=current_user.scopes,
+ granter_permissions=current_user.resolved_permissions,
current_role=str(user.role),
requested_role=updates["role"],
)
diff --git a/services/api/app/core/role_grants.py b/services/api/app/core/role_grants.py
index b073340f3..2930dfb96 100644
--- a/services/api/app/core/role_grants.py
+++ b/services/api/app/core/role_grants.py
@@ -50,7 +50,7 @@ and :data:`NEVER_GRANTABLE` from here and the vocabularies are the same object.
from __future__ import annotations
-from collections.abc import Iterable, Sequence
+from collections.abc import Collection, Iterable, Sequence
from typing import Any, Final
from app.core.security import ROLE_PERMISSIONS
@@ -127,17 +127,40 @@ def holds_wildcard(role: str) -> bool:
return WILDCARD in ROLE_PERMISSIONS.get(role, [])
-def _granter_permissions(granter_role: str, granter_scopes: Sequence[str] | None) -> frozenset[str]:
+def _granter_permissions(
+ granter_role: str,
+ granter_scopes: Sequence[str] | None,
+ granter_permissions: Collection[str] | None = 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.
+ The three branches below are the three tiers ``CurrentUser`` documents,
+ in its order, and they have to stay in its order: whatever admitted a
+ caller through the door is the only honest measure of what that caller
+ may confer. Any disagreement between the two is an escalation in
+ whichever direction the grant path is more generous.
+
+ *scopes* — an API-key principal's authority is its ``scopes`` list, not
+ the role of the user who minted it. Reading the role here would let a key
+ with two read scopes, owned by a ``tenant_admin``, grant everything
+ ``tenant_admin`` holds.
+
+ *resolved permissions* — what the RBAC tables grant, which
+ ``require_permission`` prefers over the static map for any principal with
+ rows. Omitting this tier was GHSA-4gx4-x7gm-4xq8: a ``tenant_admin``
+ deliberately narrowed to ``users:write`` in ``user_roles`` was admitted on
+ that one permission and then measured against the 28 its static role
+ carries, so it could confer the other 27 on itself and resolve them on its
+ next request.
+
+ *static role* — the fallback, and only when nothing resolved a set. A
+ tenant that never adopted database-backed roles has no rows to read, and
+ must keep conferring exactly what its role confers.
"""
if granter_scopes is not None:
return frozenset(granter_scopes)
+ if granter_permissions is not None:
+ return frozenset(granter_permissions)
return permissions_for(granter_role)
@@ -182,6 +205,7 @@ def authorize_role_grant(
granter_role: str,
requested_role: str,
granter_scopes: Sequence[str] | None = None,
+ granter_permissions: Collection[str] | None = None,
) -> str:
"""Return ``requested_role`` if this caller may confer it, else raise.
@@ -201,7 +225,7 @@ def authorize_role_grant(
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)
+ held = _granter_permissions(granter_role, granter_scopes, granter_permissions)
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)})")
@@ -213,6 +237,7 @@ def authorize_permission_grant(
granter_role: str,
requested: Sequence[str],
granter_scopes: Sequence[str] | None = None,
+ granter_permissions: Collection[str] | None = None,
subject: str = "permissions",
) -> list[str]:
"""Return ``requested`` if this caller may confer every one of them, else raise.
@@ -225,7 +250,7 @@ def authorize_permission_grant(
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)
+ held = _granter_permissions(granter_role, granter_scopes, granter_permissions)
missing = missing_permissions(held, requested)
if missing:
raise RoleGrantDenied(f"Cannot grant {subject} you do not hold: {', '.join(missing)}")
@@ -238,6 +263,7 @@ def authorize_role_change(
current_role: str,
requested_role: str,
granter_scopes: Sequence[str] | None = None,
+ granter_permissions: Collection[str] | None = None,
) -> str:
"""Authorize re-roling an existing principal.
@@ -256,6 +282,7 @@ def authorize_role_change(
granter_role=granter_role,
requested_role=requested_role,
granter_scopes=granter_scopes,
+ granter_permissions=granter_permissions,
)
diff --git a/services/api/tests/test_role_grant_effective_permissions.py b/services/api/tests/test_role_grant_effective_permissions.py
new file mode 100644
index 000000000..6f946cad2
--- /dev/null
+++ b/services/api/tests/test_role_grant_effective_permissions.py
@@ -0,0 +1,396 @@
+"""GHSA-4gx4-x7gm-4xq8: a grant check reading a different authority than the door.
+
+`CurrentUser` documents three tiers, in this order: API-key scopes, the
+database-backed RBAC tables, then the static `ROLE_PERMISSIONS` map.
+`require_permission` implements all three. `_granter_permissions` — what every
+grant route consults to decide whether the caller may confer something —
+implemented the first and the third.
+
+So a principal whose effective permissions came from the middle tier was
+admitted through the door on its *database* permissions and then had its grant
+measured against its *static* role. A `tenant_admin` deliberately restricted to
+`users:write` in `user_roles` holds 28 permissions statically, which is 27 it
+can confer on itself and then resolve on its next request.
+
+The reporter (HaiND, https://github.com/Haind03) named
+`POST /api/v1/rbac/users/{user_id}/roles`. The resolver is shared, so the same
+caller reaches it through six more: authoring a role, re-permissioning one,
+minting an API key, creating a user, delegating to a child tenant, and mapping
+an SSO group. The API-key route is the one worth noting — it needs no target
+user and yields a durable credential.
+
+**Nothing here imports `app.core.role_grants`.** A test that asserts on the
+fix's own symbols passes vacuously on a tree that never had the defect. These
+drive the shipped handlers with a restricted principal and assert the grant is
+refused, so against the pre-fix tree they fail because it *succeeded*. Every
+route is asserted in both directions: the escalating grant is refused and no
+row is written, and a grant inside the caller's effective permissions 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 _restricted(*held: str, role: str = "tenant_admin") -> CurrentUser:
+ """A principal admitted by the database tier, not by its static role.
+
+ This is the shape the advisory turns on: `role` is broad because the
+ column was never narrowed, and `resolved_permissions` is what the tenant
+ administrator actually granted. `require_permission` reads the latter.
+ """
+ return CurrentUser(
+ user_id=uuid.uuid4(),
+ tenant_id=TENANT,
+ role=role,
+ resolved_permissions=frozenset(held),
+ )
+
+
+class _Permission:
+ """A permission row good enough to build `PermissionOut` from.
+
+ A `MagicMock` would satisfy the grant check and then fail response
+ validation on `description`/`category`, so the pre-fix run would error
+ *after* the escalation instead of asserting on it — which reads like a
+ broken double rather than a caught defect.
+ """
+
+ def __init__(self, name: str) -> None:
+ self.id = uuid.uuid4()
+ self.name = name
+ self.description = f"permission {name}"
+ self.category = name.split(":")[0]
+
+
+class _Role:
+ """Likewise for `RoleOut`."""
+
+ def __init__(self, name: str, *, is_system: bool = False) -> None:
+ self.id = uuid.uuid4()
+ self.tenant_id = TENANT
+ self.name = name
+ self.description = f"role {name}"
+ self.is_system = is_system
+
+
+def _permission(name: str) -> _Permission:
+ return _Permission(name)
+
+
+def _rbac_db(*, scalars_queue: list[Any], permissions: list[Any] | None = None) -> AsyncMock:
+ """A session whose single-row reads pop a queue and whose writes are visible."""
+ db = AsyncMock()
+ db.add = MagicMock()
+ db.commit = AsyncMock()
+ pending = list(scalars_queue)
+
+ async def _refresh(obj: Any) -> None:
+ # Stands in for the server-side defaults a real flush would populate,
+ # so a handler that *should* have refused runs all the way to its
+ # response model and fails on the assertion instead of on validation.
+ for field, value in (
+ ("id", uuid.uuid4()),
+ ("created_at", datetime.now(UTC)),
+ ("is_active", True),
+ ("last_login", 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)
+
+ 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 and looking like a catch.
+ 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 or [])))
+ db.execute = AsyncMock(return_value=result)
+ return db
+
+
+def _key_db() -> AsyncMock:
+ db = AsyncMock()
+ db.add = MagicMock()
+ db.commit = AsyncMock()
+ db.flush = AsyncMock()
+
+ async def _refresh(obj: Any) -> None:
+ for field, value in (
+ ("id", uuid.uuid4()),
+ ("created_at", datetime.now(UTC)),
+ ("is_active", True),
+ ("expires_at", None),
+ ("last_used_at", None),
+ ("revoked_at", None),
+ ):
+ if getattr(obj, field, None) is None:
+ obj.id = value if field == "id" else getattr(obj, "id", None)
+ try:
+ setattr(obj, field, value)
+ except (AttributeError, ValueError): # pragma: no cover - ORM guard
+ pass
+
+ db.refresh = AsyncMock(side_effect=_refresh)
+ result = MagicMock()
+ result.scalar_one_or_none = MagicMock(return_value=None)
+ result.scalars = MagicMock(return_value=MagicMock(all=MagicMock(return_value=[])))
+ db.execute = AsyncMock(return_value=result)
+ 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/rbac/users/{user_id}/roles — the reported route
+# ---------------------------------------------------------------------------
+
+
+class TestAssignRole:
+ async def test_a_restricted_caller_cannot_attach_a_broader_role_to_itself(self) -> None:
+ """The reported path, verbatim: the caller is the target.
+
+ `users:write` opens the route, and before the fix the role it attached
+ was measured against the static `tenant_admin` map rather than the one
+ permission the tenant administrator left it.
+ """
+ caller = _restricted("users:write")
+ role = _Role("case-manager")
+ target = MagicMock(id=caller.user_id, tenant_id=TENANT)
+ db = _rbac_db(
+ scalars_queue=[role, target, None],
+ permissions=[_permission("alerts:write"), _permission("cases:write")],
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await rbac_mod.assign_role(
+ user_id=caller.user_id,
+ body=rbac_mod.UserRoleAssignment(user_id=caller.user_id, role_id=role.id),
+ current_user=caller,
+ db=db,
+ )
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db), "the refused assignment still wrote a user_roles row"
+
+ async def test_the_same_grant_to_another_user_is_refused_too(self) -> None:
+ """Self-assignment is the clearest story, not the boundary.
+
+ Conferring on a colleague what you cannot hold is the same escalation
+ with one extra step, so a fix that only rejected `user_id == caller`
+ would leave it open.
+ """
+ caller = _restricted("users:write")
+ role = _Role("case-manager")
+ colleague = MagicMock(id=uuid.uuid4(), tenant_id=TENANT)
+ db = _rbac_db(scalars_queue=[role, colleague, None], permissions=[_permission("cases:write")])
+
+ with pytest.raises(HTTPException) as exc:
+ await rbac_mod.assign_role(
+ user_id=colleague.id,
+ body=rbac_mod.UserRoleAssignment(user_id=colleague.id, role_id=role.id),
+ current_user=caller,
+ db=db,
+ )
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db)
+
+ async def test_a_role_inside_the_callers_effective_permissions_still_attaches(self) -> None:
+ """The positive direction. A restricted caller is not a refused one."""
+ caller = _restricted("users:write", "cases:write")
+ role = _Role("case-reader")
+ target = MagicMock(id=uuid.uuid4(), tenant_id=TENANT)
+ db = _rbac_db(scalars_queue=[role, target, None], permissions=[_permission("cases:write")])
+
+ out = await rbac_mod.assign_role(
+ user_id=target.id,
+ body=rbac_mod.UserRoleAssignment(user_id=target.id, role_id=role.id),
+ current_user=caller,
+ db=db,
+ )
+
+ assert out.role_name == "case-reader"
+ assert db.add.call_args_list, "a legitimate grant was refused"
+
+ async def test_a_principal_with_no_resolved_set_still_uses_the_static_map(self) -> None:
+ """Tier three is a fallback, not a casualty.
+
+ A tenant with no RBAC rows resolves `None`, and that principal must
+ keep conferring exactly what its role confers — otherwise the fix
+ locks out every deployment that never adopted database-backed roles.
+ """
+ caller = CurrentUser(
+ user_id=uuid.uuid4(),
+ tenant_id=TENANT,
+ role="tenant_admin",
+ )
+ role = _Role("triage")
+ target = MagicMock(id=uuid.uuid4(), tenant_id=TENANT)
+ db = _rbac_db(scalars_queue=[role, target, None], permissions=[_permission("alerts:write")])
+
+ out = await rbac_mod.assign_role(
+ user_id=target.id,
+ body=rbac_mod.UserRoleAssignment(user_id=target.id, role_id=role.id),
+ current_user=caller,
+ db=db,
+ )
+
+ assert out.role_name == "triage"
+
+
+# ---------------------------------------------------------------------------
+# The six further routes sharing the resolver
+# ---------------------------------------------------------------------------
+
+
+class TestRoleAuthoring:
+ async def test_authoring_a_role_beyond_the_effective_set_is_refused(self) -> None:
+ """Authoring and attaching are one escalation in two requests.
+
+ Refusing only the attachment leaves the caller able to build the role
+ and wait for anyone else to attach it.
+ """
+ caller = _restricted("roles:write")
+ perm = _permission("playbooks:write")
+ db = _rbac_db(scalars_queue=[None], permissions=[perm])
+
+ with pytest.raises(HTTPException) as exc:
+ await rbac_mod.create_role(
+ body=rbac_mod.RoleIn(name="playbook-ops", permission_ids=[perm.id]),
+ current_user=caller,
+ db=db,
+ )
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db), "the refused request still created the role row"
+
+ async def test_re_permissioning_an_existing_role_is_refused(self) -> None:
+ """`PUT` reaches the same end state as `POST` with the name reused."""
+ caller = _restricted("roles:write")
+ role = _Role("triage")
+ perm = _permission("playbooks:write")
+ db = _rbac_db(scalars_queue=[role], permissions=[perm])
+
+ with pytest.raises(HTTPException) as exc:
+ await rbac_mod.update_role(
+ role_id=role.id,
+ body=rbac_mod.RoleUpdate(permission_ids=[perm.id]),
+ current_user=caller,
+ db=db,
+ )
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db)
+
+
+class TestApiKeyScopes:
+ async def test_a_restricted_caller_cannot_mint_a_key_beyond_its_effective_set(self) -> None:
+ """No target user, and the result is a durable bearer credential.
+
+ This route needs nothing but the caller, so it is the cheapest of the
+ seven to reach and the one whose output outlives the session.
+ """
+ caller = _restricted("users:write")
+ db = _key_db()
+
+ with pytest.raises(HTTPException) as exc:
+ await api_keys_mod.create_api_key(
+ body=api_keys_mod.CreateApiKeyRequest(name="exfil", scopes=["alerts:write", "cases:write"]),
+ current_user=caller,
+ db=db,
+ )
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db), "the refused request still persisted a key"
+
+ async def test_a_key_within_the_effective_set_is_still_minted(self) -> None:
+ caller = _restricted("users:write", "alerts:read")
+ db = _key_db()
+
+ out = await api_keys_mod.create_api_key(
+ body=api_keys_mod.CreateApiKeyRequest(name="reader", scopes=["alerts:read"]),
+ current_user=caller,
+ db=db,
+ )
+
+ assert out is not None
+ assert db.add.call_args_list, "a legitimate key was refused"
+
+
+class TestUserCreation:
+ async def test_a_restricted_caller_cannot_create_a_user_holding_more(self) -> None:
+ """The static-role door onto the same escalation.
+
+ `soc_analyst` is inside `tenant_admin`'s static map, so before the fix
+ a caller left with only `users:write` could seat a colleague — or a
+ second account of its own — holding the analyst set.
+ """
+ caller = _restricted("users:write")
+ db = _rbac_db(scalars_queue=[None])
+
+ with pytest.raises(HTTPException) as exc:
+ await tenants_mod.create_user(
+ request=tenants_mod.CreateUserRequest(
+ username="second",
+ password="AnotherLongPassword2!",
+ role="soc_analyst",
+ ),
+ current_user=caller,
+ db=db,
+ )
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db)
+
+
+class TestDelegationAndSso:
+ async def test_a_delegation_cannot_name_a_role_beyond_the_effective_set(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ caller = _restricted("mssp:write")
+ db = _rbac_db(scalars_queue=[None])
+ monkeypatch.setattr(mssp_mod, "_require_own_child", AsyncMock())
+ body = MagicMock(child_tenant_id=uuid.uuid4(), granted_role="soc_analyst", expires_at=None)
+
+ with pytest.raises(HTTPException) as exc:
+ await mssp_mod.create_delegation(body=body, db=db, current_user=caller)
+
+ assert exc.value.status_code == 403
+ assert not _wrote(db)