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.

The gate credited the session as a validated row key

Beenu Arorac0bf3457a0d5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a7b5e6000..9e1ddc369 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -790,8 +790,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
alembic-managed services read as unprotected however many policies they
carried; and a policy created inside a PL/pgSQL `EXECUTE` is invisible to
it, which is why `060_rls_coverage.sql` spells out 56 literal `ALTER TABLE` /
- `CREATE POLICY` statements instead of looping over an array. `--self-test`
- grew from 8 cases to 14, covering both new rules in both directions.
+ `CREATE POLICY` statements instead of looping over an array. And the rule
+ credited the *session* as a validated key — `db` is passed to the guard and
+ appears in every raw statement's expression, so `keys & resolved` matched
+ whatever the query was really keyed on; a call receiver is now excluded
+ structurally rather than by naming `db`. `--self-test` grew from 8 cases to
+ 15, covering all of it in both directions.
- **`check_gate_coverage.py` decides what a check is from what a script does,
not what it is called.** It classified by filename — `check_*`,
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index ee8dfda3b..f32dcae63 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -128,7 +128,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| A dry run never reaches a customer's vendor | live-action dry-run contract | `ci.yml` actions job (`test_dry_run_credential_strip.py` — each client factory's read set is re-derived from its own source and compared with the adapter's strip list, stripping that set is asserted to make the factory return `None`, and an end-to-end dry run with full credentials trips a wire if any factory returns a client) | GATED | the wire covers the four SIEM factories the writeback path uses; other vendors' adapters are covered by the strip-list equality check only |
| No route lets its caller name the tenant it reads; a tenant parameter is intersected with the caller's scope | (implied by multi-tenant); `tests/isolation/README.md` | `isolation.yml :: route-scope` (`scripts/check_route_tenant_scope.py` — an AST pass over all routes under `services/`, failing in **both** directions: a route taking a tenant identifier with no auth dependency, and a route accepting one without passing it through a scope intersection. Request-body models are read too, since a `tenant_id` on a POST body is the same hole as a query parameter. `--self-test` injects a violation of each kind, asserts two clean controls pass, and strips the verifier the one conditional exemption names to prove a stale exemption is dropped; the root comes from `git rev-parse` and the scan prints how many routes across how many files it opened) + `tests/isolation/test_route_tenant_scope.py` (the vendored HS256 verifier rejects `alg: none`, a refresh token, a wrong key and an expired token; an empty scope refuses rather than widening; and a two-tenant replay seeds A and B through the real `EntityRiskEngine`, asserts both genuinely hold rows, then asserts an anonymous caller, an undeclared service token and a console session for B are each refused A's entity-risk queue) + `sync_vendored_tenant_scope.py --check` (six copies byte-identical but for `SERVICE_NAME`) | GATED | `services/mesh` is exempt by design (Ed25519 + k-anonymity; a bearer token would break federation rather than secure it) and three MSSP routes that *define* a scope rather than read within one are exempt with the constraint that stands in for the intersection named per row |
| Every route authenticates, or is public for a reason that is itself checked | (implied by multi-tenant + RBAC); `apps/docs/docs/operations/security.md` | `isolation.yml :: route-scope` (`scripts/check_route_auth.py` — default-deny over all 601 routes under `services/`, reusing the same AST collector as the tenant-scope gate so the two cannot drift. A route without an auth dependency must appear in one of three tables, each carrying its reason: a probe module, a named public route, or an **in-band credential** route whose entry names the verifier and lapses the moment the handler stops calling it. Fails in both directions — an unexplained route fails, and an exemption that no longer matches an unauthenticated route fails as stale, so the tables shrink as routes are secured. `--self-test` injects an unauthenticated mutating route, asserts router-level and module-local `Annotated[..., Depends(...)]` auth are both recognised, and strips a live in-band entry to prove a stale one is dropped) + `tests/isolation/test_route_auth_default_deny.py` (the real agents routers over ASGI: an anonymous caller is refused on all seven previously-open routes including playbook create/execute/delete, a valid console session still gets a non-empty response, a service token declaring no tenant is 403, and forged / expired / `alg: none` / refresh tokens are each refused) | GATED | `services/mesh` stays exempt by design (Ed25519 + k-anonymity; a bearer token would break federation rather than secure it), recorded as a service-level entry whose reason the inventory prints |
-| Every query on a tenant-scoped table filters on a tenant, however the row was addressed | (implied by multi-tenant) | `isolation.yml :: route-scope` (`scripts/check_tenant_query_predicates.py` — the predicate question the parameter gate structurally cannot ask, since a route matching on an id takes no tenant. Both the tenant-scoped ORM models and the tenant-scoped tables are derived from the tree (the model's `tenant_id` column, the migrations' DDL) rather than listed, so a new migration cannot slip past. Scoping is recognised structurally through five shapes — inline `.where()`, a `filters` list, a variable binding, a later `q = q.where(...)`, a join, and a helper that takes the statement and returns it filtered — plus a predicate on the authenticated principal's own identity, a key an **enforcing** guard already validated against the caller's tenant, and an RLS context bound on the connection where the table carries a policy. "Enforcing" is decided structurally: a guard whose result is tested in a branch that only logs demonstrably continues on failure and earns no credit, a guard whose callee raises does, and a callee this module cannot resolve is refused rather than guessed — the previous rule guessed yes, so a fail-soft guard written inline was indistinguishable from one that 404s. Raw SQL is parsed too, with docstrings excluded so prose about a query is not read as one. Undecidable cases sit on a **shrink-only ratchet**: each entry carries a reason, an entry whose statement is now scoped fails as stale, and `MAX_RATCHET` is asserted against the table's length so growth needs a number raised in the diff) + `tests/isolation/test_route_auth_default_deny.py` (two tenants seeded against a real database, both asserted to hold rows before either absence is asserted, then tenant B naming tenant A's `query_id` gets nothing back) | GATED | 32 ratcheted exceptions remain, each with its reason — credential lookups that *establish* a tenant, deliberately cross-tenant MSSP portfolio reads, background workers that have no caller, and two SQL-fragment builders whose only caller appends the predicate. The two ledger writes that were ratcheted as "scoped by an RLS context" are gone: the rule now recognises that shape structurally, and re-checking it found the mechanism did not work — the agents service was setting `app.tenant_id`, which no policy reads |
+| Every query on a tenant-scoped table filters on a tenant, however the row was addressed | (implied by multi-tenant) | `isolation.yml :: route-scope` (`scripts/check_tenant_query_predicates.py` — the predicate question the parameter gate structurally cannot ask, since a route matching on an id takes no tenant. Both the tenant-scoped ORM models and the tenant-scoped tables are derived from the tree (the model's `tenant_id` column, the migrations' DDL) rather than listed, so a new migration cannot slip past. Scoping is recognised structurally through five shapes — inline `.where()`, a `filters` list, a variable binding, a later `q = q.where(...)`, a join, and a helper that takes the statement and returns it filtered — plus a predicate on the authenticated principal's own identity, a key an **enforcing** guard already validated against the caller's tenant, and an RLS context bound on the connection where the table carries a policy. "Enforcing" is decided structurally: a guard whose result is tested in a branch that only logs demonstrably continues on failure and earns no credit, a guard whose callee raises does, and a callee this module cannot resolve is refused rather than guessed — the previous rule guessed yes, so a fail-soft guard written inline was indistinguishable from one that 404s. The session is excluded from the validated set by what it is used as (the receiver of a call), since `db` reaches every raw statement's name set and was crediting queries keyed on something else entirely. Raw SQL is parsed too, with docstrings excluded so prose about a query is not read as one. Undecidable cases sit on a **shrink-only ratchet**: each entry carries a reason, an entry whose statement is now scoped fails as stale, and `MAX_RATCHET` is asserted against the table's length so growth needs a number raised in the diff) + `tests/isolation/test_route_auth_default_deny.py` (two tenants seeded against a real database, both asserted to hold rows before either absence is asserted, then tenant B naming tenant A's `query_id` gets nothing back) | GATED | 32 ratcheted exceptions remain, each with its reason — credential lookups that *establish* a tenant, deliberately cross-tenant MSSP portfolio reads, background workers that have no caller, and two SQL-fragment builders whose only caller appends the predicate. The two ledger writes that were ratcheted as "scoped by an RLS context" are gone: the rule now recognises that shape structurally, and re-checking it found the mechanism did not work — the agents service was setting `app.tenant_id`, which no policy reads |
| Every tenant-scoped table carries an RLS policy, and a policy that cannot engage says so rather than reading as protection | `apps/docs/docs/operations/security.md` (multi-tenant isolation) | `integration.yml :: migrations` (`tests/isolation/test_postgres_rls.py::test_every_tenant_table_is_protected_or_named` — both directions: a tenant-scoped table with no policy fails unless it is one of the named exclusions, and an exclusion that no longer describes an unprotected table fails as stale; `FORCE` is required on every one, since without it the table owner, which is the application, walks past the policy. `test_no_policy_reads_a_session_variable_nothing_sets` closes the bug class that made seven existing policies inert — four keyed on a GUC no code path sets, two raising `unrecognized configuration parameter` on an unbound session. `test_superuser_bypasses_rls_which_is_why_the_probe_role_exists` measures the shipped role's bypass so the coverage figure is never read as a live guarantee) + `check_tenant_query_predicates.py --inventory` (coverage derived from the migration text of all five schema chains, not one) | GATED | 92 of 95; the three left are named, not rounded away — `users` is excluded so authentication can resolve a principal before a tenant exists, and `case_tasks` / `case_timeline` are ORM models no migration creates, asserted still absent. The policies are inert until the deployment connects as a role without BYPASSRLS; the grant is documented and the bypass is asserted rather than assumed |
| Documentation and marketing name no competitor product, while vendors AiSOC integrates with stay named | AGENTS.md (naming rule); docs portal + benchmark comparison tables | `competitor-names.yml` (`scripts/check_competitor_names.py` — an explicit name list plus a path allow-list for integration surfaces, both checked in both directions: a dead pattern, a stale allow entry that no longer excuses anything, and a drifted comparison-table marker each fail rather than reporting a clean tree; the scan prints the absolute root and file count so it cannot report on a tree it never read) + `tests/test_competitor_names_gate.py` (42 cases, including `Torq` asserted as a competitor in prose *and* left untouched across its connector module, manifest, docs page and tests) | GATED | the name list is AI-SOC/SOAR rivals; vendors that are purely integration targets are deliberately absent from it and are instead held out of the pinned comparison-table regions, which are checked against a wider vendor list |
| The published playbook schema describes the engine that runs playbooks | concepts/playbooks.md (step table + `x-aisoc-execution`); `schemas/playbook.schema.json` | `ci.yml` P2 job (`scripts/check_playbook_schema_parity.py --self-test` — compares the schema enum, the `StepType` enum, the engine's `_HANDLERS` table, the `x-aisoc-execution` map, `bounds.py` and the pack validator's trigger list, **every pair in both directions**; refuses to run on a tree missing its marker files instead of printing OK about files it never opened, and names the root, schema, step counts and playbook count it inspected) + `scripts/lint_playbooks.py` (every `*.playbook.json` in the tree, not the two it used to scan while reporting "2/2 passed") + `tests/test_playbook_schema_parity_gate.py` (18 cases; drift injected in each direction and the gate asserted to name it) | GATED | the `governed` execution class is compared against `engine.RESPONSE_STEP_TYPES` in both directions, and the published `StepType` union in `packages/types` against the engine's, because that file had drifted into a fourth 28-member vocabulary nothing imported. `approval` is the one remaining unimplemented type and the schema says so |
diff --git a/scripts/check_tenant_query_predicates.py b/scripts/check_tenant_query_predicates.py
index e834c02a0..ed7a643ba 100644
--- a/scripts/check_tenant_query_predicates.py
+++ b/scripts/check_tenant_query_predicates.py
@@ -597,6 +597,24 @@ def _tenant_validated_keys(
validated: set[str] = set()
if not auth_names:
return validated
+
+ # A guard is handed the session as well as the key, and for raw SQL the
+ # statement's resolved name set contains the session too (`db.execute(...)`
+ # is part of the expression). So `db` satisfied `keys & resolved` and every
+ # raw statement in a function that called *any* tenant-carrying guard was
+ # credited, whatever it was actually keyed on — a query on an unrelated id
+ # sailed through. Found by probing what the rule credits rather than what
+ # it flags.
+ #
+ # Excluded structurally by what the name is used *as*: a session is the
+ # receiver of a call, a row key is not. Naming `db` / `session` / `conn`
+ # would be the hand-written vocabulary this file exists to avoid.
+ receivers = {
+ node.func.value.id
+ for node in ast.walk(fn)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name)
+ }
+
for node in ast.walk(fn):
if not isinstance(node, ast.Call):
continue
@@ -615,7 +633,7 @@ def _tenant_validated_keys(
if not _guard_enforces(fn, node, parents, module_fns):
continue
for expr in [*node.args, *[kw.value for kw in node.keywords]]:
- if isinstance(expr, ast.Name):
+ if isinstance(expr, ast.Name) and expr.id not in receivers:
validated.add(expr.id)
return validated
@@ -1173,6 +1191,23 @@ async def read_parts(widget_id, user: AuthUser, db):
return await db.execute(select(Widget).where(Widget.id == widget_id))
"""
+_GUARD_VALIDATES_A_DIFFERENT_KEY = """
+from typing import Annotated
+from sqlalchemy import select, text
+from app.api.v1.deps import AuthUser
+from app.models.widget import Widget
+
+async def _fetch_widget(db, widget_id, tenant_id):
+ row = (await db.execute(select(Widget).where(Widget.id == widget_id, Widget.tenant_id == tenant_id))).scalar_one_or_none()
+ if row is None:
+ raise HTTPException(status_code=404)
+ return row
+
+async def read_unrelated(widget_id, other_id, user: AuthUser, db):
+ await _fetch_widget(db, widget_id, user.tenant_id)
+ return await db.execute(text("SELECT * FROM widgets WHERE owner_ref = :o").bindparams(o=other_id))
+"""
+
_GUARD_NOT_RESOLVABLE = """
from typing import Annotated
from sqlalchemy import select
@@ -1261,6 +1296,7 @@ def _self_test() -> int:
("control: guard tested with a raising handler is enforcing", {"r.py": _GUARD_TESTED_AND_RAISES}, 0, None),
("drift C: guard that logs and carries on is not a guard", {"r.py": _GUARD_THAT_FAILS_SOFT}, 1, None),
("drift D: guard defined elsewhere is undecidable, so not credited", {"r.py": _GUARD_NOT_RESOLVABLE}, 1, None),
+ ("drift F: an enforcing guard on a different key credits nothing", {"r.py": _GUARD_VALIDATES_A_DIFFERENT_KEY}, 1, None),
# The RLS-context rule, on both sides of its condition.
("control: RLS context bound on a table that has a policy", {"r.py": _RLS_CONTEXT_ON_COVERED_TABLE}, 0, _PROBE_MIGRATION),
("drift E: RLS context bound on a table with no policy", {"r.py": _RLS_CONTEXT_ON_UNCOVERED_TABLE}, 1, _PROBE_MIGRATION),