mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-24 08:35:46 +08:00
* test(closure): regression suite for unauthorized automatic alert closure Phase 1 of the closure remediation. These fail on this commit, which is the point of landing them first. `alerts.status` reaches 'resolved' from one statement — the UPDATE at the end of `ledger.persist_auto_triage`, gated on a caller-supplied `auto_closed`. Two callers set that flag and only one asked permission. `run_auto_triage` consults `closure_policy.decide(...)`; `_maybe_suppress_from_memory` sets `AgentStatus.COMPLETED` straight from a stored outcome prior and `_record` forwards it. So a tenant with `enabled = false` still got automatic closures, the kill switch did not stop them, and `require_grant` was never consulted. The live suite drives real Postgres with every migration applied, because the defect is two modules disagreeing about who asked permission and a fake connection answers both sides happily. Setup runs as the schema owner and the code under test runs as the runtime role, so RLS is in force where it matters and a superuser exemption cannot make a cross-tenant assertion pass for the wrong reason. Pre-fix, 12 of 15 live tests fail with the alert sitting at 'resolved'. The three that pass are the positive control, the shadow guard and manual closure — all three are properties the fix must preserve rather than establish. The offline suite covers what a database cannot answer: the permissive `pool is None` fallback, and an enumeration of every module that can write 'resolved'. That enumeration replaces the spot-check style of `test_closure_policy.py:199`, which asserted one substring against one function and therefore could not have noticed the second closure path. * fix(closure): one authorization chokepoint for every automatic alert closure `alerts.status` becomes 'resolved' in exactly one statement — the UPDATE at the end of `ledger.persist_auto_triage` — so the authorization now lives inside that function, between resolving the alert's tenant and opening the transaction. Three things follow that per-caller checks could not give: * a new caller is governed by default, where previously every caller had to remember and one did not; * recovery re-evaluates, because a retry, a resumed run or a deduplicated verdict is judged by the policy in force when the row changes rather than by the one in force when the model answered; * the tenant is the row's tenant, already resolved to its canonical UUID. This is not a second policy. Thresholds, the enabled flag, `require_grant` and the kill switch stay in `app/closure/policy.py` and are reached through `closure_policy.decide`. The chokepoint adds the preconditions that are not per-tenant policy — an auto-closeable verdict, a real rather than shadow run, grounded reasoning — and one call site everything passes through. `run_auto_triage` keeps its pre-check, which is advisory and is what puts "auto-close withheld" in front of an operator; both derive the alert class through one function so they cannot disagree about which policy row applies. Finding 1: `_maybe_suppress_from_memory` set COMPLETED from a stored outcome prior and `_record` forwarded it, so a tenant with closure disabled still got automatic closures and the kill switch did not stop them. A remembered verdict is not remembered permission. Finding 10: `pool is None` reported the kill switch not engaged and fell back to the process-wide threshold. That None was reachable from any `create_pool` failure and from a bootstrap probe on an unrelated table, so a missing migration disabled the policy and the switch together. The accessor now returns a reason — unconfigured, unavailable or ready — and the institutional-memory probe no longer closes the pool everything else shares. Finding 14: a tenant with no policy row auto-closed at the process-wide threshold, turning the absence of a decision into a decision. It now refuses. Migration 121 records, per tenant, which side of that change the deployment fell on; it creates no policy rows, because granting one to every tenant that had auto-closed before would infer authorization from behaviour the old default produced. `scripts/check_closure_authorization.py` holds the property the chokepoint rests on. It reads the AST and ignores docstrings, because this change quotes that SQL in prose in four places and a gate that fires on documentation gets switched off within a week; `--self-test` proves it in both directions. Four tests asserting a clean verdict auto-closes now request an explicit `authorized_closure_tenant` fixture. They are negative controls for the injection guard and tool provenance, and without it they would be asserting the closure default instead, for a reason they never mention. * chore(closure): wire the chokepoint gate into CI and record the negative controls The gate is now invoked by `ci.yml :: python-lint`, with its `--self-test` ahead of it. A gate in `scripts/` that no workflow runs is the defect this repository keeps finding, and `check_gate_coverage.py` confirms all 178 checks are reachable from a workflow. Two claim-matrix rows. The structural property — one closure statement, in one module, gated — is GATED: the script and the offline suite both run on every pull request. The end-to-end property against real Postgres is PARTIAL, because the live suite is wired into `agent-auth-live.yml` but a workflow added in a pull request has not been observed to pass on `main`, and "the gate exists" and "a pull request cannot regress it" are separate claims until it has. The row names the condition that returns it to GATED. Negative controls, each reverted alone so the result is attributable rather than showing all three changes at once: * removing the chokepoint call reds 12 of 15 live tests and the gate exits 1 naming the function; * restoring the permissive no-policy branch reds 2 offline and 3 live; * restoring the permissive `pool is None` kill-switch branch reds 2 offline. The three live tests that survive the first control are the positive control, the shadow guard and manual closure, which is the intended reading: they are properties the chokepoint preserves rather than establishes. Outputs are recorded in the remediation document along with the limitations, including the global kill-switch row being uninsertable by the runtime role under its own WITH CHECK — found while writing the suite, out of scope here, and not fixed rather than quietly worked around. * ci(closure): declare the live suite's fixture DSN as the owner, with its reason `check_runtime_db_role.py` was right to red this: the suite's second DSN connects as the role CI provisions as the superuser, and a superuser ignores every RLS policy even under FORCE ROW LEVEL SECURITY. Renaming it to a `*DATABASE_MIGRATION_URL` would have cleared the gate and been untrue — it applies no migrations. The gate's own escape hatch is the honest spelling, so the DSN now carries an `aisoc-db-role: owner` marker stating what needs the owner and why: scratch tenants, policy rows for several tenants at once, and the global kill-switch row, which its own `WITH CHECK (tenant_id = current_tenant_id())` makes uninsertable by any non-owner. The code under test still reads the runtime-role DSN, so every assertion is judged under forced RLS and the cross-tenant cases cannot pass by exemption. The gate prints the reason beside the other 19 declared owners, which is the point of declaring it at the point of use. * docs: recompute the claim-matrix counts the two new rows moved `readme_gates.py` cross-checks every published figure against the table, and it was right: the matrix's own summary block, the evidence pack and the roadmap each quote a count, and two new rows moved all three. 319/315/4 becomes 321/316/5. ROADMAP's prose enumerates the PARTIAL rows rather than only counting them, so the fifth is named with the condition that closes it: the live suite proving automatic closure against real Postgres has to be observed passing on `main`, not merely in the pull request that added it. Recomputed with `check_claim_gate_matrix.py`, which is also the gate, rather than by editing the numbers to match. * docs(closure): record that the live suite ran green on a CI runner It did, on this pull request: 15 passed inside the job that stands up Postgres with every migration applied. That is worth recording precisely, because "passes on my machine" and "passes on a runner nobody controls" are different claims and the second is the one a reviewer cares about. The row stays PARTIAL, and the reason narrows rather than disappears: that run graded the pull request's merge ref, so the job has still never run on `main`. "The gate works" and "a future pull request cannot regress it" are separate until the push-to-main run exists, which is the condition the row already names for returning to GATED. * fix(gate): resolve the closure gate's repository root from git, not from __file__ `check_gate_contract.py` caught this and was right: counting two directories above the script answers "whatever happens to be there", which is wrong the moment the file is copied, vendored or run from a build context. The repo already has one answer to this — `gate_toolkit.repo_root()`, which asks git and honours `AISOC_REPO_ROOT` — so the gate uses it, and the test that invokes the gate derives its root the same way instead of counting four levels up. That meta-gate reported exactly one finding across 178 checks and it was this one, which is the system working: a gate added this week was held to a convention nobody had to remember. Verified afterwards: the gate still refuses an empty tree (exit 1, naming the missing path), still passes from an unrelated working directory, and `check_gate_contract.py --list` reports 170 of 178 checks refusing a contentless repository with the 8 recorded exceptions unchanged. * fix(closure): take migration 122, and scope the chokepoint claim to the tree it covers Two things, both found by rebasing onto current main rather than assuming the branch was still accurate. Migration 121 was taken while this branch was open: the fusion phase merged `121_fusion_alert_outbox.sql`. Git would not have called that a conflict, because the filenames differ — both would have landed and left main with two migration 121s and no defined apply order. Renumbered to 122, re-derived against main immediately beforehand rather than assumed, and every reference moved with the file: the migration's own header, its `COMMENT ON TABLE`, the restore statement in its rollback section, the phase document's path, the same restore statement quoted there, and the comment in `closure/policy.py` that names which migration records the outcome. A renamed file with the old number still quoted in the upgrade instructions would be worse than the collision, because an operator follows the prose. The second is a correction to a claim, not to code. Asking this phase's own question against the whole tree instead of the service it changes found a second automatic closure path that predates this work and that the original audit missed: `services/connectors`'s vulnerability sweep runs `RESOLVE_REMEDIATED_SQL`, which resolves a CVE-promotion alert of its own making once every affected asset is patched. It is bounded to rows that sweep minted, tenant-scoped per statement, and a deterministic lifecycle rule rather than an autonomous verdict — a different category from the one the chokepoint governs, and in another phase's tree, so it is named rather than edited from here. What had to change is the wording. The gate walks `services/agents/app` and nothing else, so a verdict reading "the only path to 'resolved'" was a product-wide claim the gate does not support. The gate's docstring, both its verdict strings, the module docstring, the claim-matrix row and the phase document now all say which tree they mean, and the phase document carries the connectors path as an open question for a later phase to decide rather than as a silence. Verification figures re-derived on the rebased tree rather than edited to match: 137 migrations now apply cleanly in order on a fresh database, 001 through 122, with both the fusion outbox table and the closure audit table present and 122 still idempotent on re-apply. * test(kill-switch): authorize closure before asserting the release resumes it `test_releasing_it_resumes_closure` is this file's negative control: it exists so that a reader returning True unconditionally cannot satisfy every other assertion. It engaged the global switch, released it, and asserted closure resumed. Under default-deny that assertion fails for a reason that has nothing to do with the switch -- `source='default_deny'`, "this tenant has no closure policy, and automatic closure requires an explicit one" -- so the control could no longer tell "the switch was released" from "the tenant never authorized closure", which is precisely the ambiguity it exists to rule out. The tenant now gets an explicit closure policy first, so a failure to resume is attributable to the switch alone. The three sibling tests assert refusals and are unaffected: `kill_switch_engaged` is consulted before the policy, so the refusal they check still carries `source='kill_switch'`. Verified against real Postgres 16 with all 138 migrations applied: 4 passed with this change; removing the `_authorize_closure` call reproduces the original failure verbatim, 1 failed / 3 passed. * test(kill-switch): bind the tenant before inserting the closure policy The previous commit added `_authorize_closure` and I verified it against a database where the session was a superuser, which bypasses RLS. That is exactly the workaround this suite exists to refuse: seeding as the owner is how the global row's unwritability stayed hidden for 45 migrations, and the job fails on purpose if the DSN resolves to a role that can bypass. Run as `aisoc_app` the insert raises, because `aisoc_closure_policies` is FORCE ROW LEVEL SECURITY with `WITH CHECK (tenant_id = current_tenant_id())`, and this suite is otherwise unbound -- correctly so, since the global kill-switch row is written by an unbound session and the three sibling tests depend on that. The policy insert now binds `app.current_tenant_id` transaction-locally, so the binding cannot leak into the next test on a pooled connection, and the unbound default the rest of the file relies on is unchanged. Verified as `aisoc_app` with rolbypassrls=false and rolsuper=false, real Postgres 16, all 138 migrations: 4 passed. Removing the `set_config` line reproduces CI's error verbatim -- `InsufficientPrivilegeError: new row violates row-level security policy for table "aisoc_closure_policies"` -- 1 failed / 3 passed.
268 lines
10 KiB
Python
268 lines
10 KiB
Python
#!/usr/bin/env python3
|
|
"""Every automatic closure of an alert passes the closure authorization chokepoint.
|
|
|
|
Phase 1 of the closure remediation. See
|
|
`docs/remediation/phase-1-closure-authorization.md`.
|
|
|
|
What this gate is for
|
|
---------------------
|
|
`alerts.status` becomes `'resolved'` in exactly one statement in
|
|
`services/agents`: the `UPDATE alerts` at the end of
|
|
`app.investigator.ledger.persist_auto_triage`. That is what makes a chokepoint
|
|
possible at all — and it is also a property that nothing was holding.
|
|
|
|
**Scope, stated because the obvious reading is wider than the truth.** This
|
|
gate walks `services/agents/app` and nothing else, so what it proves is that
|
|
*the agent* has one governed closure path. It is not a claim about the
|
|
product: `services/connectors`'s vulnerability sweep carries its own
|
|
`RESOLVE_REMEDIATED_SQL`, which closes a CVE-promotion alert of its own making
|
|
once every affected asset is patched. That is a deterministic lifecycle rule
|
|
rather than an autonomous verdict, it is tenant-scoped, and it is outside this
|
|
phase — but a verdict string here saying "the only path to 'resolved'" would
|
|
be false, so neither this gate nor its claim row says it. A second
|
|
path to that statement had already appeared once: the outcome-memory
|
|
suppression branch reached it with `auto_closed=True` having consulted no
|
|
policy, no grant and no kill switch, and the test covering closure wiring
|
|
asserted one substring against one function, so it could not see it.
|
|
|
|
So this gate asserts two things:
|
|
|
|
1. only the ledger module contains SQL that can set an alert to `'resolved'`;
|
|
2. the function containing that SQL calls `authorize_auto_closure`.
|
|
|
|
Why it reads the AST and not the text
|
|
-------------------------------------
|
|
Grepping for `'resolved'` matches prose. This module's own docstring quotes
|
|
the SQL two paragraphs above, `authorization.py` quotes it as well, and a
|
|
line-based scanner flags both — a gate that fires on documentation gets
|
|
switched off within a week. Only string constants that are *not* docstrings
|
|
are considered, which is the difference between SQL the process executes and
|
|
English a reader reads.
|
|
|
|
Run it:
|
|
|
|
python3 scripts/check_closure_authorization.py
|
|
python3 scripts/check_closure_authorization.py --self-test
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import ast
|
|
import re
|
|
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 repo_root # noqa: E402
|
|
|
|
#: The module permitted to carry closure SQL, relative to the agents app.
|
|
LEDGER = "investigator/ledger.py"
|
|
|
|
#: The function inside it that must consult the chokepoint.
|
|
GATED_FUNCTION = "persist_auto_triage"
|
|
|
|
#: The chokepoint's name, as it is called.
|
|
CHOKEPOINT = "authorize_auto_closure"
|
|
|
|
#: A SQL fragment that can move a row's status to resolved. Matches both the
|
|
#: literal assignment and the `CASE ... THEN 'resolved'` form the ledger uses.
|
|
_CLOSURE_SQL = re.compile(
|
|
r"""(?isx)
|
|
(
|
|
status \s* = \s* ['"]resolved['"] # status = 'resolved'
|
|
| THEN \s+ ['"]resolved['"] # CASE ... THEN 'resolved'
|
|
)
|
|
"""
|
|
)
|
|
|
|
|
|
def _docstring_nodes(tree: ast.AST) -> set[int]:
|
|
"""Identity of every string constant that is a docstring.
|
|
|
|
A docstring is the first statement of a module, class or function and is
|
|
a bare string expression. Everything else that is a string constant is
|
|
data the program uses.
|
|
"""
|
|
found: set[int] = set()
|
|
for node in ast.walk(tree):
|
|
if not isinstance(node, ast.Module | ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef):
|
|
continue
|
|
body = getattr(node, "body", None) or []
|
|
if not body:
|
|
continue
|
|
first = body[0]
|
|
if isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant) and isinstance(first.value.value, str):
|
|
found.add(id(first.value))
|
|
return found
|
|
|
|
|
|
def executable_strings(source: str) -> list[str]:
|
|
"""Every string constant in `source` that is not a docstring."""
|
|
tree = ast.parse(source)
|
|
docstrings = _docstring_nodes(tree)
|
|
return [
|
|
node.value
|
|
for node in ast.walk(tree)
|
|
if isinstance(node, ast.Constant) and isinstance(node.value, str) and id(node) not in docstrings
|
|
]
|
|
|
|
|
|
def modules_with_closure_sql(app_root: Path) -> set[str]:
|
|
"""Modules under `app_root` carrying SQL that can resolve an alert."""
|
|
found: set[str] = set()
|
|
for path in sorted(app_root.rglob("*.py")):
|
|
try:
|
|
strings = executable_strings(path.read_text(encoding="utf-8"))
|
|
except SyntaxError as exc: # pragma: no cover - a broken tree fails elsewhere
|
|
print(f"check_closure_authorization: cannot parse {path}: {exc}", file=sys.stderr)
|
|
return {"<unparseable>"}
|
|
if any(_CLOSURE_SQL.search(text) for text in strings):
|
|
found.add(path.relative_to(app_root).as_posix())
|
|
return found
|
|
|
|
|
|
def function_calls(source: str, function: str) -> set[str]:
|
|
"""The names called inside `function`, however it is spelled."""
|
|
tree = ast.parse(source)
|
|
calls: set[str] = set()
|
|
for node in ast.walk(tree):
|
|
if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef) or node.name != function:
|
|
continue
|
|
for inner in ast.walk(node):
|
|
if not isinstance(inner, ast.Call):
|
|
continue
|
|
target = inner.func
|
|
if isinstance(target, ast.Name):
|
|
calls.add(target.id)
|
|
elif isinstance(target, ast.Attribute):
|
|
calls.add(target.attr)
|
|
return calls
|
|
|
|
|
|
def check(repo_root: Path) -> list[str]:
|
|
"""Returns a list of failures. Empty means the chokepoint holds."""
|
|
app_root = repo_root / "services" / "agents" / "app"
|
|
if not app_root.is_dir():
|
|
return [f"no agents app at {app_root}"]
|
|
|
|
failures: list[str] = []
|
|
|
|
writers = modules_with_closure_sql(app_root)
|
|
if writers != {LEDGER}:
|
|
extra = sorted(writers - {LEDGER})
|
|
if extra:
|
|
failures.append(
|
|
"SQL that can set an alert to 'resolved' appears outside the ledger, inside services/agents: "
|
|
+ ", ".join(extra)
|
|
+ f". Every automatic closure must go through {CHOKEPOINT}; "
|
|
"a second statement is a second path nothing governs."
|
|
)
|
|
if LEDGER not in writers:
|
|
failures.append(
|
|
f"{LEDGER} no longer contains the closure SQL this gate exists to guard. "
|
|
"If it moved, move the chokepoint with it and update this gate."
|
|
)
|
|
|
|
ledger_path = app_root / LEDGER
|
|
if ledger_path.is_file():
|
|
calls = function_calls(ledger_path.read_text(encoding="utf-8"), GATED_FUNCTION)
|
|
if CHOKEPOINT not in calls:
|
|
failures.append(
|
|
f"{LEDGER}:{GATED_FUNCTION} can set an alert to 'resolved' without calling {CHOKEPOINT}. "
|
|
"An automatic closure would bypass the tenant's policy, the earned grant and the kill switch."
|
|
)
|
|
else:
|
|
failures.append(f"{LEDGER} is missing")
|
|
|
|
return failures
|
|
|
|
|
|
_SELF_TEST_GOOD = '''
|
|
"""A module whose docstring quotes the SQL: status = 'resolved'."""
|
|
# A comment mentioning THEN 'resolved' as well.
|
|
async def unrelated(conn):
|
|
await conn.execute("UPDATE alerts SET status = 'triaged' WHERE id = $1")
|
|
'''
|
|
|
|
_SELF_TEST_BAD = """
|
|
async def sneaky(conn):
|
|
await conn.execute("UPDATE alerts SET status = 'resolved' WHERE id = $1")
|
|
"""
|
|
|
|
_SELF_TEST_CASE_FORM = """
|
|
async def sneaky(conn):
|
|
await conn.execute("UPDATE alerts SET status = CASE WHEN $1 THEN 'resolved' ELSE status END")
|
|
"""
|
|
|
|
|
|
def self_test() -> int:
|
|
"""Prove the detector fires on SQL and stays silent on prose.
|
|
|
|
Both directions, because a gate that cannot fire and a gate that fires on
|
|
everything fail the same way in practice: somebody stops believing it.
|
|
"""
|
|
failures = []
|
|
|
|
if any(_CLOSURE_SQL.search(text) for text in executable_strings(_SELF_TEST_GOOD)):
|
|
failures.append("the detector flagged a module that only mentions the SQL in a docstring or a comment")
|
|
|
|
if not any(_CLOSURE_SQL.search(text) for text in executable_strings(_SELF_TEST_BAD)):
|
|
failures.append("the detector missed a literal `status = 'resolved'` UPDATE")
|
|
|
|
if not any(_CLOSURE_SQL.search(text) for text in executable_strings(_SELF_TEST_CASE_FORM)):
|
|
failures.append("the detector missed the `CASE ... THEN 'resolved'` form the ledger actually uses")
|
|
|
|
ungated = """
|
|
async def persist_auto_triage(conn):
|
|
await conn.execute("UPDATE alerts SET status = 'resolved'")
|
|
"""
|
|
if CHOKEPOINT in function_calls(ungated, GATED_FUNCTION):
|
|
failures.append("the call detector reported a chokepoint call in a function that makes none")
|
|
|
|
gated = f"""
|
|
async def {GATED_FUNCTION}(conn):
|
|
decision = await {CHOKEPOINT}(tenant_ref="t")
|
|
await conn.execute("UPDATE alerts SET status = 'resolved'")
|
|
"""
|
|
if CHOKEPOINT not in function_calls(gated, GATED_FUNCTION):
|
|
failures.append("the call detector missed a direct chokepoint call")
|
|
|
|
for failure in failures:
|
|
print(f"check_closure_authorization: SELF-TEST FAILED — {failure}", file=sys.stderr)
|
|
if failures:
|
|
return 1
|
|
print("check_closure_authorization: self-test OK (5 cases, both directions)")
|
|
return 0
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--self-test", action="store_true", help="prove the detector works in both directions")
|
|
# `repo_root()` asks git rather than counting directories above this file.
|
|
# Two levels up is whatever happens to be there, which is the wrong answer
|
|
# the moment the script is copied, vendored or run from a build context.
|
|
parser.add_argument("--root", type=Path, default=None)
|
|
args = parser.parse_args()
|
|
|
|
if args.self_test:
|
|
return self_test()
|
|
|
|
failures = check(args.root or repo_root())
|
|
for failure in failures:
|
|
print(f"check_closure_authorization: {failure}", file=sys.stderr)
|
|
if failures:
|
|
return 1
|
|
print(
|
|
f"check_closure_authorization: OK — within services/agents, {LEDGER}:{GATED_FUNCTION} "
|
|
"is the only path to 'resolved' and it is gated"
|
|
)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|