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(api): wire eleven discarded require_permission dependencies (#1050)

Beenu Aroraf5e9db74ddc2
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index eeb13dcb1..c7ee8268c 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -109,6 +109,24 @@ paths:
security:
- HTTPBearer: []
/api/v1/api-keys:
+ get:
+ tags:
+ - api-keys
+ summary: List Api Keys
+ description: List all API keys for the current tenant (raw keys are never returned).
+ operationId: list_api_keys_api_v1_api_keys_get
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ items:
+ $ref: '#/components/schemas/ApiKeyOut'
+ type: array
+ title: Response List Api Keys Api V1 Api Keys Get
+ security:
+ - HTTPBearer: []
post:
tags:
- api-keys
@@ -118,18 +136,12 @@ paths:
The raw key value is returned **only once** in this response.'
operationId: create_api_key_api_v1_api_keys_post
- parameters:
- - name: current_user
- in: query
- required: true
- schema:
- title: Current User
requestBody:
- required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateApiKeyRequest'
+ required: true
responses:
'201':
description: Successful Response
@@ -143,24 +155,8 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
- get:
- tags:
- - api-keys
- summary: List Api Keys
- description: List all API keys for the current tenant (raw keys are never returned).
- operationId: list_api_keys_api_v1_api_keys_get
security:
- HTTPBearer: []
- responses:
- '200':
- description: Successful Response
- content:
- application/json:
- schema:
- type: array
- items:
- $ref: '#/components/schemas/ApiKeyOut'
- title: Response List Api Keys Api V1 Api Keys Get
/api/v1/api-keys/{key_id}:
get:
tags:
@@ -197,6 +193,8 @@ paths:
summary: Update Api Key
description: Update an API key's name, scopes, or expiry.
operationId: update_api_key_api_v1_api_keys__key_id__patch
+ security:
+ - HTTPBearer: []
parameters:
- name: key_id
in: path
@@ -205,11 +203,6 @@ paths:
type: string
format: uuid
title: Key Id
- - name: current_user
- in: query
- required: true
- schema:
- title: Current User
requestBody:
required: true
content:
@@ -236,6 +229,8 @@ paths:
description: Revoke (deactivate) an API key. The key can no longer be used for
authentication.
operationId: revoke_api_key_api_v1_api_keys__key_id__delete
+ security:
+ - HTTPBearer: []
parameters:
- name: key_id
in: path
@@ -244,11 +239,6 @@ paths:
type: string
format: uuid
title: Key Id
- - name: current_user
- in: query
- required: true
- schema:
- title: Current User
responses:
'204':
description: Successful Response
@@ -2621,12 +2611,9 @@ paths:
can run the same check the test runs, against their own rows.'
operationId: get_reconciliation_api_v1_usage_reconciliation_get
+ security:
+ - HTTPBearer: []
parameters:
- - name: current_user
- in: query
- required: true
- schema:
- title: Current User
- name: start
in: query
required: false
@@ -2666,12 +2653,9 @@ paths:
description: A month of usage as CSV, labelled with the organisation it belongs
to.
operationId: export_month_api_v1_usage_export_csv_get
+ security:
+ - HTTPBearer: []
parameters:
- - name: current_user
- in: query
- required: true
- schema:
- title: Current User
- name: month
in: query
required: false
@@ -6945,43 +6929,37 @@ paths:
analyst looking at a differently-branded product from their colleague.'
operationId: get_branding_api_v1_branding_get
- security:
- - HTTPBearer: []
responses:
'200':
description: Successful Response
content:
application/json:
schema:
- type: object
additionalProperties: true
+ type: object
title: Response Get Branding Api V1 Branding Get
+ security:
+ - HTTPBearer: []
put:
tags:
- branding
summary: Put Branding
description: Set branding for the organisation the caller's tenant belongs to.
operationId: put_branding_api_v1_branding_put
- parameters:
- - name: current_user
- in: query
- required: true
- schema:
- title: Current User
requestBody:
- required: true
content:
application/json:
schema:
$ref: '#/components/schemas/BrandingIn'
+ required: true
responses:
'200':
description: Successful Response
content:
application/json:
schema:
- type: object
additionalProperties: true
+ type: object
title: Response Put Branding Api V1 Branding Put
'422':
description: Validation Error
@@ -6989,6 +6967,8 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
/api/v1/branding/assets/{kind}:
post:
tags:
@@ -7003,6 +6983,8 @@ paths:
writer and the stored bytes are trusted thereafter.'
operationId: upload_asset_api_v1_branding_assets__kind__post
+ security:
+ - HTTPBearer: []
parameters:
- name: kind
in: path
@@ -7010,11 +6992,6 @@ paths:
schema:
type: string
title: Kind
- - name: current_user
- in: query
- required: true
- schema:
- title: Current User
requestBody:
required: true
content:
@@ -7042,6 +7019,8 @@ paths:
summary: Delete Asset
description: Remove an asset, returning that surface to the wordmark.
operationId: delete_asset_api_v1_branding_assets__kind__delete
+ security:
+ - HTTPBearer: []
parameters:
- name: kind
in: path
@@ -7049,11 +7028,6 @@ paths:
schema:
type: string
title: Kind
- - name: current_user
- in: query
- required: true
- schema:
- title: Current User
responses:
'204':
description: Successful Response
@@ -9667,36 +9641,30 @@ paths:
summary: List Scim Tokens
description: List this tenant's SCIM credentials. Secrets are never returned.
operationId: list_scim_tokens_api_v1_scim_tokens_get
- security:
- - HTTPBearer: []
responses:
'200':
description: Successful Response
content:
application/json:
schema:
- type: array
items:
$ref: '#/components/schemas/ScimTokenOut'
+ type: array
title: Response List Scim Tokens Api V1 Scim Tokens Get
+ security:
+ - HTTPBearer: []
post:
tags:
- scim
summary: Create Scim Token
description: Mint a SCIM credential for this tenant.
operationId: create_scim_token_api_v1_scim_tokens_post
- parameters:
- - name: current_user
- in: query
- required: true
- schema:
- title: Current User
requestBody:
- required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateScimTokenRequest'
+ required: true
responses:
'201':
description: Successful Response
@@ -9710,6 +9678,8 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
/api/v1/scim-tokens/{token_id}/rotate:
post:
tags:
@@ -9717,6 +9687,8 @@ paths:
summary: Rotate Scim Token
description: Replace a credential, leaving the old one working for a grace window.
operationId: rotate_scim_token_api_v1_scim_tokens__token_id__rotate_post
+ security:
+ - HTTPBearer: []
parameters:
- name: token_id
in: path
@@ -9725,11 +9697,6 @@ paths:
type: string
format: uuid
title: Token Id
- - name: current_user
- in: query
- required: true
- schema:
- title: Current User
requestBody:
required: true
content:
@@ -9763,6 +9730,8 @@ paths:
through it.'
operationId: revoke_scim_token_api_v1_scim_tokens__token_id__delete
+ security:
+ - HTTPBearer: []
parameters:
- name: token_id
in: path
@@ -9771,11 +9740,6 @@ paths:
type: string
format: uuid
title: Token Id
- - name: current_user
- in: query
- required: true
- schema:
- title: Current User
responses:
'204':
description: Successful Response
diff --git a/scripts/check_route_authz.py b/scripts/check_route_authz.py
index b942a7483..8f351121b 100644
--- a/scripts/check_route_authz.py
+++ b/scripts/check_route_authz.py
@@ -119,6 +119,12 @@ def _authorizing_names(tree: ast.Module) -> set[str]:
for node in ast.walk(tree):
# Alias assignments: NAME = Annotated[..., Depends(require_permission(...))]
if isinstance(node, ast.Assign):
+ # An alias can carry the discarded shape too, and then every route
+ # using it is credited for a permission FastAPI never calls. The
+ # alias is the worse place for it: one edit silently disarms a
+ # whole module.
+ if _discarded_in_annotation(node.value):
+ continue
if any(_calls_authz(node.value)):
for target in node.targets:
if isinstance(target, ast.Name):
@@ -153,8 +159,54 @@ def _calls_authz(node: ast.AST) -> list[str]:
return found
+def _discarded_in_annotation(annotation: ast.expr | None) -> list[str]:
+ """``require_permission(...)`` sitting in ``Annotated`` metadata unwrapped.
+
+ ``Annotated[Any, require_permission("users:write")]`` has no ``Depends()``.
+ FastAPI honours only ``Annotated`` metadata that is a ``Depends`` or a
+ ``FieldInfo`` and silently drops everything else, so the permission is
+ never checked and the parameter degrades into a query parameter. Eleven
+ routes across four modules shipped like this, and they read as gated —
+ which is worse than an obviously missing dependency, because a reviewer,
+ `_authorizing_names` and the ratchet all count them as authorizing.
+ """
+ if not isinstance(annotation, ast.Subscript):
+ return []
+ base = annotation.value
+ if (getattr(base, "id", None) or getattr(base, "attr", None)) != "Annotated":
+ return []
+ metadata = annotation.slice.elts[1:] if isinstance(annotation.slice, ast.Tuple) else []
+ found: list[str] = []
+ for item in metadata:
+ if isinstance(item, ast.Call):
+ name = item.func.attr if isinstance(item.func, ast.Attribute) else getattr(item.func, "id", None)
+ if name == "require_permission":
+ found.append(ast.unparse(item))
+ return found
+
+
+def find_discarded_permissions(fn: ast.FunctionDef | ast.AsyncFunctionDef) -> list[tuple[str, str]]:
+ """Discarded permissions in *fn*'s own signature.
+
+ Reported rather than folded into the ratchet because the ceiling is a debt
+ balance and this is not debt. There is no correct reason to write it, so
+ it has no ceiling: one occurrence fails the gate.
+ """
+ return [
+ (arg.arg, source)
+ for arg in [*fn.args.posonlyargs, *fn.args.args, *fn.args.kwonlyargs]
+ for source in _discarded_in_annotation(arg.annotation)
+ ]
+
+
def _route_authorizes(fn: ast.FunctionDef | ast.AsyncFunctionDef, authorizing: set[str]) -> bool:
"""True when this handler makes an authorization decision."""
+ # A permission that FastAPI discards is not an authorization decision,
+ # whatever it looks like. Checked first because `_calls_authz` below walks
+ # the argument subtree and would match the call itself, crediting the
+ # route for enforcement that never happens.
+ if find_discarded_permissions(fn):
+ return False
# In the signature: Depends(require_permission("x")), or an alias of one.
if _calls_authz(fn.args):
return True
@@ -175,6 +227,32 @@ def _names_used(node: ast.AST) -> set[str]:
return {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
+def collect_discarded(root: Path | None = None) -> list[str]:
+ """Every ``require_permission`` in the tree that FastAPI will never call.
+
+ Not restricted to state-changing routes: two of the eleven found were on
+ reads, and a read permission that enforces nothing is the same bug with a
+ smaller blast radius.
+ """
+ base = root or route_scan.REPO_ROOT
+ out: list[str] = []
+ for path in sorted((base / "services" / SERVICE / "app" / "api").rglob("*.py")):
+ try:
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ except (SyntaxError, UnicodeDecodeError): # pragma: no cover - not ours to fix
+ continue
+ shown = path.relative_to(base)
+ for node in ast.walk(tree):
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
+ for parameter, source in find_discarded_permissions(node):
+ out.append(f"{shown}:{node.lineno} {node.name}() parameter '{parameter}' annotates {source} with no Depends()")
+ elif isinstance(node, ast.Assign):
+ for source in _discarded_in_annotation(node.value):
+ alias = ", ".join(t.id for t in node.targets if isinstance(t, ast.Name)) or "<alias>"
+ out.append(f"{shown}:{node.lineno} alias '{alias}' annotates {source} with no Depends()")
+ return out
+
+
def collect(root: Path | None = None) -> list[RouteVerdict]:
"""Every state-changing route in ``services/api``, with its authz verdict."""
base = root or route_scan.REPO_ROOT
@@ -250,9 +328,10 @@ def main(argv: list[str] | None = None) -> int:
return 2
ungated = [r for r in rows if not r["authorized"]]
+ discarded = collect_discarded()
if args.json:
- print(json.dumps({"total": len(rows), "unauthorized": len(ungated), "routes": ungated}, indent=2))
+ print(json.dumps({"total": len(rows), "unauthorized": len(ungated), "discarded": discarded, "routes": ungated}, indent=2))
return 0
if args.inventory:
@@ -269,6 +348,19 @@ def main(argv: list[str] | None = None) -> int:
print(f"state-changing routes in services/{SERVICE}: {len(rows)}")
print(f" authorize: {len(rows) - len(ungated)}")
print(f" identity only: {len(ungated)} (ceiling {args.max_unauthorized})")
+ print(f" discarded perms: {len(discarded)} (ceiling 0)")
+
+ # No ceiling, and no exemptions: there is no correct reason to write a
+ # permission where FastAPI cannot see it. Reported separately from the
+ # ratchet so the diagnostic names the actual mistake — the permission is
+ # present and spelled correctly, it is simply not wired to anything.
+ if discarded:
+ print(f"\nFAIL: {len(discarded)} permission(s) declared as Annotated metadata with no Depends().")
+ print("FastAPI honours only Depends/FieldInfo metadata and drops the rest, so these are never checked")
+ print("and the parameter becomes a query parameter. Write Annotated[AuthUser, Depends(require_permission('x'))].")
+ for line in discarded:
+ print(f" {line}")
+ return 1
# Forward: the debt may not grow.
if len(ungated) > args.max_unauthorized:
@@ -324,12 +416,39 @@ def _self_test() -> int:
after = [r for r in collect(scratch) if not r["authorized"]]
- gained = len(after) - len(before)
- if gained != 3:
- print(f"FAIL: removing authorization from remediation.py's 3 write routes changed the count by {gained}, not 3")
- return 1
+ gained = len(after) - len(before)
+ if gained != 3:
+ print(f"FAIL: removing authorization from remediation.py's 3 write routes changed the count by {gained}, not 3")
+ return 1
+
+ # Second defect: the permission is still there and still correct, but
+ # written where FastAPI never reads it. Unwrapping `Depends` is the
+ # exact edit that produced the eleven shipped instances.
+ (scratch / target).write_text(original, encoding="utf-8")
+ if collect_discarded(scratch):
+ print("FAIL: self-test baseline already reports discarded permissions; the scratch tree is not clean")
+ return 2
- print(f"self-test OK: identity-only routes {len(before)} -> {len(after)} when remediation.py's permissions are removed")
+ unwrapped = original.replace("Depends(require_permission(_WRITE))", "require_permission(_WRITE)")
+ if unwrapped == original:
+ print("FAIL: self-test could not produce the discarded shape; remediation.py's dependency spelling changed")
+ return 2
+ (scratch / target).write_text(unwrapped, encoding="utf-8")
+
+ discarded = collect_discarded(scratch)
+ if len(discarded) != 1:
+ print(f"FAIL: unwrapping Depends() on the WriteUser alias was detected {len(discarded)} time(s), not 1")
+ return 1
+
+ # And it must stop crediting them, or the ratchet keeps counting a
+ # route as gated while it enforces nothing.
+ still_credited = [r for r in collect(scratch) if r["module"].endswith("remediation.py") and r["authorized"]]
+ if still_credited:
+ print(f"FAIL: {len(still_credited)} route(s) using a discarded alias are still counted as authorizing")
+ return 1
+
+ print(f"self-test OK: identity-only routes {len(before)} -> {len(after)} when remediation.py's permissions are removed;")
+ print("unwrapping Depends() on the WriteUser alias is reported once and stops crediting all 3 routes it gates")
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 7ec854136..a81d33911 100644
--- a/services/api/app/api/v1/endpoints/api_keys.py
+++ b/services/api/app/api/v1/endpoints/api_keys.py
@@ -26,9 +26,9 @@ from __future__ import annotations
import uuid
from datetime import UTC, datetime
-from typing import Annotated, Any
+from typing import Annotated
-from fastapi import APIRouter, HTTPException, status
+from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy import select
@@ -139,7 +139,7 @@ def _api_key_to_out(ak: ApiKey) -> ApiKeyOut:
async def create_api_key(
body: CreateApiKeyRequest,
db: DBSession,
- current_user: Annotated[Any, require_permission("users:write")],
+ current_user: Annotated[AuthUser, Depends(require_permission("users:write"))],
) -> CreateApiKeyResponse:
"""
Create a new scoped API key for the current tenant.
@@ -217,7 +217,7 @@ async def update_api_key(
key_id: uuid.UUID,
body: UpdateApiKeyRequest,
db: DBSession,
- current_user: Annotated[Any, require_permission("users:write")],
+ current_user: Annotated[AuthUser, Depends(require_permission("users:write"))],
) -> ApiKeyOut:
"""Update an API key's name, scopes, or expiry."""
result = await db.execute(select(ApiKey).where(ApiKey.id == key_id, ApiKey.tenant_id == current_user.tenant_id))
@@ -251,7 +251,7 @@ async def update_api_key(
async def revoke_api_key(
key_id: uuid.UUID,
db: DBSession,
- current_user: Annotated[Any, require_permission("users:write")],
+ current_user: Annotated[AuthUser, Depends(require_permission("users:write"))],
) -> None:
"""Revoke (deactivate) an API key. The key can no longer be used for authentication."""
result = await db.execute(select(ApiKey).where(ApiKey.id == key_id, ApiKey.tenant_id == current_user.tenant_id))
diff --git a/services/api/app/api/v1/endpoints/branding.py b/services/api/app/api/v1/endpoints/branding.py
index 5c21ac71a..fba520194 100644
--- a/services/api/app/api/v1/endpoints/branding.py
+++ b/services/api/app/api/v1/endpoints/branding.py
@@ -18,7 +18,7 @@ import uuid
from datetime import UTC, datetime
from typing import Annotated, Any
-from fastapi import APIRouter, File, HTTPException, Request, Response, UploadFile, status
+from fastapi import APIRouter, Depends, File, HTTPException, Request, Response, UploadFile, status
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select
@@ -104,7 +104,7 @@ async def put_branding(
body: BrandingIn,
db: DBSession,
request: Request,
- current_user: Annotated[Any, require_permission("settings:write")],
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
) -> dict[str, Any]:
"""Set branding for the organisation the caller's tenant belongs to."""
org_id = await _require_org(db, current_user.tenant_id)
@@ -139,7 +139,7 @@ async def upload_asset(
kind: str,
db: DBSession,
request: Request,
- current_user: Annotated[Any, require_permission("settings:write")],
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
file: Annotated[UploadFile, File()],
) -> dict[str, Any]:
"""Upload a logo or favicon.
@@ -274,7 +274,7 @@ async def delete_asset(
kind: str,
db: DBSession,
request: Request,
- current_user: Annotated[Any, require_permission("settings:write")],
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
) -> None:
"""Remove an asset, returning that surface to the wordmark."""
org_id = await _require_org(db, current_user.tenant_id)
diff --git a/services/api/app/api/v1/endpoints/scim_tokens.py b/services/api/app/api/v1/endpoints/scim_tokens.py
index 8a0db62b6..a294e4552 100644
--- a/services/api/app/api/v1/endpoints/scim_tokens.py
+++ b/services/api/app/api/v1/endpoints/scim_tokens.py
@@ -13,7 +13,7 @@ import uuid
from datetime import UTC, datetime, timedelta
from typing import Annotated, Any
-from fastapi import APIRouter, HTTPException, Request, status
+from fastapi import APIRouter, Depends, HTTPException, Request, status
from pydantic import BaseModel, Field
from sqlalchemy import select
@@ -96,7 +96,7 @@ async def create_scim_token(
body: CreateScimTokenRequest,
db: DBSession,
request: Request,
- current_user: Annotated[Any, require_permission("settings:write")],
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
) -> CreatedScimTokenOut:
"""Mint a SCIM credential for this tenant."""
expires_at = None
@@ -133,7 +133,7 @@ async def rotate_scim_token(
body: RotateScimTokenRequest,
db: DBSession,
request: Request,
- current_user: Annotated[Any, require_permission("settings:write")],
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
) -> CreatedScimTokenOut:
"""Replace a credential, leaving the old one working for a grace window."""
result = await db.execute(select(ScimToken).where(ScimToken.id == token_id, ScimToken.tenant_id == current_user.tenant_id))
@@ -171,7 +171,7 @@ async def revoke_scim_token(
token_id: uuid.UUID,
db: DBSession,
request: Request,
- current_user: Annotated[Any, require_permission("settings:write")],
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
) -> None:
"""Revoke a credential immediately.
diff --git a/services/api/app/api/v1/endpoints/usage.py b/services/api/app/api/v1/endpoints/usage.py
index da7140cd1..a9ffd9cd0 100644
--- a/services/api/app/api/v1/endpoints/usage.py
+++ b/services/api/app/api/v1/endpoints/usage.py
@@ -15,7 +15,7 @@ import uuid
from datetime import UTC, date, datetime, timedelta
from typing import Annotated, Any
-from fastapi import APIRouter, HTTPException, Query, Response, status
+from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy import select
from app.api.v1.deps import AuthUser, DBSession, require_permission
@@ -93,7 +93,7 @@ async def get_usage(
@router.get("/reconciliation")
async def get_reconciliation(
db: DBSession,
- current_user: Annotated[Any, require_permission("settings:read")],
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:read"))],
start: Annotated[str | None, Query()] = None,
end: Annotated[str | None, Query()] = None,
) -> dict[str, Any]:
@@ -117,7 +117,7 @@ async def get_reconciliation(
@router.get("/export.csv")
async def export_month(
db: DBSession,
- current_user: Annotated[Any, require_permission("reports:read")],
+ current_user: Annotated[AuthUser, Depends(require_permission("reports:read"))],
month: Annotated[str | None, Query(description="YYYY-MM; defaults to the current month")] = None,
) -> Response:
"""A month of usage as CSV, labelled with the organisation it belongs to."""
diff --git a/services/api/tests/test_discarded_permission_dependencies.py b/services/api/tests/test_discarded_permission_dependencies.py
new file mode 100644
index 000000000..2ab8aa031
--- /dev/null
+++ b/services/api/tests/test_discarded_permission_dependencies.py
@@ -0,0 +1,177 @@
+"""A permission that FastAPI never calls, on eleven routes across four modules.
+
+Found while closing GHSA-wj5c-88hg-5926, which was the same omission wearing
+no disguise: `remediation.py` authenticated and never authorized. These eleven
+*look* authorized. They are written
+
+ current_user: Annotated[Any, require_permission("users:write")]
+
+with no `Depends()`. FastAPI honours only `Annotated` metadata that is a
+`Depends` or a `FieldInfo` and silently drops the rest, so the permission is
+never checked and `current_user` degrades into a required query parameter.
+`POST /api-keys`, `PUT /branding` and `POST /scim-tokens` were all in this
+state — minting API keys and rotating SCIM tokens among them.
+
+This is the worse version of the bug. A reviewer reads the permission and
+moves on, and `scripts/check_route_authz.py` counted these routes among the
+143 that "authorize" because it matched the call and not the wiring.
+
+Asserted against the resolved dependency tree and against live requests rather
+than the source, because the source is exactly what is misleading here.
+"""
+
+from __future__ import annotations
+
+import uuid
+from typing import Any
+
+import pytest
+from app.api.v1.deps import CurrentUser
+from app.api.v1.endpoints import api_keys, branding, scim_tokens, usage
+from app.api.v1.endpoints.auth import get_current_user
+from app.core.security import ROLE_PERMISSIONS
+from app.db.database import get_db
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+#: Every route that carried a permission FastAPI discarded, and the permission
+#: it was meant to enforce.
+DISCARDED_ROUTES: list[tuple[Any, str, str]] = [
+ (api_keys, "create_api_key", "users:write"),
+ (api_keys, "update_api_key", "users:write"),
+ (api_keys, "revoke_api_key", "users:write"),
+ (branding, "put_branding", "settings:write"),
+ (branding, "upload_asset", "settings:write"),
+ (branding, "delete_asset", "settings:write"),
+ (scim_tokens, "create_scim_token", "settings:write"),
+ (scim_tokens, "rotate_scim_token", "settings:write"),
+ (scim_tokens, "revoke_scim_token", "settings:write"),
+ (usage, "get_reconciliation", "settings:read"),
+ (usage, "export_month", "reports:read"),
+]
+
+MODULES = [api_keys, branding, scim_tokens, usage]
+
+
+def _viewer() -> CurrentUser:
+ return CurrentUser(
+ user_id=uuid.uuid4(),
+ tenant_id=uuid.uuid4(),
+ role="viewer",
+ )
+
+
+def _route_for(module: Any, handler_name: str) -> Any:
+ handler = getattr(module, handler_name)
+ for route in module.router.routes:
+ if getattr(route, "endpoint", None) is handler:
+ return route
+ raise AssertionError(f"no route registered for {module.__name__}.{handler_name}")
+
+
+def _permissions_on(route: Any) -> list[str]:
+ """Permissions FastAPI will actually enforce, from the resolved tree.
+
+ `require_permission` returns a closure holding the permission string, so a
+ dependency that is really wired carries it here. Metadata FastAPI dropped
+ does not appear, which is the whole point: this reads what will run, not
+ what was written.
+ """
+ found: list[str] = []
+
+ def walk(dependant: Any) -> None:
+ call = getattr(dependant, "call", None)
+ for cell in getattr(call, "__closure__", None) or ():
+ try:
+ value = cell.cell_contents
+ except ValueError: # pragma: no cover - empty cell
+ continue
+ if isinstance(value, str) and ":" in value:
+ found.append(value)
+ for sub in getattr(dependant, "dependencies", []) or []:
+ walk(sub)
+
+ walk(route.dependant)
+ return found
+
+
+class TestThePermissionIsActuallyEnforced:
+ @pytest.mark.parametrize(("module", "handler", "permission"), DISCARDED_ROUTES, ids=[r[1] for r in DISCARDED_ROUTES])
+ def test_the_declared_permission_reaches_the_dependency_tree(self, module: Any, handler: str, permission: str) -> None:
+ enforced = _permissions_on(_route_for(module, handler))
+ assert permission in enforced, (
+ f"{module.__name__}.{handler} declares {permission!r} but FastAPI will enforce {enforced or 'nothing'}; "
+ f"the annotation is missing Depends()"
+ )
+
+ @pytest.mark.parametrize("module", MODULES, ids=[m.__name__.rsplit(".", 1)[-1] for m in MODULES])
+ def test_no_route_takes_the_principal_as_a_query_parameter(self, module: Any) -> None:
+ """The observable symptom, stated without reference to the cause.
+
+ When FastAPI drops the metadata it does not drop the parameter — with
+ no recognised dependency, `current_user` becomes an ordinary query
+ parameter. Any route asking the caller to *supply* their own principal
+ in the URL is broken however it came to be written.
+ """
+ for route in module.router.routes:
+ if not hasattr(route, "dependant"):
+ continue
+ supplied = [p.name for p in route.dependant.query_params if p.name in {"current_user", "user", "current_active_user"}]
+ assert not supplied, f"{module.__name__}{route.path} takes {supplied} from the query string"
+
+
+class TestAViewerIsRefused:
+ """The impact, asserted through a request rather than a signature.
+
+ Deliberately does not import any new symbol. A test that only imports
+ something the pre-fix tree lacks fails with ImportError, which proves the
+ symbol is absent rather than that the hole is closed. Everything here
+ exists on both trees, so the failure is the 200 itself.
+ """
+
+ @pytest.fixture
+ def client(self) -> TestClient:
+ app = FastAPI()
+ for module in MODULES:
+ app.include_router(module.router, prefix="/api/v1")
+ app.dependency_overrides[get_current_user] = _viewer
+ app.dependency_overrides[get_db] = lambda: None
+ return TestClient(app, raise_server_exceptions=False)
+
+ def test_the_viewer_role_holds_none_of_the_permissions_under_test(self) -> None:
+ """Without this the refusals below could pass for the wrong reason."""
+ held = set(ROLE_PERMISSIONS["viewer"])
+ required = {permission for _, _, permission in DISCARDED_ROUTES}
+ assert not (held & required - {"reports:read"}), f"viewer unexpectedly holds {held & required}"
+
+ @pytest.mark.parametrize(
+ ("method", "path"),
+ [
+ ("post", "/api/v1/api-keys"),
+ ("patch", f"/api/v1/api-keys/{uuid.uuid4()}"),
+ ("delete", f"/api/v1/api-keys/{uuid.uuid4()}"),
+ ("put", "/api/v1/branding"),
+ ("delete", "/api/v1/branding/assets/logo"),
+ ("post", "/api/v1/scim-tokens"),
+ ("delete", f"/api/v1/scim-tokens/{uuid.uuid4()}"),
+ ("get", "/api/v1/usage/reconciliation"),
+ ],
+ )
+ def test_a_read_only_token_cannot_reach_the_handler(self, client: TestClient, method: str, path: str) -> None:
+ # `request` rather than `client.get(...)`: the GET and DELETE helpers
+ # take no `json` argument, and the body is irrelevant to a 403 anyway.
+ response = client.request(method.upper(), path, json={})
+ assert response.status_code == 403, (
+ f"{method.upper()} {path} answered {response.status_code} for a viewer token. "
+ f"403 is the only acceptable answer; a 422 means the principal became a query parameter, "
+ f"and anything else means the handler was reached."
+ )
+
+ def test_an_authorised_role_is_not_refused(self, client: TestClient) -> None:
+ """A gate that refuses everyone would pass every test above."""
+ client.app.dependency_overrides[get_current_user] = lambda: CurrentUser(
+ user_id=uuid.uuid4(), tenant_id=uuid.uuid4(), role="tenant_admin", email="[email protected]"
+ )
+ response = client.put("/api/v1/branding", json={})
+ assert response.status_code != 403, "tenant_admin holds settings:write and must not be refused"