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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix: SQL injection in osquery allowlist, and missing authorization on remediation policy writes (#1048)
Beenu Arora0e3a38663765
diff --git a/.github/workflows/isolation.yml b/.github/workflows/isolation.ymlindex 1736142ac..acf3f37bf 100644--- a/.github/workflows/isolation.yml+++ b/.github/workflows/isolation.yml@@ -22,6 +22,7 @@ on:- "services/**"- "scripts/check_route_tenant_scope.py"- "scripts/check_route_auth.py"+ - "scripts/check_route_authz.py"- "scripts/check_route_shadowing.py"- "scripts/check_tenant_query_predicates.py"- "scripts/check_text_bind_casts.py"@@ -44,6 +45,7 @@ on:- "services/**"- "scripts/check_route_tenant_scope.py"- "scripts/check_route_auth.py"+ - "scripts/check_route_authz.py"- "scripts/check_route_shadowing.py"- "scripts/check_tenant_query_predicates.py"- "scripts/check_text_bind_casts.py"@@ -155,6 +157,19 @@ jobs:- name: Every route authenticates or records why it is publicrun: python scripts/check_route_auth.py+ # Authentication is not authorization. Every route in `remediation.py`+ # passed the gate above and a `viewer` could still raise the tenant's+ # autonomy tier to L4 and pre-approve a high blast-radius verb+ # (GHSA-wj5c-88hg-5926). This asks the other question.+ - name: Route-authz gate self-test (detects a removed permission)+ run: python scripts/check_route_authz.py --self-test++ - name: Identity-only write-route inventory+ run: python scripts/check_route_authz.py --inventory++ - name: State-changing routes that authorize do not decrease+ run: python scripts/check_route_authz.py+# A route can authenticate perfectly and still never run. `DELETE# /autonomy-policy/grants` sat behind `DELETE /{action}` from the day it# shipped, so an operator could earn an autonomy grant and had nodiff --git a/scripts/check_route_authz.py b/scripts/check_route_authz.pynew file mode 100644index 000000000..b942a7483--- /dev/null+++ b/scripts/check_route_authz.py@@ -0,0 +1,337 @@+#!/usr/bin/env python3+"""Ratchet: state-changing API routes that authenticate but never authorize.++``check_route_auth.py`` asks whether a route authenticates. That question was+answered "yes" for every route in ``remediation.py``, and a ``viewer`` could+still raise the tenant's autonomy tier to L4, pre-approve a high blast-radius+verb with no expiry, and suppress a containment verb mid-incident+(GHSA-wj5c-88hg-5926). Authentication had been standing in for authorization,+and the gate that would have noticed was asking the other question.++So this one asks: does a state-changing route make an *authorization* decision+at all? A route that only resolves an identity is counted, because "is this a+valid session?" is not "may this session do this?".++Why a count and not a list+--------------------------+The honest answer on the day this was written is that many routes are in this+state, and most are not defects — a handful are genuinely self-scoped (a+caller editing their own preferences, their own passkeys, their own on-call+status), and the rest need a per-route decision by someone who knows what the+route is for. Enumerating them here would be a list of things somebody once+found inconvenient, and it would be wrong within a week.++A ceiling is honest about that. It cannot rise: a new ungated route fails the+gate on the pull request that adds it. And it must not be *stale* either — if+the real count drops below the ceiling the gate fails too, demanding the+ceiling come down with it, so the number only ever moves toward zero.++``MAX_UNAUTHORIZED`` is not a target. It is a debt balance.++Usage::++ python scripts/check_route_authz.py # gate+ python scripts/check_route_authz.py --inventory # per-module table+ python scripts/check_route_authz.py --json+ python scripts/check_route_authz.py --self-test # prove it detects drift++Exit codes: 0 clean, 1 violations, 2 the scan itself could not run.+"""++from __future__ import annotations++import argparse+import ast+import json+import sys+from pathlib import Path+from typing import TypedDict++sys.path.insert(0, str(Path(__file__).resolve().parent))++# Imported as a module, not by name: `REPO_ROOT` is module state that the+# self-test rebinds to a scratch tree, and a from-import would copy the+# original at import time so this gate would go on scanning the real checkout+# while believing it was pointed somewhere else.+import check_route_tenant_scope as route_scan # noqa: E402+++class RouteVerdict(TypedDict):+ """One state-changing route and whether it authorizes.++ A TypedDict rather than a loose ``dict[str, object]`` so the fields the+ inventory sorts and joins on are typed where they are produced.+ """++ module: str+ function: str+ methods: list[str]+ route_path: str+ lineno: int+ authorized: bool+++#: Verbs that change state. GET and HEAD are out of scope: this gate is about+#: who may *write*, and read authorization is a different (real) question with+#: a different answer per route. Lower-case because the shared scanner records+#: the decorator attribute (``@router.post``) rather than the HTTP verb.+MUTATING = {"post", "put", "patch", "delete"}++#: The service whose surface this covers. `services/api` holds the tenant+#: control plane and is where `require_permission` lives.+SERVICE = "api"++#: Calls that constitute an authorization decision, as opposed to resolving an+#: identity. `require_permission` is the dependency factory in+#: `app/api/v1/deps.py`; the `*_db` forms are its RBAC-table equivalents.+AUTHZ_CALLS = frozenset(+ {+ "require_permission",+ "require_permission_db",+ "has_permission",+ "has_permission_db",+ }+)++#: The measured ceiling. Lower it whenever routes are gated; never raise it.+#: 2026-09-29: 106 on the v12.3.0 tree, 103 once GHSA-wj5c-88hg-5926 closed+#: the three write routes in `remediation.py`.+MAX_UNAUTHORIZED = 103+++def _authorizing_names(tree: ast.Module) -> set[str]:+ """Module-level names that carry an authorization decision.++ Three indirections hide enforcement from a naive scan, and all three are+ in this tree:++ * an ``Annotated`` alias — ``WriteUser = Annotated[AuthUser,+ Depends(require_permission("playbooks:write"))]`` in ``playbooks.py``;+ * a dependency helper — ``_admin_scope`` in ``mssp.py``;+ * a plain helper called from the handler body — ``_require_admin`` in+ ``waitlist.py`` and ``tenant_provision.py``.++ Missing any of them reports a gated route as ungated, which would inflate+ the ceiling with routes that are already fine and hide the real ones.+ """+ names: set[str] = set()++ for node in ast.walk(tree):+ # Alias assignments: NAME = Annotated[..., Depends(require_permission(...))]+ if isinstance(node, ast.Assign):+ if any(_calls_authz(node.value)):+ for target in node.targets:+ if isinstance(target, ast.Name):+ names.add(target.id)+ # Helper functions whose body reaches an authorization call.+ elif isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):+ if any(_calls_authz(node)):+ names.add(node.name)++ # A helper that calls a helper that authorizes. One extra hop is enough+ # for this tree; a fixpoint would be over-engineering until it is not.+ for node in ast.walk(tree):+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef) and node.name not in names:+ called = {c.func.id for c in ast.walk(node) if isinstance(c, ast.Call) and isinstance(c.func, ast.Name)}+ called |= {c.func.attr for c in ast.walk(node) if isinstance(c, ast.Call) and isinstance(c.func, ast.Attribute)}+ if called & names:+ names.add(node.name)++ return names+++def _calls_authz(node: ast.AST) -> list[str]:+ """Authorization calls reachable directly inside *node*."""+ found: list[str] = []+ for sub in ast.walk(node):+ if not isinstance(sub, ast.Call):+ continue+ func = sub.func+ name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", None)+ if name in AUTHZ_CALLS:+ found.append(name)+ return found+++def _route_authorizes(fn: ast.FunctionDef | ast.AsyncFunctionDef, authorizing: set[str]) -> bool:+ """True when this handler makes an authorization decision."""+ # In the signature: Depends(require_permission("x")), or an alias of one.+ if _calls_authz(fn.args):+ return True+ for arg in [*fn.args.args, *fn.args.kwonlyargs, *fn.args.posonlyargs]:+ if arg.annotation is not None and _names_used(arg.annotation) & authorizing:+ return True+ for default in [*fn.args.defaults, *[d for d in fn.args.kw_defaults if d is not None]]:+ if _names_used(default) & authorizing:+ return True+ # In the body: user.require_permission("x"), or a helper that does.+ if _calls_authz(fn):+ return True+ called = {c.func.id for c in ast.walk(fn) if isinstance(c, ast.Call) and isinstance(c.func, ast.Name)}+ return bool(called & authorizing)+++def _names_used(node: ast.AST) -> set[str]:+ return {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}+++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+ routes = [r for r in route_scan.collect_routes(base) if r.service == SERVICE]++ trees: dict[str, ast.Module] = {}+ authorizing: dict[str, set[str]] = {}+ handlers: dict[tuple[str, str], ast.FunctionDef | ast.AsyncFunctionDef] = {}+ for route in routes:+ if route.path in trees:+ continue+ tree = ast.parse((base / route.path).read_text(encoding="utf-8"))+ trees[route.path] = tree+ authorizing[route.path] = _authorizing_names(tree)+ for node in ast.walk(tree):+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):+ handlers[route.path, node.name] = node++ out: list[RouteVerdict] = []+ for route in routes:+ if not (set(route.methods) & MUTATING):+ continue+ # A route with no authentication at all is `check_route_auth.py`'s+ # finding, and it keeps the tables recording which of those are public+ # by design — the sign-in flow, the IdP callbacks, the HMAC-verified+ # webhooks. Counting them here would mix two different defects and+ # make this ceiling unreachable for a reason it does not describe.+ if not route.has_auth:+ continue+ fn = handlers.get((route.path, route.function))+ if fn is None:+ continue+ out.append(+ {+ "module": route.path,+ "function": route.function,+ "methods": sorted(set(route.methods) & MUTATING),+ "route_path": route.route_path,+ "lineno": route.lineno,+ "authorized": _route_authorizes(fn, authorizing[route.path]),+ }+ )+ return out+++def _refuse_empty_corpus(rows: list[RouteVerdict]) -> str | None:+ """A gate that scanned nothing must fail, not pass.++ ``security_audit.py`` once credited a tree with no manifests. The same+ shape here would report zero unauthorized routes because it found zero+ routes.+ """+ if len(rows) < 100:+ return f"found only {len(rows)} state-changing routes in services/{SERVICE}; the scanner is broken, not the tree clean"+ return None+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--inventory", action="store_true", help="print every state-changing route and its verdict")+ parser.add_argument("--json", action="store_true", help="machine-readable output")+ parser.add_argument("--self-test", action="store_true", help="prove the gate detects a removed permission")+ parser.add_argument("--max-unauthorized", type=int, default=MAX_UNAUTHORIZED)+ args = parser.parse_args(argv)++ if args.self_test:+ return _self_test()++ rows = collect()+ broken = _refuse_empty_corpus(rows)+ if broken:+ print(f"FAIL: {broken}")+ return 2++ ungated = [r for r in rows if not r["authorized"]]++ if args.json:+ print(json.dumps({"total": len(rows), "unauthorized": len(ungated), "routes": ungated}, indent=2))+ return 0++ if args.inventory:+ by_module: dict[str, list[RouteVerdict]] = {}+ for row in ungated:+ by_module.setdefault(row["module"], []).append(row)+ for module in sorted(by_module):+ print(f"\n{module}")+ for row in sorted(by_module[module], key=lambda r: r["lineno"]):+ print(f" {','.join(row['methods']):18s} {row['route_path'] or '/':34s} {row['function']}()")+ print(f"\n{len(ungated)} of {len(rows)} state-changing routes make no authorization decision")+ return 0++ 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})")++ # Forward: the debt may not grow.+ if len(ungated) > args.max_unauthorized:+ added = sorted(f"{r['module']}:{r['lineno']} {r['function']}()" for r in ungated)+ print(f"\nFAIL: {len(ungated)} exceeds the ceiling of {args.max_unauthorized}.")+ print("A state-changing route must make an authorization decision, not just resolve an identity.")+ print('Add Depends(require_permission("...")) — see services/api/app/api/v1/endpoints/remediation.py.')+ print(f"\ncurrent identity-only routes ({len(added)}):")+ for line in added:+ print(f" {line}")+ return 1++ # Reverse: a ceiling that no longer describes the tree is stale, and a+ # stale ceiling is how a list of exemptions turns into a list of excuses.+ if len(ungated) < args.max_unauthorized:+ print(f"\nFAIL: the ceiling is stale. {len(ungated)} routes are identity-only but MAX_UNAUTHORIZED is {args.max_unauthorized}.")+ print(f"Lower MAX_UNAUTHORIZED in {Path(__file__).name} to {len(ungated)}.")+ return 1++ print("\nOK")+ return 0+++def _self_test() -> int:+ """Prove the gate fails when a permission is removed from a real route.++ A gate must be proven against a tree that has the defect. Asserting it+ passes on a clean tree proves only that it can print OK.+ """+ import shutil # noqa: PLC0415+ import tempfile # noqa: PLC0415++ target = Path("services/api/app/api/v1/endpoints/remediation.py")+ original = (route_scan.REPO_ROOT / target).read_text(encoding="utf-8")+ if "require_permission" not in original:+ print("FAIL: self-test fixture is stale — remediation.py no longer enforces a permission")+ return 2++ with tempfile.TemporaryDirectory() as tmp:+ scratch = Path(tmp) / "tree"+ shutil.copytree(route_scan.REPO_ROOT / "services", scratch / "services", dirs_exist_ok=True)++ before = [r for r in collect(scratch) if not r["authorized"]]++ # Regress exactly the defect the advisory described.+ regressed = original.replace("Depends(require_permission(_WRITE))", "Depends(get_current_user)").replace(+ "Depends(require_permission(_READ))", "Depends(get_current_user)"+ )+ if regressed == original:+ print("FAIL: self-test could not regress remediation.py; its dependency spelling changed")+ return 2+ (scratch / target).write_text(regressed, encoding="utf-8")++ 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++ print(f"self-test OK: identity-only routes {len(before)} -> {len(after)} when remediation.py's permissions are removed")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/services/actions/app/clients/osquery_allowlist.py b/services/actions/app/clients/osquery_allowlist.pyindex 577e5da0d..a0af844e9 100644--- a/services/actions/app/clients/osquery_allowlist.py+++ b/services/actions/app/clients/osquery_allowlist.py@@ -7,17 +7,132 @@ approved here.Usage-----+from app.clients.osquery_allowlist import render_query, TEMPLATESsql = render_query("running_processes", pid=1234) # KeyError if unknown templatesql = render_query("active_connections") # no params needed++Every parameter declares a type in :data:`PARAM_SPECS`, and a value that is+not that type is refused. See the parameter-contract section below for why+that is the control rather than a scan for dangerous substrings."""from __future__ import annotationsimport re+from dataclasses import dataclassfrom typing import Any++class AllowlistError(ValueError):+ """Raised when a query or parameter fails allowlist validation."""+++# ---------------------------------------------------------------------------+# Parameter contract+# ---------------------------------------------------------------------------+#+# This module used to interpolate whatever the caller passed and then scan the+# result for `--`, `/*` and `;`. A denylist enumerates what is forbidden, so+# everything it failed to think of was permitted: `'` was not on the list, and+# `recent_files` wraps `directory` in single quotes, so a value of+# `' OR 1=1 OR directory='` closed the literal and replaced the WHERE clause.+# The numeric parameters were never coerced either, so `LIMIT {limit}` accepted+# `1 UNION SELECT ...` verbatim. (GHSA-p37g-cjqx-56hq.)+#+# Each parameter now declares what it *is* — a bounded whole number, or an+# absolute filesystem path — and a value that is not that is refused. osquery+# is reached through FleetDM's and osctrl's REST APIs, both of which take a+# finished SQL string and expose no bind-parameter channel, so binding is not+# available at this boundary; making the dangerous value unrepresentable is.+#+# Refusing rather than escaping is deliberate. An escaped path is still a+# path: it reaches the endpoint, matches nothing, and returns zero rows. On a+# forensic query that is indistinguishable from a clean host, so an operator+# reads a successful answer to a question that was never asked. A refusal is+# loud and cannot be mistaken for a result.+++#: What makes a path absolute, per platform: POSIX (`/var/log`), Windows+#: (`C:\\Windows`) or UNC (`\\\\host\\share`). A relative path is refused+#: because the `file` table resolves against the agent's working directory,+#: which is not a property the caller gets to depend on.+_ABSOLUTE_PREFIX_RE = re.compile(r"^(?:/|[A-Za-z]:[\\/]|\\\\)")++#: Characters a path value may not contain.+#:+#: `'` and `;` are the two that carry structure in the rendered statement: a+#: quote ends the literal the value sits in, and a semicolon starts a second+#: statement. Excluding them is what makes the injection unrepresentable+#: rather than filtered. `"` and backtick are SQLite's identifier quotes —+#: inert inside a single-quoted literal, but illegal in Windows paths and+#: vanishingly rare elsewhere, so refusing them costs nothing and removes a+#: whole class of argument about dialects. The C0 range and DEL are refused+#: because a newline in a path is a log-forging primitive, not a path.+#:+#: Everything else printable is allowed, including parentheses, spaces and+#: non-ASCII: `C:\\Program Files (x86)` is on every Windows host, and a path+#: refused here is a forensic question that cannot be asked at all. Backslash+#: is permitted because osquery uses SQLite syntax, where backslash is not an+#: escape character inside a string literal.+_FORBIDDEN_IN_PATH_RE = re.compile("[\x00-\x1f\x7f'\"`;]")+++@dataclass(frozen=True)+class _Integer:+ """A whole number within an inclusive range, and nothing else."""++ minimum: int+ maximum: int++ def describe(self) -> str:+ return f"a whole number between {self.minimum} and {self.maximum}"++ def coerce(self, name: str, value: Any) -> int:+ # `bool` is a subclass of `int`; `LIMIT True` is not a limit.+ if isinstance(value, bool) or not isinstance(value, int | str):+ raise AllowlistError(f"Parameter '{name}' must be {self.describe()}, not {type(value).__name__}.")+ try:+ number = int(str(value).strip())+ except ValueError:+ raise AllowlistError(f"Parameter '{name}' must be {self.describe()}; got {value!r}.") from None+ if not self.minimum <= number <= self.maximum:+ raise AllowlistError(f"Parameter '{name}' must be {self.describe()}; got {number}.")+ return number+++@dataclass(frozen=True)+class _AbsolutePath:+ """An absolute filesystem path, and nothing else."""++ max_length: int = 4096++ def describe(self) -> str:+ return "an absolute filesystem path"++ def coerce(self, name: str, value: Any) -> str:+ if not isinstance(value, str):+ raise AllowlistError(f"Parameter '{name}' must be {self.describe()}, not {type(value).__name__}.")+ if not value or len(value) > self.max_length:+ raise AllowlistError(f"Parameter '{name}' must be {self.describe()} of 1 to {self.max_length} characters; got {len(value)}.")+ if not _ABSOLUTE_PREFIX_RE.match(value):+ raise AllowlistError(+ f"Parameter '{name}' must be {self.describe()} starting with '/', a drive letter such as 'C:\\', or a UNC '\\\\' prefix."+ )+ if _FORBIDDEN_IN_PATH_RE.search(value):+ # A path that legitimately contains one of these is refused rather+ # than escaped — see the parameter-contract note above.+ raise AllowlistError(+ f"Parameter '{name}' must be {self.describe()} and may not contain quotes, backticks, semicolons or control characters."+ )+ return value+++#: The declared type of every parameter, by template.+_ParamType = _Integer | _AbsolutePath++# ---------------------------------------------------------------------------# Template registry# ---------------------------------------------------------------------------@@ -28,7 +143,9 @@ from typing import Any## Rules for adding templates:# 1. SQL must use parameterised placeholders in the form {param_name}.-# 2. The companion PARAM_SPECS entry must list every placeholder name.+# 2. The companion PARAM_SPECS entry must declare a type for every+# placeholder name. There is no untyped parameter: a placeholder with no+# spec raises rather than falling through to raw interpolation.# 3. No DML (INSERT/UPDATE/DELETE) or DDL (CREATE/DROP/ALTER) is allowed.# 4. Subqueries must not invoke osquery attach or join against .autoload tables# that modify host state.@@ -96,22 +213,61 @@ _DEFAULTS: dict[str, dict[str, Any]] = {"package_inventory": {"limit": 500},}-# Explicit spec of which parameters each template accepts.-PARAM_SPECS: dict[str, set[str]] = {- "running_processes": {"limit"},- "active_connections": {"limit"},- "logged_in_users": {"limit"},- "recent_files": {"directory", "limit"},- "process_tree": {"pid", "max_depth"},- "package_inventory": {"limit"},+#: A row cap, not a free integer: osquery returns these rows over the wire to+#: every targeted host's result set.+_LIMIT = _Integer(minimum=1, maximum=10_000)++# Explicit spec of which parameters each template accepts, and what each one is.+PARAM_SPECS: dict[str, dict[str, _ParamType]] = {+ "running_processes": {"limit": _LIMIT},+ "active_connections": {"limit": _LIMIT},+ "logged_in_users": {"limit": _LIMIT},+ "recent_files": {"directory": _AbsolutePath(), "limit": _LIMIT},+ "process_tree": {+ # PID 0 is the kernel scheduler on Linux and a valid row; the ceiling+ # is the widest value a pid_t can hold.+ "pid": _Integer(minimum=0, maximum=2**31 - 1),+ "max_depth": _Integer(minimum=1, maximum=64),+ },+ "package_inventory": {"limit": _LIMIT},}# Compile a regex that matches parameterised placeholders in the templates._PLACEHOLDER_RE = re.compile(r"\{(\w+)\}")+#: Tokens whose count must survive interpolation unchanged. A value that adds+#: a quote has escaped its string literal; a value that adds a semicolon has+#: appended a statement. Comment introducers are deliberately absent: inside a+#: literal they are inert, and `/opt/my--tool` is a legitimate path.+_STRUCTURAL_TOKENS: tuple[tuple[str, str], ...] = (+ ("'", "string delimiter"),+ (";", "statement terminator"),+)-class AllowlistError(ValueError):- """Raised when a query or parameter fails allowlist validation."""++def _assert_string_params_are_quoted() -> None:+ """Every string parameter must sit inside a SQL string literal.++ :class:`_AbsolutePath` permits characters that are inert inside a quoted+ literal and would not be outside one — `--` and `/*` among them, because+ `/opt/my--tool` is a real path and refusing it would cost a forensic+ answer for a token that cannot do anything from where it sits. That+ reasoning only holds while the template actually quotes the placeholder,+ so the shape is asserted here at import rather than left as a property+ the next person to add a template has to remember.+ """+ for template_id, specs in PARAM_SPECS.items():+ template = TEMPLATES[template_id]+ for name, spec in specs.items():+ if isinstance(spec, _AbsolutePath) and f"'{{{name}}}'" not in template:+ raise AllowlistError(+ f"Template '{template_id}' interpolates string parameter "+ f"'{name}' outside a quoted literal. Either quote it as "+ f"'{{{name}}}' or give it a parameter type that is safe unquoted."+ )+++_assert_string_params_are_quoted()def list_templates() -> list[str]:@@ -119,6 +275,23 @@ def list_templates() -> list[str]:return sorted(TEMPLATES)+def _assert_structure_intact(template_id: str, template: str, rendered: str) -> None:+ """Fail closed if interpolation changed the statement's structure.++ The parameter types are the control; this is the assertion that they held.+ It compares the rendered SQL against the template it came from — the+ direction that drifts — so it stays true for a parameter type added later+ that forgets what its predecessors had to exclude.+ """+ for token, label in _STRUCTURAL_TOKENS:+ if rendered.count(token) != template.count(token):+ raise AllowlistError(+ f"Rendering template '{template_id}' changed the number of "+ f"{label} characters, so a parameter value escaped its "+ f"position. Refusing to emit the query."+ )++def render_query(template_id: str, **params: Any) -> str:"""Render *template_id* with the supplied keyword parameters.@@ -129,7 +302,8 @@ def render_query(template_id: str, **params: Any) -> str:**params:Parameter values to substitute. Unknown keys raise:class:`AllowlistError`; missing keys are filled from- :data:`_DEFAULTS`.+ :data:`_DEFAULTS`. Every supplied value must match the type its+ parameter declares in :data:`PARAM_SPECS`.Returns-------@@ -140,12 +314,14 @@ def render_query(template_id: str, **params: Any) -> str:------AllowlistErrorIf *template_id* is not in the allowlist, if an unknown parameter- is supplied, or if a required parameter has no default.+ is supplied, if a required parameter has no default, or if a value+ is not what its parameter is declared to be."""if template_id not in TEMPLATES:raise AllowlistError(f"Unknown template '{template_id}'. Available: {', '.join(list_templates())}")- allowed_keys = PARAM_SPECS[template_id]+ specs = PARAM_SPECS[template_id]+ allowed_keys = set(specs)unknown = set(params) - allowed_keysif unknown:raise AllowlistError(@@ -158,21 +334,25 @@ def render_query(template_id: str, **params: Any) -> str:merged: dict[str, Any] = {**_DEFAULTS.get(template_id, {}), **params}# Verify that all placeholders have values after merging.- required = {m.group(1) for m in _PLACEHOLDER_RE.finditer(TEMPLATES[template_id])}+ template = TEMPLATES[template_id]+ required = {m.group(1) for m in _PLACEHOLDER_RE.finditer(template)}missing = required - set(merged)if missing:raise AllowlistError(f"Template '{template_id}' requires parameter(s) with no default: {', '.join(sorted(missing))}")- # Basic sanitisation: reject values that contain SQL comment sequences or- # statement terminators other than the trailing semicolon already in the- # template. This is defence-in-depth; the primary protection is the- # allowlist itself.- for key, value in merged.items():- val_str = str(value)- if "--" in val_str or "/*" in val_str or ";" in val_str:- raise AllowlistError(f"Parameter '{key}' contains disallowed characters.")+ # A placeholder the spec does not describe would otherwise reach+ # format_map() unvalidated, which is the original defect in miniature.+ undeclared = required - allowed_keys+ if undeclared:+ raise AllowlistError(f"Template '{template_id}' has placeholder(s) with no PARAM_SPECS entry: {', '.join(sorted(undeclared))}.")++ # Coerce each value to the type its parameter declares. A value that is+ # not that type is refused, never repaired.+ typed = {key: specs[key].coerce(key, value) for key, value in merged.items()}- return TEMPLATES[template_id].format_map(merged)+ rendered = template.format_map(typed)+ _assert_structure_intact(template_id, template, rendered)+ return rendereddef validate_raw_sql(sql: str) -> None:diff --git a/services/actions/tests/test_osquery_allowlist.py b/services/actions/tests/test_osquery_allowlist.pyindex 9007a99ba..70d053128 100644--- a/services/actions/tests/test_osquery_allowlist.py+++ b/services/actions/tests/test_osquery_allowlist.py@@ -67,12 +67,29 @@ class TestRenderQuery:render_query("running_processes", bad_param="evil")def test_sql_injection_via_directory_raises(self) -> None:- with pytest.raises(AllowlistError, match="disallowed characters"):+ # Refused because a path may not contain a quote or a semicolon, not+ # because this particular payload was recognised. The full injection+ # surface is covered in test_osquery_allowlist_injection.py.+ with pytest.raises(AllowlistError, match="quotes, backticks, semicolons"):render_query("recent_files", directory="/tmp'; DROP TABLE processes; --")- def test_sql_comment_in_param_raises(self) -> None:- with pytest.raises(AllowlistError, match="disallowed characters"):- render_query("recent_files", directory="/tmp -- comment")+ def test_sql_comment_in_param_is_an_ordinary_directory_name(self) -> None:+ """`--` inside a quoted literal is a filename, not a comment.++ This assertion is inverted from the version that shipped before+ GHSA-p37g-cjqx-56hq, and deliberately. The old code refused `--`+ anywhere in a value, which read as a comment-injection defence but was+ really a denylist standing in for one — it missed the quote that+ actually breaks out, while refusing legitimate paths like+ `/opt/my--tool`. Now a quote is unrepresentable, so the value cannot+ leave its literal and `--` inside it is inert; the module asserts at+ import that every string parameter is quoted, which is what makes that+ true rather than hoped for.+ """+ sql = render_query("recent_files", directory="/tmp -- comment")+ assert sql.count("'") == 2 # still exactly the template's own quotes+ assert sql.count(";") == 1 # still exactly one statement+ assert "WHERE directory = '/tmp -- comment'" in sqldef test_returns_string(self) -> None:result = render_query("running_processes")diff --git a/services/actions/tests/test_osquery_allowlist_injection.py b/services/actions/tests/test_osquery_allowlist_injection.pynew file mode 100644index 000000000..d0ede0cce--- /dev/null+++ b/services/actions/tests/test_osquery_allowlist_injection.py@@ -0,0 +1,179 @@+"""GHSA-p37g-cjqx-56hq: parameter values must not be able to alter the SQL.++`render_query()` interpolated caller-supplied parameters into osquery SQL with+`str.format_map()` and then scanned the *result* for `--`, `/*` and `;`. A+denylist enumerates what is forbidden, so what it did not enumerate was+allowed: `'` was not on the list, and `recent_files` wraps `directory` in+single quotes, so `' OR 1=1 OR directory='` closed the literal and replaced+the WHERE clause. The numeric parameters were never coerced, so `LIMIT+{limit}` took `1 UNION SELECT ...` verbatim — a hole the advisory did not+name and which the `recent_files` fix alone would not have closed.++Every assertion here is written against symbols that exist on both sides of+the fix — `render_query`, `AllowlistError`, `TEMPLATES`, `PARAM_SPECS` — so+that on the vulnerable tree these tests fail because the injection succeeds,+not because an import is missing. A test that fails with `ImportError` has+proved a symbol absent, which is not the same as proving a vulnerability+caught.++The load-bearing test is `TestStatementStructure`, which is a property over+every template and every parameter rather than a list of payloads. The+payload list is what the denylist got wrong; enumerating a longer one would+repeat the mistake at a larger size.+"""++from __future__ import annotations++import pytest+from app.clients.osquery_allowlist import (+ PARAM_SPECS,+ TEMPLATES,+ AllowlistError,+ render_query,+)++#: Values that carry SQL structure. Each is hostile in *some* parameter+#: position; the tests below assert the outcome is the same in every position,+#: which is the property that was missing.+HOSTILE_VALUES: list[str] = [+ # The advisory's proof of concept: neither contains --, /* or ;.+ "' OR 1=1 OR directory='",+ "' UNION SELECT key,value,'','','','','','','','' FROM process_envs WHERE key LIKE '%SECRET%' AND ''='",+ # A bare quote is the whole vulnerability reduced to one character.+ "'",+ # Numeric positions are unquoted, so they need no quote to be injectable.+ "1 UNION SELECT 1,2,3,4,5,6,7,8,9 FROM users",+ "1 OR 1=1",+ # These three the old denylist did catch; they must keep failing.+ "/tmp'; DROP TABLE processes; --",+ "/tmp -- comment",+ "/tmp/*x*/",+]+++def _structural_counts(sql: str) -> tuple[int, int]:+ """Single quotes and semicolons — the two characters that carry structure.++ A value that adds a quote has left the string literal it was placed in; a+ value that adds a semicolon has appended a second statement. Counting them+ on the rendered SQL and comparing against the template detects both without+ needing to know which payload was used.+ """+ return sql.count("'"), sql.count(";")+++class TestAdvisoryProofOfConcept:+ """The two payloads in the report, asserted directly."""++ def test_quote_cannot_break_out_of_the_directory_literal(self) -> None:+ # Pre-fix this returns:+ # ... WHERE directory = '' OR 1=1 OR directory='' LIMIT 100;+ # and the WHERE clause is gone.+ with pytest.raises(AllowlistError):+ render_query("recent_files", directory="' OR 1=1 OR directory='")++ def test_union_select_cannot_exfiltrate_the_process_environment(self) -> None:+ payload = "' UNION SELECT key,value,'','','','','','','','' FROM process_envs WHERE key LIKE '%SECRET%' AND ''='"+ with pytest.raises(AllowlistError):+ render_query("recent_files", directory=payload)++ def test_a_single_quote_is_refused(self) -> None:+ """The vulnerability at its smallest: one character the denylist lacked."""+ with pytest.raises(AllowlistError):+ render_query("recent_files", directory="/tmp'")+++class TestNumericParameters:+ """Unquoted positions need no quote to be injectable.++ The advisory names `directory`; these were injectable too, and a fix scoped+ to `recent_files` would have left them open.+ """++ def test_limit_is_not_interpolated_verbatim(self) -> None:+ with pytest.raises(AllowlistError):+ render_query("running_processes", limit="1 UNION SELECT 1,2,3,4,5,6,7,8,9 FROM users")++ def test_pid_is_not_interpolated_verbatim(self) -> None:+ with pytest.raises(AllowlistError):+ render_query("process_tree", pid="1 OR 1=1")++ def test_max_depth_is_not_interpolated_verbatim(self) -> None:+ with pytest.raises(AllowlistError):+ render_query("process_tree", max_depth="5 UNION SELECT 1")++ def test_a_boolean_is_not_a_row_count(self) -> None:+ # bool subclasses int, so an unguarded int() check accepts it.+ with pytest.raises(AllowlistError):+ render_query("running_processes", limit=True)+++class TestStatementStructure:+ """The property, over every template and every parameter.++ This is the test that would have caught the original defect without anyone+ having guessed the payload: for any value, in any parameter of any+ template, `render_query` either refuses it or emits SQL whose structure is+ identical to the template's.+ """++ @pytest.mark.parametrize("template_id", sorted(TEMPLATES))+ @pytest.mark.parametrize("hostile", HOSTILE_VALUES)+ def test_no_parameter_can_alter_the_statement(self, template_id: str, hostile: str) -> None:+ expected = _structural_counts(TEMPLATES[template_id])++ # ``PARAM_SPECS[template_id]`` yields parameter names whether it maps+ # each template to a set of names or to a dict keyed by them, so this+ # loop runs unchanged on both the vulnerable and the fixed module.+ for param_name in PARAM_SPECS[template_id]:+ try:+ rendered = render_query(template_id, **{param_name: hostile})+ except AllowlistError:+ continue # refused, which is the intended outcome+ assert _structural_counts(rendered) == expected, (+ f"{template_id}.{param_name} accepted {hostile!r} and the rendered SQL no longer has the template's structure: {rendered}"+ )++ @pytest.mark.parametrize("template_id", sorted(TEMPLATES))+ def test_every_placeholder_has_a_declared_type(self, template_id: str) -> None:+ """No parameter reaches interpolation without a spec describing it."""+ import re # noqa: PLC0415++ placeholders = {m.group(1) for m in re.finditer(r"\{(\w+)\}", TEMPLATES[template_id])}+ declared = set(PARAM_SPECS[template_id])+ assert placeholders <= declared, f"{template_id} interpolates {placeholders - declared} with no PARAM_SPECS entry"+++class TestLegitimateValuesStillWork:+ """Refusing everything would also pass the tests above.++ A forensic query that cannot name the directory it is asked about is not a+ fix, so these pin the values an operator actually uses. `C:\\Program Files+ (x86)` is the one that matters: it is on every Windows host, and the+ parentheses are inert inside a string literal.+ """++ @pytest.mark.parametrize(+ "directory",+ [+ "/tmp",+ "/var/log",+ "/opt/my-app_v2.1 (beta)",+ "C:\\Windows\\System32",+ "C:\\Program Files (x86)",+ "\\\\fileserver\\share",+ "/home/josé/docs",+ ],+ )+ def test_real_directories_render(self, directory: str) -> None:+ sql = render_query("recent_files", directory=directory)+ assert directory in sql+ assert _structural_counts(sql) == _structural_counts(TEMPLATES["recent_files"])++ def test_numeric_parameters_accept_numbers(self) -> None:+ assert "50" in render_query("running_processes", limit=50)+ assert "1234" in render_query("process_tree", pid=1234)++ def test_every_template_renders_with_its_defaults(self) -> None:+ for template_id in TEMPLATES:+ assert render_query(template_id).endswith(";")diff --git a/services/api/app/api/v1/endpoints/remediation.py b/services/api/app/api/v1/endpoints/remediation.pyindex a112487d6..fdfd8c12d 100644--- a/services/api/app/api/v1/endpoints/remediation.py+++ b/services/api/app/api/v1/endpoints/remediation.py@@ -1,23 +1,85 @@-"""L0–L4 auto-remediation maturity tier endpoints."""+"""L0–L4 auto-remediation maturity tier endpoints.++Authorization+-------------+These routes are the tenant's autonomous-response control plane, not a+preference surface. ``remediation_maturity.maturity_tier`` and+``action_overrides`` are read by ``services/actions`` when it grades a+response action: ``force_auto`` becomes ``AutonomyMode.AUTO`` with an L4 tier+label, ``block`` becomes ``AutonomyMode.BLOCKED``, and a+``remediation_whitelist`` row is the artefact that lets L4 execute a high+blast-radius verb unattended.++Every route here authenticated and none of them authorized, so a ``viewer``+— a role holding five read permissions and nothing else — could raise the+tier, pre-approve a destructive verb against every target with no expiry, or+suppress a containment verb during an incident (GHSA-wj5c-88hg-5926).++Writes therefore require ``settings:write``, which only ``tenant_admin`` and+the wildcard roles hold. ``actions:execute`` was the other candidate and is+the wrong one: ``soc_lead`` and ``soc_analyst`` hold it, so it would let the+same principal who dispatches an action pre-approve its own future+dispatches, which is the separation of duties the approval path already+enforces. Reads require ``actions:read``, which every human role holds — an+analyst can see the posture they are working under — but ``api_service``+does not, so a machine key must be scoped for it deliberately.+"""from __future__ import annotations+import reimport uuidfrom datetime import UTC, datetime-from typing import Any+from typing import Annotated, Anyfrom fastapi import APIRouter, Depends, HTTPException, Query, status-from pydantic import BaseModel, ConfigDict, Field+from pydantic import BaseModel, ConfigDict, Field, field_validatorfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession-from app.api.v1.deps import CurrentUser-from app.api.v1.endpoints.auth import get_current_user+from app.api.v1.deps import CurrentUser, require_permissionfrom app.db.database import get_dbfrom app.models.remediation import RemediationGateLog, RemediationMaturity, RemediationWhitelistrouter = APIRouter(prefix="/remediation", tags=["remediation"])+#: Reading the tenant's response posture. Held by every human role.+_READ = "actions:read"++#: Changing it. Held by ``tenant_admin`` and the wildcard roles only.+_WRITE = "settings:write"++#: The only flags ``services/actions`` reads out of an action override+#: (``live_actions/dispatcher.py::_govern``). Anything else written here is+#: dead weight in a security-relevant row, so it is refused rather than stored.+_OVERRIDE_FLAGS = frozenset({"block", "force_auto"})++#: The shape of a response verb. Deliberately a shape rather than an import of+#: ``ActionType`` from ``services/actions``: the API service does not depend on+#: that package, and adding the import to validate a vocabulary would make this+#: service fail to start wherever the package is absent.+_ACTION_TYPE_RE = re.compile(r"^[a-z][a-z0-9_]{1,63}$")+++#: The two access levels, as FastAPI dependencies. Declared once so the+#: permission a route enforces is a property of the alias rather than repeated+#: at each signature, and so `require_permission` is called at import rather+#: than in an argument default.+ReadUser = Annotated[CurrentUser, Depends(require_permission(_READ))]+WriteUser = Annotated[CurrentUser, Depends(require_permission(_WRITE))]+++def _isoformat(value: Any) -> Any:+ """Render a timestamp column as the ``str`` these schemas declare.++ The columns are ``DateTime`` and the schemas declare ``str``; Pydantic v2+ does not coerce between the two, so every response below raised+ ``ResponseValidationError`` *after* its handler had already committed —+ the write landed and the caller saw a 500. Normalising here rather than+ retyping the fields keeps the published OpenAPI schema unchanged.+ """+ return value.isoformat() if isinstance(value, datetime) else value+# ---------------------------------------------------------------------------# Pydantic schemas@@ -28,6 +90,24 @@ class MaturityConfig(BaseModel):maturity_tier: int = Field(..., ge=0, le=4)action_overrides: dict[str, Any] = Field(default_factory=dict)+ @field_validator("action_overrides")+ @classmethod+ def _only_known_flags(cls, value: dict[str, Any]) -> dict[str, Any]:+ for action_type, override in value.items():+ if not _ACTION_TYPE_RE.match(action_type):+ raise ValueError(f"'{action_type}' is not a response action type")+ if not isinstance(override, dict):+ raise ValueError(f"override for '{action_type}' must be an object")+ unknown = set(override) - _OVERRIDE_FLAGS+ if unknown:+ raise ValueError(+ f"override for '{action_type}' has unknown flag(s) {sorted(unknown)}; known flags are {sorted(_OVERRIDE_FLAGS)}"+ )+ for flag, flag_value in override.items():+ if not isinstance(flag_value, bool):+ raise ValueError(f"'{action_type}.{flag}' must be true or false")+ return value+class MaturityOut(BaseModel):id: uuid.UUID@@ -39,6 +119,8 @@ class MaturityOut(BaseModel):model_config = ConfigDict(from_attributes=True)+ _normalise_timestamps = field_validator("changed_at", "created_at", mode="before")(_isoformat)+class GateLogOut(BaseModel):id: uuid.UUID@@ -54,6 +136,8 @@ class GateLogOut(BaseModel):model_config = ConfigDict(from_attributes=True)+ _normalise_timestamps = field_validator("created_at", mode="before")(_isoformat)+class WhitelistCreate(BaseModel):action_type: str@@ -70,6 +154,8 @@ class WhitelistOut(WhitelistCreate):model_config = ConfigDict(from_attributes=True)+ _normalise_timestamps = field_validator("created_at", mode="before")(_isoformat)+# ---------------------------------------------------------------------------# Maturity config endpoints@@ -78,8 +164,8 @@ class WhitelistOut(WhitelistCreate):@router.get("/config", response_model=MaturityOut)async def get_maturity_config(+ current_user: ReadUser,db: AsyncSession = Depends(get_db),- current_user: CurrentUser = Depends(get_current_user),) -> RemediationMaturity:result = await db.execute(select(RemediationMaturity).where(RemediationMaturity.tenant_id == current_user.tenant_id))config = result.scalar_one_or_none()@@ -97,8 +183,8 @@ async def get_maturity_config(@router.put("/config", response_model=MaturityOut)async def update_maturity_config(body: MaturityConfig,+ current_user: WriteUser,db: AsyncSession = Depends(get_db),- current_user: CurrentUser = Depends(get_current_user),) -> RemediationMaturity:result = await db.execute(select(RemediationMaturity).where(RemediationMaturity.tenant_id == current_user.tenant_id))config = result.scalar_one_or_none()@@ -122,11 +208,11 @@ async def update_maturity_config(@router.get("/gate-log", response_model=list[GateLogOut])async def list_gate_log(+ current_user: ReadUser,decision: str | None = Query(None),limit: int = Query(50, le=500),offset: int = Query(0, ge=0),db: AsyncSession = Depends(get_db),- current_user: CurrentUser = Depends(get_current_user),) -> list[RemediationGateLog]:q = select(RemediationGateLog).where(RemediationGateLog.tenant_id == current_user.tenant_id)if decision:@@ -143,8 +229,8 @@ async def list_gate_log(@router.get("/whitelist", response_model=list[WhitelistOut])async def list_whitelist(+ current_user: ReadUser,db: AsyncSession = Depends(get_db),- current_user: CurrentUser = Depends(get_current_user),) -> list[RemediationWhitelist]:result = await db.execute(select(RemediationWhitelist).where(RemediationWhitelist.tenant_id == current_user.tenant_id))return list(result.scalars().all())@@ -153,8 +239,8 @@ async def list_whitelist(@router.post("/whitelist", response_model=WhitelistOut, status_code=status.HTTP_201_CREATED)async def add_to_whitelist(body: WhitelistCreate,+ current_user: WriteUser,db: AsyncSession = Depends(get_db),- current_user: CurrentUser = Depends(get_current_user),) -> RemediationWhitelist:entry = RemediationWhitelist(**body.model_dump(),@@ -170,8 +256,8 @@ async def add_to_whitelist(@router.delete("/whitelist/{entry_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)async def remove_from_whitelist(entry_id: uuid.UUID,+ current_user: WriteUser,db: AsyncSession = Depends(get_db),- current_user: CurrentUser = Depends(get_current_user),) -> None:entry = await db.get(RemediationWhitelist, entry_id)if not entry or entry.tenant_id != current_user.tenant_id:diff --git a/services/api/tests/test_remediation_authorization.py b/services/api/tests/test_remediation_authorization.pynew file mode 100644index 000000000..c7f8ef144--- /dev/null+++ b/services/api/tests/test_remediation_authorization.py@@ -0,0 +1,243 @@+"""GHSA-wj5c-88hg-5926: the remediation router authenticated but never authorized.++`services/api/app/api/v1/endpoints/remediation.py` is the tenant's+autonomous-response control plane. `maturity_tier` and `action_overrides` are+read by `services/actions` when it grades a response action — `force_auto`+becomes `AutonomyMode.AUTO` at an L4 tier label, `block` becomes+`AutonomyMode.BLOCKED` — and a `remediation_whitelist` row is what lets L4+execute a high blast-radius verb unattended.++Every route depended on `get_current_user` and none on `require_permission`,+so a `viewer` (five read permissions, no write of any kind) could raise the+tier, pre-approve a destructive verb against every target with no expiry, or+suppress a containment verb mid-incident.++Two things these tests are careful about:++*They fail on the vulnerable tree for the defect.* Every symbol imported here+— `remediation`, `CurrentUser`, `require_permission`, `get_current_user` —+exists on both sides of the fix, so a run against the pre-fix module fails+because the write lands, not because an import is missing.++*They assert the write did not land, not merely the status code.* The handler+commits before FastAPI serialises the response, so on the vulnerable tree the+policy row was written on a request that returned 500. A test that asserted+`!= 200` would have passed against a successful attack.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime+from types import SimpleNamespace+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 remediation+from app.api.v1.endpoints.auth import get_current_user+from app.db.database import get_db+from fastapi import FastAPI+from fastapi.testclient import TestClient++TENANT = uuid.UUID("11111111-1111-1111-1111-111111111111")++#: Every mutating route in the module, by handler name. The advisory names two+#: of these; enforcing only those would leave the third open.+WRITE_HANDLERS = ["update_maturity_config", "add_to_whitelist", "remove_from_whitelist"]+READ_HANDLERS = ["get_maturity_config", "list_gate_log", "list_whitelist"]++#: The advisory's proof-of-concept requests, in order.+POLICY_WRITES: list[tuple[str, str, str, dict[str, Any] | None]] = [+ (+ "raise the tier and force-auto a destructive verb",+ "PUT",+ "/api/v1/remediation/config",+ {"maturity_tier": 4, "action_overrides": {"isolate_host": {"force_auto": True}}},+ ),+ (+ "suppress a containment verb",+ "PUT",+ "/api/v1/remediation/config",+ {"maturity_tier": 0, "action_overrides": {"isolate_host": {"block": True}}},+ ),+ (+ "install a never-expiring high blast-radius pre-approval",+ "POST",+ "/api/v1/remediation/whitelist",+ {"action_type": "isolate_host", "blast_radius": "high", "constraints": {}, "expires_at": None},+ ),+ (+ "delete a whitelist entry",+ "DELETE",+ f"/api/v1/remediation/whitelist/{uuid.uuid4()}",+ None,+ ),+]+++def _user(role: str) -> CurrentUser:+ return CurrentUser(user_id=uuid.uuid4(), tenant_id=TENANT, role=role, email=f"{role}@tenant-a.example")+++def _row() -> SimpleNamespace:+ now = datetime.now(UTC)+ return SimpleNamespace(+ id=uuid.uuid4(),+ tenant_id=TENANT,+ maturity_tier=0,+ action_overrides={},+ changed_by=None,+ changed_at=now,+ created_at=now,+ action_type="isolate_host",+ blast_radius="high",+ constraints={},+ approved_by=None,+ expires_at=None,+ )+++def _db() -> AsyncMock:+ result = MagicMock()+ result.scalar_one_or_none = MagicMock(return_value=_row())+ result.scalars = MagicMock(return_value=MagicMock(all=MagicMock(return_value=[])))+ db = AsyncMock()+ db.execute = AsyncMock(return_value=result)+ db.get = AsyncMock(return_value=_row())+ db.commit = AsyncMock()+ db.refresh = AsyncMock()+ db.delete = AsyncMock()+ db.add = MagicMock()+ return db+++def _request(role: str, method: str, path: str, payload: dict[str, Any] | None) -> tuple[int, bool]:+ """Issue one request as *role*; return the status and whether it committed."""+ app = FastAPI()+ app.include_router(remediation.router, prefix="/api/v1")+ db = _db()+ app.dependency_overrides[get_current_user] = lambda: _user(role)+ app.dependency_overrides[get_db] = lambda: db+ client = TestClient(app, raise_server_exceptions=False)+ response = client.request(method, path, json=payload)+ return response.status_code, db.commit.await_count > 0+++def _permissions_on(route: Any) -> list[str]:+ """Permissions FastAPI will actually enforce, read from the dependency tree.++ Walking the resolved tree rather than the source is deliberate: a+ dependency that is present but wired to the wrong thing satisfies a grep+ and enforces nothing. `require_permission` returns a closure named+ `_check` holding the permission string in its cell.+ """+ found: list[str] = []++ def walk(dependant: Any) -> None:+ call = getattr(dependant, "call", None)+ if getattr(call, "__name__", "") == "_check":+ for cell in getattr(call, "__closure__", None) or ():+ if isinstance(cell.cell_contents, str):+ found.append(cell.cell_contents)+ for sub in getattr(dependant, "dependencies", []):+ walk(sub)++ walk(route.dependant)+ return found+++def _route_for(handler_name: str) -> Any:+ for route in remediation.router.routes:+ if getattr(route, "endpoint", None) is getattr(remediation, handler_name):+ return route+ raise AssertionError(f"no route registered for {handler_name}")+++class TestViewerCannotWriteThePolicy:+ """The advisory's proof of concept, executed."""++ @pytest.mark.parametrize(("label", "method", "path", "payload"), POLICY_WRITES, ids=[p[0] for p in POLICY_WRITES])+ def test_viewer_write_is_refused_and_does_not_commit(self, label: str, method: str, path: str, payload: dict[str, Any] | None) -> None:+ status, committed = _request("viewer", method, path, payload)+ assert not committed, f"viewer was able to {label}: the transaction committed"+ assert status == 403, f"viewer got HTTP {status} rather than 403 when trying to {label}"++ @pytest.mark.parametrize("role", ["soc_analyst", "soc_lead", "threat_hunter"])+ def test_action_dispatchers_cannot_pre_approve_their_own_actions(self, role: str) -> None:+ """`actions:execute` must not be enough to write the policy.++ `soc_lead` and `soc_analyst` hold `actions:execute`. Gating the+ whitelist on it — the other candidate permission — would let the+ principal who dispatches an action pre-approve its own future+ dispatches, which is the separation of duties the approval path+ already enforces elsewhere.+ """+ status, committed = _request(+ role,+ "POST",+ "/api/v1/remediation/whitelist",+ {"action_type": "isolate_host", "blast_radius": "high", "constraints": {}, "expires_at": None},+ )+ assert not committed+ assert status == 403+++class TestAuthorizedCallersStillWork:+ """Refusing everyone would also satisfy the tests above."""++ def test_tenant_admin_can_update_the_policy(self) -> None:+ status, committed = _request(+ "tenant_admin",+ "PUT",+ "/api/v1/remediation/config",+ {"maturity_tier": 2, "action_overrides": {"isolate_host": {"force_auto": True}}},+ )+ assert status == 200, f"tenant_admin got HTTP {status}"+ assert committed++ def test_viewer_can_still_read_the_posture_it_works_under(self) -> None:+ status, _ = _request("viewer", "GET", "/api/v1/remediation/config", None)+ assert status == 200+++class TestEveryRouteIsGated:+ """Read from the route table, so a new handler cannot quietly arrive ungated."""++ @pytest.mark.parametrize("handler", WRITE_HANDLERS)+ def test_write_routes_require_settings_write(self, handler: str) -> None:+ assert _permissions_on(_route_for(handler)) == ["settings:write"]++ @pytest.mark.parametrize("handler", READ_HANDLERS)+ def test_read_routes_require_a_permission(self, handler: str) -> None:+ assert _permissions_on(_route_for(handler)) == ["actions:read"]++ def test_no_state_changing_route_in_the_module_is_unguarded(self) -> None:+ """Catches a route added later that this file does not name."""+ unguarded = [+ f"{sorted(r.methods - {'HEAD', 'OPTIONS'})} {r.path}"+ for r in remediation.router.routes+ if r.methods & {"POST", "PUT", "PATCH", "DELETE"} and not _permissions_on(r)+ ]+ assert not unguarded, f"state-changing routes with no permission: {unguarded}"+++class TestOverrideShape:+ """`action_overrides` was a free-form dict written straight into a security row."""++ @pytest.mark.parametrize(+ "overrides",+ [+ {"isolate_host": {"force_auto": "yes"}}, # not a boolean+ {"isolate_host": {"unknown_flag": True}}, # not a flag the gate reads+ {"isolate_host": "force_auto"}, # not an object+ {"Robert'); DROP TABLE--": {"block": True}}, # not an action type+ ],+ )+ def test_malformed_overrides_are_refused(self, overrides: dict[str, Any]) -> None:+ status, committed = _request(+ "tenant_admin", "PUT", "/api/v1/remediation/config", {"maturity_tier": 1, "action_overrides": overrides}+ )+ assert status == 422, f"expected 422, got {status}"+ assert not committed