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.

merge: renumber lane C's migrations to 104/105 after a claim collision

Beenu Aroraf29c399a3f9f
diff --cc .github/workflows/verification-live.yml
index a8f148e40,000000000..a9c5e1b28
mode 100644,000000..100644
--- a/.github/workflows/verification-live.yml
+++ b/.github/workflows/verification-live.yml
@@@ -1,104 -1,0 +1,104 @@@
+name: Stateful user verification (live)
+
+# Depth 5.4. The verification workflow is covered offline against a double
+# that honours the predicates the real statements carry, and a double cannot
+# answer the two questions that matter here: whether migration 102 applies,
+# and whether the conditional UPDATEs really are atomic claims. Postgres
+# answers both.
+#
+# The offline suite is the one that runs on every pull request; this one
+# grades the storage layer the offline suite stands in for.
+
+on:
+ pull_request:
+ paths:
- - "services/api/migrations/102_playbook_verification.sql"
++ - "services/api/migrations/104_playbook_verification.sql"
+ - "services/agents/app/playbook/pause.py"
+ - "services/agents/app/playbook/verification.py"
+ - "tests/isolation/test_verification_pause_live.py"
+ - ".github/workflows/verification-live.yml"
+ push:
+ branches: [main]
+ workflow_dispatch:
+
+# Per commit on a push and per pull request on a PR. Keying on `github.ref`
+# makes a push to `main` cancel the run before it, which across this
+# repository left 0 of 22 required checks graded on all of the last 30
+# commits.
+concurrency:
+ group: verification-live-${{ github.event_name == 'push' && github.sha || github.event.pull_request.number }}
+ cancel-in-progress: false
+
+jobs:
+ verification-live:
+ name: A verification pause survives, escalates once and answers once
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+
+ services:
+ postgres:
+ image: public.ecr.aws/docker/library/postgres:16-alpine
+ env:
+ POSTGRES_USER: aisoc
+ POSTGRES_PASSWORD: aisoc_ci_only
+ POSTGRES_DB: aisoc
+ ports: ["5432:5432"]
+ options: >-
+ --health-cmd "pg_isready -U aisoc"
+ --health-interval 5s
+ --health-timeout 5s
+ --health-retries 20
+
+ env:
+ LIVE_DSN: postgresql://aisoc:aisoc_ci_only@localhost:5432/aisoc
+ PGPASSWORD: aisoc_ci_only
+ OTEL_SDK_DISABLED: "true"
+
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+
+ - uses: actions/setup-python@e9d6f990972a57673cdb72ec29e19d42ba28880f # v6
+ with:
+ python-version: "3.11"
+
+ - name: Install agents from its lockfile
+ working-directory: services/agents
+ run: |
+ set -euo pipefail
+ python -m pip install --quiet --upgrade pip "poetry==2.4.1"
+ poetry config virtualenvs.create false
+ poetry install --no-root --no-interaction
+ python -m pip install --quiet pytest pytest-asyncio
+
+ - name: Apply every migration, in order
+ run: |
+ set -euo pipefail
+ for f in services/api/migrations/*.sql; do
+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -f "$f"
+ done
+
+ # The migration applying is itself the first assertion: `102` alters a
+ # CHECK constraint, and a constraint name that drifted would fail here
+ # rather than on somebody's deployment.
+ - name: The pause table carries the verification columns
+ run: |
+ set -euo pipefail
+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \
+ "SELECT verification_stage, verification_outcome FROM aisoc_playbook_pauses WHERE false;"
+
+ - name: The verification pause, against the real schema
+ working-directory: services/agents
+ env:
+ ISOLATION_VERIFICATION_DSN: ${{ env.LIVE_DSN }}
+ run: python -m pytest ../../tests/isolation/test_verification_pause_live.py -v --tb=short -rs
+
+ # A suite that skipped reports the same word as one that passed, so the
+ # job asserts the DSN was set rather than trusting the run.
+ - name: No suite may report success having skipped
+ if: always()
+ run: |
+ set -euo pipefail
+ if [ -z "${LIVE_DSN}" ]; then
+ echo "::error::LIVE_DSN is empty, so the live suite skipped and this job proved nothing."
+ exit 1
+ fi
diff --cc DEPTH_PROGRESS.md
index 827b356b2,aec08e1cf..58ed5f4c7
--- a/DEPTH_PROGRESS.md
+++ b/DEPTH_PROGRESS.md
@@@ -55,12 -55,13 +55,18 @@@ is written. Next free at capture: migra
| Number | Claimed by | Status |
|---|---|---|
- | migration `102` | 5.4 stateful user/manager verification (verification requests, answers, tenant opt-in) | claimed |
- | migration `103` | 5.6 plain-language playbook drafts (draft, preview, approval) | claimed |
-
- The highest migration on `main` at the time of claiming is
- `101_audit_immutable_nullify.sql`; the plan's "next free `095`" is stale
- because six landed between capture and now. No ADR is claimed by Lane C.
+ | ADR `0010` | 2.7 — entity and session context in CORE | **landed**, `docs/decisions/0010-entity-and-session-context-in-core.md`, accepted |
+ | migration `102` | 2.4 — `102_sessions.sql` | claimed |
+ | migration `103` | 2.5 — `103_posture_snapshots.sql` | claimed |
++| migration `104` | 5.4 stateful user/manager verification (verification requests, answers, tenant opt-in) | claimed |
++| migration `105` | 5.6 plain-language playbook drafts (draft, preview, approval) | claimed |
+
-Highest migration on `main` at claim time was `101_audit_immutable_nullify.sql`,
-so `095`--`101` were taken by sibling lanes between the capture above and this
-claim; re-read `services/api/migrations/` rather than trusting the capture row.
++Lane B claimed `102`/`103` and landed that claim on `main` first, so Lane C's
++two moved to `104`/`105` and `102_playbook_verification.sql` was renamed with
++it. Both lanes had claimed before writing, as the plan requires -- what the
++rule cannot prevent is two lanes claiming the same free number before either
++merges, so re-read `services/api/migrations/` **and** this table before
++picking one.
## Phase 0: Kickoff
diff --cc scripts/check_stateful_verification.py
index e1135a39f,000000000..bacac462b
mode 100644,000000..100644
--- a/scripts/check_stateful_verification.py
+++ b/scripts/check_stateful_verification.py
@@@ -1,448 -1,0 +1,448 @@@
+#!/usr/bin/env python3
+"""Gate: asking a person about their own activity is a workflow, not a message.
+
+Depth plan 5.4. ``chatops_verify`` already posted a prompt and returned
+"awaiting completion", and that was honest about one message. What makes it
+a control rather than a notification is the four properties below, each of
+which can be removed without any test failing — the step would keep sending,
+the prompt would keep arriving, and the run would quietly stop branching.
+
+What this checks, and what each catches when it goes
+-----------------------------------------------------
+
+**A signed answer, bound to its stage.** The link arrives in a chat message
+to somebody holding no session, so the URL is the whole credential. Drop the
+signature and the route takes an answer from anyone who can reach it; drop
+the stage from the signature and the subject's own link answers on their
+manager's behalf an hour later, which defeats the escalation.
+
+**A deadline that escalates and then ends with an outcome.** A prompt nobody
+answers has to become ``timed_out``, a value a playbook can branch on.
+Without the sweep the run sits ``paused`` forever and the console shows a
+containment that is neither done nor abandoned.
+
+**Two refusals, in the right order.** Never on a confirmed true positive —
+no opt-out, because the message tells an attacker holding the account that
+they have been seen — and auto-sent only for classes a tenant opted into.
+The order matters: checking the opt-in first would let a tenant opt into
+messaging a compromised account.
+
+**A writer for the opt-in table.** The refusal fails closed, so a table with
+a reader and no writer is a feature that can never be switched on. That shape
+has shipped in this repository more than once.
+
+Run:
+ python3 scripts/check_stateful_verification.py
+ python3 scripts/check_stateful_verification.py --self-test
+"""
+
+from __future__ import annotations
+
+import argparse
+import re
+import shutil
+import sys
+import tempfile
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from gate_toolkit import TREE_SHAPES, refuses_an_empty_tree, repo_root
+
+REPO_ROOT = repo_root()
+
+VERIFICATION_PY = Path("services/agents/app/playbook/verification.py")
+ENGINE_PY = Path("services/agents/app/playbook/engine.py")
+PAUSE_PY = Path("services/agents/app/playbook/pause.py")
+SWEEPER_PY = Path("services/agents/app/playbook/sweeper.py")
+ROUTES_PY = Path("services/agents/app/api/playbooks.py")
+POLICY_ROUTES_PY = Path("services/api/app/api/v1/endpoints/verification_policies.py")
- MIGRATION = Path("services/api/migrations/102_playbook_verification.sql")
++MIGRATION = Path("services/api/migrations/104_playbook_verification.sql")
+
+#: Every outcome a run may branch on. Declared here so the three places that
+#: spell them — the module, the migration's CHECK and the pause writer — are
+#: compared against one list rather than against each other in a cycle.
+OUTCOMES = ("acknowledged", "denied", "unsure", "timed_out", "no_manager")
+
+
+def _function_body(source: str, name: str) -> str | None:
+ """One top-level function's source, by name.
+
+ Written as "until the next top-level def, or the end of the file"
+ rather than as "until two blank lines". The first version of this gate
+ matched `\n\n\n`, which silently found nothing for the *last* function
+ in a module — so the ordering rule below was skipped entirely and the
+ gate reported OK over an injected violation.
+ """
+ start = source.find(f"async def {name}(")
+ if start < 0:
+ start = source.find(f"def {name}(")
+ if start < 0:
+ return None
+ rest = source[start:]
+ nxt = re.search(r"\n(?:async def |def |class |@)", rest[1:])
+ return rest if nxt is None else rest[: nxt.start() + 1]
+
+
+def _read(root: Path, rel: Path) -> str | None:
+ path = root / rel
+ return path.read_text(encoding="utf-8") if path.is_file() else None
+
+
+def evaluate(root: Path) -> list[str]:
+ failures: list[str] = []
+ read_any = False
+
+ verification = _read(root, VERIFICATION_PY)
+ if verification is None:
+ failures.append(f"{VERIFICATION_PY} is missing: there is no stateful verification to check.")
+ else:
+ read_any = True
+ failures.extend(_check_signature(verification))
+ failures.extend(_check_refusals(verification))
+
+ engine = _read(root, ENGINE_PY)
+ if engine is None:
+ failures.append(f"{ENGINE_PY} is missing.")
+ else:
+ read_any = True
+ failures.extend(_check_engine(engine))
+
+ pause = _read(root, PAUSE_PY)
+ if pause is None:
+ failures.append(f"{PAUSE_PY} is missing.")
+ else:
+ read_any = True
+ failures.extend(_check_pause(pause))
+
+ sweeper = _read(root, SWEEPER_PY)
+ if sweeper is None:
+ failures.append(f"{SWEEPER_PY} is missing.")
+ else:
+ read_any = True
+ if "resume_due_verifications" not in sweeper:
+ failures.append(
+ f"{SWEEPER_PY} never calls resume_due_verifications, so a prompt nobody answers never escalates and "
+ f"never times out. The run sits paused forever and the only symptom is a containment that did not happen."
+ )
+
+ routes = _read(root, ROUTES_PY)
+ if routes is None:
+ failures.append(f"{ROUTES_PY} is missing.")
+ else:
+ read_any = True
+ if "verifications_router" not in routes:
+ failures.append(f"{ROUTES_PY} declares no verification callback route, so every answer link in every prompt is a 404.")
+ elif re.search(r"verifications_router\s*=\s*APIRouter\([^)]*dependencies\s*=", routes):
+ failures.append(
+ f"{ROUTES_PY}: the verification router declares an auth dependency. The person answering is the subject "
+ f"of an alert and holds no session by construction; the signature is the credential."
+ )
+
+ policy_routes = _read(root, POLICY_ROUTES_PY)
+ if policy_routes is None:
+ failures.append(
+ f"{POLICY_ROUTES_PY} is missing, so aisoc_verification_policies has a reader and no writer. The refusal "
+ f"fails closed, so a tenant could never switch automatic verification on and the feature reads as broken."
+ )
+ else:
+ read_any = True
+ if "require_permission" not in policy_routes:
+ failures.append(f"{POLICY_ROUTES_PY} does not check a permission, so any authenticated caller could grant this.")
+
+ migration = _read(root, MIGRATION)
+ if migration is None:
+ failures.append(f"{MIGRATION} is missing: the pause has nowhere to record a stage or an answer.")
+ else:
+ read_any = True
+ failures.extend(_check_migration(migration))
+
+ if not read_any:
+ failures.append(
+ "none of the files this gate checks exist. A clean result over a tree with nothing in it is the shape "
+ "this toolkit exists to refuse."
+ )
+ return failures
+
+
+def _check_signature(source: str) -> list[str]:
+ failures: list[str] = []
+ match = re.search(r"def sign_answer\(.*?\n(?:.|\n)*?return hmac\.new\(key, (\w+), hashlib\.sha256\)", source)
+ if not match:
+ failures.append(
+ f"{VERIFICATION_PY}: sign_answer does not end in an HMAC over a message. Without a signature the callback "
+ f"takes an answer from anybody who reaches the route."
+ )
+ return failures
+
+ message = re.search(r'message = f"\{([^"]*)\}"\.encode\(\)', source) or re.search(r"message = f\"([^\"]*)\"\.encode\(\)", source)
+ signed = message.group(1) if message else ""
+ for part, why in (
+ ("resume_token", "a signature that omits the token is reusable across pauses"),
+ ("answer", "a signature that omits the answer lets a holder of one link assert a different one"),
+ ("stage", "a signature that omits the stage lets the subject's own link answer for their manager"),
+ ):
+ if part not in signed:
+ failures.append(f"{VERIFICATION_PY}: sign_answer does not cover {part!r} — {why}.")
+
+ if "compare_digest" not in source:
+ failures.append(
+ f"{VERIFICATION_PY}: the signature is not compared with hmac.compare_digest, so the comparison leaks "
+ f"timing about how much of a forged signature was right."
+ )
+ if "VerificationConfigError" not in source:
+ failures.append(
+ f"{VERIFICATION_PY}: a missing secret does not raise. Returning an unsigned link instead would be a prompt "
+ f"whose answer nothing can authenticate."
+ )
+ return failures
+
+
+def _check_refusals(source: str) -> list[str]:
+ failures: list[str] = []
+ if "is_confirmed_true_positive" not in source:
+ failures.append(
+ f"{VERIFICATION_PY}: nothing refuses a confirmed true positive. Messaging an account an attacker holds "
+ f"tells them they are seen, and neither answer is worth having."
+ )
+ if "aisoc_verification_policies" not in source:
+ failures.append(f"{VERIFICATION_PY}: the opt-in table is never read, so a prompt is auto-sent for every alert class.")
+
+ text = _function_body(source, "may_auto_send")
+ if text:
+ tp = text.find("is_confirmed_true_positive")
+ opt_in = text.find("aisoc_verification_policies")
+ if tp < 0:
+ failures.append(f"{VERIFICATION_PY}: may_auto_send does not consult the true-positive refusal at all.")
+ elif 0 <= opt_in < tp:
+ failures.append(
+ f"{VERIFICATION_PY}: may_auto_send reads the opt-in table before the true-positive refusal. The "
+ f"true-positive rule has no opt-out, so it must be first — otherwise a tenant can opt into messaging "
+ f"a compromised account."
+ )
+ if "Unreadable permission is not permission" not in text and "could not be read" not in text:
+ failures.append(
+ f"{VERIFICATION_PY}: may_auto_send does not fail closed when the policy cannot be read. An unreadable grant is not a grant."
+ )
+ return failures
+
+
+def _check_engine(source: str) -> list[str]:
+ failures: list[str] = []
+ if "StepType.VERIFY_USER: _control_verify_user" not in source:
+ failures.append(f"{ENGINE_PY}: verify_user is not in the control-flow table, so the engine would fail it closed.")
+ if "resume_verification" not in source:
+ failures.append(f"{ENGINE_PY}: no resume path for a verification answer, so a signed answer wakes nothing.")
+ if "resume_due_verifications" not in source:
+ failures.append(f"{ENGINE_PY}: nothing escalates or times out a verification.")
+ if '"timed_out"' not in source:
+ failures.append(
+ f"{ENGINE_PY}: no timed_out outcome. An unanswered prompt would leave the run neither waiting nor finished, "
+ f"which is not something a playbook can branch on."
+ )
+ if "escalate_to_manager" not in source:
+ failures.append(f"{ENGINE_PY}: nothing escalates to a manager, so the second half of the workflow does not exist.")
+
+ # The run-loop break. Without it a durable pause writes its row and the
+ # run carries on into the steps the pause exists to hold back, then runs
+ # them again when the callback resumes.
+ if not re.search(r"StepStatus\.PENDING and result\.get\(\"paused\"\)", source):
+ failures.append(
+ f"{ENGINE_PY}: the run loop does not stop on a durable pause. A step that suspends to Postgres and returns "
+ f"PENDING would keep running, and the resume would run everything after it a second time."
+ )
+ return failures
+
+
+def _check_pause(source: str) -> list[str]:
+ failures: list[str] = []
+ for needed, why in (
+ ("find_verification_by_token", "the callback cannot find the run that is waiting"),
+ ("due_verifications", "nothing sweeps a stage deadline"),
+ ("escalate_to_manager", "the question never reaches a second person"),
+ ("record_verification_outcome", "the answer is never made durable"),
+ ):
+ if needed not in source:
+ failures.append(f"{PAUSE_PY}: {needed} is missing — {why}.")
+
+ escalation = _function_body(source, "escalate_to_manager")
+ if escalation and not re.search(r"AND\s+verification_stage\s*=\s*'user'", escalation):
+ failures.append(
+ f"{PAUSE_PY}: escalate_to_manager does not require the row to still be on the user stage, so two sweeper "
+ f"replicas would escalate the same pause twice and the manager would be asked twice."
+ )
+ outcome = _function_body(source, "record_verification_outcome")
+ if outcome and not re.search(r"AND\s+verification_outcome\s+IS\s+NULL", outcome):
+ failures.append(
+ f"{PAUSE_PY}: record_verification_outcome does not require the row to be unanswered, so a double click "
+ f"would overwrite the first answer."
+ )
+ lookup = _function_body(source, "find_verification_by_token")
+ # The SQL clause, not the phrase. This function's own docstring quotes
+ # the predicate, so a prose match survives deleting the clause — the
+ # exact blindness that makes a gate report OK over the defect it exists
+ # to catch.
+ if lookup and not re.search(r"AND\s+kind\s*=\s*'verification'", lookup):
+ failures.append(
+ f"{PAUSE_PY}: find_verification_by_token does not filter on kind, so a wait token could resolve as a "
+ f"verification and answer a question nobody asked."
+ )
+ return failures
+
+
+def _check_migration(source: str) -> list[str]:
+ failures: list[str] = []
+ if "'verification'" not in source:
+ failures.append(f"{MIGRATION}: the kind constraint does not admit 'verification', so every pause write would be refused.")
+ for outcome in OUTCOMES:
+ if f"'{outcome}'" not in source:
+ failures.append(
+ f"{MIGRATION}: the outcome constraint does not admit {outcome!r}. The code writes it, so Postgres would "
+ f"refuse the row at the moment somebody answered."
+ )
+ if "ENABLE ROW LEVEL SECURITY" not in source:
+ failures.append(
+ f"{MIGRATION}: aisoc_verification_policies has no row-level security, so one tenant's opt-in list is readable by another."
+ )
+ if "manager_ref" not in source:
+ failures.append(f"{MIGRATION}: no manager column, so the escalation has nobody to escalate to.")
+ return failures
+
+
+def _self_test() -> int:
+ results: list[tuple[str, bool]] = []
+ tracked = (VERIFICATION_PY, ENGINE_PY, PAUSE_PY, SWEEPER_PY, ROUTES_PY, POLICY_ROUTES_PY, MIGRATION)
+
+ baseline = evaluate(REPO_ROOT)
+ results.append(("the undisturbed tree is clean, so a caught case means something", not baseline))
+ for line in baseline[:8]:
+ print(f" {line}")
+
+ cases = (
+ ("an answer signature that omits the stage", "NO_STAGE"),
+ ("a signature compared with ==", "TIMING"),
+ ("an opt-in read before the true-positive refusal", "WRONG_ORDER"),
+ ("a sweeper that never escalates", "NO_SWEEP"),
+ ("a run loop that does not stop on a durable pause", "NO_BREAK"),
+ ("an escalation two replicas could run twice", "DOUBLE_ESCALATE"),
+ ("an outcome that can be overwritten by a second click", "DOUBLE_ANSWER"),
+ ("a verification token lookup that would match a wait", "KIND_BLIND"),
+ ("an outcome the migration's CHECK would refuse", "CHECK_DRIFT"),
+ ("an opt-in table with no writer", "NO_WRITER"),
+ ("a callback route behind an auth dependency nobody answering holds", "GUARDED_CALLBACK"),
+ )
+
+ for label, kind in cases:
+ tmp = Path(tempfile.mkdtemp(prefix="aisoc-verify-selftest-"))
+ try:
+ for rel in tracked:
+ src = REPO_ROOT / rel
+ if src.is_file():
+ (tmp / rel).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(src, tmp / rel)
+ _inject(tmp, kind)
+ results.append((f"catches {label}", bool(evaluate(tmp))))
+ finally:
+ shutil.rmtree(tmp, ignore_errors=True)
+
+ details: list[str] = []
+ for shape in TREE_SHAPES:
+ refused, detail = refuses_an_empty_tree(Path(__file__).name, shape=shape)
+ results.append((f"refuses a {shape} tree rather than reporting it clean", refused))
+ details.append(f"{shape}: {detail}")
+
+ ok = True
+ for description, passed in results:
+ ok &= passed
+ print(f" {'PASS' if passed else 'FAIL'} {description}")
+ for line in "\n".join(details).splitlines():
+ print(f" {line}")
+ print()
+ if not ok:
+ print(f"{Path(__file__).name}: self-test FAILED")
+ return 1
+ print(f"{Path(__file__).name}: self-test OK")
+ return 0
+
+
+def _inject(root: Path, kind: str) -> None:
+ """One realistic regression per rule, written the way it would be written."""
+ verification = root / VERIFICATION_PY
+ engine = root / ENGINE_PY
+ pause = root / PAUSE_PY
+
+ if kind == "NO_STAGE":
+ text = verification.read_text(encoding="utf-8")
+ verification.write_text(text.replace('f"{resume_token}|{answer}|{stage}"', 'f"{resume_token}|{answer}"'), encoding="utf-8")
+ elif kind == "TIMING":
+ text = verification.read_text(encoding="utf-8")
+ verification.write_text(text.replace('hmac.compare_digest(expected, signature or "")', "expected == signature"), encoding="utf-8")
+ elif kind == "WRONG_ORDER":
+ text = verification.read_text(encoding="utf-8")
+ start = text.find("async def may_auto_send")
+ head, tail = text[:start], text[start:]
+ refusal_start = tail.find(" if is_confirmed_true_positive(context):")
+ refusal_end = tail.find(" classes = _alert_classes(")
+ refusal = tail[refusal_start:refusal_end]
+ # Genuinely moved, not disabled: an injection that leaves the call
+ # where it was would be caught by a gate reading the call's position
+ # and would prove nothing about the ordering rule.
+ tail = tail[:refusal_start] + tail[refusal_end:]
+ anchor = tail.find(" if row is None:")
+ verification.write_text(head + tail[:anchor] + refusal + tail[anchor:], encoding="utf-8")
+ elif kind == "NO_SWEEP":
+ path = root / SWEEPER_PY
+ path.write_text(path.read_text(encoding="utf-8").replace("resume_due_verifications", "_unused_sweep"), encoding="utf-8")
+ elif kind == "NO_BREAK":
+ text = engine.read_text(encoding="utf-8")
+ engine.write_text(re.sub(r'if step_status == StepStatus\.PENDING and result\.get\("paused"\)', "if False", text), encoding="utf-8")
+ elif kind == "DOUBLE_ESCALATE":
+ text = pause.read_text(encoding="utf-8")
+ pause.write_text(text.replace(" AND verification_stage = 'user'\n", "", 1), encoding="utf-8")
+ elif kind == "DOUBLE_ANSWER":
+ text = pause.read_text(encoding="utf-8")
+ pause.write_text(text.replace(" AND verification_outcome IS NULL\n", "", 1), encoding="utf-8")
+ elif kind == "KIND_BLIND":
+ text = pause.read_text(encoding="utf-8")
+ start = text.find("async def find_verification_by_token")
+ head, tail = text[:start], text[start:]
+ pause.write_text(head + tail.replace(" AND kind = 'verification'\n", "", 1), encoding="utf-8")
+ elif kind == "CHECK_DRIFT":
+ path = root / MIGRATION
+ path.write_text(path.read_text(encoding="utf-8").replace("'no_manager'", "'no_mgr'"), encoding="utf-8")
+ elif kind == "NO_WRITER":
+ (root / POLICY_ROUTES_PY).unlink(missing_ok=True)
+ elif kind == "GUARDED_CALLBACK":
+ path = root / ROUTES_PY
+ path.write_text(
+ path.read_text(encoding="utf-8").replace(
+ 'verifications_router = APIRouter(prefix="/api/v1/playbook-verifications", tags=["playbooks"])',
+ 'verifications_router = APIRouter(prefix="/api/v1/playbook-verifications", tags=["playbooks"], '
+ "dependencies=[Depends(require_console_or_service_auth)])",
+ ),
+ encoding="utf-8",
+ )
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--self-test", action="store_true", help="inject one violation per rule and require each to be caught")
+ args = parser.parse_args(argv)
+ if args.self_test:
+ return _self_test()
+
+ failures = evaluate(REPO_ROOT)
+ if failures:
+ print("STATEFUL VERIFICATION GATE FAILED:", file=sys.stderr)
+ for failure in failures:
+ print(f" - {failure}", file=sys.stderr)
+ return 1
+ print(
+ "stateful-verification: OK — the answer is signed and bound to its stage, an unanswered prompt escalates and "
+ "then times out with an outcome, a confirmed true positive is never asked, and the opt-in table has a writer."
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --cc services/agents/app/api/playbooks.py
index 7e5aca624,0e1394cf0..318596b4b
--- a/services/agents/app/api/playbooks.py
+++ b/services/agents/app/api/playbooks.py
@@@ -270,74 -259,3 +270,74 @@@ async def _resume_wait_in_background(re
logger.info("playbook wait callback matched no waiting run (already resumed)")
return
_runs[run.run_id] = run
+
+
+# ---------------------------------------------------------------------------
+# Verification answers
+# ---------------------------------------------------------------------------
+
+
+@verifications_router.get(
+ "/{resume_token}/{answer}",
+ summary="Record a verification answer and resume the run",
+ response_class=HTMLResponse,
+)
+async def answer_verification(resume_token: str, answer: str, sig: str = Query("", max_length=128)) -> HTMLResponse:
+ """The link in the chat message. A GET, because it is clicked.
+
+ Answers HTML rather than JSON: it lands in whatever browser the chat
+ client opens, in front of a person who is not an operator and should
+ see a sentence rather than a payload.
+
+ One refusal for every way this can fail — unknown token, wrong
+ signature, stale stage, already answered. Distinguishing them would
+ turn the route into an oracle for whether a token was ever valid, and
+ the person clicking cannot act on the difference anyway.
+
+ The run resumes **inline** rather than in a background task, unlike the
+ wait callback next door. A vendor's webhook sender wants a fast 2xx and
+ retries on a slow one; a person wants to be told their answer was
+ recorded, and the containment that follows is the thing they are
+ waiting to hear about.
+ """
+ if answer not in verification.ANSWERS:
+ return HTMLResponse(_verification_html(_VERIFY_REFUSED_TITLE, _VERIFY_REFUSED_BODY, ok=False), status_code=400)
+
+ run = await engine_module.resume_verification(resume_token=resume_token, answer=answer, signature=sig)
+ if run is None:
+ return HTMLResponse(_verification_html(_VERIFY_REFUSED_TITLE, _VERIFY_REFUSED_BODY, ok=False), status_code=400)
+
+ _runs[run.run_id] = run
+ return HTMLResponse(
+ _verification_html(
+ "Thanks — that's recorded",
+ "Your security team has your answer and the alert has been updated. You do not need to do anything else.",
+ ok=True,
+ ),
+ status_code=200,
+ )
+
+
+_VERIFY_REFUSED_TITLE = "We couldn't record that"
+_VERIFY_REFUSED_BODY = (
+ "This link is no longer valid — it may have expired, already been used, or been replaced by a newer request. "
+ "Contact your security team if you still need to respond."
+)
+
+
+def _verification_html(title: str, body: str, *, ok: bool) -> str:
+ """A plain acknowledgement page.
+
+ No framework and no external asset: this is served to a person's
+ browser from a service that is not the console, and a page that fetches
+ anything would fail differently on every corporate network.
+ """
+ colour = "#0f766e" if ok else "#b91c1c"
+ return (
+ "<!doctype html><html lang='en'><head><meta charset='utf-8'>"
+ "<meta name='viewport' content='width=device-width,initial-scale=1'>"
+ f"<title>{html.escape(title)}</title></head>"
- "<body style=\"font-family:Arial,sans-serif;max-width:34rem;margin:4rem auto;padding:0 1rem;line-height:1.6\">"
++ '<body style="font-family:Arial,sans-serif;max-width:34rem;margin:4rem auto;padding:0 1rem;line-height:1.6">'
+ f"<h1 style='color:{colour};font-size:1.3rem'>{html.escape(title)}</h1>"
+ f"<p>{html.escape(body)}</p></body></html>"
+ )
diff --cc services/api/migrations/104_playbook_verification.sql
index e7e05266c,000000000..68dc77c6a
mode 100644,000000..100644
--- a/services/api/migrations/104_playbook_verification.sql
+++ b/services/api/migrations/104_playbook_verification.sql
@@@ -1,151 -1,0 +1,151 @@@
- -- 102_playbook_verification.sql — make "ask the user, then their manager" a
++-- 104_playbook_verification.sql — make "ask the user, then their manager" a
+-- state a run can sit in, rather than a message it sends and forgets.
+--
+-- Depth plan 5.4. `chatops_verify` posts an interactive prompt and returns
+-- AWAITING_COMPLETION. That is honest about one prompt and is not a
+-- workflow: nothing remembers who was asked, nothing escalates when the
+-- person does not answer, and the signed reply lands on a callback that
+-- writes a timeline event and ends there. A playbook therefore cannot
+-- branch on the answer, which is the only reason to ask the question.
+--
+-- Three columns and one table, on the same reasoning migration 096 used for
+-- `wait`: `aisoc_playbook_pauses` already stores the position, the context
+-- and the step results a suspended run needs, and does so on disk because
+-- surviving a restart is the requirement. A verification needs all of that
+-- plus who is being asked and which stage it has reached.
+--
+-- Why a third `kind` rather than a second table
+-- ---------------------------------------------
+-- The sweeper, the resume path and the RLS policy would all have to be
+-- written twice, and the second copy is where "a pause that never wakes"
+-- comes back. A verification *is* a pause: it is waiting on a person, like
+-- an approval, and on a clock, like a wait.
+--
+-- Why the stage is a column and not inferred
+-- ------------------------------------------
+-- The escalation to the manager reuses the same row: the deadline moves and
+-- the stage advances. Inferring "we must be on the manager now" from a
+-- non-null manager column would make a resolved manager with an unanswered
+-- user prompt look like an escalation that already happened.
+--
+-- Reversible: DROP COLUMN IF EXISTS on each, DROP TABLE on the policy table,
+-- and the CHECK reverts to the two-value form.
+
+-- ── The pause grows a third kind ────────────────────────────────────────────
+
+ALTER TABLE aisoc_playbook_pauses
+ DROP CONSTRAINT IF EXISTS aisoc_playbook_pauses_kind_check;
+
+ALTER TABLE aisoc_playbook_pauses
+ ADD CONSTRAINT aisoc_playbook_pauses_kind_check
+ CHECK (kind IN ('approval', 'wait', 'verification'));
+
+-- Which half of the workflow this row is in. NULL for an approval and a
+-- wait, which have no stages.
+ALTER TABLE aisoc_playbook_pauses
+ ADD COLUMN IF NOT EXISTS verification_stage TEXT
+ CHECK (verification_stage IS NULL OR verification_stage IN ('user', 'manager'));
+
+-- Who the alert is about. Kept beside the pause rather than dug out of
+-- `run_context` at resume time, because the escalation needs it before the
+-- run is rebuilt and a context key is not a contract.
+ALTER TABLE aisoc_playbook_pauses
+ ADD COLUMN IF NOT EXISTS verification_subject TEXT;
+
+-- Who was asked second, resolved once at the point of escalation. NULL both
+-- before the escalation and when no manager could be resolved at all —
+-- which are different facts, and `verification_outcome` records the second
+-- one as `no_manager` rather than leaving it to be inferred from a NULL.
+ALTER TABLE aisoc_playbook_pauses
+ ADD COLUMN IF NOT EXISTS verification_manager TEXT;
+
+-- The answer, once there is one. Written by the callback before the run
+-- resumes, so a replayed click reads an already-answered row.
+ALTER TABLE aisoc_playbook_pauses
+ ADD COLUMN IF NOT EXISTS verification_outcome TEXT
+ CHECK (verification_outcome IS NULL OR verification_outcome IN (
+ 'acknowledged', 'denied', 'unsure', 'timed_out', 'no_manager'
+ ));
+
+COMMENT ON COLUMN aisoc_playbook_pauses.verification_stage IS
+ 'user = the affected person was asked; manager = it escalated to their manager.';
+COMMENT ON COLUMN aisoc_playbook_pauses.verification_outcome IS
+ 'The signed answer, or timed_out / no_manager. A run branches on this.';
+
+-- The sweeper's second query: verifications whose stage deadline has passed.
+-- Partial for the reason the wait index is: resolved rows accumulate and a
+-- full scan every tick costs history rather than work.
+CREATE INDEX IF NOT EXISTS aisoc_playbook_pauses_verification_due_idx
+ ON aisoc_playbook_pauses (resume_at)
+ WHERE status = 'waiting' AND kind = 'verification' AND resume_at IS NOT NULL;
+
+-- ── Who may be asked without a human saying so ──────────────────────────────
+--
+-- The contract's caution, as data. Two rules, and they are not the same
+-- rule:
+--
+-- * A confirmed true positive is never asked. Messaging the account an
+-- attacker is sitting on tells the attacker they are seen, and the
+-- answer is worthless either way — the person whose credentials were
+-- stolen will truthfully say "no, that wasn't me" and the person who is
+-- the attacker will say whatever keeps the session alive.
+-- * Everything else is asked only for alert classes this tenant opted
+-- into. A verification prompt is a message to a colleague from a
+-- security system; a product that sends those by default on day one is
+-- uninstalled by the end of the week.
+--
+-- Default-deny: a tenant with no row here auto-sends nothing. A playbook an
+-- analyst runs by hand is a human decision and is not governed by this
+-- table.
+CREATE TABLE IF NOT EXISTS aisoc_verification_policies (
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+
+ -- The alert class, matched case-insensitively against the alert's
+ -- `rule_id`, `category` or `alert_class`. One row per class rather than
+ -- an array column so a grant can be revoked by deleting a row and the
+ -- audit trail reads as a list of decisions.
+ alert_class TEXT NOT NULL,
+
+ -- Who turned it on, for the review that follows the first complaint.
+ enabled_by UUID REFERENCES users(id) ON DELETE SET NULL,
+ enabled_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+
+ PRIMARY KEY (tenant_id, alert_class)
+);
+
+COMMENT ON TABLE aisoc_verification_policies IS
+ 'Alert classes a tenant allows automatic user-verification prompts for. Absent = never auto-send.';
+
+ALTER TABLE aisoc_verification_policies ENABLE ROW LEVEL SECURITY;
+ALTER TABLE aisoc_verification_policies FORCE ROW LEVEL SECURITY;
+
+DROP POLICY IF EXISTS tenant_isolation ON aisoc_verification_policies;
+CREATE POLICY tenant_isolation ON aisoc_verification_policies
+ -- The unbound arm matches `aisoc_playbook_pauses` above and exists for
+ -- the same reason: the agents service reads this from a Kafka consumer
+ -- that binds no tenant, and without it every policy lookup would come
+ -- back empty — which fails *closed* here, so the table would look
+ -- installed and refuse every prompt.
+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)
+ WITH CHECK (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);
+
+-- ── The manager, from SCIM ──────────────────────────────────────────────────
+--
+-- SCIM's enterprise extension carries `manager.value`, and every IdP that
+-- provisions users sends it when the directory has one. The column was
+-- missing, so the platform held a provisioned directory and could not
+-- answer "who does this person report to" — the one question an escalation
+-- needs.
+--
+-- Stored as the provider's own reference (`manager.value` is an id in Okta
+-- and Entra, an email in some others) rather than resolved to a local user
+-- id, because the manager is frequently not an AiSOC user at all.
+ALTER TABLE aisoc_scim_users
+ ADD COLUMN IF NOT EXISTS manager_ref TEXT;
+
+COMMENT ON COLUMN aisoc_scim_users.manager_ref IS
+ 'manager.value from the SCIM enterprise user extension; the provider''s own reference, not a local user id.';
+
+CREATE INDEX IF NOT EXISTS aisoc_scim_users_manager_idx
+ ON aisoc_scim_users (tenant_id, manager_ref)
+ WHERE manager_ref IS NOT NULL;
diff --cc tests/isolation/test_verification_pause_live.py
index 6519ea71c,000000000..c569b670b
mode 100644,000000..100644
--- a/tests/isolation/test_verification_pause_live.py
+++ b/tests/isolation/test_verification_pause_live.py
@@@ -1,336 -1,0 +1,336 @@@
+"""The verification pause, against real Postgres and the real SQL.
+
+Depth plan 5.4.
+
+Why this suite exists at all
+---------------------------
+``services/agents/tests/test_playbook_verification.py`` drives the whole
+workflow against a double, and that double is written to honour the
+predicates the real statements carry. It is still a double, and this
+repository's most expensive recurring defect is a double that is more
+capable than the thing it stands in for. Specifically, nothing offline can
+tell you:
+
+* whether migration 102's DDL applies at all, or whether its ``CHECK``
+ constraints accept the five outcome values the code writes — a rejected
+ value would surface as "the answer was not recorded" on a live
+ deployment and nowhere else;
+* whether the conditional ``UPDATE``s really are atomic claims. The double
+ asserts the predicates by reading them out of the SQL text; Postgres
+ asserts them by refusing the second writer.
+
+So the same four functions run here against the real schema.
+
+What is deliberately not covered
+--------------------------------
+The engine. This suite is about the storage layer and says so: the
+branching, the escalation and the refusals are covered offline, where they
+can run on every pull request without a container.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import uuid
+from collections.abc import AsyncIterator
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+
+import pytest
+import pytest_asyncio
+
+pytestmark = [
+ pytest.mark.asyncio(loop_scope="module"),
+ pytest.mark.skipif(
+ not os.environ.get("ISOLATION_VERIFICATION_DSN", "").strip(),
+ reason="ISOLATION_VERIFICATION_DSN is not set; this suite needs a live Postgres",
+ ),
+]
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+#: The three migrations that own this table, applied in order. Not the whole
+#: chain: `001_init` brings up the entire product schema and this suite is
+#: about three columns and one constraint. The two stub tables below stand
+#: in for the only foreign keys that reach outside those files.
+_MIGRATIONS = (
+ "081_playbook_pauses.sql",
+ "096_playbook_wait_pauses.sql",
- "102_playbook_verification.sql",
++ "104_playbook_verification.sql",
+)
+
+#: Enough of `tenants`, `users` and `aisoc_scim_users` for the foreign keys
+#: and the manager lookup. Written here rather than imported from
+#: `001_init` so this file states exactly what it depends on, and so a
+#: change to an unrelated column in the real schema cannot break it.
+_STUBS = """
+CREATE EXTENSION IF NOT EXISTS pgcrypto;
+CREATE TABLE IF NOT EXISTS tenants (id UUID PRIMARY KEY, name TEXT);
+CREATE TABLE IF NOT EXISTS users (
+ id UUID PRIMARY KEY,
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+ email TEXT NOT NULL
+);
+CREATE TABLE IF NOT EXISTS aisoc_scim_users (
+ user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+ external_id TEXT
+);
+CREATE OR REPLACE FUNCTION current_tenant_id() RETURNS UUID AS $$
+ SELECT NULLIF(current_setting('app.current_tenant_id', true), '')::uuid;
+$$ LANGUAGE sql STABLE;
+"""
+
+
+def _dsn() -> str:
+ value = os.environ.get("ISOLATION_VERIFICATION_DSN", "").strip()
+ if not value:
+ pytest.skip("ISOLATION_VERIFICATION_DSN is not set")
+ return value
+
+
+@pytest_asyncio.fixture(loop_scope="module", scope="module")
+async def pool() -> AsyncIterator[object]:
+ import asyncpg
+
+ created = await asyncpg.create_pool(_dsn(), min_size=1, max_size=4)
+ assert created is not None
+ async with created.acquire() as conn:
+ # In CI the whole chain is already applied by the job, and
+ # re-running the stubs there would replace `current_tenant_id()` —
+ # the function every RLS policy in the product calls — with the
+ # simplified one below. So the schema is detected rather than
+ # assumed, and the standalone path is the only one that writes.
+ migrated = await conn.fetchval(
+ "SELECT 1 FROM information_schema.columns WHERE table_name = 'aisoc_playbook_pauses' AND column_name = 'verification_stage'"
+ )
+ if not migrated:
+ await conn.execute(_STUBS)
+ for name in _MIGRATIONS:
+ await conn.execute((REPO_ROOT / "services" / "api" / "migrations" / name).read_text(encoding="utf-8"))
+ yield created
+ await created.close()
+
+
+@pytest_asyncio.fixture(loop_scope="module")
+async def wired(pool: object, monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[tuple[object, str]]:
+ """Point `app.playbook.pause` at the live pool and seed one tenant."""
+ import sys
+
+ sys.path.insert(0, str(REPO_ROOT / "services" / "agents"))
+ from app.playbook import pause as playbook_pause
+
+ async def _pool() -> object:
+ return pool
+
+ monkeypatch.setattr(playbook_pause, "_pool", _pool)
+
+ tenant_id = str(uuid.uuid4())
+ async with pool.acquire() as conn: # type: ignore[attr-defined]
+ await conn.execute("INSERT INTO tenants (id, name) VALUES ($1::uuid, 'live')", tenant_id)
+ yield playbook_pause, tenant_id
+
+
+async def _suspend(playbook_pause: object, tenant_id: str, token: str) -> object:
+ return await playbook_pause.suspend( # type: ignore[attr-defined]
+ kind="verification",
+ resume_at=datetime.now(UTC) + timedelta(minutes=30),
+ resume_token=token,
+ tenant_id=tenant_id,
+ run_id=f"run-{uuid.uuid4().hex[:12]}",
+ playbook_id="pb-live",
+ playbook_name="live verification",
+ step_index=0,
+ step_id="ask",
+ run_context={"tenant_id": tenant_id},
+ step_results=[],
+ verification_stage="user",
+ verification_subject="[email protected]",
+ )
+
+
+async def test_the_migration_accepts_a_verification_pause(wired: tuple[object, str]) -> None:
+ """`kind = 'verification'` and a stage both pass the real CHECKs."""
+ playbook_pause, tenant_id = wired
+ pause = await _suspend(playbook_pause, tenant_id, uuid.uuid4().hex)
+
+ assert pause is not None
+ assert pause.kind == "verification"
+ assert pause.verification_stage == "user"
+ assert pause.verification_subject == "[email protected]"
+
+
[email protected]("outcome", ["acknowledged", "denied", "unsure", "timed_out", "no_manager"])
+async def test_every_outcome_the_code_writes_passes_the_check(wired: tuple[object, str], outcome: str) -> None:
+ """The constraint and the vocabulary must agree.
+
+ They are written in two files — the migration's ``CHECK`` and
+ ``verification.OUTCOMES`` — and a value in one and not the other is a
+ row Postgres refuses at the moment somebody answers.
+ """
+ playbook_pause, tenant_id = wired
+ pause = await _suspend(playbook_pause, tenant_id, uuid.uuid4().hex)
+ assert pause is not None
+
+ assert await playbook_pause.record_verification_outcome( # type: ignore[attr-defined]
+ pause_id=pause.id, tenant_id=tenant_id, outcome=outcome
+ )
+
+
+async def test_an_outcome_is_written_once(wired: tuple[object, str]) -> None:
+ """Postgres refuses the second answer, not the double.
+
+ ``verification_outcome IS NULL`` in the predicate is what makes a
+ double click resolve once, and this is the only place that claim is
+ tested against a real transaction.
+ """
+ playbook_pause, tenant_id = wired
+ pause = await _suspend(playbook_pause, tenant_id, uuid.uuid4().hex)
+ assert pause is not None
+
+ assert await playbook_pause.record_verification_outcome(pause_id=pause.id, tenant_id=tenant_id, outcome="denied") # type: ignore[attr-defined]
+ assert not await playbook_pause.record_verification_outcome( # type: ignore[attr-defined]
+ pause_id=pause.id, tenant_id=tenant_id, outcome="acknowledged"
+ )
+
+
+async def test_a_pause_escalates_once_and_keeps_its_token(wired: tuple[object, str]) -> None:
+ """Two sweeper replicas racing the same row escalate it once."""
+ playbook_pause, tenant_id = wired
+ token = uuid.uuid4().hex
+ pause = await _suspend(playbook_pause, tenant_id, token)
+ assert pause is not None
+ deadline = datetime.now(UTC) + timedelta(hours=1)
+
+ assert await playbook_pause.escalate_to_manager( # type: ignore[attr-defined]
+ pause_id=pause.id, tenant_id=tenant_id, manager="[email protected]", resume_at=deadline
+ )
+ assert not await playbook_pause.escalate_to_manager( # type: ignore[attr-defined]
+ pause_id=pause.id, tenant_id=tenant_id, manager="[email protected]", resume_at=deadline
+ )
+
+ found = await playbook_pause.find_verification_by_token(resume_token=token) # type: ignore[attr-defined]
+ assert found is not None
+ assert found.verification_stage == "manager"
+ assert found.verification_manager == "[email protected]"
+
+
+async def test_a_wait_token_does_not_resolve_as_a_verification(wired: tuple[object, str]) -> None:
+ """``kind`` is in the predicate, so the two callbacks cannot cross."""
+ playbook_pause, tenant_id = wired
+ token = uuid.uuid4().hex
+ await playbook_pause.suspend( # type: ignore[attr-defined]
+ kind="wait",
+ resume_at=None,
+ resume_token=token,
+ tenant_id=tenant_id,
+ run_id=f"run-wait-{uuid.uuid4().hex[:12]}",
+ playbook_id="pb-live",
+ playbook_name="live wait",
+ step_index=0,
+ step_id="hold",
+ run_context={},
+ step_results=[],
+ )
+
+ assert await playbook_pause.find_verification_by_token(resume_token=token) is None # type: ignore[attr-defined]
+ assert await playbook_pause.find_wait_by_token(resume_token=token) is not None # type: ignore[attr-defined]
+
+
+async def test_due_verifications_sees_only_waiting_verification_rows(wired: tuple[object, str]) -> None:
+ """The sweep's predicate, against the real partial index."""
+ playbook_pause, tenant_id = wired
+ pause = await _suspend(playbook_pause, tenant_id, uuid.uuid4().hex)
+ assert pause is not None
+
+ later = datetime.now(UTC) + timedelta(hours=2)
+ due_ids = {p.id for p in await playbook_pause.due_verifications(now=later, limit=100)} # type: ignore[attr-defined]
+ assert pause.id in due_ids
+
+ await playbook_pause.resolve(pause_id=pause.id, tenant_id=tenant_id, status="resumed", resolution="answered") # type: ignore[attr-defined]
+ due_ids = {p.id for p in await playbook_pause.due_verifications(now=later, limit=100)} # type: ignore[attr-defined]
+ assert pause.id not in due_ids
+
+
+async def test_the_policy_table_is_tenant_scoped_and_default_deny(pool: object) -> None:
+ """A tenant with no row opts into nothing, and cannot read another's.
+
+ The RLS policy carries an unbound arm so the agents service — which
+ reads this from a consumer that binds no tenant — is not locked out.
+ That arm is exactly the thing worth checking: with a tenant bound, it
+ must not leak.
+ """
+ import asyncpg
+
+ tenant_a, tenant_b = str(uuid.uuid4()), str(uuid.uuid4())
+ async with pool.acquire() as conn: # type: ignore[attr-defined]
+ await conn.execute("INSERT INTO tenants (id, name) VALUES ($1::uuid, 'a'), ($2::uuid, 'b')", tenant_a, tenant_b)
+ await conn.execute(
+ "INSERT INTO aisoc_verification_policies (tenant_id, alert_class) VALUES ($1::uuid, 'impossible_travel')",
+ tenant_a,
+ )
+
+ # A non-superuser, because RLS is bypassed by the owner and by a
+ # superuser — the exact mistake that made 92 policies decorative in
+ # this repository once already.
+ async with pool.acquire() as conn: # type: ignore[attr-defined]
+ # Created if absent rather than dropped and recreated: the role
+ # holds grants, so `DROP ROLE` fails on the second run of this
+ # suite against the same database and the failure reads as a
+ # tenancy problem rather than as test housekeeping.
+ await conn.execute(
+ "DO $$ BEGIN "
+ "IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'lanec_reader') THEN "
+ "CREATE ROLE lanec_reader LOGIN PASSWORD 'lanec_reader_pw'; END IF; END $$"
+ )
+ await conn.execute("GRANT SELECT ON aisoc_verification_policies TO lanec_reader")
+ await conn.execute("GRANT USAGE ON SCHEMA public TO lanec_reader")
+
+ dsn = _dsn()
+ reader_dsn = dsn.replace("postgres:lanec@", "lanec_reader:lanec_reader_pw@").replace("postgres@", "lanec_reader@")
+ reader = await asyncpg.connect(reader_dsn)
+ try:
+ await reader.execute("SELECT set_config('app.current_tenant_id', $1, false)", tenant_b)
+ rows = await reader.fetch("SELECT alert_class FROM aisoc_verification_policies")
+ assert rows == [], "tenant B read tenant A's verification policy"
+
+ await reader.execute("SELECT set_config('app.current_tenant_id', $1, false)", tenant_a)
+ rows = await reader.fetch("SELECT alert_class FROM aisoc_verification_policies")
+ assert [r["alert_class"] for r in rows] == ["impossible_travel"]
+ finally:
+ await reader.close()
+
+
+async def test_the_stored_context_survives_a_round_trip(wired: tuple[object, str]) -> None:
+ """The escalation reads the step's params back off the pause.
+
+ They go in as JSON and come back as a string from asyncpg, which
+ ``_row_to_pause`` decodes. A change there would leave the escalation
+ asking on the default channel with the default message.
+ """
+ playbook_pause, tenant_id = wired
+ token = uuid.uuid4().hex
+ await playbook_pause.suspend( # type: ignore[attr-defined]
+ kind="verification",
+ resume_at=datetime.now(UTC) + timedelta(minutes=30),
+ resume_token=token,
+ tenant_id=tenant_id,
+ run_id=f"run-ctx-{uuid.uuid4().hex[:12]}",
+ playbook_id="pb-live",
+ playbook_name="live verification",
+ step_index=0,
+ step_id="ask",
+ run_context={"tenant_id": tenant_id, "_verification_step_params": {"channel": "teams"}},
+ step_results=[{"step_id": "earlier", "status": "success"}],
+ verification_stage="user",
+ verification_subject="[email protected]",
+ )
+
+ found = await playbook_pause.find_verification_by_token(resume_token=token) # type: ignore[attr-defined]
+ assert found is not None
+ assert found.run_context["_verification_step_params"] == {"channel": "teams"}
+ assert found.step_results == [{"step_id": "earlier", "status": "success"}]
+ # Proves the decode rather than a passthrough: a raw row would be a str.
+ assert not isinstance(found.run_context, str)
+ json.dumps(found.run_context)