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(api): four write routes that could never reach the database (#981)
Beenu Arora7d6c3a9f5030
diff --git a/.github/workflows/isolation.yml b/.github/workflows/isolation.ymlindex 60c24ce45..1736142ac 100644--- a/.github/workflows/isolation.yml+++ b/.github/workflows/isolation.yml@@ -24,6 +24,7 @@ on:- "scripts/check_route_auth.py"- "scripts/check_route_shadowing.py"- "scripts/check_tenant_query_predicates.py"+ - "scripts/check_text_bind_casts.py"- "scripts/sync_vendored_tenant_scope.py"# The runtime-DB-role gate reads these, so a change to any of them has# to re-run it. A gate whose inputs are outside its own path filter is@@ -45,6 +46,7 @@ on:- "scripts/check_route_auth.py"- "scripts/check_route_shadowing.py"- "scripts/check_tenant_query_predicates.py"+ - "scripts/check_text_bind_casts.py"- "scripts/sync_vendored_tenant_scope.py"# The runtime-DB-role gate reads these, so a change to any of them has# to re-run it. A gate whose inputs are outside its own path filter is@@ -177,6 +179,16 @@ jobs:- name: Every query on a tenant-scoped table filters on a tenantrun: python scripts/check_tenant_query_predicates.py+ # A tenant predicate is worth nothing in a statement that cannot be+ # built. `:tenant_id::uuid` declares `tenant_i`, so `.bindparams()`+ # raises before the query is sent and the predicate gate above still+ # reads the filter it wanted in the source text.+ - name: Bind-cast gate self-test (the defect, and three near misses)+ run: python scripts/check_text_bind_casts.py --self-test++ - name: No bind parameter is followed by a `::` cast+ run: python scripts/check_text_bind_casts.py+# The second layer, which was decoration until 061_runtime_app_role.sql:# every service connected as a superuser, and a superuser ignores RLS# policies even under FORCE ROW LEVEL SECURITY. This is the static half —diff --git a/scripts/check_text_bind_casts.py b/scripts/check_text_bind_casts.pynew file mode 100644index 000000000..be1d7e713--- /dev/null+++ b/scripts/check_text_bind_casts.py@@ -0,0 +1,197 @@+#!/usr/bin/env python3+"""Refuse a `:name::type` cast inside a SQLAlchemy ``text()`` statement.++SQLAlchemy finds bind parameters in a ``text()`` string with+``(?<![:\\w\\x5c]):(\\w+)(?!:)``. The trailing ``(?!:)`` is there so the+Postgres ``::`` cast operator is not mistaken for a parameter — but it does+not skip the construct, it *backtracks one character* and declares a+different, shorter name. So ``:payload::jsonb`` declares ``payloa``,+``:urls::text[]`` declares ``url``, and the ``.bindparams(payload=...)`` that+follows raises ``ArgumentError``.++Three properties make this worth a gate rather than a code review note:++* It raises on the ``.bindparams()`` call, which in every instance found sat+ *outside* the handler's ``try``. So the route did not degrade to its 503+ path — it 500'd, and the statement never reached a connection.+* It is invisible to a reading eye. ``:payload::jsonb`` is what the Postgres+ documentation shows, and the truncated name never appears in the source.+* It survived because the tests covering those routes read the handler's+ source text instead of calling it. A substring assertion cannot fail on+ this, because the substring is present and correct.++Four route handlers were dead this way: ``compliance.collect_evidence``,+``phishing.submit``, ``phishing.retriage`` and ``knowledge_base.ingest``.+``knowledge_base.query_kb`` carried the same spelling, was found, and was+fixed to ``CAST(:kinds AS text[])`` — while the sibling INSERT twenty lines+above it kept the broken form. A gate is what closes that gap.++The fix is always ``CAST(:name AS type)``, which is standard SQL, means the+same thing to Postgres, and leaves the parameter name intact.++Usage:+ python3 scripts/check_text_bind_casts.py+ python3 scripts/check_text_bind_casts.py --self-test+"""++from __future__ import annotations++import ast+import re+import subprocess+import sys+from pathlib import Path++# `scripts/` is on sys.path when this file is run as a program, but not when a+# test loads it by path with importlib. gate_toolkit sits beside it either way.+sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import SELF_TEST_FLAG, repo_root, self_test_main++# Verbatim from `sqlalchemy.sql.elements.TextClause._bind_params_regex`. If a+# future SQLAlchemy changes it, this gate reports names that release does not,+# which is the safe direction: it can complain about a statement that works,+# never stay quiet about one that raises.+SQLA_BIND_RE = re.compile(r"(?<![:\w\x5c]):(\w+)(?!:)")++# A `:name` whose next two characters are `::`. The lookbehind mirrors+# SQLAlchemy's so a `::` that is not preceded by a parameter (an `a::b` cast of+# a column, say) is not reported.+CAST_ADJACENT_RE = re.compile(r"(?<![:\w\\]):(\w+)::")++# The historical prototype subtree is reference-only and is `paths-ignore`d by+# CodeQL for the same reason.+SKIP_PREFIXES = ("plans/",)+++def _tracked_python_files(root: Path) -> list[Path]:+ out = subprocess.run(+ ["git", "ls-files", "-z", "*.py"],+ cwd=root,+ capture_output=True,+ text=True,+ check=True,+ ).stdout+ return [root / rel for rel in out.split("\0") if rel and not rel.startswith(SKIP_PREFIXES)]+++def _static_string(node: ast.AST) -> str | None:+ """Return the statement text when it can be read without executing anything.++ Handles the three spellings that appear in this tree: a plain literal, an+ implicit or explicit concatenation of literals, and an f-string whose+ interpolations are irrelevant to where the colons fall. A `text()` built+ from a variable is skipped — reporting on it would need dataflow, and the+ statements this defect lives in are all inline literals.+ """+ if isinstance(node, ast.Constant):+ return node.value if isinstance(node.value, str) else None+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):+ left, right = _static_string(node.left), _static_string(node.right)+ return None if left is None or right is None else left + right+ if isinstance(node, ast.JoinedStr):+ parts = []+ for value in node.values:+ if isinstance(value, ast.Constant) and isinstance(value.value, str):+ parts.append(value.value)+ else:+ # An interpolated fragment. Substitute a placeholder that+ # carries no colon so it cannot invent or mask a match.+ parts.append(" ")+ return "".join(parts)+ return None+++def _is_text_call(node: ast.Call) -> bool:+ func = node.func+ if isinstance(func, ast.Name):+ return func.id == "text"+ if isinstance(func, ast.Attribute):+ return func.attr == "text"+ return False+++def violations(source: str, rel: str) -> list[str]:+ """Report every `:name::type` inside a `text()` statement in ``source``."""+ try:+ tree = ast.parse(source)+ except SyntaxError as exc:+ return [f"{rel}: could not parse ({exc})"]++ found: list[str] = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call) or not _is_text_call(node) or not node.args:+ continue+ statement = _static_string(node.args[0])+ if statement is None:+ continue+ declared = set(SQLA_BIND_RE.findall(statement))+ for match in CAST_ADJACENT_RE.finditer(statement):+ intended = match.group(1)+ if intended in declared:+ # SQLAlchemy resolved this name anyway (it also appears in the+ # statement somewhere a cast does not follow it), so the+ # bindparams call will not raise. Still worth nothing here.+ continue+ truncated = next((d for d in declared if intended.startswith(d) and d != intended), "no parameter")+ found.append(+ f"{rel}:{node.lineno}: `:{intended}::` declares `{truncated}`, so `.bindparams({intended}=...)` raises. "+ f"Write `CAST(:{intended} AS <type>)`."+ )+ return found+++def main() -> int:+ root = repo_root()+ files = _tracked_python_files(root)+ # Every statement this gate is about lives in a service. `scripts/` alone+ # is a runnable copy of the gate over none of its subject, and reporting+ # OK there is a verdict about a tree that is not this one.+ services = [p for p in files if p.relative_to(root).parts[:1] == ("services",)]+ if not services:+ print(+ "check_text_bind_casts: no tracked Python files under services/ — refusing to report a clean tree",+ file=sys.stderr,+ )+ return 1++ problems: list[str] = []+ for path in files:+ try:+ source = path.read_text(encoding="utf-8")+ except (OSError, UnicodeDecodeError):+ continue+ if "text(" not in source:+ continue+ problems.extend(violations(source, str(path.relative_to(root))))++ if problems:+ print("A bind parameter is followed by a `::` cast, so SQLAlchemy declares a different name:\n", file=sys.stderr)+ for problem in problems:+ print(f" {problem}", file=sys.stderr)+ print(f"\n{len(problems)} statement(s) would raise before reaching a connection.", file=sys.stderr)+ return 1++ print(f"OK: {len(files)} tracked Python file(s) scanned ({len(services)} under services/), no `:name::type` inside a text() statement")+ return 0+++_CLEAN = 'q = text("INSERT INTO t (a, b) VALUES (CAST(:payload AS jsonb), :other)").bindparams(payload=x, other=y)'+_BROKEN = 'q = text("INSERT INTO t (a, b) VALUES (:payload::jsonb, :other)").bindparams(payload=x, other=y)'+_NOT_SQL = 'if ":iam::" in resource_id and ":policy/" in resource_id:\n kind = "policy"'+_CONCAT = 'q = text("SELECT * FROM t" " WHERE k = ANY(:kinds::text[])")'+++def _rule_self_test() -> list[tuple[str, bool]]:+ return [+ ("the CAST() spelling is not reported", not violations(_CLEAN, "f.py")),+ ("an injected `:payload::jsonb` is reported", any("payloa" in v for v in violations(_BROKEN, "f.py"))),+ ("an ARN literal outside a text() call is not reported", not violations(_NOT_SQL, "f.py")),+ ("a `::` cast in a concatenated statement is reported", any(":kinds::" in v for v in violations(_CONCAT, "f.py"))),+ ]+++if __name__ == "__main__":+ if SELF_TEST_FLAG in sys.argv[1:]:+ sys.exit(self_test_main(Path(__file__).name, extra=_rule_self_test()))+ sys.exit(main())diff --git a/scripts/mypy_baseline.json b/scripts/mypy_baseline.jsonindex abc7fa1d5..ec1b538fb 100644--- a/scripts/mypy_baseline.json+++ b/scripts/mypy_baseline.json@@ -397,9 +397,7 @@"misc": 1},"tests/test_compliance_phishing_kb_tenant_isolation.py": {- "assignment": 1,- "method-assign": 1,- "misc": 2,+ "misc": 1,"var-annotated": 1},"tests/test_credential_vault_envelope.py": {diff --git a/services/api/app/api/v1/deps.py b/services/api/app/api/v1/deps.pyindex 03a4cf830..4382a6e74 100644--- a/services/api/app/api/v1/deps.py+++ b/services/api/app/api/v1/deps.py@@ -74,6 +74,14 @@ class CurrentUser:self.email = emailself.scopes = scopes # None → role-based; list → API-key scoped+ def __repr__(self) -> str:+ # Without this a stray `str(user)` persists `<...CurrentUser object at+ # 0x...>` into whatever column it was bound to, which is what happened+ # to three actor columns. `email` is deliberately omitted: this value+ # reaches logs and tracebacks, and the address of the person holding+ # the session is not something a stack trace should carry.+ return f"CurrentUser(user_id={self.user_id}, tenant_id={self.tenant_id}, role={self.role})"+def require_permission(self, permission: str) -> None:if self.scopes is not None:# API-key path: check explicit scopes listdiff --git a/services/api/app/api/v1/endpoints/compliance.py b/services/api/app/api/v1/endpoints/compliance.pyindex 4d84b92a5..1d9198320 100644--- a/services/api/app/api/v1/endpoints/compliance.py+++ b/services/api/app/api/v1/endpoints/compliance.py@@ -255,7 +255,7 @@ async def collect_evidence(body: CollectEvidenceRequest, db: DBSession, user: Aucollected_at, status, created_at) VALUES (:id, :tenant_id, :case_id, :fw, :ctrl, :title,- :kind, :summary, :payload::jsonb, :hash, :prev,+ :kind, :summary, CAST(:payload AS jsonb), :hash, :prev,:now, 'pending', :now) RETURNING *""").bindparams(@@ -340,7 +340,7 @@ async def review_evidence(evidence_id: uuid.UUID, body: ReviewEvidenceRequest, dUPDATE aisoc_compliance_evidenceSET status = :decision, reviewed_by = :reviewer, reviewed_at = :nowWHERE id = :id AND tenant_id = :tenant_id RETURNING *- """).bindparams(id=evidence_id, tenant_id=user.tenant_id, decision=body.decision, reviewer=body.reviewer or str(user), now=now)+ """).bindparams(id=evidence_id, tenant_id=user.tenant_id, decision=body.decision, reviewer=body.reviewer or user.email, now=now)try:row = (await db.execute(q)).fetchone()if not row:diff --git a/services/api/app/api/v1/endpoints/knowledge_base.py b/services/api/app/api/v1/endpoints/knowledge_base.pyindex d56bf6644..f008fa122 100644--- a/services/api/app/api/v1/endpoints/knowledge_base.py+++ b/services/api/app/api/v1/endpoints/knowledge_base.py@@ -167,7 +167,7 @@ async def ingest(body: IngestRequest, db: DBSession, user: AuthUser) -> list[KBDid, tenant_id, title, doc_kind, source_url, content, tags,chunk_index, chunk_total, created_at, updated_at, created_by) VALUES (- :id, :tenant_id, :title, :kind, :url, :content, :tags::text[],+ :id, :tenant_id, :title, :kind, :url, :content, CAST(:tags AS text[]),:idx, :total, :now, :now, :user) RETURNING *""").bindparams(@@ -181,7 +181,7 @@ async def ingest(body: IngestRequest, db: DBSession, user: AuthUser) -> list[KBDidx=idx,total=len(chunks),now=now,- user=str(user) if user else "system",+ user=user.email if user else "system",)try:row = (await db.execute(q)).fetchone()diff --git a/services/api/app/api/v1/endpoints/phishing.py b/services/api/app/api/v1/endpoints/phishing.pyindex 1724a9377..e82572c9c 100644--- a/services/api/app/api/v1/endpoints/phishing.py+++ b/services/api/app/api/v1/endpoints/phishing.py@@ -295,13 +295,13 @@ async def submit(body: SubmitRequest, db: DBSession, user: AuthUser) -> Submissisubmitted_at, triaged_at, created_at) VALUES (:id, :tenant_id, :by, :kind, :content, :sender, :subject,- :urls::text[], :verdict, :conf, :iocs::jsonb, :mitre,+ CAST(:urls AS text[]), :verdict, :conf, CAST(:iocs AS jsonb), :mitre,:now, :now, :now) RETURNING *""").bindparams(id=sub_id,tenant_id=user.tenant_id,- by=str(user) if user else "system",+ by=user.email if user else "system",kind=body.artifact_kind,content=body.raw_content,sender=body.sender,@@ -389,7 +389,7 @@ async def retriage(submission_id: uuid.UUID, db: DBSession, user: AuthUser) -> Snow = datetime.now(UTC)q = text("""UPDATE aisoc_phishing_submissions- SET verdict = :verdict, confidence = :conf, indicators = :iocs::jsonb,+ SET verdict = :verdict, confidence = :conf, indicators = CAST(:iocs AS jsonb),mitre_technique = :mitre, triaged_at = :nowWHERE id = :id AND tenant_id = :tenant_id RETURNING *""").bindparams(diff --git a/services/api/tests/test_authenticated_principal_attrs.py b/services/api/tests/test_authenticated_principal_attrs.pyindex 9873a8cb7..c6603c06b 100644--- a/services/api/tests/test_authenticated_principal_attrs.py+++ b/services/api/tests/test_authenticated_principal_attrs.py@@ -30,9 +30,12 @@ from __future__ import annotationsimport astimport pathlib+import uuidfrom app.api.v1.deps import CurrentUser+_UUID = uuid.uuid4()+ENDPOINTS = pathlib.Path(__file__).resolve().parents[1] / "app" / "api" / "v1" / "endpoints"# Names the codebase binds to the resolved principal.@@ -97,6 +100,74 @@ def test_no_handler_reads_an_attribute_the_principal_lacks() -> None:assert not offenders, "authenticated principal has no such attribute:\n " + "\n ".join(offenders)+def _stringified_principals(fn: ast.AST, bound: set[str]) -> list[str]:+ """Calls to ``str()`` on a name bound to the principal, inside ``fn``."""+ found: list[str] = []+ for node in ast.walk(fn):+ if (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "str"+ and len(node.args) == 1+ and isinstance(node.args[0], ast.Name)+ and node.args[0].id in bound+ ):+ found.append(f"{node.lineno} str({node.args[0].id})")+ return found+++def test_no_handler_stringifies_the_principal() -> None:+ """``str(user)`` is a memory address, and three actor columns held one.++ The attribute gate above walks ``ast.Attribute`` and so never saw this:+ ``str(user)`` is an ``ast.Call``. ``CurrentUser`` is a plain class, so the+ value bound into ``submitted_by``, ``created_by`` and ``reviewed_by`` was+ ``<app.api.v1.deps.CurrentUser object at 0x...>`` — in the column an+ auditor reads, and for ``created_by`` rendered back over the API. It+ passed because the test helper assigned ``__str__`` to its mock, making+ the fake friendlier than the thing it stood in for.++ Bind the attribute you mean (``user.email``, ``user.user_id``). A+ ``__repr__`` now exists on ``CurrentUser`` so a stray one is at least+ legible, but a repr is a diagnostic, never an actor identity.+ """+ offenders: list[str] = []+ for path in sorted(ENDPOINTS.glob("*.py")):+ tree = ast.parse(path.read_text(), filename=str(path))+ for fn in ast.walk(tree):+ if not isinstance(fn, ast.FunctionDef | ast.AsyncFunctionDef):+ continue+ bound = _principal_locals(fn)+ if not bound:+ continue+ offenders.extend(f"{path.name}:{hit}" for hit in _stringified_principals(fn, bound))++ assert not offenders, "stringify the attribute, not the principal:\n " + "\n ".join(offenders)+++def test_the_stringify_gate_would_catch_the_defect_it_was_written_for() -> None:+ """Feed it the original shape; a gate that cannot fail is decorative."""+ source = (+ "async def submit(\n"+ " user: AuthUser,\n"+ "):\n"+ " return q.bindparams(by=str(user) if user else 'system', tenant=str(user.tenant_id))\n"+ )+ fn = ast.parse(source).body[0]+ bound = _principal_locals(fn)+ assert bound == {"user"}+ hits = _stringified_principals(fn, bound)+ assert len(hits) == 1 and hits[0].endswith("str(user)"), hits+++def test_the_authenticated_principal_is_legible_when_printed() -> None:+ """No ``CurrentUser`` should ever render as an address, gate or no gate."""+ rendered = str(CurrentUser(user_id=_UUID, tenant_id=_UUID, role="analyst", email="[email protected]"))+ assert "object at 0x" not in rendered, rendered+ assert str(_UUID) in rendered and "analyst" in rendered, rendered+ assert "[email protected]" not in rendered, "the repr reaches logs and tracebacks; keep the address out of it"++def test_the_gate_would_catch_the_defect_it_was_written_for() -> None:"""A gate that cannot fail is decorative. Feed it the original shape."""source = (diff --git a/services/api/tests/test_compliance_phishing_kb_tenant_isolation.py b/services/api/tests/test_compliance_phishing_kb_tenant_isolation.pyindex b5136ae09..35819b2bf 100644--- a/services/api/tests/test_compliance_phishing_kb_tenant_isolation.py+++ b/services/api/tests/test_compliance_phishing_kb_tenant_isolation.py@@ -11,6 +11,7 @@ Follows the same mock-session pattern used byfrom __future__ import annotations+import jsonimport reimport uuidfrom datetime import UTC, datetime@@ -18,20 +19,38 @@ from typing import Anyfrom unittest.mock import AsyncMock, MagicMockimport pytest+from app.api.v1.deps import CurrentUser# ────────────────────────────────────────────────────────────────────────────# Helpers# ────────────────────────────────────────────────────────────────────────────-def _user(tenant_id: uuid.UUID | None = None) -> MagicMock:- """Construct an AuthUser-like object without touching DB or JWT."""- u = MagicMock()- u.tenant_id = tenant_id or uuid.uuid4()- u.user_id = uuid.uuid4()- u.email = "[email protected]"- u.__str__ = lambda self: self.email- return u+def _bound(executed: list[tuple[str, dict[str, Any]]], fragment: str) -> dict[str, Any]:+ """Return the bound parameters of the one executed statement matching ``fragment``."""+ normalized = [(re.sub(r"\s+", " ", sql).lower(), params) for sql, params in executed]+ matches = [params for sql, params in normalized if fragment.lower() in sql]+ assert matches, f"no executed statement contained {fragment!r}; saw {[s for s, _ in normalized]}"+ return matches[0]+++def _user(tenant_id: uuid.UUID | None = None) -> CurrentUser:+ """Construct the real authenticated principal without touching DB or JWT.++ This used to be a ``MagicMock`` that assigned ``__str__``. That one line+ made ``str(user)`` return an email under test while the real+ :class:`CurrentUser` returned ``<...CurrentUser object at 0x...>``, so+ three handlers stamping an actor column that way passed their tests and+ wrote an object address to the column an auditor reads. Use the real+ class: a principal fake that is friendlier than the principal proves+ nothing about the principal.+ """+ return CurrentUser(+ user_id=uuid.uuid4(),+ tenant_id=tenant_id or uuid.uuid4(),+ role="analyst",+ email="[email protected]",+ )def _mk_db(rows: list[Any]) -> MagicMock:@@ -196,21 +215,35 @@ class TestComplianceTenantIsolation:assert exc.value.status_code == 404_assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_compliance_evidence")- def test_collect_evidence_sql_includes_tenant_id(self) -> None:- """The INSERT statement in collect_evidence must include tenant_id.-- We inspect the source rather than calling the function because- SQLAlchemy's ``text().bindparams()`` cannot resolve PostgreSQL- cast syntax (``::jsonb``) without a live DB connection.+ @pytest.mark.asyncio+ async def test_collect_evidence_binds_the_callers_tenant(self) -> None:+ """The INSERT must run, and must bind the caller's tenant_id.++ This asserted on ``inspect.getsource`` under a docstring claiming+ ``text().bindparams()`` needed a live connection to resolve a+ ``::jsonb`` cast. ``bindparams()`` never opens a connection, and the+ cast was not being resolved at all: SQLAlchemy's scanner refuses a+ parameter name followed by a colon, so ``:payload::jsonb`` declared+ ``payload`` minus its last character and ``.bindparams(payload=...)``+ raised before the route reached the ``try``. Calling the handler is+ what makes that visible."""- import inspect+ from app.api.v1.endpoints.compliance import CollectEvidenceRequest, collect_evidence- from app.api.v1.endpoints.compliance import collect_evidence+ user = _user()+ row = _evidence_row(user.tenant_id)+ db = _mk_db([None, row]) # _latest_hash finds nothing, then the INSERT returns+ body = CollectEvidenceRequest(+ framework="SOC2", control_id="CC7.2", evidence_kind="alert", summary="Evidence summary", raw_payload={"a": 1}+ )- src = inspect.getsource(collect_evidence)- # The INSERT column list and VALUES list must both mention tenant_id.- assert "tenant_id" in src, "collect_evidence INSERT must include tenant_id"- assert "user.tenant_id" in src, "collect_evidence must bind user.tenant_id"+ result = await collect_evidence(body=body, db=db, user=user)++ assert result.id == row.id+ _assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_compliance_evidence")+ params = _bound(db.executed, "insert into aisoc_compliance_evidence")+ assert params["tenant_id"] == user.tenant_id+ assert params["payload"] == '{"a": 1}', "the jsonb cast must not swallow the bound payload"@pytest.mark.asyncioasync def test_review_evidence_cross_tenant_returns_404(self) -> None:@@ -225,6 +258,25 @@ class TestComplianceTenantIsolation:assert exc.value.status_code == 404_assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_compliance_evidence")+ @pytest.mark.asyncio+ async def test_review_evidence_stamps_a_readable_reviewer(self) -> None:+ """``reviewed_by`` is the sign-off field on a compliance record.++ The handler falls back to the caller when the body names no reviewer,+ and that fallback was ``str(user)`` — so the requests that did not+ name a reviewer are exactly the ones whose sign-off became an object+ address.+ """+ from app.api.v1.endpoints.compliance import ReviewEvidenceRequest, review_evidence++ user = _user()+ db = _mk_db([_evidence_row(user.tenant_id)])+ await review_evidence(evidence_id=uuid.uuid4(), body=ReviewEvidenceRequest(decision="accepted"), db=db, user=user)++ params = _bound(db.executed, "update aisoc_compliance_evidence")+ assert params["reviewer"] == "[email protected]", f"reviewed_by must name the reviewer, got {params['reviewer']!r}"+ assert "object at 0x" not in params["reviewer"]+@pytest.mark.asyncioasync def test_compliance_report_scopes_by_tenant(self) -> None:from app.api.v1.endpoints.compliance import compliance_report@@ -268,20 +320,35 @@ class TestPhishingTenantIsolation:assert exc.value.status_code == 404_assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_phishing_submissions")- def test_submit_sql_includes_tenant_id(self) -> None:- """The INSERT statement in submit must include tenant_id.-- SQLAlchemy's ``text().bindparams()`` cannot resolve PostgreSQL- array cast syntax (``::text[]``) without a live DB connection,- so we inspect the source instead.+ @pytest.mark.asyncio+ async def test_submit_binds_the_callers_tenant_and_a_readable_actor(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """The INSERT must run, bind the caller's tenant, and name a real actor.++ Was an ``inspect.getsource`` substring check. Two defects hid behind+ it: ``:urls::text[]`` and ``:iocs::jsonb`` each declared a truncated+ parameter, so ``.bindparams()`` raised on every call; and+ ``submitted_by`` was stamped with ``str(user)``, which on the real+ principal is an object address."""- import inspect+ from app.api.v1.endpoints import phishing as phishing_mod+ from app.api.v1.endpoints.phishing import SubmitRequest, submit- from app.api.v1.endpoints.phishing import submit+ monkeypatch.setattr(phishing_mod, "_triage", AsyncMock(return_value=None))+ user = _user()+ row = _phishing_row(user.tenant_id)+ db = _mk_db([row])+ body = SubmitRequest(artifact_kind="email", raw_content="Click here to verify", urls=["https://evil.com/phish"])- src = inspect.getsource(submit)- assert "tenant_id" in src, "submit INSERT must include tenant_id"- assert "user.tenant_id" in src, "submit must bind user.tenant_id"+ result = await submit(body=body, db=db, user=user)++ assert result.id == row.id+ _assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_phishing_submissions")+ params = _bound(db.executed, "insert into aisoc_phishing_submissions")+ assert params["tenant_id"] == user.tenant_id+ assert params["urls"] == ["https://evil.com/phish"], "the text[] cast must not swallow the bound urls"+ assert json.loads(params["iocs"]), "the jsonb cast must not swallow the bound indicators"+ assert params["by"] == "[email protected]", f"submitted_by must name the analyst, got {params['by']!r}"+ assert "object at 0x" not in params["by"]@pytest.mark.asyncioasync def test_retriage_cross_tenant_returns_404(self) -> None:@@ -295,6 +362,30 @@ class TestPhishingTenantIsolation:assert exc.value.status_code == 404_assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_phishing_submissions")+ @pytest.mark.asyncio+ async def test_retriage_reaches_the_update(self, monkeypatch: pytest.MonkeyPatch) -> None:+ """The UPDATE must run. Only the 404 branch was covered.++ ``test_retriage_cross_tenant_returns_404`` hands the handler an empty+ SELECT, so it returns before the UPDATE. That left the UPDATE's+ ``indicators = :iocs::jsonb`` unexercised, and it raised on every+ request that got past the SELECT.+ """+ from app.api.v1.endpoints import phishing as phishing_mod+ from app.api.v1.endpoints.phishing import retriage++ monkeypatch.setattr(phishing_mod, "_triage", AsyncMock(return_value=None))+ user = _user()+ existing = _phishing_row(user.tenant_id)+ db = _mk_db([existing, _phishing_row(user.tenant_id)])++ result = await retriage(submission_id=existing.id, db=db, user=user)++ assert result.verdict+ params = _bound(db.executed, "update aisoc_phishing_submissions")+ assert params["tenant_id"] == user.tenant_id+ assert json.loads(params["iocs"]) is not None, "the jsonb cast must not swallow the bound indicators"+# ────────────────────────────────────────────────────────────────────────────# Knowledge Base endpoint tests@@ -358,17 +449,29 @@ class TestKnowledgeBaseTenantIsolation:normalized = re.sub(r"\s+", " ", sql).lower()assert "tenant_id" in normalized, f"DELETE against aisoc_kb_documents missing tenant_id: {sql}"- def test_ingest_sql_includes_tenant_id(self) -> None:- """The INSERT statement in ingest must include tenant_id.-- SQLAlchemy's ``text().bindparams()`` cannot resolve PostgreSQL- array cast syntax (``::text[]``) without a live DB connection,- so we inspect the source instead.+ @pytest.mark.asyncio+ async def test_ingest_binds_the_callers_tenant_and_a_readable_actor(self) -> None:+ """The INSERT must run, bind the caller's tenant, and name a real actor.++ Was an ``inspect.getsource`` substring check, which hid the same two+ defects as ``phishing.submit``: ``:tags::text[]`` declared ``tag`` and+ ``.bindparams(tags=...)`` raised, and ``created_by`` was stamped with+ ``str(user)``. ``created_by`` is returned by the API, so the object+ address was rendered back to the operator."""- import inspect+ from app.api.v1.endpoints.knowledge_base import IngestRequest, ingest- from app.api.v1.endpoints.knowledge_base import ingest+ user = _user()+ row = _kb_row(user.tenant_id)+ db = _mk_db([row])+ body = IngestRequest(title="Incident Response Runbook", doc_kind="runbook", content="Step 1: contain.", tags=["ir", "runbook"])- src = inspect.getsource(ingest)- assert "tenant_id" in src, "ingest INSERT must include tenant_id"- assert "user.tenant_id" in src, "ingest must bind user.tenant_id"+ result = await ingest(body=body, db=db, user=user)++ assert result and result[0].id == row.id+ _assert_tenant_scoped(db.executed, user.tenant_id, "aisoc_kb_documents")+ params = _bound(db.executed, "insert into aisoc_kb_documents")+ assert params["tenant_id"] == user.tenant_id+ assert params["tags"] == ["ir", "runbook"], "the text[] cast must not swallow the bound tags"+ assert params["user"] == "[email protected]", f"created_by must name the analyst, got {params['user']!r}"+ assert "object at 0x" not in params["user"]