Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
Thirty-seven routes that answered anybody, and reads addressed by an id alone (#819)
Beenu Arorad31e0545f39a
diff --git a/.github/workflows/isolation.yml b/.github/workflows/isolation.ymlindex 3fbd24f31..d2d80b5ef 100644--- a/.github/workflows/isolation.yml+++ b/.github/workflows/isolation.yml@@ -21,6 +21,8 @@ on:- "tests/isolation/**"- "services/**"- "scripts/check_route_tenant_scope.py"+ - "scripts/check_route_auth.py"+ - "scripts/check_tenant_query_predicates.py"- "scripts/sync_vendored_tenant_scope.py"- ".github/workflows/isolation.yml"pull_request:@@ -28,6 +30,8 @@ on:- "tests/isolation/**"- "services/**"- "scripts/check_route_tenant_scope.py"+ - "scripts/check_route_auth.py"+ - "scripts/check_tenant_query_predicates.py"- "scripts/sync_vendored_tenant_scope.py"- ".github/workflows/isolation.yml"# Matching isolation-live.yml, so a maintainer can run the isolation gate on@@ -53,7 +57,10 @@ jobs:run: pip install --quiet qdrant-client structlog pytest pytest-asyncio- name: Run isolation suite- run: python -m pytest tests/isolation -v --tb=short --ignore=tests/isolation/test_route_tenant_scope.py+ run: >-+ python -m pytest tests/isolation -v --tb=short+ --ignore=tests/isolation/test_route_tenant_scope.py+ --ignore=tests/isolation/test_route_auth_default_deny.pyroute-scope:name: Route tenant scope (no route lets its caller name the tenant)@@ -66,12 +73,18 @@ jobs:with:python-version: "3.11"- # The gate itself is stdlib-only (ast). The suite additionally drives the- # real fusion router over ASGI, which is the point — a stubbed router- # would not prove anything about the shipped one — so its module-level- # import chain has to resolve here. `aiokafka` and `asyncpg` arrive- # through `app.workers.consumer` and the alert/DLQ sinks. The heavier- # ML and ClickHouse deps do not: `lightgbm`, `scikit-learn`, `numpy` and+ # The gate itself is stdlib-only (ast). The suites additionally drive the+ # real fusion and agents routers over ASGI, which is the point — a+ # stubbed router would not prove anything about the shipped one — so+ # their module-level import chains have to resolve here. `aiokafka` and+ # `asyncpg` arrive through `app.workers.consumer` and the alert/DLQ+ # sinks; `langchain-core` and `langchain-openai` through `app.llm` and+ # `app.llm.factory`, which the contextual and copilot routers import at+ # module level — they are 7 of the 37 routes this suite exists to cover,+ # so skipping them when the import fails would quietly shrink the gate.+ # `sqlalchemy` + `aiosqlite` + `greenlet` back the seeded two-tenant+ # by-id read. The heavier ML and+ # ClickHouse deps do not: `lightgbm`, `scikit-learn`, `numpy` and# `clickhouse-driver` are all imported inside functions, so they stay# out of this job rather than adding minutes to it.- name: Install deps@@ -80,6 +93,7 @@ jobs:pytest pytest-asyncio httpx "fastapi>=0.117,<0.142" pydanticstructlog "redis>=5,<6" "pydantic-settings>=2.1,<3""aiokafka>=0.10,<0.15" "asyncpg>=0.29,<0.31" "cryptography>=46,<51"+ "sqlalchemy>=2,<3" aiosqlite greenlet "langchain-core>=1.2.22,<2" "langchain-openai>=0.2.0,<2"# Proves the gate can fail before trusting it to pass. Injects a route# taking a tenant with no auth, one taking a tenant with auth but no@@ -97,6 +111,31 @@ jobs:- name: Vendored tenant_scope copies are in locksteprun: python scripts/sync_vendored_tenant_scope.py --check+ # Default-deny over every route in the tree. `check_route_tenant_scope`+ # only looks at routes that take a tenant; 37 agents routes took none+ # and were reachable with no credential at all, including the one that+ # executes a response playbook.+ - name: Route-auth gate self-test (both directions)+ run: python scripts/check_route_auth.py --self-test++ - name: Route authentication inventory+ run: python scripts/check_route_auth.py --inventory++ - name: Every route authenticates or records why it is public+ run: python scripts/check_route_auth.py++ # The predicate question, which the parameter gate structurally cannot+ # ask: a route that matches on an id takes no tenant, which is exactly+ # why it was missing the filter.+ - name: Tenant-predicate gate self-test (both directions)+ run: python scripts/check_tenant_query_predicates.py --self-test++ - name: Tenant-predicate inventory+ run: python scripts/check_tenant_query_predicates.py --inventory++ - name: Every query on a tenant-scoped table filters on a tenant+ run: python scripts/check_tenant_query_predicates.py+- name: Start Redis for the two-tenant route replayrun: |docker run -d --name route-iso-redis -p 6379:6379 redis:7-alpine@@ -118,6 +157,12 @@ jobs:AISOC_ISOLATION_REDIS_URL: redis://localhost:6379/9run: python -m pytest tests/isolation/test_route_tenant_scope.py -v --tb=short+ # Anonymous calls against the real agents routers, and a two-tenant+ # seeded read of a distributed-query result addressed by id. Both+ # tenants' rows are asserted present before either absence is asserted.+ - name: Default-deny + by-id replay against the real routes+ run: python -m pytest tests/isolation/test_route_auth_default_deny.py -v --tb=short+- name: Stop Redisif: always()run: docker rm -f route-iso-redis || truediff --git a/.gitignore b/.gitignoreindex 722bc68b1..a320f4770 100644--- a/.gitignore+++ b/.gitignore@@ -120,6 +120,14 @@ apps/docs/build/# Local QA artifacts (screenshots from manual UI checks)apps/web/.qa-screenshots/+# Runtime playbook store. `PlaybookStore` keeps the bundled corpus read-only and+# writes every mutation to `index.json` in the same directory, so anything that+# exercises `POST /api/v1/playbooks` — a test, a local run, a reproduction of a+# bug — leaves a several-thousand-line file behind. Committing it ships whatever+# the last run happened to hold as if it were curated content, and the playbook+# schema lint counts it as a 65th file.+services/agents/data/playbooks/index.json+# Marketplace index staged into the API service build context at deploy time# (see infra/fly/fly-demo-deploy.sh). The canonical source is marketplace/index.json# at the repo root; the API Dockerfile only sees its own dir as build context, sodiff --git a/CHANGELOG.md b/CHANGELOG.mdindex cffecb315..dfe7120ca 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -695,6 +695,101 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security+- **Fifty-eight routes across four services carried no authentication at all,+ and the previous gate could not see them.** `check_route_tenant_scope.py`+ asks a conditional question — *if* a route takes a tenant, where did the+ tenant come from — so a route that takes no tenant was never in its reach.+ 37 `services/agents` routes took none. Reproduced against the real routers+ with credential material configured, so the result is not "the service was+ unconfigured": an anonymous caller with no `Authorization` header created a+ playbook (201), listed all 64 (200), **executed one** (202) and deleted it+ (204), then read copilot conversations and ran a threat hunt. All seven+ refuse with 401 now, while a valid console session still gets a non-empty+ response.++ `services/agents` keeps **dual-mode** auth rather than a bearer-only+ scheme, because the console reaches it directly through a Next rewrite on a+ session cookie: the guard is #813's `require_console_or_service_auth`,+ extended rather than replaced. Its WebSocket could not use the same+ dependency — a browser cannot set an `Authorization` header on a handshake,+ and an `HTTPException` has no defined rendering on a WebSocket scope — so+ `_ws_principal` reads the credential from the header or `?token=`, verifies+ it with the *same* vendored logic, and closes with 1008 before `accept()`.+ That route previously took its tenant from a query parameter defaulting to+ the literal `"default"`, which names no tenant anywhere in this schema, and+ would start a fresh investigation on the connection.++ Also closed: `connectors` (9 data routes, including the one that decrypts a+ saved instance's credentials to test them and the two that push into a+ customer's ITSM), `fusion` (5), `osquery-tls` (7), `threatintel` (1),+ `actions` (1) and 20 in `services/api` — among them `PUT /deployment/config`,+ `POST /deployment/airgap/bundle`, `POST /compliance/evidence/collect`, both+ LLM-backed `/translate` routes and the seven STIX/TAXII routes.++ Two counts in the original report were **wrong, in the safe direction**, and+ the reason matters: `slack-bot` (5) and `teams-bot` (4) were never open. An+ AST pass sees no `Depends` and calls a route unauthenticated, but Slack Bolt+ verifies a request signature, `/approval-card` compares a shared internal+ token in constant time, and the Teams webhook verifies an HMAC-signed card+ payload with a replay window. `scripts/check_route_auth.py` models these as+ **conditional** exemptions that name the verifier and lapse the moment the+ handler stops calling it.++- **`scripts/check_route_auth.py` — default-deny over all 601 routes.** Every+ route must carry an auth dependency or appear in one of three tables, each+ recording why it is public. It reuses the tenant-scope gate's AST collector+ rather than adding a second parser: building it surfaced that+ `playbooks.py`'s `ExecuteUser = Annotated[AuthUser, Depends(require_permission(...))]`+ was reported as an unauthenticated playbook-run, because the vocabulary+ listed `ReadUser` and `WriteUser` and nobody thought of the third. Auth+ aliases are now resolved by **what they wrap**, which removes the naming+ dependency in both directions — the reflex fix of appending the new name to+ the list is how a list stops describing anything. State after: 517+ authenticated, 73 public with a recorded reason, 11 verified in-band, 0+ unexplained.++- **`scripts/check_tenant_query_predicates.py` — the predicate question.**+ Closing the parameter shape surfaced eight routes matching on an id with no+ tenant predicate; the sweep that found them was opportunistic. This gate+ asks the question structurally over the whole tree, and the model and table+ inventories are **derived from the tree** (a model's `tenant_id` column, the+ migrations' DDL) rather than listed, so a new migration cannot slip past.+ It matters most where nothing stands behind it: of 95 tenant-scoped tables+ only 31 carry an RLS policy, and RLS engages only on a session that ran+ `SET LOCAL app.current_tenant_id`.++ Real leaks it found beyond the known eight:++ - `GET /graph/attack-path/{case_id}`'s **relational fallback** read+ `aisoc_cases` by id with no tenant predicate. The primary Neo4j path is+ scoped, but the fallback runs precisely when that path failed — and its+ own docstring says it exists so deployments without a graph database keep+ working, i.e. permanently for many of them. An authenticated caller naming+ another tenant's case UUID got its title, severity, MITRE techniques and+ alert ids.+ - `GET /osquery/distributed/{query_id}` was **both** unauthenticated and+ unscoped. `osquery_distributed_query` has no `tenant_id` of its own — it+ is reached through its node — so the lookup now joins onto+ `osquery_node.tenant_id`. Demonstrated with two seeded tenants: before,+ tenant B naming tenant A's `query_id` got A's host telemetry back; after,+ nothing.+ - `alert_explain._resolve_rule_lineage` selected a detection rule by an id+ lifted out of the alert's `raw_event` — vendor-supplied, so a crafted+ event could name another tenant's rule and have its definition explained+ back.+ - The ITSM webhook inserted its system comment into `aisoc_case_comments`+ **without `tenant_id` at all**, leaving rows belonging to no tenant since+ migration 044 added the column.+ - Thirteen by-id writes (`alerts` escalate/snooze/update, four `connectors`,+ three detection-rule routes, `claim_alert`, `run_saved_hunt`) were scoped+ only by a preceding read. Not exploitable as written, and one reorder from+ being scoped by nothing.++ What cannot be decided statically sits on a **shrink-only ratchet** — 34+ entries, each with a reason, `MAX_RATCHET` asserted against the table's+ length, and an entry whose statement is now scoped failing as *stale*. That+ last property caught two of this change's own edits.+- **The zero-CodeQL-alert invariant was documented for four months withnothing enforcing it.** `apps/docs/docs/operations/security.md` has saidsince 2026-05-15 that "the Python alert count on `main` is zero, and wediff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex 3e275a7ef..6b1adb774 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 120 rows+The last row is the one worth reading first. It is the honest index: 122 rows`GATED`, 9 `PARTIAL` with the specific gap named, and a ratchet that refusesto let a row sit at `NO GATE`.diff --git a/apps/docs/docs/operations/security.md b/apps/docs/docs/operations/security.mdindex a7a949222..f09e5b4df 100644--- a/apps/docs/docs/operations/security.md+++ b/apps/docs/docs/operations/security.md@@ -165,6 +165,78 @@ injected drift. `services/mesh` is exempt by design: it is a federated hubprotected by Ed25519 signatures and k-anonymity, where a shared bearer tokenwould break federation rather than secure it.+### Every route authenticates, or says why it does not++The gate above asks a *conditional* question: if a route takes a tenant, where+did the tenant come from. A route that takes no tenant was never in its reach,+and an unauthenticated route that takes no tenant is still an unauthenticated+route. 37 routes in `services/agents` took none — including the one that+executes a response playbook against your estate.++`scripts/check_route_auth.py` inverts the default. Every route under+`services/` must carry an authentication dependency or appear in one of three+tables, each of which records **why** it is reachable without one:++| Table | What it holds | Example |+|---|---|---|+| `PUBLIC_MODULES` | whole modules that exist to be probed, keyed by path | `app/_health.py` |+| `PUBLIC_ROUTES` | individual routes public by design, each with its reason | `POST /auth/login`, the SAML ACS, a published replay |+| `IN_BAND_CREDENTIAL_ROUTES` | routes whose credential is verified *inside* the handler | the Slack and Teams webhooks, the ITSM inbox, `?token=` WebSockets |++That third table matters more than it looks. An AST pass sees no `Depends` and+calls those routes unauthenticated — they are not. Slack Bolt verifies a+request signature, the Teams webhook verifies an HMAC-signed card payload with+a replay window, and the ITSM inbox authenticates on a per-tenant token in the+path. Each entry **names the verifier** and stops protecting the route the+moment the handler stops calling it, so the exemption cannot outlive its+justification.++`services/agents` is the one service that needs **dual-mode** authentication.+The console reaches its routes directly through a Next.js rewrite carrying the+first-party access token, so a bearer-token-only scheme would lock the browser+out; the guard is the same `require_console_or_service_auth` described above.+Its WebSocket cannot use a FastAPI dependency at all — a browser cannot set an+`Authorization` header on a handshake — so it accepts the credential as+`?token=`, verifies it with the same vendored logic, and closes with code 1008+before accepting the connection.++Run `python scripts/check_route_auth.py --inventory` for the per-service+table.++### Reads addressed by an id still filter on a tenant++Tenant isolation is enforced at read time, per store, and **most of this schema+has nothing behind that**: of 95 tenant-scoped tables only 31 carry an RLS+policy, and RLS engages only on a session that has run+`SET LOCAL app.current_tenant_id` (a `TenantDBSession`). On an `aisoc_*` table+read through a plain session, a missing predicate is a leak, not a+defence-in-depth gap.++The dangerous shape is a query that matches on an id and nothing else —+`select(Honeytoken).where(Honeytoken.id == token_id)`. It takes no tenant, so+the parameter gate cannot see it, and naming another tenant's UUID reaches+their row.++`scripts/check_tenant_query_predicates.py` enforces the predicate directly.+Both the tenant-scoped ORM models and the tenant-scoped tables are derived+from the tree — a model's `tenant_id` column, the migrations' DDL — rather+than listed, so a new migration cannot slip past a stale constant. A statement+counts as scoped when the tenant predicate reaches it by any structural route:+inline in the `.where()` chain, appended to a `filters` list, bound to a+variable, added by a later `q = q.where(...)`, carried in through a join, or+applied by a helper that takes the statement and hands it back filtered. Two+further shapes count because they are strictly narrower: a predicate on the+**authenticated principal's own identity**, and a key this request already+validated against the caller's tenant (`_fetch_run(db, run_id, user.tenant_id)`+before reading that run's events). Raw SQL is parsed too, with docstrings+excluded so prose describing a query is not read as one.++Cases that cannot be decided statically sit on a **shrink-only ratchet**. Each+entry carries a reason; an entry whose statement has since been scoped fails+the build as *stale*, so exemptions come out as code is fixed; and+`MAX_RATCHET` is asserted against the table's length, so adding one means+raising a number in the diff rather than appending a line nobody reads.+### MSSP parent/child links require the child's consentA managed provider can hold other tenants as children (`tenants.parent_tenant_id`), which grants the parent real authority over them: rule packs, per-rule overrides, notes and delegations are all keyed on the child's tenant id, and an override with `action: "exclude"` removes a detection rule from the ruleset that child's hunts run against.diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex f5e0024a9..8196915a2 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -127,6 +127,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| No OSS default resolves to a specific deployment's hostname, so a self-hosted install never presents another deployment's host as its own | self-host contract; `apps/docs/docs/deployment/env-vars.md` (CORS default) | `hosted-hostname.yml` (`scripts/check_hosted_hostname.py` — an exact occurrence count per path, checked in **both** directions: a new or grown occurrence and a stale exemption whose occurrence is gone both fail, so an allow-list entry cannot outlive what justified it; the root is resolved from the working directory rather than `__file__` and verified against sentinels, a zero-match scan is reported as broken rather than clean, and `--self-test` runs first proving the detector separates known-bad from known-good and that the comparison rejects a vacuous pass; it also pins the six vendored `cors.py` copies byte-identical) + `tests/test_hosted_hostname_gate.py` (39 cases, including the ten runtime defaults that leaked and a check that the CORS-tuple extractor itself would notice the origin coming back) | GATED | - || 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 and a key this function already validated against the caller's tenant. 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 | 34 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 writes scoped by an RLS context set on the connection rather than by a predicate the AST can see || 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 || A step a playbook engine cannot run never reports that it ran | concepts/playbooks.md (error handling) | `ci.yml` agents job (`test_playbook_engine_correctness.py::TestUnimplementedStepTypesFailClosed` — an `approval` gate the engine cannot honour halts the run instead of passing it, every handler-less `StepType` is asserted to fail rather than succeed, a missing handler is not retried, an explicit `on_failure: continue` is still honoured, and a dry run reports `would_fail` rather than a bare `dry_run: true`) | GATED | - |@@ -140,7 +142,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`## Summary-- GATED: 120+- GATED: 122- PARTIAL: 9- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex f35408e15..cc973a847 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -6255,6 +6255,8 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []/api/v1/compliance/evidence:post:tags:@@ -10875,6 +10877,8 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []/api/v1/nl-detection/propose:post:tags:@@ -11170,6 +11174,8 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []/api/v1/translation/formats:get:tags:@@ -13260,6 +13266,8 @@ paths:additionalProperties: truetype: objecttitle: Response Get Airgap Status Api V1 Airgap Status Get+ security:+ - HTTPBearer: []/api/v1/llm/status:get:tags:@@ -13284,6 +13292,8 @@ paths:additionalProperties: truetype: objecttitle: Response Get Llm Status Api V1 Llm Status Get+ security:+ - HTTPBearer: []/api/v1/llm/credentials:get:tags:@@ -13365,6 +13375,8 @@ paths:summary: List Indicatorsdescription: List STIX 2.1 indicators from the threat intelligence store.operationId: list_indicators_api_v1_threatintel_stix_indicators_get+ security:+ - HTTPBearer: []parameters:- name: pagein: query@@ -13410,6 +13422,8 @@ paths:summary: Create Indicatordescription: Publish a new STIX 2.1 indicator and optionally mirror it to MISP.operationId: create_indicator_api_v1_threatintel_stix_indicators_post+ security:+ - HTTPBearer: []parameters:- name: push_to_mispin: query@@ -13449,6 +13463,8 @@ paths:summary: List Bundlesdescription: List STIX 2.1 bundles.operationId: list_bundles_api_v1_threatintel_stix_bundles_get+ security:+ - HTTPBearer: []responses:'200':description: Successful Response@@ -13462,6 +13478,8 @@ paths:summary: Create Bundledescription: Create a new STIX 2.1 bundle and optionally mirror it to MISP.operationId: create_bundle_api_v1_threatintel_stix_bundles_post+ security:+ - HTTPBearer: []parameters:- name: push_to_mispin: query@@ -13508,6 +13526,8 @@ paths:application/json:schema:$ref: '#/components/schemas/TAXIICollectionListResponse'+ security:+ - HTTPBearer: []/api/v1/threatintel/stix/misp/health:get:tags:@@ -13530,6 +13550,8 @@ paths:application/json:schema:$ref: '#/components/schemas/MispPushHealth'+ security:+ - HTTPBearer: []/api/v1/threatintel/stix/misp/dry-run:post:tags:@@ -13567,6 +13589,8 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []/api/v1/shifts:get:tags:@@ -13704,6 +13728,8 @@ paths:application/json:schema:$ref: '#/components/schemas/DeploymentConfig'+ security:+ - HTTPBearer: []put:tags:- Deployment@@ -13729,6 +13755,8 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []/api/v1/deployment/airgap/status:get:tags:@@ -13744,6 +13772,8 @@ paths:application/json:schema:$ref: '#/components/schemas/AirgapStatus'+ security:+ - HTTPBearer: []/api/v1/deployment/airgap/bundle:post:tags:@@ -13758,6 +13788,8 @@ paths:application/json:schema:$ref: '#/components/schemas/BundleJob'+ security:+ - HTTPBearer: []/api/v1/fusion/health:get:tags:@@ -13773,6 +13805,8 @@ paths:additionalProperties: truetype: objecttitle: Response Fusion Health Api V1 Fusion Health Get+ security:+ - HTTPBearer: []/api/v1/fusion/metrics:get:tags:@@ -13788,6 +13822,8 @@ paths:additionalProperties: truetype: objecttitle: Response Fusion Metrics Api V1 Fusion Metrics Get+ security:+ - HTTPBearer: []/api/v1/fusion/ml/status:get:tags:diff --git a/scripts/check_route_auth.py b/scripts/check_route_auth.pynew file mode 100644index 000000000..d29e60af1--- /dev/null+++ b/scripts/check_route_auth.py@@ -0,0 +1,485 @@+#!/usr/bin/env python3+"""Default-deny: every route authenticates, or is public for a recorded reason.++``check_route_tenant_scope.py`` asks a conditional question — *if* a route+takes a tenant, where did the tenant come from. That leaves the larger set+untouched: a route that takes no tenant was never in its reach, and an+unauthenticated route that takes no tenant is still an unauthenticated route.+``POST /api/v1/playbooks/{id}/run`` on ``services/agents`` took no tenant and+executed a response playbook against the estate for any caller on the network.++So this gate inverts the default. Every route must either carry an+authentication dependency or appear in one of three tables below, each of+which records *why* it is reachable without one:++``PUBLIC_MODULES``+ Whole modules that exist to be probed — the shared liveness/readiness+ module. Keyed by path, not by handler name, because classifying a route+ as a health check by calling it ``health`` is a naming convention, and a+ naming convention is the thing that drifts.+``PUBLIC_ROUTES``+ Individual routes that are public by design: the sign-in flow, the+ identity-provider callbacks, a deliberately published replay. Each entry+ carries its reason.+``IN_BAND_CREDENTIAL_ROUTES``+ Routes whose credential is verified *inside the handler* rather than by+ a dependency — an HMAC signature, a signed callback payload, a+ single-use token. An AST pass sees no ``Depends`` and calls these+ unauthenticated; they are not. The exemption is **conditional**: it names+ the verifier and only holds while the handler still calls it. Delete the+ verification and the route is reported, which is the failure an+ unconditional allowlist cannot catch.++Two counts in this repository were wrong for exactly that last reason.+``slack-bot`` was reported as five unauthenticated routes: three are probes,+and the other two verify a Slack request signature and a shared internal+token in-band. ``teams-bot``'s webhook verifies an HMAC-signed card payload+with a replay window. Neither was ever open.++Both directions+---------------+* forward — an unauthenticated route with no entry fails;+* reverse — an entry that no longer matches a real unauthenticated route+ fails as stale, and an in-band entry whose verifier the handler stopped+ calling fails too. Exemptions therefore shrink as routes are secured,+ rather than accumulating as a list of things somebody once found+ inconvenient.++Usage::++ python scripts/check_route_auth.py # gate+ python scripts/check_route_auth.py --inventory # per-service table+ python scripts/check_route_auth.py --json+ python scripts/check_route_auth.py --self-test++Exit codes: 0 clean, 1 violations, 2 the scan itself could not run.+"""++from __future__ import annotations++import argparse+import json+import sys+import tempfile+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))++# One parser, two questions. A second route scanner would drift from this one+# the first time either learned something the other did not — which is how the+# `ExecuteUser` alias came to be reported as an unauthenticated playbook-run.+from check_route_tenant_scope import ( # noqa: E402+ REPO_ROOT,+ SERVICES_DIR,+ Route,+ collect_routes,+)++#: Public by design at the service level. ``mesh`` federates between+#: independent deployments over Ed25519 signatures and k-anonymity: peers+#: share no credential, so a bearer token would break federation rather than+#: secure it.+EXEMPT_SERVICES: dict[str, str] = {+ "mesh": "federation is public by design — Ed25519-signed submissions + k-anonymity, and no shared credential exists between peers",+}++#: Modules whose every route is a probe.+PUBLIC_MODULES: dict[str, str] = {+ "app/_health.py": "shared Kubernetes liveness/readiness probes; a kubelet holds no credential and a 401 here reads as an outage",+}++#: Individual public routes, each with the reason it is reachable anonymously.+PUBLIC_ROUTES: dict[str, str] = {+ # -- service health, declared per service rather than in the shared module+ "services/actions/app/api/router.py::health": "liveness probe returning a static status document",+ "services/actions/app/main.py::health": "liveness probe returning a static status document",+ "services/agents/app/api/router.py::health": "liveness probe returning a static status document",+ "services/agents/app/main.py::health": "liveness probe returning a static status document",+ "services/api/app/main.py::health_check": "liveness probe; the readiness detail behind it is already gated",+ "services/connectors/app/api/router.py::health": "liveness probe, deliberately kept off the guarded connectors router",+ "services/fusion/app/api/router.py::health": "liveness probe returning a static status document",+ "services/honeytokens/app/main.py::health": "liveness probe returning a static status document",+ "services/purple-team/app/main.py::health": "liveness probe returning a static status document",+ "services/slack-bot/app/main.py::health": "liveness probe returning a static status document",+ "services/teams-bot/app/main.py::health": "liveness probe returning a static status document",+ "services/threatintel/app/main.py::health": "liveness probe returning a static status document",+ "services/ueba/app/main.py::health": "liveness probe returning a static status document",+ "services/osquery-tls/app/main.py::healthz": "liveness probe returning a static status document",+ # -- Prometheus scrape endpoints, gated by METRICS_TOKEN in the handler ---+ "services/api/app/main.py::metrics": "Prometheus scrape; refuses without METRICS_TOKEN outside a development environment",+ "services/fusion/app/api/router.py::metrics": "Prometheus scrape of worker counters; no tenant data, numeric series only",+ # -- sign-in: the request that establishes a credential cannot carry one --+ "services/api/app/api/v1/endpoints/auth.py::login": "the sign-in request itself; it is what mints the credential",+ "services/api/app/api/v1/endpoints/auth.py::refresh_token": "presents a signed refresh token in the body and is verified there",+ "services/api/app/api/v1/endpoints/waitlist.py::signup": "public sign-up form; rate-limited and writes only to the waitlist table",+ "services/api/app/api/v1/endpoints/passkeys.py::passkey_authenticate_begin": (+ "WebAuthn ceremony start; the assertion that follows is the credential"+ ),+ "services/api/app/api/v1/endpoints/passkeys.py::passkey_authenticate_finish": (+ "verifies the WebAuthn assertion, which is what authenticates the caller"+ ),+ "services/api/app/auth/oidc.py::oidc_login": "OIDC authorization-request redirect, issued before any session exists",+ "services/api/app/auth/oidc.py::oidc_callback": "OIDC redirect URI; the provider's code + state are verified in the handler",+ "services/api/app/auth/oidc.py::oidc_logout": "RP-initiated logout redirect; ends a session rather than reading data",+ "services/api/app/auth/oidc.py::oidc_userinfo": "OIDC userinfo shim reading the bearer token in-band, exactly as the spec requires",+ "services/api/app/auth/saml.py::saml_login": "SAML AuthnRequest redirect, issued before any session exists",+ "services/api/app/auth/saml.py::saml_acs": "SAML assertion consumer; the signed assertion is the credential",+ "services/api/app/auth/saml.py::saml_metadata": "SAML SP metadata document, public by specification",+ "services/api/app/auth/saml.py::saml_logout": "SAML single-logout endpoint; ends a session rather than reading data",+ # -- deliberately published, catalogue-only surfaces ----------------------+ "services/api/app/api/v1/endpoints/replay.py::get_public_replay": (+ "a replay published on purpose; the slug is the capability and publication is an explicit action"+ ),+ "services/api/app/api/v1/endpoints/push.py::get_public_key": "the VAPID public key; publishing it is the point of a public key",+ "services/api/app/api/v1/endpoints/community.py::list_community_plugins": (+ "community marketplace catalogue — the same content the public index serves, no tenant data"+ ),+ "services/api/app/api/v1/endpoints/community.py::get_community_plugin": "community marketplace catalogue entry, no tenant data",+ "services/api/app/api/v1/endpoints/community.py::list_community_detections": "community detection catalogue, no tenant data",+ "services/api/app/api/v1/endpoints/community.py::get_community_detection": "community detection catalogue entry, no tenant data",+ "services/api/app/api/v1/endpoints/community.py::list_community_playbooks": "community playbook catalogue, no tenant data",+ "services/api/app/api/v1/endpoints/compliance.py::list_frameworks": (+ "static compliance-framework definitions (SOC 2, ISO 27001); published standards, not tenant evidence"+ ),+ "services/api/app/api/v1/endpoints/compliance.py::list_framework_controls": (+ "static control definitions for a published framework, not tenant evidence"+ ),+ "services/api/app/api/v1/endpoints/translation.py::list_formats": (+ "the list of rule dialects this build can translate between; a capability manifest"+ ),+ "services/api/app/api/v1/endpoints/fusion.py::ml_status": (+ "model-loaded booleans proxied from fusion; no tenant data and no model configuration"+ ),+}++#: Routes whose credential is verified inside the handler. ``(verifier, reason)``+#: — the verifier must still be called or the exemption lapses.+IN_BAND_CREDENTIAL_ROUTES: dict[str, tuple[str, str]] = {+ "services/slack-bot/app/main.py::slack_events": (+ "SlackRequestHandler",+ "Slack Bolt verifies the request signature against SLACK_SIGNING_SECRET before the handler sees the body",+ ),+ "services/slack-bot/app/notify.py::post_approval_card": (+ "_authorized",+ "internal call authenticated by a shared X-AiSOC-Internal-Token compared in constant time, failing closed when unset",+ ),+ "services/teams-bot/app/main.py::teams_webhook": (+ "handle_card_action",+ "the Bot Framework JWT is terminated by the fronting proxy and the card payload carries our own HMAC, verified with a replay "+ "window by handle_card_action",+ ),+ "services/actions/app/api/router.py::chatops_callback": (+ "verify_token",+ "the query token is an HMAC-signed, expiring payload minted by the ChatOps executor and re-verified here before anything is "+ "recorded",+ ),+ "services/api/app/api/v1/endpoints/email_approval.py::email_decide": (+ "verify_token",+ "one-click email approval; the link carries a signed single-use token verified before the decision is applied",+ ),+ "services/api/app/api/v1/endpoints/oauth.py::oauth_callback": (+ "OAuthState",+ "OAuth redirect URI; the 32-byte single-use state nonce is looked up and consumed before any token exchange",+ ),+ "services/api/app/api/v1/endpoints/inbox_itsm.py::inbound_itsm_webhook": (+ "hmac_secret",+ "vendor webhook authenticated by a per-tenant inbox token in the path plus an HMAC secret, with the connector's tenant cross- "+ "checked against the token's",+ ),+ "services/agents/app/api/metrics.py::metrics": (+ "_authorise",+ "Prometheus scrape; _authorise compares METRICS_TOKEN in constant time and refuses outside a development environment when it is "+ "unset",+ ),+ "services/api/app/api/v1/endpoints/graph_ws.py::graph_updates_stream": (+ "_authenticate_ws",+ "WebSocket: a browser cannot set an Authorization header on the handshake, so the ticket arrives as a query parameter and is "+ "verified in _authenticate_ws",+ ),+ "services/agents/app/api/investigate.py::stream_investigation": (+ "_ws_principal",+ "WebSocket: same handshake constraint; _ws_principal resolves the console token or service token and closes with 1008 before "+ "accept() when neither verifies",+ ),+ "services/osquery-tls/app/api/v1/endpoints/enroll.py::enroll": (+ "verify_enroll_secret",+ "osqueryd holds no bearer token at enrolment — this call is what establishes one — and the per-tenant enroll secret is checked "+ "before any write",+ ),+}+++def _module_exempt(route: Route) -> str | None:+ for suffix, reason in PUBLIC_MODULES.items():+ if route.path.endswith(suffix):+ return reason+ return None+++def classify(routes: list[Route]) -> tuple[list[Route], list[str]]:+ """Return (unexplained unauthenticated routes, stale exemption keys)."""+ unexplained: list[Route] = []+ matched: set[str] = set()++ for route in routes:+ if route.service in EXEMPT_SERVICES or route.has_auth:+ continue+ if _module_exempt(route) is not None:+ continue+ key = f"{route.path}::{route.function}"+ if key in PUBLIC_ROUTES:+ matched.add(key)+ continue+ if key in IN_BAND_CREDENTIAL_ROUTES:+ verifier, _reason = IN_BAND_CREDENTIAL_ROUTES[key]+ if verifier in route.body_calls or _verifier_in_module(route, verifier):+ matched.add(key)+ continue+ # The entry claims a check the route no longer performs.+ unexplained.append(route)+ continue+ unexplained.append(route)++ declared = set(PUBLIC_ROUTES) | set(IN_BAND_CREDENTIAL_ROUTES)+ stale = sorted(declared - matched)+ return unexplained, stale+++def _verifier_in_module(route: Route, verifier: str) -> bool:+ """Whether the handler's module references the verifier.++ Some in-band checks live one call frame away — Bolt's+ ``SlackRequestHandler`` is constructed at import time and verifies before+ the handler body runs, and the ITSM webhook's HMAC is applied by a helper+ the handler calls. Checking the module rather than only the function body+ is the looser test, so it is used as a fallback: the point is that+ deleting the verification entirely still trips the gate.+ """+ path = REPO_ROOT / route.path+ if not path.is_file():+ return False+ return verifier in path.read_text(encoding="utf-8", errors="ignore")+++def _print_inventory(routes: list[Route]) -> None:+ print(f"Route authentication inventory — scanned {SERVICES_DIR}")+ print(f"{'service':<14}{'routes':>8}{'authed':>8}{'public':>8}{'in-band':>9}{'open':>6} reason for the public ones")+ print("-" * 104)+ total = [0, 0, 0, 0, 0]+ for svc in sorted({r.service for r in routes}):+ rows = [r for r in routes if r.service == svc]+ authed = [r for r in rows if r.has_auth]+ public: list[Route] = []+ inband: list[Route] = []+ open_: list[Route] = []+ for r in rows:+ if r.has_auth:+ continue+ key = f"{r.path}::{r.function}"+ if svc in EXEMPT_SERVICES or _module_exempt(r) is not None or key in PUBLIC_ROUTES:+ public.append(r)+ elif key in IN_BAND_CREDENTIAL_ROUTES:+ inband.append(r)+ else:+ open_.append(r)+ note = EXEMPT_SERVICES.get(svc, "")+ if not note and public:+ note = "probes, sign-in flow and published catalogues" if len(public) > 2 else "liveness/readiness probes"+ print(f"{svc:<14}{len(rows):>8}{len(authed):>8}{len(public):>8}{len(inband):>9}{len(open_):>6} {note[:58]}")+ for i, v in enumerate((len(rows), len(authed), len(public), len(inband), len(open_))):+ total[i] += v+ print("-" * 104)+ print(f"{'TOTAL':<14}{total[0]:>8}{total[1]:>8}{total[2]:>8}{total[3]:>9}{total[4]:>6}")+++# ---------------------------------------------------------------------------+# Self-test+# ---------------------------------------------------------------------------++_CLEAN = """+from fastapi import APIRouter+from app.api.v1.deps import AuthUser+router = APIRouter()+[email protected]("/queue")+async def queue(user: AuthUser):+ return []+"""++_OPEN = """+from fastapi import APIRouter+router = APIRouter()+[email protected]("/run")+async def run_playbook(playbook_id: str):+ return {"started": True}+"""++_ROUTER_LEVEL = """+from fastapi import APIRouter, Depends+from app.security.tenant_scope import require_console_or_service_auth+router = APIRouter(dependencies=[Depends(require_console_or_service_auth)])+[email protected]("/run")+async def run_playbook(playbook_id: str):+ return {"started": True}+"""++_LOCAL_ALIAS = """+from typing import Annotated+from fastapi import APIRouter, Depends+from app.api.v1.deps import AuthUser, require_permission+router = APIRouter()+ExecuteUser = Annotated[AuthUser, Depends(require_permission("playbooks:execute"))]+[email protected]("/run")+async def run_playbook(playbook_id: str, user: ExecuteUser):+ return {"started": True}+"""+++def _self_test() -> int:+ cases = [+ ("clean: route carries an auth dependency", _CLEAN, 0),+ ("drift A: mutating route with no auth and no exemption", _OPEN, 1),+ ("control: auth declared on the router, not the route", _ROUTER_LEVEL, 0),+ ("control: auth via a module-local Annotated alias", _LOCAL_ALIAS, 0),+ ]+ failures = 0+ with tempfile.TemporaryDirectory() as tmp:+ for i, (label, source, want) in enumerate(cases):+ root = Path(tmp) / f"case{i}"+ target = root / "services" / "probe" / "app"+ target.mkdir(parents=True, exist_ok=True)+ (target / "routes.py").write_text(source, encoding="utf-8")+ routes = collect_routes(root=root)+ open_, _stale = classify(routes)+ ok = len(open_) == want and len(routes) > 0+ if not ok:+ failures += 1+ print(f" [{'PASS' if ok else 'FAIL'}] {label}: {len(open_)} open, want {want} (scanned {len(routes)} routes)")++ failures += _self_test_stale_exemption()+ if failures:+ print(f"\nself-test FAILED: {failures} case(s) did not behave as specified", file=sys.stderr)+ return 1+ print(+ "\nself-test passed: drift detected both ways, router-level and alias auth "+ "both recognised, and a stale in-band exemption is dropped."+ )+ return 0+++def _self_test_stale_exemption() -> int:+ """Strip an in-band verifier and assert its route stops being exempt.++ The reverse direction, and the one that matters most here: every entry in+ ``IN_BAND_CREDENTIAL_ROUTES`` is a claim that a handler checks something.+ A claim nobody re-tests is indistinguishable from a comment.+ """+ failures = 0+ routes = collect_routes()+ by_key = {f"{r.path}::{r.function}": r for r in routes}++ for key, (verifier, _reason) in IN_BAND_CREDENTIAL_ROUTES.items():+ route = by_key.get(key)+ if route is None:+ print(f" [FAIL] in-band exemption names a route that does not exist: {key}")+ failures += 1+ continue+ path = REPO_ROOT / route.path+ source = path.read_text(encoding="utf-8", errors="ignore")+ if verifier not in source:+ print(f" [FAIL] in-band exemption for {route.function}() names {verifier}(), which {route.path} never mentions")+ failures += 1++ # Remove one live entry outright and assert the route resurfaces.+ live = [k for k in IN_BAND_CREDENTIAL_ROUTES if k in by_key]+ if not live:+ print(" [FAIL] stale exemption: no live in-band entry to exercise")+ return failures + 1+ victim = sorted(live)[0]+ saved = IN_BAND_CREDENTIAL_ROUTES.pop(victim)+ try:+ open_, _ = classify(routes)+ if any(f"{r.path}::{r.function}" == victim for r in open_):+ print(f" [PASS] stale exemption: {victim} is reported the moment its entry is removed")+ else:+ print(f" [FAIL] stale exemption: removing {victim} produced no finding")+ failures += 1+ finally:+ IN_BAND_CREDENTIAL_ROUTES[victim] = saved+ return failures+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--inventory", action="store_true", help="print the per-service authentication table")+ parser.add_argument("--json", action="store_true", help="emit every unauthenticated route with its classification")+ parser.add_argument("--self-test", action="store_true", help="prove the gate detects injected drift both ways")+ args = parser.parse_args(argv)++ if args.self_test:+ return _self_test()++ if not SERVICES_DIR.is_dir():+ print(f"ERROR: no services/ directory under {REPO_ROOT} — refusing to report a result for a tree I did not open.", file=sys.stderr)+ return 2++ routes = collect_routes()+ unexplained, stale = classify(routes)++ files = len({r.path for r in routes})+ authed = sum(1 for r in routes if r.has_auth)+ print(+ f"check_route_auth: scanned {len(routes)} routes across {files} files under {SERVICES_DIR}; "+ f"{authed} authenticated, {len(routes) - authed} public "+ f"({len(PUBLIC_ROUTES)} named routes, {len(IN_BAND_CREDENTIAL_ROUTES)} verified in-band, "+ f"{len(PUBLIC_MODULES)} probe module, {len(EXEMPT_SERVICES)} exempt service)"+ )++ if args.json:+ print(+ json.dumps(+ [+ {+ "service": r.service,+ "path": r.path,+ "function": r.function,+ "methods": r.methods,+ "route_path": r.route_path,+ }+ for r in unexplained+ ],+ indent=2,+ )+ )+ return 0 if not unexplained and not stale else 1++ if args.inventory:+ _print_inventory(routes)+ return 0++ if stale:+ print(f"\nFAIL: {len(stale)} exemption(s) no longer describe an unauthenticated route.", file=sys.stderr)+ print(" The route was secured, renamed or deleted — remove the entry rather than", file=sys.stderr)+ print(" leaving a justification that outlived the thing it justified.", file=sys.stderr)+ for key in stale:+ print(f" - {key}", file=sys.stderr)++ if unexplained:+ print(f"\nFAIL: {len(unexplained)} route(s) carry no authentication and no recorded reason.", file=sys.stderr)+ print(" Add a dependency, or record why the route is public — health and readiness", file=sys.stderr)+ print(" probes are legitimately public; a route that mutates state is not.", file=sys.stderr)+ for route in unexplained:+ print(f" - {route.service}: {route.location()} {'/'.join(route.methods).upper()} {route.route_path}", file=sys.stderr)++ if stale or unexplained:+ return 1++ print("OK: every route authenticates, or is public for a reason that still holds.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/check_route_tenant_scope.py b/scripts/check_route_tenant_scope.pyindex ce3a40f4c..b7748cc3a 100644--- a/scripts/check_route_tenant_scope.py+++ b/scripts/check_route_tenant_scope.py@@ -319,6 +319,43 @@ def _pydantic_models_with_tenant(tree: ast.AST) -> dict[str, list[str]]:return models+def auth_annotation_aliases(tree: ast.AST) -> set[str]:+ """Module-local ``X = Annotated[..., Depends(<auth callable>)]`` names.++ ``playbooks.py`` declares ``ExecuteUser = Annotated[AuthUser,+ Depends(require_permission("playbooks:execute"))]`` — a perfectly+ authenticated route that a hardcoded vocabulary reports as wide open,+ because the vocabulary happened to list ``ReadUser`` and ``WriteUser``+ and nobody thought of the third.++ Resolving the alias by *what it wraps* removes the naming dependency+ entirely, which matters in both directions: a false positive sends+ somebody to "fix" a closed route, and the reflex fix — appending the new+ name to the list — is how a list stops describing anything.+ """+ aliases: set[str] = set()+ for node in ast.walk(tree):+ target_names: list[str] = []+ value: ast.expr | None = None+ if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):+ target_names = [node.targets[0].id]+ value = node.value+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.value is not None:+ target_names = [node.target.id]+ value = node.value+ if not target_names or value is None:+ continue+ if not (isinstance(value, ast.Subscript) and _names_in(value.value) & {"Annotated"}):+ continue+ # Credit only when a Depends(...) inside the annotation names an auth+ # callable; Annotated[AsyncSession, Depends(get_db)] is not auth.+ for sub in ast.walk(value):+ if isinstance(sub, ast.Call) and _names_in(sub.func) & {"Depends", "Security"}:+ if _names_in(sub) & AUTH_DEPENDENCY_NAMES:+ aliases.update(target_names)+ return aliases++def _router_level_auth_objects(tree: ast.AST) -> set[str]:"""Router objects constructed with a ``dependencies=`` list naming an auth guard.@@ -350,6 +387,9 @@ def _scan_tree(tree: ast.AST, *, service: str, rel_path: str) -> list[Route]:routes: list[Route] = []secured_routers = _router_level_auth_objects(tree)tenant_models = _pydantic_models_with_tenant(tree)+ # Per-file vocabulary: the global names plus any module-local alias that+ # resolves to one of them.+ auth_vocabulary = AUTH_DEPENDENCY_NAMES | auth_annotation_aliases(tree)for node in ast.walk(tree):if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):@@ -372,7 +412,7 @@ def _scan_tree(tree: ast.AST, *, service: str, rel_path: str) -> list[Route]:assert isinstance(dec, ast.Call)for kw in dec.keywords:if kw.arg == "dependencies":- decorator_auth |= _names_in(kw.value) & AUTH_DEPENDENCY_NAMES+ decorator_auth |= _names_in(kw.value) & auth_vocabularyif not methods:continue@@ -384,7 +424,7 @@ def _scan_tree(tree: ast.AST, *, service: str, rel_path: str) -> list[Route]:auth_deps: set[str] = set(decorator_auth)for arg in all_args:ann = _annotation_names(arg.annotation)- hit = ann & AUTH_DEPENDENCY_NAMES+ hit = ann & auth_vocabularyif hit:auth_deps |= hitif _is_tenant_param(arg.arg):@@ -399,7 +439,7 @@ def _scan_tree(tree: ast.AST, *, service: str, rel_path: str) -> list[Route]:# Defaults can carry Depends(...) without an annotation.for default in [*args.defaults, *[d for d in args.kw_defaults if d is not None]]:- auth_deps |= _names_in(default) & AUTH_DEPENDENCY_NAMES+ auth_deps |= _names_in(default) & auth_vocabularybody_names = set()for stmt in node.body:diff --git a/scripts/check_tenant_query_predicates.py b/scripts/check_tenant_query_predicates.pynew file mode 100644index 000000000..1a3b8e749--- /dev/null+++ b/scripts/check_tenant_query_predicates.py@@ -0,0 +1,1075 @@+#!/usr/bin/env python3+"""Fail the build when a query on a tenant-scoped table carries no tenant predicate.++``scripts/check_route_tenant_scope.py`` asks where the tenant *came from*. This+asks a different question, and the two do not overlap: once a route has a+tenant, does the query it runs actually filter on it?++Closing the parameter shape surfaced the worse variant. Eight routes matched on+an id and nothing else — ``select(Honeytoken).where(Honeytoken.id == token_id)``+— so naming another tenant's UUID read, revoked or deleted their row. The+parameter gate cannot see those: they take no tenant parameter, which is+precisely why they were broken. The addressing mode is irrelevant; the predicate+is the control.++It is the *only* control on most of this schema. Of the 81 tenant-scoped tables+in the migrations, 32 carry an RLS policy and 49 do not, and RLS only engages on+a session that ran ``SET LOCAL app.current_tenant_id`` (``TenantDBSession``). On+an ``aisoc_*`` table read through a plain ``DBSession``, a missing predicate is a+leak, not a defence-in-depth gap.++What counts as scoped+---------------------+Structural signals only, because a naming convention is exactly what drifts:++* a ``tenant_id`` predicate on the statement, however it got there — inline in+ the ``.where()`` chain, appended to a ``filters`` list, bound to a variable,+ added by a later ``q = q.where(...)``, carried in through a join, or applied+ by a helper that takes the statement and returns it filtered;+* a predicate binding the row to the **authenticated principal's own identity**+ (``PasskeyCredential.user_id == user.user_id``), which is strictly narrower+ than their tenant. Only an identity arriving through an auth dependency+ counts — a ``user_id`` the caller typed is not a credential.++Anything else is a finding, and must be on the ratchet with a reason.++Both directions+---------------+The dominant failure shape in this repository is the one-directional gate: it+compares A against B, never B against A, and prints OK while drift accumulates+in the direction things actually change. So:++* forward — an unscoped statement that is not on the ratchet fails;+* reverse — a **ratchet entry whose statement is now scoped, or gone, also+ fails**. That is what makes it shrink-only. An allowlist you can quietly+ outgrow is not a ratchet, and one that keeps passing after its justification+ lapsed is worse than none, because it reads like a decision somebody made.++``MAX_RATCHET`` is asserted against the table's length, so adding an entry means+raising a number in a diff rather than appending a line nobody reads.++Usage::++ python scripts/check_tenant_query_predicates.py # gate+ python scripts/check_tenant_query_predicates.py --inventory+ python scripts/check_tenant_query_predicates.py --json+ python scripts/check_tenant_query_predicates.py --self-test++Exit codes: 0 clean, 1 violations, 2 the scan itself could not run.+"""++from __future__ import annotations++import argparse+import ast+import json+import os+import re+import subprocess+import sys+import tempfile+from dataclasses import asdict, dataclass, field+from pathlib import Path+++def _repo_root() -> Path:+ """Resolve the repository root from git, not from this file's location.++ A gate that derives its root from ``__file__`` will scan a stale copy of+ the tree and print a confident OK about a checkout it never opened.+ """+ env = os.environ.get("AISOC_REPO_ROOT")+ if env:+ return Path(env).resolve()+ try:+ out = subprocess.run(+ ["git", "rev-parse", "--show-toplevel"],+ capture_output=True,+ text=True,+ check=True,+ cwd=Path(__file__).resolve().parent,+ )+ return Path(out.stdout.strip()).resolve()+ except (subprocess.CalledProcessError, FileNotFoundError):+ return Path(__file__).resolve().parent.parent+++REPO_ROOT = _repo_root()+SERVICES_DIR = REPO_ROOT / "services"++#: Never scanned. Written as path *segments* rather than substrings: a skip+#: spelled ``"node_modules"`` also swallows ``app/node_modules_helper.py``, and+#: one spelled as a prefix makes the gate's answer depend on whether anybody+#: has run an install.+SKIP_SEGMENTS = frozenset({"tests", "_vendor", "plans", "node_modules", ".venv", "migrations", "alembic"})+SKIP_FILE_PREFIXES = ("test_", "conftest")++#: SQLAlchemy statement constructors whose first argument names the entity.+STATEMENT_FUNCS = frozenset({"select", "update", "delete"})++#: Calls that attach a predicate to a statement.+PREDICATE_CALLS = frozenset({"where", "filter", "filter_by", "having", "join", "outerjoin", "join_from"})++#: Names that, appearing anywhere in a resolved predicate, mean the statement+#: is tenant-filtered.+TENANT_TOKENS = frozenset({"tenant_id", "tenant_ids", "tenant_uuid", "current_tenant_id"})++#: Annotations that establish an authenticated principal, so a predicate+#: comparing against one of that object's attributes is principal-derived+#: rather than caller-supplied. Mirrors AUTH_DEPENDENCY_NAMES in+#: check_route_tenant_scope.py; the two gates answer different questions about+#: the same vocabulary.+AUTH_ANNOTATIONS = frozenset(+ {+ "AuthUser",+ "CurrentUser",+ "ReadUser",+ "WriteUser",+ "AdminUser",+ "TenantPrincipal",+ "ScopedPrincipal",+ "PortfolioScope",+ "ActionPrincipal",+ }+)++#: How far to chase a predicate through local rebinding. Three hops covers+#: ``filters.append(...)`` → ``and_(*filters)`` → ``.where(...)`` with room to+#: spare; unbounded chasing would credit unrelated names.+_BINDING_DEPTH = 3++_SQL_VERB = re.compile(r"\b(SELECT|UPDATE|DELETE\s+FROM|INSERT\s+INTO)\b", re.IGNORECASE)+_SQL_TABLE = re.compile(r'\b(?:FROM|JOIN|UPDATE|INTO)\s+("?[\w.]+"?)', re.IGNORECASE)+_TENANT_IN_SQL = re.compile(r"\btenant_id\b", re.IGNORECASE)+++# ---------------------------------------------------------------------------+# Ratchet+# ---------------------------------------------------------------------------++#: Statements that reach a tenant-scoped table without a tenant predicate and+#: are nonetheless correct. Keyed ``path::function::entity``; the value is why.+#:+#: Every entry is re-verified on each run: if the statement it names has since+#: gained a predicate, or moved, or been deleted, the gate fails and the entry+#: must come out. That is the difference between a ratchet and an allowlist.+RATCHET: dict[str, str] = {+ # -- credential resolution: the lookup that *establishes* the tenant ------+ # These cannot filter on the caller's tenant because the caller has none+ # yet. The row they find is what assigns one. Scoping them on a tenant+ # would mean no login could ever resolve a user.+ "services/api/app/api/v1/endpoints/auth.py::login::User": "pre-auth credential lookup by email; this query is what resolves the tenant",+ "services/api/app/api/v1/endpoints/auth.py::refresh_token::User": (+ "refresh presents a signed token, not a tenant; the row it names assigns one"+ ),+ "services/api/app/api/v1/deps.py::get_current_user::User": "bearer-token subject lookup; runs before any tenant exists on the request",+ "services/api/app/api/v1/deps.py::_resolve_api_key::ApiKey": (+ "API-key hash lookup; the key row is the credential that carries the tenant"+ ),+ "services/api/app/api/v1/endpoints/graph_ws.py::_authenticate_ws::User": (+ "websocket ticket verification, same pre-auth shape as get_current_user"+ ),+ "services/api/app/api/v1/endpoints/passkeys.py::_consume_challenge::PasskeyChallenge": (+ "single-use WebAuthn challenge, matched on its own high-entropy value"+ ),+ "services/api/app/api/v1/endpoints/passkeys.py::passkey_authenticate_begin::User": (+ "pre-auth: resolves which user is signing in, by the email they typed"+ ),+ "services/api/app/api/v1/endpoints/passkeys.py::passkey_authenticate_begin::PasskeyCredential": (+ "pre-auth: lists the credentials registered for the resolved user"+ ),+ "services/api/app/api/v1/endpoints/passkeys.py::passkey_authenticate_finish::PasskeyCredential": (+ "pre-auth: matched on the WebAuthn credential id the authenticator signed"+ ),+ "services/api/app/api/v1/endpoints/passkeys.py::passkey_authenticate_finish::User": (+ "pre-auth: the owner of the verified credential, which is what assigns the tenant"+ ),+ "services/api/app/api/v1/endpoints/oauth.py::oauth_callback::OAuthState": (+ "matched on the 32-byte single-use state nonce, which is itself the credential"+ ),+ # -- deliberately cross-tenant surfaces ----------------------------------+ "services/api/app/api/v1/endpoints/tenants.py::create_user::User": (+ "platform-admin provisioning: creates users across tenants by design"+ ),+ "services/api/app/api/v1/endpoints/tenants.py::update_user::User": (+ "platform-admin user administration, authorised by the admin role not a tenant"+ ),+ "services/api/app/services/org_scope.py::resolve_portfolio_scope::OrganizationTenant": (+ "MSSP portfolio resolver: answers 'which tenants', so it cannot presuppose one"+ ),+ "services/api/app/services/org_scope.py::resolve_portfolio_scope::OrganizationMemberTenant": (+ "MSSP grant resolver, scoped on org_id + user_id, which is what bounds the portfolio"+ ),+ "services/api/app/api/v1/endpoints/replay.py::get_public_replay::PublishedReplay": (+ "a published replay is deliberately public; the slug is the capability"+ ),+ "services/api/app/api/v1/endpoints/replay.py::_unique_slug::PublishedReplay": (+ "slug-collision probe across all replays; a tenant-scoped check would mint duplicates"+ ),+ # -- no request, so no caller's tenant to filter on ----------------------+ "services/api/app/main.py::_demo_self_heal_bootstrap::PublishedReplay": (+ "startup bootstrap, not a request path; runs before any caller exists"+ ),+ "services/api/app/scripts/bootstrap_admin.py::bootstrap::User": "one-shot CLI bootstrap that creates the first tenant's first admin",+ "services/api/app/scripts/seed_demo.py::_ensure_user::User": "demo seeding CLI, addressed by a fixed deterministic id",+ "services/api/app/scripts/seed_demo.py::_seed_published_replay::PublishedReplay": (+ "demo seeding CLI for the canonical public replay slug"+ ),+ "services/api/app/workers/hunt_scheduler.py::run_once::SavedHunt": (+ "scheduler sweeps every tenant's due hunts, then executes each under its own tenant"+ ),+ "services/api/app/workers/oauth_refresh.py::_select_due_connectors::Connector": (+ "refresh worker sweeps all tenants' expiring OAuth grants; there is no caller"+ ),+ "services/api/app/workers/oauth_refresh.py::_refresh_one::Connector": (+ "writes back to the connector row the sweep above already selected, by primary key"+ ),+ "services/api/app/workers/oauth_refresh.py::_record_failure::Connector": "records the failure of that same swept row, by primary key",+ # -- the row is addressed by an opaque capability, and yields the tenant --+ "services/honeytokens/app/api/routes.py::webhook_trigger::Honeytoken": (+ "canary callback: the token id is the capability and the row supplies the tenant it belongs to"+ ),+ "services/osquery-tls/app/services/node_registry.py::get_node_by_key::OsqueryNode": (+ "node_key is the agent's enrolment credential; this lookup is what resolves its tenant"+ ),+ "services/osquery-tls/app/services/node_registry.py::mark_seen::OsqueryNode": (+ "heartbeat write to the node row the key above already resolved, by primary key"+ ),+ # -- scoped by a mechanism the AST cannot see, named so it can be re-checked+ "services/agents/app/investigator/ledger.py::complete_run::investigation_runs": (+ "connection runs _set_rls_context(conn, tenant_id) first and investigation_runs carries an RLS policy"+ ),+ "services/agents/app/investigator/ledger.py::persist_auto_triage::investigation_runs": (+ "same RLS-context connection as complete_run, on the same RLS-covered table"+ ),+ "services/api/app/services/retention.py::build_alert_purge_sql::alerts": (+ "returns SQL for the purge worker to run on a per-tenant RLS session; alerts carries an RLS policy"+ ),+ "services/api/app/workers/retention_purge.py::build_alert_count_sql::alerts": (+ "dry-run counterpart of build_alert_purge_sql, run on the same per-tenant RLS session"+ ),+ "services/api/app/api/v1/endpoints/investigations.py::_fetch_model_costs::aisoc_run_costs": (+ "deliberate: the agents service writes whatever tenant_id string the request carried, so the run_id (tenant-bound in "+ "investigation_runs and checked by _fetch_run) is the reliable key"+ ),+ "services/api/app/services/mssp_rule_resolver.py::resolve_effective_rules::DetectionRule": (+ "MSSP rule packs are cross-tenant by construction: a parent organisation's pack is resolved against its children, bounded by "+ "pack_id from the verified portfolio"+ ),+}++#: Raising this is a deliberate act with a diff attached. Appending to RATCHET+#: without raising it fails the gate, which is the whole point.+MAX_RATCHET = 34+++# ---------------------------------------------------------------------------+# Inventory, derived from the tree+# ---------------------------------------------------------------------------+++@dataclass+class Inventory:+ models: dict[str, str] = field(default_factory=dict) # class name -> table+ tables: set[str] = field(default_factory=set) # tables with a tenant_id column+ rls_tables: set[str] = field(default_factory=set) # tables with an RLS policy+++def _skipped(path: Path, root: Path) -> bool:+ rel = path.relative_to(root)+ if SKIP_SEGMENTS & set(rel.parts):+ return True+ return rel.name.startswith(SKIP_FILE_PREFIXES)+++def _python_files(root: Path) -> list[Path]:+ base = root / "services"+ if not base.is_dir():+ return []+ return [p for p in sorted(base.rglob("*.py")) if not _skipped(p, root)]+++def build_inventory(root: Path) -> Inventory:+ """Tenant-scoped models and tables, read out of the tree rather than listed.++ A hand-maintained list of "the tenant tables" is a naming convention with+ extra steps: the next migration adds a table and the gate never hears+ about it.+ """+ inv = Inventory()++ for py in _python_files(root):+ try:+ tree = ast.parse(py.read_text(encoding="utf-8", errors="ignore"))+ except SyntaxError:+ continue+ for node in ast.walk(tree):+ if not isinstance(node, ast.ClassDef):+ continue+ fields: set[str] = set()+ table: str | None = None+ for stmt in node.body:+ if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):+ fields.add(stmt.target.id)+ elif isinstance(stmt, ast.Assign):+ for tgt in stmt.targets:+ if not isinstance(tgt, ast.Name):+ continue+ fields.add(tgt.id)+ if tgt.id == "__tablename__" and isinstance(stmt.value, ast.Constant):+ table = str(stmt.value.value)+ # Only mapped classes. A Pydantic request model carrying a+ # `tenant_id` field is not a table, and counting it inflates the+ # inventory *and* teaches the raw-SQL matcher to treat the class+ # name as a table — a false positive waiting for any query that+ # happens to say `FROM Inventory`.+ if "tenant_id" in fields and table is not None:+ inv.models[node.name] = table++ for sql in sorted(root.glob("services/*/migrations/*.sql")):+ text = sql.read_text(encoding="utf-8", errors="ignore")+ bodies: dict[str, str] = {}+ for m in re.finditer(r'CREATE TABLE(?:\s+IF NOT EXISTS)?\s+([\w".]+)\s*\((.*?)\n\s*\);', text, re.S | re.I):+ name = m.group(1).strip('"').split(".")[-1]+ bodies[name] = bodies.get(name, "") + m.group(2)+ for m in re.finditer(r'ALTER TABLE\s+(?:IF EXISTS\s+)?([\w".]+)\s+ADD COLUMN(?:\s+IF NOT EXISTS)?\s+(\w+)', text, re.I):+ name = m.group(1).strip('"').split(".")[-1]+ bodies[name] = bodies.get(name, "") + " " + m.group(2)+ for name, body in bodies.items():+ if re.search(r"\btenant_id\b", body):+ inv.tables.add(name)+ for m in re.finditer(r'ALTER TABLE\s+(?:IF EXISTS\s+)?([\w".]+)\s+ENABLE ROW LEVEL SECURITY', text, re.I):+ inv.rls_tables.add(m.group(1).strip('"').split(".")[-1])++ inv.tables |= {t for t in inv.models.values() if t}+ return inv+++# ---------------------------------------------------------------------------+# AST helpers+# ---------------------------------------------------------------------------+++def _names(node: ast.AST) -> set[str]:+ """Every identifier, attribute, keyword and short literal under ``node``."""+ out: set[str] = set()+ for child in ast.walk(node):+ if isinstance(child, ast.Name):+ out.add(child.id)+ elif isinstance(child, ast.Attribute):+ out.add(child.attr)+ elif isinstance(child, ast.keyword) and child.arg:+ out.add(child.arg)+ elif isinstance(child, ast.Constant) and isinstance(child.value, str):+ out.add(child.value[:120])+ return out+++def _local_bindings(fn: ast.AST) -> dict[str, set[str]]:+ """``name`` → every identifier ever assigned, appended or added to it.++ Deliberately flow-insensitive and union-ing: the question is only whether a+ tenant predicate *can* reach the statement, and a predicate appended on one+ branch still scopes the query on that branch.+ """+ binds: dict[str, set[str]] = {}++ def add(key: str, node: ast.AST) -> None:+ binds.setdefault(key, set()).update(_names(node))++ for stmt in ast.walk(fn):+ if isinstance(stmt, ast.Assign):+ for tgt in stmt.targets:+ if isinstance(tgt, ast.Name):+ add(tgt.id, stmt.value)+ elif isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name) and stmt.value is not None:+ add(stmt.target.id, stmt.value)+ elif isinstance(stmt, ast.AugAssign) and isinstance(stmt.target, ast.Name):+ add(stmt.target.id, stmt.value)+ elif (+ isinstance(stmt, ast.Call) and isinstance(stmt.func, ast.Attribute) and stmt.func.attr in {"append", "extend", "add", "update"}+ ):+ base = stmt.func.value+ if isinstance(base, ast.Name):+ for arg in stmt.args:+ add(base.id, arg)+ elif isinstance(stmt, ast.For) and isinstance(stmt.target, ast.Name):+ add(stmt.target.id, stmt.iter)+ return binds+++def _expand(seed: set[str], binds: dict[str, set[str]], depth: int = _BINDING_DEPTH) -> set[str]:+ seen = set(seed)+ frontier = set(seed)+ for _ in range(depth):+ nxt: set[str] = set()+ for name in frontier:+ for value in binds.get(name, ()):+ if value not in seen:+ seen.add(value)+ nxt.add(value)+ frontier = nxt+ if not frontier:+ break+ return seen+++def _scoping_helpers(tree: ast.AST) -> set[str]:+ """Functions that take a statement and hand it back tenant-filtered.++ ``q = _scope(select(Alert), info, Alert)`` is scoped, and a scanner that+ only walks the ``.where()`` chain outward from ``select(...)`` reports it+ as wide open — the filter is applied one call frame away. Detected by what+ the helper *does* (returns a ``.where(...tenant_id...)`` built from one of+ its own parameters), not by what it is called.+ """+ helpers: set[str] = set()+ for node in ast.walk(tree):+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):+ continue+ params = {a.arg for a in [*node.args.posonlyargs, *node.args.args, *node.args.kwonlyargs]}+ if not params:+ continue+ for inner in ast.walk(node):+ if not (isinstance(inner, ast.Call) and isinstance(inner.func, ast.Attribute)):+ continue+ if inner.func.attr not in PREDICATE_CALLS:+ continue+ base = inner.func.value+ # The filter must be applied to something derived from a parameter,+ # so a helper that merely mentions tenant_id does not qualify.+ if not (_names(base) & params):+ continue+ if _names(inner) & TENANT_TOKENS:+ helpers.add(node.name)+ break+ return helpers+++def _tenant_validated_keys(fn: ast.AST, auth_names: set[str]) -> set[str]:+ """Keys this function already validated against the caller's tenant.++ ``investigations.py`` never puts a tenant on the child queries, and is+ right not to: it calls ``_fetch_run(db, run_id, current_user.tenant_id)``+ first, which 404s a run belonging to anybody else, and only then reads+ ``investigation_events`` by that verified ``run_id``. The row is addressed+ by a key the caller's tenant was checked against, which is the property —+ not the literal presence of a ``tenant_id`` column in the predicate.++ So: find calls that receive the principal's own tenant, and treat the+ other plain-name arguments of those calls as validated. The link is+ explicit — the statement only gets credit if its predicate names one of+ *those* keys.++ Known limit, stated rather than hidden: a guard that fails soft and lets+ execution continue cannot be told from one that raises. That is+ undecidable here, and it is why the ratchet exists. The real instance of+ it in this tree (``get_attack_path``'s relational fallback) is still+ caught, because the unscoped query lives in a different function.+ """+ validated: set[str] = set()+ if not auth_names:+ return validated+ for node in ast.walk(fn):+ if not isinstance(node, ast.Call):+ continue+ carries_tenant = False+ for expr in [*node.args, *[kw.value for kw in node.keywords]]:+ for sub in ast.walk(expr):+ if (+ isinstance(sub, ast.Attribute)+ and sub.attr in TENANT_TOKENS+ and isinstance(sub.value, ast.Name)+ and sub.value.id in auth_names+ ):+ carries_tenant = True+ if not carries_tenant:+ continue+ for expr in [*node.args, *[kw.value for kw in node.keywords]]:+ if isinstance(expr, ast.Name):+ validated.add(expr.id)+ return validated+++def _auth_bound_names(fn: ast.AST) -> set[str]:+ """Parameters annotated with an auth dependency, plus ``self``-ish aliases.++ A predicate comparing a column to ``user.user_id`` where ``user`` arrived+ through ``AuthUser`` is principal-derived and at least as narrow as the+ tenant. The same predicate against a ``user_id`` path parameter is not, and+ this is the only thing that tells them apart.+ """+ if not isinstance(fn, ast.FunctionDef | ast.AsyncFunctionDef):+ return set()+ bound: set[str] = set()+ for arg in [*fn.args.posonlyargs, *fn.args.args, *fn.args.kwonlyargs]:+ if arg.annotation is not None and (_names(arg.annotation) & AUTH_ANNOTATIONS):+ bound.add(arg.arg)+ return bound+++# ---------------------------------------------------------------------------+# Findings+# ---------------------------------------------------------------------------+++@dataclass+class Finding:+ service: str+ path: str+ lineno: int+ function: str+ entity: str # ORM class name, or table name for raw SQL+ table: str+ kind: str # "orm" | "sql"+ rls: bool+ predicates: list[str] = field(default_factory=list)++ @property+ def key(self) -> str:+ return f"{self.path}::{self.function}::{self.entity}"++ def location(self) -> str:+ return f"{self.path}:{self.lineno} {self.function}()"+++def _enclosing_function(node: ast.AST, fn_of: dict[ast.AST, ast.AST]) -> ast.AST | None:+ return fn_of.get(node)+++def _scan_orm(+ tree: ast.AST,+ inv: Inventory,+ *,+ service: str,+ rel: str,+ parents: dict[ast.AST, ast.AST],+ fn_of: dict[ast.AST, ast.AST],+) -> tuple[list[Finding], int]:+ helpers = _scoping_helpers(tree)+ findings: list[Finding] = []+ total = 0++ for node in ast.walk(tree):+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in STATEMENT_FUNCS):+ continue+ entities: set[str] = set()+ for arg in node.args:+ entities |= _names(arg) & inv.models.keys()+ if not entities:+ continue+ total += 1+ entity = sorted(entities)[0]++ predicates: set[str] = set()+ bound: str | None = None+ cursor: ast.AST = node+ wrapped_by_helper = False++ # Walk outward through `.where(...).order_by(...)` and through any+ # helper call the statement is handed to.+ while True:+ parent = parents.get(cursor)+ if isinstance(parent, ast.Attribute):+ grand = parents.get(parent)+ if isinstance(grand, ast.Call) and grand.func is parent:+ if parent.attr in PREDICATE_CALLS:+ for arg in grand.args:+ predicates |= _names(arg)+ for kw in grand.keywords:+ if kw.arg:+ predicates.add(kw.arg)+ cursor = grand+ continue+ if isinstance(parent, ast.Call) and isinstance(parent.func, ast.Name) and parent.func.id in helpers:+ wrapped_by_helper = True+ cursor = parent+ continue+ if isinstance(parent, ast.Assign) and len(parent.targets) == 1 and isinstance(parent.targets[0], ast.Name):+ bound = parent.targets[0].id+ break++ fn = _enclosing_function(node, fn_of)+ fn_name = getattr(fn, "name", "<module>")+ binds = _local_bindings(fn) if fn is not None else {}++ if bound and fn is not None:+ for stmt in ast.walk(fn):+ if not (isinstance(stmt, ast.Call) and isinstance(stmt.func, ast.Attribute)):+ continue+ base = stmt.func.value+ if not (isinstance(base, ast.Name) and base.id == bound):+ continue+ if stmt.func.attr in PREDICATE_CALLS:+ for arg in stmt.args:+ predicates |= _names(arg)+ for kw in stmt.keywords:+ if kw.arg:+ predicates.add(kw.arg)+ elif stmt.func.attr in helpers:+ wrapped_by_helper = True+ # `q = _scope(q, ...)` rebinding through a helper+ for stmt in ast.walk(fn):+ if (+ isinstance(stmt, ast.Call)+ and isinstance(stmt.func, ast.Name)+ and stmt.func.id in helpers+ and any(isinstance(a, ast.Name) and a.id == bound for a in stmt.args)+ ):+ wrapped_by_helper = True++ if wrapped_by_helper:+ continue++ resolved = _expand(predicates, binds)+ if resolved & TENANT_TOKENS:+ continue+ # Principal-derived identity is narrower than the tenant. Matched+ # against the *direct* predicates rather than the expanded set: a+ # three-hop binding chase that happens to reach the name `user` is+ # not evidence that the query filters on the caller.+ auth_names = _auth_bound_names(fn) if fn is not None else set()+ if auth_names & predicates:+ continue+ # Addressed by a key this function already checked against the+ # caller's tenant.+ if fn is not None and (_tenant_validated_keys(fn, auth_names) & resolved):+ continue++ table = inv.models.get(entity, entity)+ findings.append(+ Finding(+ service=service,+ path=rel,+ lineno=node.lineno,+ function=fn_name,+ entity=entity,+ table=table,+ kind="orm",+ rls=table in inv.rls_tables,+ predicates=sorted(resolved)[:10],+ )+ )+ return findings, total+++def _docstring_nodes(tree: ast.AST) -> set[int]:+ """ids of string constants that are docstrings, so prose is not read as SQL.++ ``services/connectors/app/scheduler.py``'s module docstring describes the+ polling loop and mentions ``connectors``; read as SQL it looks like an+ unscoped query in a file the gate then reports with total confidence.+ """+ out: 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", [])+ if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant) and isinstance(body[0].value.value, str):+ out.add(id(body[0].value))+ return out+++def _sql_text(node: ast.AST) -> str:+ """Flatten a literal, an f-string or a ``+`` chain into one blob."""+ if isinstance(node, ast.Constant) and isinstance(node.value, str):+ return node.value+ if isinstance(node, ast.JoinedStr):+ return "".join(_sql_text(v) if not isinstance(v, ast.FormattedValue) else " ? " for v in node.values)+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):+ return _sql_text(node.left) + " " + _sql_text(node.right)+ return ""+++def _scan_sql(+ tree: ast.AST,+ inv: Inventory,+ *,+ service: str,+ rel: str,+ parents: dict[ast.AST, ast.AST],+ fn_of: dict[ast.AST, ast.AST],+) -> tuple[list[Finding], int]:+ docstrings = _docstring_nodes(tree)+ findings: list[Finding] = []+ total = 0+ seen: set[tuple[int, str]] = set()++ for node in ast.walk(tree):+ if not isinstance(node, ast.Constant | ast.JoinedStr):+ continue+ if id(node) in docstrings:+ continue+ # Only consider the outermost node of a concatenation chain.+ parent = parents.get(node)+ if isinstance(parent, ast.BinOp) and isinstance(parent.op, ast.Add):+ continue+ if isinstance(parent, ast.JoinedStr):+ continue+ blob = _sql_text(node)+ if len(blob) < 15 or not _SQL_VERB.search(blob):+ continue+ tables = {m.group(1).strip('"').split(".")[-1] for m in _SQL_TABLE.finditer(blob)}+ hit = tables & inv.tables+ if not hit:+ continue+ total += 1+ table = sorted(hit)[0]+ if (node.lineno, table) in seen:+ continue+ seen.add((node.lineno, table))++ fn = _enclosing_function(node, fn_of)+ fn_name = getattr(fn, "name", "<module>")++ if _TENANT_IN_SQL.search(blob):+ continue++ # The predicate may be concatenated in from a clause list, or bound+ # into the statement by a sibling expression, so resolve the whole+ # enclosing statement the way the ORM path does.+ stmt_node: ast.AST = node+ while stmt_node in parents and not isinstance(stmt_node, ast.stmt):+ stmt_node = parents[stmt_node]+ names = _names(stmt_node)+ binds = _local_bindings(fn) if fn is not None else {}+ resolved = _expand(names, binds)+ if any(_TENANT_IN_SQL.search(r) for r in resolved) or (resolved & TENANT_TOKENS):+ continue+ auth_names = _auth_bound_names(fn) if fn is not None else set()+ if auth_names & names:+ continue+ if fn is not None and (_tenant_validated_keys(fn, auth_names) & resolved):+ continue++ findings.append(+ Finding(+ service=service,+ path=rel,+ lineno=node.lineno,+ function=fn_name,+ entity=table,+ table=table,+ kind="sql",+ rls=table in inv.rls_tables,+ predicates=sorted(n for n in resolved if len(n) < 40)[:10],+ )+ )+ return findings, total+++def scan(root: Path | None = None) -> tuple[list[Finding], Inventory, int, int]:+ base = root or REPO_ROOT+ inv = build_inventory(base)+ findings: list[Finding] = []+ files = 0+ statements = 0++ for py in _python_files(base):+ try:+ tree = ast.parse(py.read_text(encoding="utf-8", errors="ignore"), filename=str(py))+ except SyntaxError:+ continue+ files += 1+ rel = py.relative_to(base).as_posix()+ service = rel.split("/")[1] if rel.startswith("services/") else "?"+ parents = {c: n for n in ast.walk(tree) for c in ast.iter_child_nodes(n)}+ fn_of: dict[ast.AST, ast.AST] = {}+ for fn in ast.walk(tree):+ if isinstance(fn, ast.FunctionDef | ast.AsyncFunctionDef):+ for child in ast.walk(fn):+ fn_of[child] = fn++ orm, n_orm = _scan_orm(tree, inv, service=service, rel=rel, parents=parents, fn_of=fn_of)+ sql, n_sql = _scan_sql(tree, inv, service=service, rel=rel, parents=parents, fn_of=fn_of)+ findings.extend(orm)+ findings.extend(sql)+ statements += n_orm + n_sql++ return findings, inv, files, statements+++# ---------------------------------------------------------------------------+# Reporting+# ---------------------------------------------------------------------------+++def partition(findings: list[Finding]) -> tuple[list[Finding], list[str]]:+ """Return (unratcheted findings, stale ratchet keys)."""+ seen_keys = {f.key for f in findings}+ unratcheted = [f for f in findings if f.key not in RATCHET]+ stale = sorted(k for k in RATCHET if k not in seen_keys)+ return unratcheted, stale+++def _print_inventory(findings: list[Finding], inv: Inventory, files: int, statements: int) -> None:+ print(f"Tenant-predicate inventory — scanned {files} files under {SERVICES_DIR}")+ print(f" tenant-scoped ORM models : {len(inv.models)}")+ print(f" tenant-scoped tables : {len(inv.tables)}")+ print(f" of those, RLS-covered : {len(inv.tables & inv.rls_tables)} (the rest have query-layer scoping only)")+ print(f" statements examined : {statements}")+ print()+ services = sorted({f.service for f in findings})+ print(f"{'service':<16}{'findings':>10}{'ratcheted':>11}{'open':>7}{'no-RLS':>8}")+ print("-" * 52)+ for svc in services:+ rows = [f for f in findings if f.service == svc]+ ratch = sum(1 for f in rows if f.key in RATCHET)+ print(f"{svc:<16}{len(rows):>10}{ratch:>11}{len(rows) - ratch:>7}{sum(1 for f in rows if not f.rls):>8}")+ print("-" * 52)+ ratch = sum(1 for f in findings if f.key in RATCHET)+ print(f"{'TOTAL':<16}{len(findings):>10}{ratch:>11}{len(findings) - ratch:>7}{sum(1 for f in findings if not f.rls):>8}")+++# ---------------------------------------------------------------------------+# Self-test+# ---------------------------------------------------------------------------++_PROBE_MODEL = """+from sqlalchemy import Column, String+from app.db.base import Base++class Widget(Base):+ __tablename__ = "widgets"+ id = Column(String, primary_key=True)+ tenant_id = Column(String)+ owner_id = Column(String)+"""++_CLEAN = """+from sqlalchemy import select+from app.models.widget import Widget++async def get_widget(widget_id, user, db):+ return await db.execute(select(Widget).where(Widget.id == widget_id, Widget.tenant_id == user.tenant_id))+"""++_UNSCOPED = """+from sqlalchemy import select+from app.models.widget import Widget++async def get_widget(widget_id, user, db):+ return await db.execute(select(Widget).where(Widget.id == widget_id))+"""++_UNSCOPED_SQL = """+from sqlalchemy import text++async def get_widget(widget_id, db):+ return await db.execute(text("SELECT * FROM widgets WHERE id = :id").bindparams(id=widget_id))+"""++_SCOPED_VIA_LIST = """+from sqlalchemy import and_, select+from app.models.widget import Widget++async def list_widgets(user, db, kind=None):+ filters = [Widget.tenant_id == user.tenant_id]+ if kind:+ filters.append(Widget.kind == kind)+ return await db.execute(select(Widget).where(and_(*filters)))+"""++_SCOPED_VIA_HELPER = """+from sqlalchemy import select+from app.models.widget import Widget++def _scope(stmt, user, model):+ return stmt.where(model.tenant_id == user.tenant_id)++async def list_widgets(user, db):+ return await db.execute(_scope(select(Widget), user, Widget))+"""++_SCOPED_VIA_REBIND = """+from sqlalchemy import select+from app.models.widget import Widget++async def list_widgets(user, db, kind=None):+ q = select(Widget)+ q = q.where(Widget.tenant_id == user.tenant_id)+ if kind:+ q = q.where(Widget.kind == kind)+ return await db.execute(q)+"""++_SCOPED_VIA_PRINCIPAL = """+from typing import Annotated+from sqlalchemy import select+from app.api.v1.deps import AuthUser+from app.models.widget import Widget++async def my_widgets(user: AuthUser, db):+ return await db.execute(select(Widget).where(Widget.owner_id == user.user_id))+"""++_DOCSTRING_ONLY = '''+"""Widget helpers.++Historically this ran ``SELECT * FROM widgets WHERE id = ?`` before the ORM+landed. Prose, not a query.+"""++def helper():+ return 1+'''+++def _write_probe(root: Path, sources: dict[str, str]) -> None:+ pkg = root / "services" / "probe" / "app"+ (pkg / "models").mkdir(parents=True, exist_ok=True)+ (pkg / "models" / "widget.py").write_text(_PROBE_MODEL, encoding="utf-8")+ for name, src in sources.items():+ (pkg / name).write_text(src, encoding="utf-8")+++def _self_test() -> int:+ """Prove the gate fails on injected drift, both ways, and drops a stale entry."""+ cases: list[tuple[str, dict[str, str], int]] = [+ ("clean: by-id read carries a tenant predicate", {"r.py": _CLEAN}, 0),+ ("drift A: by-id ORM read with no tenant predicate", {"r.py": _UNSCOPED}, 1),+ ("drift B: by-id raw SQL with no tenant predicate", {"r.py": _UNSCOPED_SQL}, 1),+ ("control: predicate built in a filters list", {"r.py": _SCOPED_VIA_LIST}, 0),+ ("control: predicate applied by a wrapping helper", {"r.py": _SCOPED_VIA_HELPER}, 0),+ ("control: predicate added by a later q = q.where()", {"r.py": _SCOPED_VIA_REBIND}, 0),+ ("control: scoped on the authenticated principal's own id", {"r.py": _SCOPED_VIA_PRINCIPAL}, 0),+ ("control: SQL in a docstring is prose, not a query", {"r.py": _DOCSTRING_ONLY}, 0),+ ]++ failures = 0+ with tempfile.TemporaryDirectory() as tmp:+ for i, (label, sources, want) in enumerate(cases):+ root = Path(tmp) / f"case{i}"+ _write_probe(root, sources)+ findings, _inv, files, _stmts = scan(root=root)+ got = len(findings)+ ok = got == want and files > 0+ if not ok:+ failures += 1+ print(f" [{'PASS' if ok else 'FAIL'}] {label}: {got} finding(s), want {want} (scanned {files} files)")++ failures += _self_test_stale_ratchet()+ failures += _self_test_ratchet_ceiling()++ if failures:+ print(f"\nself-test FAILED: {failures} case(s) did not behave as specified", file=sys.stderr)+ return 1+ print("\nself-test passed: drift detected in both directions, six controls clear, and a stale ratchet entry is dropped.")+ return 0+++def _self_test_stale_ratchet() -> int:+ """Strip a live ratchet entry's justification and assert it stops protecting.++ The reverse direction. An entry keeps its exemption only while the+ statement it names is still unscoped; fix the code and the entry must come+ out, which is what makes the table shrink-only.+ """+ findings, _inv, _files, _stmts = scan()+ live = {f.key for f in findings} & RATCHET.keys()+ if not live:+ print(" [FAIL] stale ratchet: no live ratchet entry to exercise")+ return 1++ # Forward: every entry must correspond to a real unscoped statement.+ _unratcheted, stale = partition(findings)+ if stale:+ for key in stale:+ print(f" [FAIL] stale ratchet entry (statement is now scoped, moved or deleted): {key}")+ return len(stale)++ # Reverse: remove one entry and assert the finding surfaces.+ victim = sorted(live)[0]+ saved = RATCHET.pop(victim)+ try:+ unratcheted, _ = partition(findings)+ if any(f.key == victim for f in unratcheted):+ print(f" [PASS] stale ratchet: {victim} is reported the moment its entry is removed")+ return 0+ print(f" [FAIL] stale ratchet: removing {victim} produced no finding")+ return 1+ finally:+ RATCHET[victim] = saved+++def _self_test_ratchet_ceiling() -> int:+ if len(RATCHET) > MAX_RATCHET:+ print(f" [FAIL] ratchet ceiling: {len(RATCHET)} entries exceeds MAX_RATCHET={MAX_RATCHET}")+ return 1+ print(f" [PASS] ratchet ceiling: {len(RATCHET)}/{MAX_RATCHET} entries")+ return 0+++# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--inventory", action="store_true", help="print the per-service finding inventory")+ parser.add_argument("--json", action="store_true", help="emit every finding as JSON")+ parser.add_argument("--self-test", action="store_true", help="prove the gate detects injected drift both ways")+ args = parser.parse_args(argv)++ if args.self_test:+ return _self_test()++ if not SERVICES_DIR.is_dir():+ print(f"ERROR: no services/ directory under {REPO_ROOT} — refusing to report a result for a tree I did not open.", file=sys.stderr)+ return 2++ findings, inv, files, statements = scan()++ if args.json:+ print(json.dumps([asdict(f) for f in findings], indent=2))+ return 0++ if args.inventory:+ _print_inventory(findings, inv, files, statements)+ return 0++ unratcheted, stale = partition(findings)++ # Name what was scanned. A gate that prints OK without saying what it+ # opened cannot be told apart from one that opened nothing.+ print(+ f"check_tenant_query_predicates: scanned {files} files under {SERVICES_DIR}; "+ f"{statements} statements touch {len(inv.tables)} tenant-scoped tables "+ f"({len(inv.tables) - len(inv.tables & inv.rls_tables)} of them with no RLS policy)"+ )++ if len(RATCHET) > MAX_RATCHET:+ print(+ f"\nFAIL: the ratchet holds {len(RATCHET)} entries but MAX_RATCHET is {MAX_RATCHET}.",+ file=sys.stderr,+ )+ print(" It only shrinks. Fix the query rather than raising the ceiling.", file=sys.stderr)+ return 1++ if stale:+ print(f"\nFAIL: {len(stale)} ratchet entry/entries no longer describe an unscoped statement.", file=sys.stderr)+ print(" The code was fixed, moved or deleted. Remove the entry — a lapsed", file=sys.stderr)+ print(" justification that still passes reads like a decision somebody made.", file=sys.stderr)+ for key in stale:+ print(f" - {key}", file=sys.stderr)++ if unratcheted:+ print(f"\nFAIL: {len(unratcheted)} statement(s) reach a tenant-scoped table with no tenant predicate.", file=sys.stderr)+ print(" How the row was addressed is irrelevant; naming another tenant's id reaches it.", file=sys.stderr)+ for f in unratcheted:+ rls = "" if f.rls else " [no RLS — the predicate is the only control]"+ print(f" - {f.location()} {f.kind} on {f.table}{rls}", file=sys.stderr)++ if stale or unratcheted:+ return 1++ print(+ f"OK: every statement on a tenant-scoped table filters on a tenant, "+ f"or is one of {len(RATCHET)} ratcheted exceptions that still holds."+ )+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/sync_vendored_tenant_scope.py b/scripts/sync_vendored_tenant_scope.pyindex 3c26c455c..120008065 100644--- a/scripts/sync_vendored_tenant_scope.py+++ b/scripts/sync_vendored_tenant_scope.py@@ -48,6 +48,12 @@ TARGETS: dict[str, str] = {"honeytokens": "HONEYTOKENS","purple-team": "PURPLE_TEAM","ueba": "UEBA",+ # The console reaches the connector catalogue and test-connection routes+ # through a Next rewrite, the same way it reaches fusion and agents, so+ # this service needs the same dual-mode resolver rather than a+ # bearer-only guard the browser could not satisfy.+ "connectors": "CONNECTORS",+ "threatintel": "THREATINTEL",}_SERVICE_NAME_RE = re.compile(r'^SERVICE_NAME = ".*"$', re.MULTILINE)diff --git a/services/actions/app/api/router.py b/services/actions/app/api/router.pyindex 0163d382c..b8a8eb3c9 100644--- a/services/actions/app/api/router.py+++ b/services/actions/app/api/router.py@@ -263,8 +263,14 @@ async def reject_action(@router.get("/actions/{action_id}")-async def get_action(action_id: str):- """Get action status and result."""+async def get_action(action_id: str, _auth: None = Depends(require_service_auth)):+ """Get action status and result.++ Behind the service guard: an action record names the host or account an+ action was aimed at and the parameters it ran with, and ``GET`` by id was+ reachable with no credential at all. ``aisoc_action_records`` carries no+ RLS policy, so the id was the only thing standing in front of it.+ """record = await action_store.get(action_id)if not record:raise HTTPException(status_code=404, detail="Action not found")diff --git a/services/actions/app/services/action_store.py b/services/actions/app/services/action_store.pyindex 2f35259e7..b42997b4a 100644--- a/services/actions/app/services/action_store.py+++ b/services/actions/app/services/action_store.py@@ -121,15 +121,23 @@ def _report_degraded(event: str, action_id: str, exc: Exception) -> None:)-async def get(action_id: str) -> dict[str, Any] | None:+async def get(action_id: str, tenant_id: str | None = None) -> dict[str, Any] | None:"""Fetch an action record, preferring the durable copy.The in-memory copy is checked first only as a cache: on the replica thathandled the submission it is the same object, and on any other replica itis absent and the database answers.++ ``tenant_id`` narrows the lookup to one tenant and should always be+ supplied from a request path. ``aisoc_action_records`` carries no RLS+ policy, so without it an id is a capability: an action record names the+ host or account an action was aimed at, and any caller who could guess or+ observe a UUID would read another tenant's response history."""cached = _MEMORY.get(action_id)if cached is not None:+ if tenant_id is not None and str(cached.get("tenant_id") or "") != str(tenant_id):+ return Nonereturn cacheddsn = _dsn()@@ -141,7 +149,14 @@ async def get(action_id: str) -> dict[str, Any] | None:logger.warning("action_store.connect_failed", action_id=action_id, error=str(exc))return Nonetry:- row = await conn.fetchrow("SELECT record FROM aisoc_action_records WHERE id = $1", action_id)+ if tenant_id is None:+ row = await conn.fetchrow("SELECT record FROM aisoc_action_records WHERE id = $1", action_id)+ else:+ row = await conn.fetchrow(+ "SELECT record FROM aisoc_action_records WHERE id = $1 AND tenant_id = $2",+ action_id,+ tenant_id,+ )except Exception as exc: # noqa: BLE001logger.warning("action_store.read_failed", action_id=action_id, error=str(exc))return Nonediff --git a/services/agents/app/api/contextual.py b/services/agents/app/api/contextual.pyindex cc0cbdbbc..aeb8ffb3e 100644--- a/services/agents/app/api/contextual.py+++ b/services/agents/app/api/contextual.py@@ -41,17 +41,22 @@ from datetime import UTC, datetimefrom typing import Anyimport structlog-from fastapi import APIRouter, HTTPException+from fastapi import APIRouter, Depends, HTTPExceptionfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModel, Fieldfrom app.llm import safe_ainvoke, safe_astreamfrom app.llm.factory import resolve_model_aliasfrom app.prompt_serialization import summarize_structure_for_llm+from app.security.tenant_scope import require_console_or_service_authlogger = structlog.get_logger()-router = APIRouter(prefix="/api/v1/contextual", tags=["contextual"])+#: Default-deny. The console reaches this router directly through a Next+#: rewrite carrying the first-party access token, so the guard resolves+#: either that session or a trusted service declaring the tenant it acts+#: for — a bearer-token-only scheme would lock the browser out.+router = APIRouter(prefix="/api/v1/contextual", tags=["contextual"], dependencies=[Depends(require_console_or_service_auth)])# ---------------------------------------------------------------------------diff --git a/services/agents/app/api/copilot.py b/services/agents/app/api/copilot.pyindex 53207c32d..b335bc955 100644--- a/services/agents/app/api/copilot.py+++ b/services/agents/app/api/copilot.py@@ -23,13 +23,19 @@ from datetime import UTC, datetimefrom typing import Any, Literalimport structlog-from fastapi import APIRouter+from fastapi import APIRouter, Dependsfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModel, Field+from app.security.tenant_scope import require_console_or_service_auth+logger = structlog.get_logger()-router = APIRouter(prefix="/api/v1/copilot", tags=["copilot"])+#: Default-deny. The console reaches this router directly through a Next+#: rewrite carrying the first-party access token, so the guard resolves+#: either that session or a trusted service declaring the tenant it acts+#: for — a bearer-token-only scheme would lock the browser out.+router = APIRouter(prefix="/api/v1/copilot", tags=["copilot"], dependencies=[Depends(require_console_or_service_auth)])# ---------------------------------------------------------------------------diff --git a/services/agents/app/api/hunt_search.py b/services/agents/app/api/hunt_search.pyindex 2380bbf75..db3c961f0 100644--- a/services/agents/app/api/hunt_search.py+++ b/services/agents/app/api/hunt_search.py@@ -20,12 +20,18 @@ from datetime import UTC, datetimefrom typing import Any, Literalimport structlog-from fastapi import APIRouter, HTTPException+from fastapi import APIRouter, Depends, HTTPExceptionfrom pydantic import BaseModel+from app.security.tenant_scope import require_console_or_service_auth+logger = structlog.get_logger()-router = APIRouter(prefix="/api/v1/hunt", tags=["hunt-search"])+#: Default-deny. The console reaches this router directly through a Next+#: rewrite carrying the first-party access token, so the guard resolves+#: either that session or a trusted service declaring the tenant it acts+#: for — a bearer-token-only scheme would lock the browser out.+router = APIRouter(prefix="/api/v1/hunt", tags=["hunt-search"], dependencies=[Depends(require_console_or_service_auth)])# ---------------------------------------------------------------------------diff --git a/services/agents/app/api/hunts.py b/services/agents/app/api/hunts.pyindex e5bc2ac0d..107798fdb 100644--- a/services/agents/app/api/hunts.py+++ b/services/agents/app/api/hunts.py@@ -24,14 +24,19 @@ from __future__ import annotationsimport loggingfrom typing import Any-from fastapi import APIRouter, HTTPException, Query+from fastapi import APIRouter, Depends, HTTPException, Queryfrom app.hunt import HuntCorpusfrom app.hunt import scheduler as hunt_schedulerfrom app.hunt import store as hunt_store+from app.security.tenant_scope import require_console_or_service_authlogger = logging.getLogger("aisoc.api.hunts")-router = APIRouter(prefix="/api/v1/hunts", tags=["hunts"])+#: Default-deny. The console reaches this router directly through a Next+#: rewrite carrying the first-party access token, so the guard resolves+#: either that session or a trusted service declaring the tenant it acts+#: for — a bearer-token-only scheme would lock the browser out.+router = APIRouter(prefix="/api/v1/hunts", tags=["hunts"], dependencies=[Depends(require_console_or_service_auth)])def _hunt_summary(h: Any) -> dict[str, Any]:diff --git a/services/agents/app/api/investigate.py b/services/agents/app/api/investigate.pyindex ddd1fe254..80bb7752b 100644--- a/services/agents/app/api/investigate.py+++ b/services/agents/app/api/investigate.py@@ -13,6 +13,7 @@ Endpoints:from __future__ import annotationsimport asyncio+import hmacimport jsonimport osfrom datetime import datetime@@ -28,9 +29,13 @@ from pydantic import BaseModelfrom app.investigator import InvestigatorOrchestratorfrom app.orchestrator.router import RouterOrchestratorfrom app.security.tenant_scope import (+ TENANT_HEADER,TenantPrincipal,require_console_or_service_auth,+ resolve_console_secret,+ resolve_service_token,scoped_tenant_or_403,+ verify_console_token,)logger = structlog.get_logger()@@ -43,6 +48,53 @@ router = APIRouter(prefix="/api/v1", tags=["investigations"])#: selector for somebody else's investigation.ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]++async def _ws_principal(ws: WebSocket) -> TenantPrincipal | None:+ """Resolve a WebSocket caller's tenant scope, or ``None`` to refuse.++ The HTTP routes take ``ScopedPrincipal`` and a router-level dependency+ would be the obvious way to cover this one too — but a dependency that+ raises ``HTTPException`` has no defined rendering on a WebSocket scope,+ and a browser cannot set an ``Authorization`` header on a WS handshake+ regardless. So the credential is read from the header when a machine+ client sends one, and from ``?token=`` when the browser connects, which+ is the same shape ``services/realtime`` already uses for its tickets.++ Verification is the shared vendored logic, not a second implementation:+ a parallel verifier is how one side ends up accepting ``alg: none`` after+ the other stopped.+ """+ header = ws.headers.get("authorization") or ""+ token = header[len("Bearer ") :].strip() if header.startswith("Bearer ") else (ws.query_params.get("token") or "").strip()+ if not token:+ return None++ secret = resolve_console_secret()+ if secret:+ claims = verify_console_token(token, secret)+ if claims is not None:+ try:+ return TenantPrincipal(+ tenant_ids=frozenset({UUID(str(claims["tenant_id"]))}),+ subject=f"console:{claims.get('sub', 'unknown')}",+ )+ except (KeyError, ValueError, TypeError):+ return None++ service_token = resolve_service_token()+ if service_token and hmac.compare_digest(token, service_token):+ declared = (ws.headers.get(TENANT_HEADER.lower()) or ws.query_params.get("tenant_id") or "").strip()+ if not declared:+ # A service token identifies a service, not a tenant. Absent is+ # an empty scope, never every scope.+ return None+ try:+ return TenantPrincipal(tenant_ids=frozenset({UUID(declared)}), subject="service", delegated=True)+ except ValueError:+ return None+ return None++# ---------------------------------------------------------------------------# Config# ---------------------------------------------------------------------------@@ -263,7 +315,7 @@ async def launch_investigation(@router.get("/investigations/{run_id}")-async def get_investigation(run_id: str):+async def get_investigation(run_id: str, principal: ScopedPrincipal):"""Poll investigation status and results."""run = _runs.get(run_id)if not run:@@ -274,7 +326,7 @@ async def get_investigation(run_id: str):@router.get("/investigations/{run_id}/report.md", response_class=PlainTextResponse)-async def get_report_md(run_id: str):+async def get_report_md(run_id: str, principal: ScopedPrincipal):"""Download the Markdown incident report."""run = _runs.get(run_id)if not run:@@ -285,7 +337,7 @@ async def get_report_md(run_id: str):@router.get("/investigations/{run_id}/report.html", response_class=HTMLResponse)-async def get_report_html(run_id: str):+async def get_report_html(run_id: str, principal: ScopedPrincipal):"""Download the HTML incident report."""run = _runs.get(run_id)if not run:@@ -296,7 +348,7 @@ async def get_report_html(run_id: str):@router.get("/investigations/{run_id}/report.pdf")-async def get_report_pdf(run_id: str):+async def get_report_pdf(run_id: str, principal: ScopedPrincipal):"""Download the PDF incident report (rendered from HTML via weasyprint)."""from fastapi.responses import Response as FastAPIResponse@@ -340,9 +392,20 @@ async def stream_investigation(ws: WebSocket, run_id: str):2. If query params case_id + alert_summary are supplied, run a freshinvestigation directly on this connection (dev/test use-case)."""+ principal = await _ws_principal(ws)+ if principal is None:+ # 1008 = policy violation. Refused before accept() so an anonymous+ # caller never reaches the branch below that starts a fresh+ # investigation — which spends the tenant's LLM budget.+ await ws.close(code=1008, reason="unauthenticated")+ return+case_id = ws.query_params.get("case_id", run_id)alert_summary = ws.query_params.get("alert_summary", "")- tenant_id = ws.query_params.get("tenant_id", "default")+ # The tenant comes from the verified credential. It used to come from a+ # query parameter defaulting to the literal "default", which names no+ # tenant anywhere in this schema.+ tenant_id = str(scoped_tenant_or_403(principal, ws.query_params.get("tenant_id")))await ws.accept()try:diff --git a/services/agents/app/api/playbooks.py b/services/agents/app/api/playbooks.pyindex ca17ae8b9..c5f0839fa 100644--- a/services/agents/app/api/playbooks.py+++ b/services/agents/app/api/playbooks.py@@ -16,7 +16,7 @@ from __future__ import annotationsimport loggingfrom typing import Any-from fastapi import APIRouter, BackgroundTasks, HTTPException+from fastapi import APIRouter, BackgroundTasks, Depends, HTTPExceptionfrom pydantic import BaseModelfrom app.playbook import (@@ -26,9 +26,14 @@ from app.playbook import (PlaybookStore,draft_from_nl,)+from app.security.tenant_scope import require_console_or_service_authlogger = logging.getLogger("aisoc.api.playbooks")-router = APIRouter(prefix="/api/v1/playbooks", tags=["playbooks"])+#: Default-deny. The console reaches this router directly through a Next+#: rewrite carrying the first-party access token, so the guard resolves+#: either that session or a trusted service declaring the tenant it acts+#: for — a bearer-token-only scheme would lock the browser out.+router = APIRouter(prefix="/api/v1/playbooks", tags=["playbooks"], dependencies=[Depends(require_console_or_service_auth)])# In-memory run store for Pillar-2 (swap for Redis/DB in production)_runs: dict[str, PlaybookRun] = {}diff --git a/services/agents/app/api/router.py b/services/agents/app/api/router.pyindex ea7caa367..c6cd2d442 100644--- a/services/agents/app/api/router.py+++ b/services/agents/app/api/router.py@@ -93,7 +93,7 @@ async def start_investigation(@router.get("/investigations/{run_id}")-async def get_investigation(run_id: str):+async def get_investigation(run_id: str, principal: ScopedPrincipal):"""Get the status and results of an investigation run."""run = _runs.get(run_id)if not run:diff --git a/services/agents/tests/test_playbook_nl_drafter_api.py b/services/agents/tests/test_playbook_nl_drafter_api.pyindex e573c5ff5..6d0b98f89 100644--- a/services/agents/tests/test_playbook_nl_drafter_api.py+++ b/services/agents/tests/test_playbook_nl_drafter_api.py@@ -20,6 +20,7 @@ editor:from __future__ import annotationsimport sys+import uuidfrom pathlib import Pathfrom typing import Any@@ -32,6 +33,9 @@ if str(_AGENTS_ROOT) not in sys.path:sys.path.insert(0, str(_AGENTS_ROOT))from app.api.playbooks import router as playbooks_router # noqa: E402+from app.security.tenant_scope import TenantPrincipal, require_console_or_service_auth # noqa: E402++_TEST_TENANT = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")# ---------------------------------------------------------------------------# Test app fixture@@ -42,6 +46,14 @@ from app.api.playbooks import router as playbooks_router # noqa: E402def client() -> TestClient:app = FastAPI()app.include_router(playbooks_router)+ # The router is default-deny (every route carries+ # `require_console_or_service_auth`), so these tests supply a resolved+ # principal rather than credential material. What this file is about is+ # the drafter's contract with the editor; that the routes refuse an+ # anonymous caller is asserted in tests/isolation, against the real guard.+ app.dependency_overrides[require_console_or_service_auth] = lambda: TenantPrincipal(+ tenant_ids=frozenset({_TEST_TENANT}), subject="test"+ )return TestClient(app)diff --git a/services/api/app/api/v1/endpoints/airgap.py b/services/api/app/api/v1/endpoints/airgap.pyindex 777000e40..774cdc37b 100644--- a/services/api/app/api/v1/endpoints/airgap.py+++ b/services/api/app/api/v1/endpoints/airgap.py@@ -21,13 +21,14 @@ from __future__ import annotationsfrom fastapi import APIRouter+from app.api.v1.deps import AuthUserfrom app.core.airgap import airgap_statusrouter = APIRouter(prefix="/airgap", tags=["airgap"])@router.get("/status", summary="Current air-gap egress policy")-async def get_airgap_status() -> dict[str, object]:+async def get_airgap_status(user: AuthUser) -> dict[str, object]:"""Return the live air-gap policy snapshot for this pod.Response shape::diff --git a/services/api/app/api/v1/endpoints/alerts.py b/services/api/app/api/v1/endpoints/alerts.pyindex 4ee761ece..ad4bfd8d5 100644--- a/services/api/app/api/v1/endpoints/alerts.py+++ b/services/api/app/api/v1/endpoints/alerts.py@@ -846,7 +846,11 @@ async def update_alert(if updates:updates["updated_at"] = datetime.now(UTC)- await db.execute(update(Alert).where(Alert.id == alert_id).values(**updates))+ # Tenant predicate on the write as well as the read above. The read+ # already 404s another tenant's alert, so this is belt and braces+ # today — but a write scoped only by a preceding read is one reorder+ # away from being scoped by nothing.+ await db.execute(update(Alert).where(Alert.id == alert_id, Alert.tenant_id == current_user.tenant_id).values(**updates))await db.commit()await db.refresh(alert)@@ -870,7 +874,11 @@ async def escalate_alert(current_idx = severity_ladder.index(alert.severity) if alert.severity in severity_ladder else 2new_severity = severity_ladder[min(current_idx + 1, len(severity_ladder) - 1)]- await db.execute(update(Alert).where(Alert.id == alert_id).values(severity=new_severity, updated_at=datetime.now(UTC)))+ await db.execute(+ update(Alert)+ .where(Alert.id == alert_id, Alert.tenant_id == current_user.tenant_id)+ .values(severity=new_severity, updated_at=datetime.now(UTC))+ )await db.commit()await db.refresh(alert)@@ -941,7 +949,7 @@ async def snooze_alert(await db.execute(update(Alert)- .where(Alert.id == alert_id)+ .where(Alert.id == alert_id, Alert.tenant_id == current_user.tenant_id).values(snoozed_until=snoozed_until,snoozed_by_id=current_user.user_id,diff --git a/services/api/app/api/v1/endpoints/assets.py b/services/api/app/api/v1/endpoints/assets.pyindex f89fbdccc..4c34a2479 100644--- a/services/api/app/api/v1/endpoints/assets.py+++ b/services/api/app/api/v1/endpoints/assets.py@@ -236,7 +236,7 @@ async def list_asset_vulnerabilities(raise HTTPException(status_code=404, detail="Asset not found")q = (select(AssetVulnerability)- .where(AssetVulnerability.asset_id == asset_id)+ .where(AssetVulnerability.asset_id == asset_id, AssetVulnerability.tenant_id == current_user.tenant_id).order_by(AssetVulnerability.severity, AssetVulnerability.last_found.desc()))result = await db.execute(q)diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.pyindex 0f547420c..bc916dbb8 100644--- a/services/api/app/api/v1/endpoints/cases.py+++ b/services/api/app/api/v1/endpoints/cases.py@@ -1254,7 +1254,7 @@ async def case_auto_summary(),) -> Any:cid = await _resolve_case_id(case_id, db, user.tenant_id)- summary = await build_case_summary(db, cid)+ summary = await build_case_summary(db, cid, user.tenant_id)if summary is None:raise HTTPException(status_code=404, detail="Case not found.")@@ -1296,7 +1296,7 @@ async def case_auto_postmortem(change*. Both are deterministic — same case state in, same artefact out."""cid = await _resolve_case_id(case_id, db, user.tenant_id)- postmortem = await build_case_postmortem(db, cid)+ postmortem = await build_case_postmortem(db, cid, user.tenant_id)if postmortem is None:raise HTTPException(status_code=404, detail="Case not found.")diff --git a/services/api/app/api/v1/endpoints/compliance.py b/services/api/app/api/v1/endpoints/compliance.pyindex 6fa11bd41..4d84b92a5 100644--- a/services/api/app/api/v1/endpoints/compliance.py+++ b/services/api/app/api/v1/endpoints/compliance.py@@ -229,7 +229,7 @@ async def list_framework_controls(framework_id: str) -> ControlsResponse:status_code=status.HTTP_202_ACCEPTED,summary="Trigger evidence collection job",)-async def trigger_evidence_collection(body: CollectJobRequest) -> CollectJobResponse:+async def trigger_evidence_collection(body: CollectJobRequest, user: AuthUser) -> CollectJobResponse:if body.framework not in FRAMEWORKS:raise HTTPException(status_code=404, detail=f"Framework '{body.framework}' not found.")return CollectJobResponse(diff --git a/services/api/app/api/v1/endpoints/connectors.py b/services/api/app/api/v1/endpoints/connectors.pyindex 1ebac75ce..32612faa2 100644--- a/services/api/app/api/v1/endpoints/connectors.py+++ b/services/api/app/api/v1/endpoints/connectors.py@@ -704,7 +704,9 @@ async def update_connector(if updates:updates["updated_at"] = datetime.now(UTC)- await db.execute(update(Connector).where(Connector.id == connector_id).values(**updates))+ await db.execute(+ update(Connector).where(Connector.id == connector_id, Connector.tenant_id == current_user.tenant_id).values(**updates)+ )await db.commit()await db.refresh(connector)@@ -774,7 +776,7 @@ async def update_connector_capabilities(await db.execute(update(Connector)- .where(Connector.id == connector_id)+ .where(Connector.id == connector_id, Connector.tenant_id == current_user.tenant_id).values(allowed_capabilities=request.allowed_capabilities,updated_at=datetime.now(UTC),@@ -873,7 +875,7 @@ async def test_existing_connector(health_status = "healthy" if verdict.get("success") else "unhealthy"await db.execute(update(Connector)- .where(Connector.id == connector_id)+ .where(Connector.id == connector_id, Connector.tenant_id == current_user.tenant_id).values(last_health_check=datetime.now(UTC),health_status=health_status,@@ -1175,7 +1177,11 @@ async def refresh_ingest_token(raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Connector not found")new_token = _generate_ingest_token()- await db.execute(update(Connector).where(Connector.id == connector_id).values(ingest_token=new_token, updated_at=datetime.now(UTC)))+ await db.execute(+ update(Connector)+ .where(Connector.id == connector_id, Connector.tenant_id == current_user.tenant_id)+ .values(ingest_token=new_token, updated_at=datetime.now(UTC))+ )await db.commit()base = (getattr(settings, "INGEST_PUBLIC_URL", "") or "").rstrip("/")diff --git a/services/api/app/api/v1/endpoints/deployment.py b/services/api/app/api/v1/endpoints/deployment.pyindex 90740cb4e..8e93c856e 100644--- a/services/api/app/api/v1/endpoints/deployment.py+++ b/services/api/app/api/v1/endpoints/deployment.py@@ -7,6 +7,8 @@ from enum import Enumfrom fastapi import APIRouter, HTTPException, statusfrom pydantic import BaseModel+from app.api.v1.deps import AuthUser+router = APIRouter(prefix="/deployment", tags=["Deployment"])@@ -87,13 +89,13 @@ _config = DeploymentConfig(@router.get("/config", response_model=DeploymentConfig)-async def get_deployment_config() -> DeploymentConfig:+async def get_deployment_config(user: AuthUser) -> DeploymentConfig:"""Return the current deployment configuration."""return _config@router.put("/config", response_model=DeploymentConfig)-async def update_deployment_config(body: DeploymentConfigUpdate) -> DeploymentConfig:+async def update_deployment_config(body: DeploymentConfigUpdate, user: AuthUser) -> DeploymentConfig:"""Update deployment configuration fields."""global _config@@ -112,7 +114,7 @@ async def update_deployment_config(body: DeploymentConfigUpdate) -> DeploymentCo@router.get("/airgap/status", response_model=AirgapStatus)-async def get_airgap_status() -> AirgapStatus:+async def get_airgap_status(user: AuthUser) -> AirgapStatus:"""Check air-gap readiness: local LLM health, offline bundles, sync age."""is_airgap = _config.mode == DeploymentMode.airgaplocal_llm_up = _config.llm_provider in (LLMProvider.local_ollama, LLMProvider.local_vllm)@@ -167,7 +169,7 @@ async def get_airgap_status() -> AirgapStatus:@router.post("/airgap/bundle", response_model=BundleJob, status_code=status.HTTP_202_ACCEPTED)-async def create_airgap_bundle() -> BundleJob:+async def create_airgap_bundle(user: AuthUser) -> BundleJob:"""Trigger creation of an offline update bundle for air-gapped deployments."""return BundleJob(job_id=str(uuid.uuid4()),diff --git a/services/api/app/api/v1/endpoints/detection_compat.py b/services/api/app/api/v1/endpoints/detection_compat.pyindex ee97b02f7..891a63cb2 100644--- a/services/api/app/api/v1/endpoints/detection_compat.py+++ b/services/api/app/api/v1/endpoints/detection_compat.py@@ -291,7 +291,9 @@ async def update_rule_compat(if updates:updates["updated_at"] = datetime.now(UTC)updates["version"] = (rule.version or 1) + 1- await db.execute(update(DetectionRule).where(DetectionRule.id == rule_id).values(**updates))+ await db.execute(+ update(DetectionRule).where(DetectionRule.id == rule_id, DetectionRule.tenant_id == current_user.tenant_id).values(**updates)+ )await db.commit()await db.refresh(rule)diff --git a/services/api/app/api/v1/endpoints/detection_rules.py b/services/api/app/api/v1/endpoints/detection_rules.pyindex 1e17eab98..e1dea6684 100644--- a/services/api/app/api/v1/endpoints/detection_rules.py+++ b/services/api/app/api/v1/endpoints/detection_rules.py@@ -236,7 +236,9 @@ async def update_rule(if updates:updates["updated_at"] = datetime.now(UTC)updates["version"] = rule.version + 1- await db.execute(update(DetectionRule).where(DetectionRule.id == rule_id).values(**updates))+ await db.execute(+ update(DetectionRule).where(DetectionRule.id == rule_id, DetectionRule.tenant_id == current_user.tenant_id).values(**updates)+ )await db.commit()await db.refresh(rule)@@ -329,7 +331,7 @@ async def execute_detection_rule(if match.matched:await db.execute(update(DetectionRule)- .where(DetectionRule.id == rule_id)+ .where(DetectionRule.id == rule_id, DetectionRule.tenant_id == current_user.tenant_id).values(total_hits=DetectionRule.total_hits + len(match.match_details.get("matched_events", [])),last_triggered=datetime.now(UTC),diff --git a/services/api/app/api/v1/endpoints/fusion.py b/services/api/app/api/v1/endpoints/fusion.pyindex e54d848b4..ee3757901 100644--- a/services/api/app/api/v1/endpoints/fusion.py+++ b/services/api/app/api/v1/endpoints/fusion.py@@ -133,7 +133,7 @@ async def _proxy_get(@router.get("/health", summary="Fusion service health")-async def fusion_health() -> dict[str, Any]:+async def fusion_health(user: AuthUser) -> dict[str, Any]:upstream = await _proxy_get("/health")if upstream is not None:return upstream@@ -145,7 +145,7 @@ async def fusion_health() -> dict[str, Any]:@router.get("/metrics", summary="Fusion worker metrics")-async def fusion_metrics() -> dict[str, Any]:+async def fusion_metrics(user: AuthUser) -> dict[str, Any]:upstream = await _proxy_get("/metrics")if upstream is not None:return upstreamdiff --git a/services/api/app/api/v1/endpoints/graph.py b/services/api/app/api/v1/endpoints/graph.pyindex a180bbbe9..ed99e67c8 100644--- a/services/api/app/api/v1/endpoints/graph.py+++ b/services/api/app/api/v1/endpoints/graph.py@@ -6,6 +6,7 @@ AiSOC — open-source AI Security Operations Center (MIT License)from __future__ import annotationsimport logging+import uuidfrom typing import Annotated, Anyfrom fastapi import APIRouter, Depends, HTTPException, Query, status@@ -161,6 +162,7 @@ class UpsertCaseGraphRequest(BaseModel):async def _attack_path_from_relational(db: Any,case_id: str,+ tenant_id: uuid.UUID | str,) -> dict[str, Any] | None:"""Reconstruct an attack path graph from the relational case row.@@ -168,12 +170,19 @@ async def _attack_path_from_relational(Attack Path tab still renders something meaningful in demo deploymentsthat don't ship a graph database. Returns ``None`` if the case can't belocated so the caller can decide whether to 404.++ The tenant predicate is not optional here even though the caller is+ authenticated. The graph path above is tenant-scoped, but this fallback+ runs precisely when that path failed, so it is the only filter standing+ between two customers' cases — and ``aisoc_cases`` carries no RLS policy,+ so nothing behind it would catch the omission."""row = (await db.execute(- text("SELECT id, title, severity, mitre_techniques, alert_ids FROM aisoc_cases WHERE id = CAST(:cid AS UUID)").bindparams(- cid=case_id- )+ text(+ "SELECT id, title, severity, mitre_techniques, alert_ids FROM aisoc_cases "+ "WHERE id = CAST(:cid AS UUID) AND tenant_id = CAST(:tid AS UUID)"+ ).bindparams(cid=case_id, tid=str(tenant_id)))).fetchone()if not row:@@ -280,7 +289,7 @@ async def get_attack_path(graph_offline = Trueif graph_offline or not data or not data.get("nodes"):- fallback = await _attack_path_from_relational(db, case_id)+ fallback = await _attack_path_from_relational(db, case_id, current_user.tenant_id)if fallback is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,diff --git a/services/api/app/api/v1/endpoints/inbox_itsm.py b/services/api/app/api/v1/endpoints/inbox_itsm.pyindex f29f0e3a8..0916088c7 100644--- a/services/api/app/api/v1/endpoints/inbox_itsm.py+++ b/services/api/app/api/v1/endpoints/inbox_itsm.py@@ -460,6 +460,7 @@ async def _apply_status_to_case(db: Any,*,case_row: Any,+ tenant_id: Any,new_status: str,actor_label: str,external_id: str,@@ -506,9 +507,9 @@ async def _apply_status_to_case({triaged_at_set}{resolved_at_set}{closed_at_set}- WHERE id = :id+ WHERE id = :id AND tenant_id = :tid"""- ).bindparams(status=new_status, now=now, id=case_row.id)+ ).bindparams(status=new_status, now=now, id=case_row.id, tid=tenant_id))await db.execute(@@ -518,13 +519,14 @@ async def _apply_status_to_case(SET external_status = :ext_status,last_synced_at = :now,updated_at = :now- WHERE case_id = :case_id AND external_id = :external_id+ WHERE case_id = :case_id AND external_id = :external_id AND tenant_id = :tid""").bindparams(ext_status=new_status,now=now,case_id=case_row.id,external_id=external_id,+ tid=tenant_id,))@@ -533,12 +535,13 @@ async def _apply_status_to_case(text("""INSERT INTO aisoc_case_comments- (id, case_id, author, body, is_system, created_at)+ (id, tenant_id, case_id, author, body, is_system, created_at)VALUES- (:id, :case_id, :author, :body, TRUE, :now)+ (:id, :tid, :case_id, :author, :body, TRUE, :now)""").bindparams(id=uuid.uuid4(),+ tid=tenant_id,case_id=case_row.id,author=actor_label,body=note_body,@@ -659,13 +662,14 @@ async def inbound_itsm_webhook(SELECT r.id, r.case_id, r.external_status,c.id AS aisoc_case_id, c.case_number, c.statusFROM case_external_refs r- JOIN aisoc_cases c ON c.id = r.case_id+ JOIN aisoc_cases c ON c.id = r.case_id AND c.tenant_id = :tenant_idWHERE r.connector_instance_id = :connector_idAND r.external_id = :external_id""").bindparams(connector_id=connector_instance_id,external_id=external_id,+ tenant_id=token_row.tenant_id,))).fetchone()@@ -698,7 +702,11 @@ async def inbound_itsm_webhook(# status changed, so operators can see "this token is alive". Done# on every successful auth+resolve, not just on writes.now = datetime.now(UTC)- await db.execute(text("UPDATE tenant_inbox_tokens SET last_used_at = :now WHERE token = :tok").bindparams(now=now, tok=tenant_token))+ await db.execute(+ text("UPDATE tenant_inbox_tokens SET last_used_at = :now WHERE token = :tok AND tenant_id = :tenant_id").bindparams(+ now=now, tok=tenant_token, tenant_id=token_row.tenant_id+ )+ )new_status = _map_inbound_status(vendor, raw_status)if new_status is None:@@ -758,6 +766,7 @@ async def inbound_itsm_webhook(await _apply_status_to_case(db,case_row=ref_row,+ tenant_id=token_row.tenant_id,new_status=new_status,actor_label=actor_label,external_id=external_id,diff --git a/services/api/app/api/v1/endpoints/llm_status.py b/services/api/app/api/v1/endpoints/llm_status.pyindex adc8ba9f4..51f969a50 100644--- a/services/api/app/api/v1/endpoints/llm_status.py+++ b/services/api/app/api/v1/endpoints/llm_status.py@@ -61,6 +61,7 @@ from fastapi import APIRouterfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from app.api.v1.deps import AuthUserfrom app.core.airgap import is_host_allowed_for_airgapfrom app.core.config import settingsfrom app.models.llm_credential import TenantLlmCredential@@ -381,7 +382,7 @@ async def tenant_llm_status(@router.get("/status", summary="Current LLM provider configuration")-async def get_llm_status() -> dict[str, object]:+async def get_llm_status(user: AuthUser) -> dict[str, object]:"""Return the env-only LLM provider snapshot for this pod.Intentionally **unauthenticated** and **env-only**, mirroringdiff --git a/services/api/app/api/v1/endpoints/nl_detection.py b/services/api/app/api/v1/endpoints/nl_detection.pyindex 6540102cb..1d801dfa7 100644--- a/services/api/app/api/v1/endpoints/nl_detection.py+++ b/services/api/app/api/v1/endpoints/nl_detection.py@@ -195,7 +195,7 @@ def _template_fallback(request: NLDetectionRequest) -> dict[str, str | None]:@router.post("/translate", response_model=NLDetectionResponse)-async def translate_detection(payload: NLDetectionRequest) -> NLDetectionResponse:+async def translate_detection(payload: NLDetectionRequest, user: AuthUser) -> NLDetectionResponse:"""Convert a plain-English threat description into multi-platform detection rules."""if not payload.description.strip():raise HTTPException(diff --git a/services/api/app/api/v1/endpoints/replay.py b/services/api/app/api/v1/endpoints/replay.pyindex 4d6493126..c0d6d407b 100644--- a/services/api/app/api/v1/endpoints/replay.py+++ b/services/api/app/api/v1/endpoints/replay.py@@ -120,7 +120,10 @@ async def _load_run_and_events(events = list((await db.execute(- select(InvestigationEvent).where(InvestigationEvent.run_id == run_id).order_by(InvestigationEvent.seq.asc()).limit(10000)+ select(InvestigationEvent)+ .where(InvestigationEvent.run_id == run_id, InvestigationEvent.tenant_id == tenant_id)+ .order_by(InvestigationEvent.seq.asc())+ .limit(10000))).scalars()diff --git a/services/api/app/api/v1/endpoints/saved_hunts.py b/services/api/app/api/v1/endpoints/saved_hunts.pyindex 857915e36..6c799918a 100644--- a/services/api/app/api/v1/endpoints/saved_hunts.py+++ b/services/api/app/api/v1/endpoints/saved_hunts.py@@ -476,7 +476,7 @@ async def run_saved_hunt(# reset the cron" bug.await db.execute(update(SavedHunt)- .where(SavedHunt.id == hunt_uuid)+ .where(SavedHunt.id == hunt_uuid, SavedHunt.tenant_id == user.tenant_id).values(translated_query=translated.model_dump(),last_run_at=now,diff --git a/services/api/app/api/v1/endpoints/stix_taxii.py b/services/api/app/api/v1/endpoints/stix_taxii.pyindex 91802db4e..de7b4d876 100644--- a/services/api/app/api/v1/endpoints/stix_taxii.py+++ b/services/api/app/api/v1/endpoints/stix_taxii.py@@ -16,6 +16,7 @@ from enum import Enumfrom fastapi import APIRouter, HTTPException, Query, statusfrom pydantic import BaseModel, Field+from app.api.v1.deps import AuthUserfrom app.core.airgap import AirgapViolationfrom app.core.config import settingsfrom app.services.misp_push import (@@ -257,6 +258,7 @@ DEMO_TAXII_COLLECTIONS: list[TAXIICollection] = [@router.get("/indicators", response_model=IndicatorListResponse)async def list_indicators(+ user: AuthUser,page: int = Query(default=1, ge=1),page_size: int = Query(default=25, ge=1, le=200),label: str | None = Query(default=None),@@ -345,6 +347,7 @@ async def _push_bundle_or_swallow(bundle: STIXBundle) -> MispPushResult | None:)async def create_indicator(body: STIXIndicatorCreate,+ user: AuthUser,push_to_misp: bool | None = Query(default=None,description=("Mirror this indicator to the configured MISP instance. Defaults to the value of MISP_PUSH_AUTO."),@@ -376,7 +379,7 @@ async def create_indicator(@router.get("/bundles", response_model=BundleListResponse)-async def list_bundles() -> BundleListResponse:+async def list_bundles(user: AuthUser) -> BundleListResponse:"""List STIX 2.1 bundles."""return BundleListResponse(items=DEMO_BUNDLES, total=len(DEMO_BUNDLES))@@ -388,6 +391,7 @@ async def list_bundles() -> BundleListResponse:)async def create_bundle(body: STIXBundleCreate,+ user: AuthUser,push_to_misp: bool | None = Query(default=None,description=(@@ -418,7 +422,7 @@ async def create_bundle(@router.get("/taxii/collections", response_model=TAXIICollectionListResponse)-async def list_taxii_collections() -> TAXIICollectionListResponse:+async def list_taxii_collections(user: AuthUser) -> TAXIICollectionListResponse:"""List TAXII 2.1 collections for server compatibility."""return TAXIICollectionListResponse(items=DEMO_TAXII_COLLECTIONS,@@ -430,7 +434,7 @@ async def list_taxii_collections() -> TAXIICollectionListResponse:@router.get("/misp/health", response_model=MispPushHealth, tags=["MISP push"])-async def misp_push_health() -> MispPushHealth:+async def misp_push_health(user: AuthUser) -> MispPushHealth:"""Check whether MISP push is configured and reachable.Surfaces enough state for an operator to debug a misconfigured@@ -463,7 +467,7 @@ async def misp_push_health() -> MispPushHealth:@router.post("/misp/dry-run", response_model=MispDryRunResponse, tags=["MISP push"])-async def misp_push_dry_run(body: MispDryRunRequest) -> MispDryRunResponse:+async def misp_push_dry_run(body: MispDryRunRequest, user: AuthUser) -> MispDryRunResponse:"""Show the MISP event payload that *would* be pushed, without sending it.Useful for operators tuning STIX → MISP mappings, and for provingdiff --git a/services/api/app/api/v1/endpoints/translation.py b/services/api/app/api/v1/endpoints/translation.pyindex 15a42b1af..77760b7bd 100644--- a/services/api/app/api/v1/endpoints/translation.py+++ b/services/api/app/api/v1/endpoints/translation.py@@ -21,6 +21,7 @@ from typing import Any, Literalfrom fastapi import APIRouter, HTTPException, statusfrom pydantic import BaseModel, Field+from app.api.v1.deps import AuthUserfrom app.core.airgap import AirgapViolation, enforce_airgap_for_urlfrom app.services.llm_safety import LLMContractViolation, safe_chat_completions_requestfrom app.services.model_aliases import resolve_model_alias@@ -246,7 +247,7 @@ def _fallback_templates(req: TranslateRequest) -> dict[str, Any]:status_code=status.HTTP_200_OK,summary="Translate a detection rule across formats",)-async def translate_rule(body: TranslateRequest) -> TranslateResponse:+async def translate_rule(body: TranslateRequest, user: AuthUser) -> TranslateResponse:if not body.target_formats:raise HTTPException(status_code=400, detail="At least one target_format is required.")diff --git a/services/api/app/services/alert_explain.py b/services/api/app/services/alert_explain.pyindex 74e60cfbe..1990bdb36 100644--- a/services/api/app/services/alert_explain.py+++ b/services/api/app/services/alert_explain.py@@ -51,7 +51,7 @@ from dataclasses import dataclassfrom datetime import UTC, datetime, timedeltafrom typing import Any-from sqlalchemy import and_, func, select+from sqlalchemy import and_, func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.airgap import AirgapViolation, enforce_airgap_for_url@@ -230,7 +230,16 @@ async def _resolve_rule_lineage(db: AsyncSession, alert: Alert) -> tuple[Detecti# 1. Explicit reference in raw_event or tags.explicit_id = _explicit_rule_id_from_alert(alert)if explicit_id is not None:- result = await db.execute(select(DetectionRule).where(DetectionRule.id == explicit_id))+ # `explicit_id` is read out of the alert's raw_event, so it is+ # vendor-supplied rather than ours. Narrowed to this alert's tenant+ # plus the platform-wide rules, or a crafted raw_event could name+ # another tenant's rule and have its definition explained back.+ result = await db.execute(+ select(DetectionRule).where(+ DetectionRule.id == explicit_id,+ or_(DetectionRule.tenant_id == alert.tenant_id, DetectionRule.tenant_id.is_(None)),+ )+ )rule = result.scalar_one_or_none()if rule is not None:# The raw_event probe wins over the tag probe; we don'tdiff --git a/services/api/app/services/alert_queue.py b/services/api/app/services/alert_queue.pyindex 2a329b6b1..034c9a9c0 100644--- a/services/api/app/services/alert_queue.py+++ b/services/api/app/services/alert_queue.py@@ -468,7 +468,7 @@ async def claim_alert(now = datetime.now(UTC)update_result = await db.execute(update(Alert)- .where(Alert.id == alert_id, Alert.assigned_to_id.is_(None))+ .where(Alert.id == alert_id, Alert.tenant_id == tenant_id, Alert.assigned_to_id.is_(None)).values(assigned_to_id=user_id, assigned_at=now, updated_at=now).returning(Alert.assigned_to_id))@@ -476,7 +476,7 @@ async def claim_alert(if winner is None or winner != user_id:# Someone else grabbed it between our SELECT and UPDATE.# Re-read so the error carries the actual owner.- refresh = await db.execute(select(Alert.assigned_to_id).where(Alert.id == alert_id))+ refresh = await db.execute(select(Alert.assigned_to_id).where(Alert.id == alert_id, Alert.tenant_id == tenant_id))actual_owner = refresh.scalar_one_or_none()if actual_owner is None:raise AlertNotFoundError(str(alert_id))diff --git a/services/api/app/services/alert_rail.py b/services/api/app/services/alert_rail.pyindex fe28c89af..cee5e3067 100644--- a/services/api/app/services/alert_rail.py+++ b/services/api/app/services/alert_rail.py@@ -482,7 +482,12 @@ async def build_mini_timeline(# ── Case timeline ───────────────────────────────────────────────────if alert.case_id is not None:- case_q = select(CaseTimeline).where(CaseTimeline.case_id == alert.case_id).order_by(CaseTimeline.created_at.desc()).limit(limit)+ case_q = (+ select(CaseTimeline)+ .where(CaseTimeline.case_id == alert.case_id, CaseTimeline.tenant_id == alert.tenant_id)+ .order_by(CaseTimeline.created_at.desc())+ .limit(limit)+ )case_rows = (await db.execute(case_q)).scalars().all()events.extend(_case_event(row) for row in case_rows)diff --git a/services/api/app/services/case_postmortem.py b/services/api/app/services/case_postmortem.pyindex c28805a51..625cc53ca 100644--- a/services/api/app/services/case_postmortem.py+++ b/services/api/app/services/case_postmortem.py@@ -875,6 +875,7 @@ def build_postmortem_from_rows(async def build_case_postmortem(db: AsyncSession,case_id: uuid.UUID,+ tenant_id: uuid.UUID,*,now: datetime | None = None,) -> CasePostmortem | None:@@ -884,13 +885,16 @@ async def build_case_postmortem(clean 404 without conflating the data layer with HTTP semantics.SQL access is delegated to the auto-summary fetchers — they already- return the exact dataclasses we need.+ return the exact dataclasses we need, and they now take the tenant for+ the same reason: none of ``aisoc_cases``, ``aisoc_case_comments`` or+ ``aisoc_case_tasks`` carries an RLS policy, so the predicate is the only+ thing between two customers' retrospectives."""- case = await _fetch_case_for_summary(db, case_id)+ case = await _fetch_case_for_summary(db, case_id, tenant_id)if case is None:return None- comments = await _fetch_comments(db, case_id)- tasks = await _fetch_tasks(db, case_id)+ comments = await _fetch_comments(db, case_id, tenant_id)+ tasks = await _fetch_tasks(db, case_id, tenant_id)inputs = PostmortemInputs(case=case, comments=comments, tasks=tasks)return build_postmortem_from_rows(inputs, now=now)diff --git a/services/api/app/services/case_summary.py b/services/api/app/services/case_summary.pyindex 986888707..2ef7a09bc 100644--- a/services/api/app/services/case_summary.py+++ b/services/api/app/services/case_summary.py@@ -609,17 +609,20 @@ def _row_to_summary_case(row: Any) -> SummaryCaseRow:)-async def _fetch_case_for_summary(db: AsyncSession, case_id: uuid.UUID) -> SummaryCaseRow | None:- row = (await db.execute(text("SELECT * FROM aisoc_cases WHERE id = :id").bindparams(id=case_id))).fetchone()+async def _fetch_case_for_summary(db: AsyncSession, case_id: uuid.UUID, tenant_id: uuid.UUID) -> SummaryCaseRow | None:+ row = (+ await db.execute(text("SELECT * FROM aisoc_cases WHERE id = :id AND tenant_id = :tid").bindparams(id=case_id, tid=tenant_id))+ ).fetchone()return _row_to_summary_case(row) if row else None-async def _fetch_comments(db: AsyncSession, case_id: uuid.UUID) -> list[SummaryCommentRow]:+async def _fetch_comments(db: AsyncSession, case_id: uuid.UUID, tenant_id: uuid.UUID) -> list[SummaryCommentRow]:rows = (await db.execute(- text("SELECT author, body, is_system, created_at FROM aisoc_case_comments WHERE case_id = :id ORDER BY created_at").bindparams(- id=case_id- )+ text(+ "SELECT author, body, is_system, created_at FROM aisoc_case_comments "+ "WHERE case_id = :id AND tenant_id = :tid ORDER BY created_at"+ ).bindparams(id=case_id, tid=tenant_id))).fetchall()return [@@ -633,15 +636,15 @@ async def _fetch_comments(db: AsyncSession, case_id: uuid.UUID) -> list[SummaryC]-async def _fetch_tasks(db: AsyncSession, case_id: uuid.UUID) -> list[SummaryTaskRow]:+async def _fetch_tasks(db: AsyncSession, case_id: uuid.UUID, tenant_id: uuid.UUID) -> list[SummaryTaskRow]:"""Pull tasks; tolerate the absence of ``aisoc_case_tasks`` on older deployments."""try:rows = (await db.execute(text("SELECT title, status, assignee, due_at, created_at, updated_at "- "FROM aisoc_case_tasks WHERE case_id = :id ORDER BY created_at"- ).bindparams(id=case_id)+ "FROM aisoc_case_tasks WHERE case_id = :id AND tenant_id = :tid ORDER BY created_at"+ ).bindparams(id=case_id, tid=tenant_id))).fetchall()except Exception: # pragma: no cover — defensive: missing table on older DBs.@@ -662,6 +665,7 @@ async def _fetch_tasks(db: AsyncSession, case_id: uuid.UUID) -> list[SummaryTaskasync def build_case_summary(db: AsyncSession,case_id: uuid.UUID,+ tenant_id: uuid.UUID,*,now: datetime | None = None,) -> CaseAutoSummary | None:@@ -669,12 +673,17 @@ async def build_case_summary(Returns ``None`` if the case isn't found, so endpoints can surface aclean 404 without conflating the data layer with HTTP semantics.++ ``tenant_id`` is required rather than optional. The caller resolves the+ case id against the tenant before getting here, but none of these three+ tables carries an RLS policy, so a caller that forgot would read another+ tenant's case body, comments and tasks with nothing to stop it."""- case = await _fetch_case_for_summary(db, case_id)+ case = await _fetch_case_for_summary(db, case_id, tenant_id)if case is None:return None- comments = await _fetch_comments(db, case_id)- tasks = await _fetch_tasks(db, case_id)+ comments = await _fetch_comments(db, case_id, tenant_id)+ tasks = await _fetch_tasks(db, case_id, tenant_id)inputs = CaseSummaryInputs(case=case, comments=comments, tasks=tasks)return build_summary_from_rows(inputs, now=now)diff --git a/services/api/app/services/rule_tuning.py b/services/api/app/services/rule_tuning.pyindex 290644df7..623cabd0a 100644--- a/services/api/app/services/rule_tuning.py+++ b/services/api/app/services/rule_tuning.py@@ -527,7 +527,16 @@ async def _load_rule_for_tenant(tenant's workbench would leak the change to every other tenant. We letanalysts *see* them in projections but reject mutations."""- result = await db.execute(select(DetectionRule).where(DetectionRule.id == rule_id))+ # Narrowed to this tenant's rules plus the platform-wide ones, because+ # the two get different refusals below: a platform rule is a 403 (it+ # exists, it just isn't tuneable from here) and another tenant's rule is+ # a 404 (it must not be distinguishable from absent).+ result = await db.execute(+ select(DetectionRule).where(+ DetectionRule.id == rule_id,+ or_(DetectionRule.tenant_id == tenant_id, DetectionRule.tenant_id.is_(None)),+ )+ )rule = result.scalar_one_or_none()if rule is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Detection rule not found")diff --git a/services/api/tests/test_inbox_itsm_endpoint.py b/services/api/tests/test_inbox_itsm_endpoint.pyindex 266efa748..83a8280e1 100644--- a/services/api/tests/test_inbox_itsm_endpoint.py+++ b/services/api/tests/test_inbox_itsm_endpoint.py@@ -526,6 +526,7 @@ async def test_apply_status_to_case_writes_three_rows() -> None:await _apply_status_to_case(db,+ tenant_id=uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a"),case_row=case_row,new_status="resolved",actor_label="jira-webhook",@@ -557,6 +558,7 @@ async def test_apply_status_to_case_resolved_sets_resolved_at() -> None:await _apply_status_to_case(db,+ tenant_id=uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a"),case_row=case_row,new_status="resolved",actor_label="jira-webhook",@@ -580,6 +582,7 @@ async def test_apply_status_to_case_closed_sets_closed_at() -> None:await _apply_status_to_case(db,+ tenant_id=uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a"),case_row=case_row,new_status="closed",actor_label="snow-webhook",@@ -600,6 +603,7 @@ async def test_apply_status_to_case_triaged_does_not_stamp_resolved_or_closed()await _apply_status_to_case(db,+ tenant_id=uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a"),case_row=case_row,new_status="triaged",actor_label="jira-webhook",@@ -635,6 +639,7 @@ async def test_apply_status_to_case_writes_system_comment_with_provenance() -> Nawait _apply_status_to_case(db,+ tenant_id=uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a"),case_row=case_row,new_status="resolved",actor_label="jira-webhook",diff --git a/services/api/tests/test_misp_push.py b/services/api/tests/test_misp_push.pyindex 151c50269..f5ddc12ea 100644--- a/services/api/tests/test_misp_push.py+++ b/services/api/tests/test_misp_push.py@@ -22,11 +22,13 @@ by ``test_security_defaults.py``.from __future__ import annotations+import uuidfrom typing import Anyfrom unittest.mock import AsyncMock, MagicMockimport httpximport pytest+from app.api.v1.deps import CurrentUser, get_current_userfrom app.api.v1.endpoints import stix_taxiifrom app.api.v1.endpoints.stix_taxii import (MispPushResult,@@ -791,6 +793,17 @@ def stub_app() -> FastAPI:"""app = FastAPI()app.include_router(stix_router, prefix="/api/v1")+ # The STIX routes are authenticated now (they read and write tenant threat+ # intelligence). This file is about routing and serialization, so it+ # supplies a resolved user rather than credential material; that the+ # routes refuse an anonymous caller is asserted by scripts/check_route_auth.py.+ app.dependency_overrides[get_current_user] = lambda: CurrentUser(+ user_id=uuid.UUID("11111111-1111-1111-1111-111111111111"),+ tenant_id=uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a"),+ email="[email protected]",+ role="admin",+ scopes=["*"],+ )return appdiff --git a/services/connectors/app/api/router.py b/services/connectors/app/api/router.pyindex cc1f3c8fc..312596cd2 100644--- a/services/connectors/app/api/router.py+++ b/services/connectors/app/api/router.py@@ -29,7 +29,7 @@ import refrom typing import Anyimport structlog-from fastapi import APIRouter, HTTPException, Query, status+from fastapi import APIRouter, Depends, HTTPException, Query, statusfrom pydantic import BaseModelfrom pydantic import Field as PydField@@ -39,9 +39,20 @@ from app.db.connector_repo import fetch_enabled_connectorsfrom app.db.engine import get_enginefrom app.federated.query import QueryError, parse_unified_queryfrom app.security.credential_vault import CredentialVaultError, get_vault+from app.security.tenant_scope import require_console_or_service_authlogger = structlog.get_logger()-router = APIRouter()+#: Default-deny. Everything on this router either reads the connector+#: catalogue, decrypts a saved instance's credentials to test them, or+#: pushes a case into a customer's ITSM — none of which should answer an+#: anonymous caller. The console reaches these routes directly through a+#: Next rewrite, so the guard accepts a console session as well as a+#: service token declaring the tenant it acts for.+router = APIRouter(dependencies=[Depends(require_console_or_service_auth)])++#: Liveness is deliberately off the guarded router: a probe holds no+#: credential, and an unauthenticated 401 would read as an outage.+health_router = APIRouter()_CTRL_RE = re.compile(r"[\x00-\x1f\x7f]")@@ -570,6 +581,6 @@ async def push_status_change(connector_id: str, payload: PushStatusChangeRequestreturn result[email protected]("/health")+@health_router.get("/health")async def health():return {"status": "healthy", "service": "aisoc-connectors"}diff --git a/services/connectors/app/main.py b/services/connectors/app/main.pyindex 5de5718b6..e28b40278 100644--- a/services/connectors/app/main.py+++ b/services/connectors/app/main.py@@ -25,7 +25,7 @@ from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom app._health import install_health_routes-from app.api.router import router+from app.api.router import health_router, routerfrom app.db.engine import dispose_enginefrom app.scheduler import ConnectorScheduler, scheduler_disabledfrom app.security.cors import build_cors_kwargs@@ -100,3 +100,4 @@ app.add_middleware()app.include_router(router, prefix="/api/v1")+app.include_router(health_router, prefix="/api/v1")diff --git a/services/connectors/app/security/tenant_scope.py b/services/connectors/app/security/tenant_scope.pynew file mode 100644index 000000000..386283466--- /dev/null+++ b/services/connectors/app/security/tenant_scope.py@@ -0,0 +1,383 @@+"""Resolve which tenant a request may read, from the caller's credential.++Vendored byte-identical into each Python service that needs it, following the+same convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.+Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the+build if they drift.++Why this exists+---------------+``/fusion/entity-risk/*`` took the tenant as a query parameter with no auth+dependency on the route, on both the API gateway and the fusion service. The+console reaches fusion *directly* through a Next rewrite when ``FUSION_URL`` is+set, so that parameter was reachable from any browser on the internet, and+naming somebody else's tenant UUID returned their entity-risk queue.++Validating the parameter's *value* does not fix that. A UUID that parses is+still a UUID the caller chose. The scope has to come from somewhere the caller+does not control, which means the credential.++Two credential shapes reach these services, so this module resolves both:++``console`` — the browser's first-party access token, HS256-signed by+ ``services/api`` (``create_access_token``) and carrying a verified+ ``tenant_id`` claim. That claim is authoritative.+``service`` — the shared service bearer token used for service-to-service+ calls. It identifies *a trusted service*, not a tenant, so a caller+ presenting it must also assert which tenant it is acting for, on the+ ``X-AiSOC-Tenant-ID`` header. The assertion is explicit and required: a+ service token with no tenant header resolves to an **empty** scope, and an+ empty scope refuses rather than widening.++That last sentence is the whole design. Every cross-tenant leak this codebase+has had took the same shape — a scope that was absent rather than narrow, and+a read that treated absent as "no filter".++We verify HS256 by hand with the standard library rather than adding a JWT+dependency to five services, exactly as ``services/realtime/src/auth.ts`` does+for the same reason on the Node side. ``services/api`` remains the sole issuer;+this is a read path, like the vendored ``decrypt_dict()`` that lets the+connector scheduler decrypt without owning the write path.++Configuration+-------------+``SECRET_KEY``+ The HS256 secret ``services/api`` signs console tokens with. Without it+ this service cannot verify a console session and will only accept service+ tokens.+``AISOC_SERVICE_TOKEN`` / ``AISOC_<SERVICE>_SERVICE_TOKEN``+ Shared secret for service-to-service calls, resolved by+ ``app.security.service_auth.resolve_token`` where that module exists.+``AISOC_DEV_MODE``+ When set and *no* credential material is configured at all, requests+ resolve to the demo tenant so a local ``docker compose up`` works. This is+ the single canonical dev-mode flag; ``tests/test_security_defaults.py``+ asserts no shortcut is reachable when it is unset.+"""++from __future__ import annotations++import base64+import binascii+import hashlib+import hmac+import json+import logging+import os+import time+import uuid+from dataclasses import dataclass, field++from fastapi import Header, HTTPException, status++#: Set by each vendored copy so the per-service token override resolves.+SERVICE_NAME = "CONNECTORS"++logger = logging.getLogger("aisoc.tenant_scope")++_TRUTHY = {"1", "true", "yes", "on"}++#: Mirrors ``INSECURE_SECRET_KEY_DEFAULTS`` in services/api/app/core/config.py+#: so a placeholder secret is treated as "unset" on this side too. Verifying a+#: token signed with a well-known literal would authenticate anybody who read+#: the repository.+INSECURE_SECRET_DEFAULTS = frozenset(+ {+ "change-me-in-production-at-least-32-chars",+ "dev_secret_key_change_in_production",+ "changeme",+ "secret",+ }+)++#: Deterministic demo tenant, matching ``DEMO_TENANT_ID`` in+#: services/api/app/api/v1/dev_auth.py. Only ever used under AISOC_DEV_MODE.+DEV_TENANT_ID = uuid.UUID("00000000-0000-0000-0000-000000000001")++#: Header a trusted service uses to declare which tenant it is acting for.+TENANT_HEADER = "X-AiSOC-Tenant-ID"++#: 30s clock-skew leeway, matching the Node verifier and common JWT defaults.+_CLOCK_SKEW_SECONDS = 30++#: Refs that mean "the caller did not name a tenant" rather than naming one.+#: Several request models default ``tenant_id`` to the string ``"default"``,+#: which is a placeholder, not a tenant — migration 001 seeds the canonical+#: tenant with that *slug* and the demo seed renames it, so the literal+#: identifies nothing anywhere. Treating it as a request for a tenant called+#: "default" would refuse every caller who simply left the field alone.+PLACEHOLDER_TENANT_REFS = frozenset({"", "default", "none", "null"})+++class TenantScopeError(Exception):+ """A read was attempted without a resolved tenant scope.++ Raised by :func:`resolve_scoped_tenant`. Routes let it surface as a 403;+ it means a query was about to run with no tenant filter, or with one the+ caller is not authorised for.+ """+++@dataclass(frozen=True)+class TenantPrincipal:+ """The tenants one credential may read, and what kind of credential it is.++ ``tenant_ids`` is authoritative and exhaustive. Nothing downstream may+ widen it, and no code path may substitute "all tenants" for an empty one.+ """++ tenant_ids: frozenset[uuid.UUID] = field(default_factory=frozenset)+ subject: str = "anonymous"+ #: True when a service token asserted the tenant rather than a verified+ #: console claim carrying it. Surfaced so logs can tell the two apart.+ delegated: bool = False++ @property+ def is_empty(self) -> bool:+ return not self.tenant_ids++ def covers(self, tenant_id: uuid.UUID) -> bool:+ return tenant_id in self.tenant_ids++ def ordered_ids(self) -> list[uuid.UUID]:+ return sorted(self.tenant_ids)+++EMPTY_PRINCIPAL = TenantPrincipal()+++def resolve_scoped_tenant(+ principal: TenantPrincipal,+ requested: uuid.UUID | str | None = None,+) -> uuid.UUID:+ """The one tenant this request may read, or refuse to name one.++ Intersection only. A ``requested`` tenant inside the principal's scope is+ honoured — that is an MSSP operator narrowing to one managed customer. A+ ``requested`` tenant outside it narrows to nothing and raises, rather than+ reaching outside. Passing ``None`` means "the caller's own tenant", which+ is the common case and the safe default.+ """+ if principal.is_empty:+ raise TenantScopeError("refusing to read with an empty tenant scope")++ if isinstance(requested, str) and requested.strip().lower() in PLACEHOLDER_TENANT_REFS:+ requested = None++ if requested is None:+ if len(principal.tenant_ids) != 1:+ raise TenantScopeError(f"caller reaches {len(principal.tenant_ids)} tenants; the request must name one")+ return next(iter(principal.tenant_ids))++ try:+ wanted = requested if isinstance(requested, uuid.UUID) else uuid.UUID(str(requested))+ except (ValueError, AttributeError, TypeError) as exc:+ raise TenantScopeError("requested tenant is not a UUID") from exc++ if not principal.covers(wanted):+ # Logged at warning with the subject, because a caller reaching for a+ # tenant they do not hold is a security event, not routine noise.+ logger.warning(+ "tenant_scope.refused subject=%s requested=%s scope_size=%d",+ # Sanitised inline rather than through a helper: CodeQL does not+ # track a helper across the call boundary, and `subject` really is+ # attacker-influenced — it carries the JWT `sub` claim.+ str(principal.subject).replace("\r", "").replace("\n", " ")[:128],+ str(wanted).replace("\r", "").replace("\n", " ")[:64],+ len(principal.tenant_ids),+ )+ raise TenantScopeError("requested tenant is outside the caller's authorised scope")+ return wanted+++# ---------------------------------------------------------------------------+# Credential resolution+# ---------------------------------------------------------------------------+++def _dev_mode() -> bool:+ return os.getenv("AISOC_DEV_MODE", "").strip().lower() in _TRUTHY+++def resolve_console_secret() -> str:+ """The HS256 secret console tokens are signed with, or "" when unusable."""+ secret = (os.getenv("SECRET_KEY") or "").strip()+ if not secret or secret in INSECURE_SECRET_DEFAULTS:+ return ""+ return secret+++def resolve_service_token() -> str:+ """Per-service override wins, then the shared platform token."""+ specific = os.getenv(f"AISOC_{SERVICE_NAME}_SERVICE_TOKEN", "").strip()+ if specific:+ return specific+ return os.getenv("AISOC_SERVICE_TOKEN", "").strip()+++def _b64url_decode(segment: str) -> bytes:+ padding = "=" * (-len(segment) % 4)+ return base64.urlsafe_b64decode(segment + padding)+++def verify_console_token(token: str, secret: str) -> dict | None:+ """Verify a first-party HS256 access token. Return claims, or None.++ Mirrors ``verifyRealtimeTicket`` in services/realtime/src/auth.ts. The+ signing side is ``create_access_token`` in services/api/app/core/security.py+ and must stay in sync with the claims checked here.+ """+ if not token or not secret:+ return None+ parts = token.split(".")+ if len(parts) != 3:+ return None+ header_b64, payload_b64, sig_b64 = parts++ try:+ header = json.loads(_b64url_decode(header_b64))+ except (ValueError, binascii.Error, UnicodeDecodeError):+ return None+ # Reject "alg: none" and asymmetric algorithms so a caller cannot downgrade+ # the verification into no verification at all.+ if not isinstance(header, dict) or header.get("alg") != "HS256":+ return None++ expected = hmac.new(+ secret.encode("utf-8"),+ f"{header_b64}.{payload_b64}".encode(),+ hashlib.sha256,+ ).digest()+ try:+ provided = _b64url_decode(sig_b64)+ except (ValueError, binascii.Error):+ return None+ if not hmac.compare_digest(expected, provided):+ return None++ try:+ claims = json.loads(_b64url_decode(payload_b64))+ except (ValueError, binascii.Error, UnicodeDecodeError):+ return None+ if not isinstance(claims, dict):+ return None++ # A refresh token must not buy access; the API sets type="access" on the+ # short-lived one and type="refresh" on the long-lived one.+ if claims.get("type") != "access":+ return None+ exp = claims.get("exp")+ if not isinstance(exp, int | float):+ return None+ if exp + _CLOCK_SKEW_SECONDS < time.time():+ return None+ if not claims.get("tenant_id"):+ return None+ return claims+++def _principal_from_claims(claims: dict) -> TenantPrincipal | None:+ try:+ tenant = uuid.UUID(str(claims["tenant_id"]))+ except (KeyError, ValueError, TypeError):+ return None+ return TenantPrincipal(+ tenant_ids=frozenset({tenant}),+ subject=f"console:{claims.get('sub', 'unknown')}",+ delegated=False,+ )+++async def require_console_or_service_auth(+ authorization: str | None = Header(default=None),+ x_aisoc_tenant_id: str | None = Header(default=None, alias=TENANT_HEADER),+) -> TenantPrincipal:+ """FastAPI dependency. Resolve the caller's tenant scope, or fail closed.++ Order matters only for clarity — the two credential shapes are disjoint. A+ console token carries its own tenant; a service token must declare one.+ """+ console_secret = resolve_console_secret()+ service_token = resolve_service_token()++ if not console_secret and not service_token:+ if _dev_mode():+ return TenantPrincipal(+ tenant_ids=frozenset({DEV_TENANT_ID}),+ subject="dev",+ delegated=False,+ )+ # No credential material configured at all: refuse to serve rather+ # than serve openly. This is the same fail-closed posture as+ # ``require_service_auth``.+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail=(+ "tenant-scoped auth is not configured; set SECRET_KEY and/or "+ f"AISOC_SERVICE_TOKEN (or AISOC_{SERVICE_NAME}_SERVICE_TOKEN) "+ "before exposing this service"+ ),+ )++ if not authorization or not authorization.startswith("Bearer "):+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="missing bearer credential",+ headers={"WWW-Authenticate": "Bearer"},+ )+ token = authorization[len("Bearer ") :].strip()++ # --- console session ---+ if console_secret:+ claims = verify_console_token(token, console_secret)+ if claims is not None:+ principal = _principal_from_claims(claims)+ if principal is not None:+ return principal++ # --- trusted service acting for a declared tenant ---+ if service_token and hmac.compare_digest(token, service_token):+ if not x_aisoc_tenant_id or not x_aisoc_tenant_id.strip():+ # An absent tenant is an empty scope, never every scope.+ logger.warning(+ "tenant_scope.service_token_without_tenant service=%s header=%s",+ SERVICE_NAME,+ TENANT_HEADER,+ )+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=f"service token must declare the tenant it acts for on {TENANT_HEADER}",+ )+ try:+ tenant = uuid.UUID(x_aisoc_tenant_id.strip())+ except ValueError:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=f"{TENANT_HEADER} must be a UUID",+ ) from None+ return TenantPrincipal(+ tenant_ids=frozenset({tenant}),+ subject="service",+ delegated=True,+ )++ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="invalid or missing credential",+ headers={"WWW-Authenticate": "Bearer"},+ )+++def scoped_tenant_or_403(+ principal: TenantPrincipal,+ requested: uuid.UUID | str | None = None,+) -> uuid.UUID:+ """:func:`resolve_scoped_tenant`, surfaced to HTTP as 403.++ Routes call this so the refusal reaches the client as a refusal rather+ than a 500, without every route repeating the try/except.+ """+ try:+ return resolve_scoped_tenant(principal, requested)+ except TenantScopeError as exc:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from excdiff --git a/services/connectors/tests/test_tenant_scope.py b/services/connectors/tests/test_tenant_scope.pynew file mode 100644index 000000000..f2c30dded--- /dev/null+++ b/services/connectors/tests/test_tenant_scope.py@@ -0,0 +1,274 @@+"""Unit tests for the vendored tenant-scope resolver.++Vendored byte-identical into each service that carries+``app/security/tenant_scope.py``, and kept in lockstep by+``scripts/sync_vendored_tenant_scope.py``. The module is the thing that+decides which tenant a request may read, so every copy is tested where it+lives rather than trusting that the one covered by ``tests/isolation`` stands+in for the other five.++The cross-service two-tenant replay lives in+``tests/isolation/test_route_tenant_scope.py``; this file covers the+credential and intersection logic on its own.+"""++from __future__ import annotations++import base64+import hashlib+import hmac+import json+import time+import uuid++import pytest+from app.security import tenant_scope as ts+from fastapi import HTTPException++SECRET = "unit-test-secret-key-at-least-32-characters"+SERVICE_TOKEN = "unit-test-service-token"++TENANT_A = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")+TENANT_B = uuid.UUID("bbbbbbbb-0000-0000-0000-00000000000b")+++def _b64(raw: bytes) -> str:+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()+++def _token(+ tenant: uuid.UUID | None = TENANT_A,+ *,+ secret: str = SECRET,+ alg: str = "HS256",+ token_type: str = "access",+ ttl: int = 600,+ sub: str = "user-1",+) -> str:+ header = _b64(json.dumps({"alg": alg, "typ": "JWT"}, separators=(",", ":")).encode())+ claims: dict[str, object] = {"sub": sub, "type": token_type, "exp": int(time.time()) + ttl}+ if tenant is not None:+ claims["tenant_id"] = str(tenant)+ payload = _b64(json.dumps(claims, separators=(",", ":")).encode())+ sig = _b64(hmac.new(secret.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest())+ return f"{header}.{payload}.{sig}"++[email protected](autouse=True)+def _configured(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("SECRET_KEY", SECRET)+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)+ monkeypatch.delenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", raising=False)+++# ---------------------------------------------------------------------------+# Token verification+# ---------------------------------------------------------------------------+++def test_valid_token_yields_its_tenant() -> None:+ claims = ts.verify_console_token(_token(), SECRET)+ assert claims is not None and claims["tenant_id"] == str(TENANT_A)+++ ("label", "kwargs"),+ [+ # An `alg: none` header is the classic downgrade: a verifier that+ # reads the header to decide how to verify must refuse anything else.+ ("alg none", {"alg": "none"}),+ ("wrong key", {"secret": "a-completely-different-secret-key-32ch"}),+ # A refresh token is long-lived by design; buying access with it would+ # make the short access-token expiry meaningless.+ ("refresh token", {"token_type": "refresh"}),+ ("expired", {"ttl": -3600}),+ ("no tenant claim", {"tenant": None}),+ ],+)+def test_unacceptable_tokens_are_refused(label: str, kwargs: dict) -> None:+ assert ts.verify_console_token(_token(**kwargs), SECRET) is None, label++[email protected]("malformed", ["", "not-a-jwt", "a.b", "a.b.c.d", "...", "%%%.%%%.%%%"])+def test_malformed_tokens_are_refused(malformed: str) -> None:+ assert ts.verify_console_token(malformed, SECRET) is None+++def test_no_secret_means_no_verification() -> None:+ """An unconfigured secret must not verify anything, least of all everything."""+ assert ts.verify_console_token(_token(), "") is None+++def test_placeholder_secrets_count_as_unset() -> None:+ for placeholder in ts.INSECURE_SECRET_DEFAULTS:+ assert ts.resolve_console_secret.__doc__ # module contract exists+ assert placeholder in ts.INSECURE_SECRET_DEFAULTS+++# ---------------------------------------------------------------------------+# Intersection+# ---------------------------------------------------------------------------+++def _principal(*tenants: uuid.UUID) -> ts.TenantPrincipal:+ return ts.TenantPrincipal(tenant_ids=frozenset(tenants), subject="console:test")+++def test_no_request_tenant_means_the_callers_own() -> None:+ assert ts.resolve_scoped_tenant(_principal(TENANT_A)) == TENANT_A+++def test_a_tenant_inside_scope_is_honoured() -> None:+ assert ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B), TENANT_B) == TENANT_B+++def test_a_tenant_outside_scope_narrows_to_nothing() -> None:+ with pytest.raises(ts.TenantScopeError):+ ts.resolve_scoped_tenant(_principal(TENANT_A), TENANT_B)+++def test_empty_scope_refuses_rather_than_widening() -> None:+ """The invariant every cross-tenant leak in this codebase has broken."""+ with pytest.raises(ts.TenantScopeError):+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL)+ with pytest.raises(ts.TenantScopeError):+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, TENANT_A)+++def test_a_multi_tenant_caller_must_name_one() -> None:+ """Silently picking one of several would be a coin toss over customers."""+ with pytest.raises(ts.TenantScopeError):+ ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B))+++def test_a_non_uuid_request_tenant_is_refused() -> None:+ with pytest.raises(ts.TenantScopeError):+ ts.resolve_scoped_tenant(_principal(TENANT_A), "not-a-uuid")++[email protected]("placeholder", ["", " ", "default", "DEFAULT", "none", "null"])+def test_a_placeholder_means_the_caller_did_not_ask(placeholder: str) -> None:+ """A placeholder is the absence of a request, not a tenant named "default".++ Several request models default `tenant_id` to the literal `"default"`.+ That string names no tenant anywhere — migration 001 seeds the canonical+ tenant with it as a *slug* and the demo seed renames that to `demo` — so+ treating it as a requested tenant would refuse every caller who left the+ field at its default.+ """+ assert ts.resolve_scoped_tenant(_principal(TENANT_A), placeholder) == TENANT_A+++def test_a_placeholder_still_cannot_widen_an_empty_scope() -> None:+ with pytest.raises(ts.TenantScopeError):+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, "default")+++def test_scoped_tenant_or_403_surfaces_a_refusal_as_403() -> None:+ with pytest.raises(HTTPException) as exc:+ ts.scoped_tenant_or_403(_principal(TENANT_A), TENANT_B)+ assert exc.value.status_code == 403+++# ---------------------------------------------------------------------------+# The dependency+# ---------------------------------------------------------------------------+++# `require_console_or_service_auth` is a FastAPI dependency: its parameters+# are normally resolved by FastAPI from the request. Calling it directly means+# supplying both, including the tenant header as an explicit `None` — leaving+# it out hands the function FastAPI's `Header(...)` sentinel rather than the+# absent value the test means to describe.+++async def test_console_session_resolves_to_its_own_tenant() -> None:+ principal = await ts.require_console_or_service_auth(authorization=f"Bearer {_token()}", x_aisoc_tenant_id=None)+ assert principal.tenant_ids == frozenset({TENANT_A})+ assert principal.delegated is False+++async def test_service_token_must_declare_the_tenant_it_acts_for() -> None:+ """A service credential identifies a service, not a tenant."""+ with pytest.raises(HTTPException) as exc:+ await ts.require_console_or_service_auth(authorization=f"Bearer {SERVICE_TOKEN}", x_aisoc_tenant_id=None)+ assert exc.value.status_code == 403+++async def test_service_token_with_a_declared_tenant_is_delegated() -> None:+ principal = await ts.require_console_or_service_auth(+ authorization=f"Bearer {SERVICE_TOKEN}",+ x_aisoc_tenant_id=str(TENANT_B),+ )+ assert principal.tenant_ids == frozenset({TENANT_B})+ assert principal.delegated is True+++async def test_a_declared_tenant_must_be_a_uuid() -> None:+ with pytest.raises(HTTPException) as exc:+ await ts.require_console_or_service_auth(+ authorization=f"Bearer {SERVICE_TOKEN}",+ x_aisoc_tenant_id="the-big-customer",+ )+ assert exc.value.status_code == 400++[email protected]("header", [None, "", "Basic abc", "Bearer ", "Bearer nonsense"])+async def test_a_missing_or_unrecognised_credential_is_401(header: str | None) -> None:+ with pytest.raises(HTTPException) as exc:+ await ts.require_console_or_service_auth(authorization=header, x_aisoc_tenant_id=None)+ assert exc.value.status_code == 401+++async def test_unconfigured_credentials_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None:+ """No credential material and no dev mode serves 503, never the route."""+ monkeypatch.setenv("SECRET_KEY", "")+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)+ with pytest.raises(HTTPException) as exc:+ await ts.require_console_or_service_auth(authorization="Bearer anything", x_aisoc_tenant_id=None)+ assert exc.value.status_code == 503+++async def test_dev_mode_only_applies_with_nothing_configured(monkeypatch: pytest.MonkeyPatch) -> None:+ """Dev mode is a fallback for an unconfigured stack, not an auth bypass.++ With a secret configured, `AISOC_DEV_MODE` must not let an unauthenticated+ caller through — otherwise setting one flag in the wrong environment opens+ every tenant-scoped route.+ """+ monkeypatch.setenv("AISOC_DEV_MODE", "1")+ monkeypatch.setenv("SECRET_KEY", SECRET)+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)+ with pytest.raises(HTTPException) as exc:+ await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)+ assert exc.value.status_code == 401++ monkeypatch.setenv("SECRET_KEY", "")+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")+ principal = await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)+ assert principal.tenant_ids == frozenset({ts.DEV_TENANT_ID})+++async def test_a_per_service_token_override_wins(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", "service-specific")+ principal = await ts.require_console_or_service_auth(+ authorization="Bearer service-specific",+ x_aisoc_tenant_id=str(TENANT_A),+ )+ assert principal.delegated is True+ # The shared token must no longer be accepted once an override exists.+ with pytest.raises(HTTPException):+ await ts.require_console_or_service_auth(+ authorization=f"Bearer {SERVICE_TOKEN}",+ x_aisoc_tenant_id=str(TENANT_A),+ )diff --git a/services/fusion/app/api/router.py b/services/fusion/app/api/router.pyindex dc147dff5..729e4ec5d 100644--- a/services/fusion/app/api/router.py+++ b/services/fusion/app/api/router.py@@ -42,7 +42,7 @@ async def metrics():@router.get("/ml/status")-async def ml_status():+async def ml_status(principal: ScopedPrincipal):"""Return current ML model training status."""if _worker_ref is None or _worker_ref.engine is None:raise HTTPException(status_code=503, detail="Fusion worker not ready")@@ -50,7 +50,7 @@ async def ml_status():@router.post("/ml/feedback")-async def submit_feedback(feedback: AnalystFeedback):+async def submit_feedback(feedback: AnalystFeedback, principal: ScopedPrincipal):"""Submit analyst feedback to improve ML ranker."""if _worker_ref is None or _worker_ref.engine is None:raise HTTPException(status_code=503, detail="Fusion worker not ready")@@ -59,7 +59,7 @@ async def submit_feedback(feedback: AnalystFeedback):@router.post("/ml/retrain")-async def trigger_retrain():+async def trigger_retrain(principal: ScopedPrincipal):"""Manually trigger ML model retraining."""if _worker_ref is None or _worker_ref.engine is None:raise HTTPException(status_code=503, detail="Fusion worker not ready")@@ -73,7 +73,7 @@ async def trigger_retrain():@router.post("/process", response_model=FusedAlert)-async def process_alert(alert: RawAlert) -> FusedAlert:+async def process_alert(alert: RawAlert, principal: ScopedPrincipal) -> FusedAlert:"""Run a single ``RawAlert`` through the full fusion pipeline.The Kafka consumer path (``FusionWorker``) is still the production@@ -172,7 +172,7 @@ async def entity_risk_detail(@router.post("/confidence/score")-async def score_confidence(alert: RawAlert):+async def score_confidence(alert: RawAlert, principal: ScopedPrincipal):"""Run an alert through the confidence + explainability scorer inisolation and return the rationale chain.diff --git a/services/fusion/tests/test_process_endpoint.py b/services/fusion/tests/test_process_endpoint.pyindex f9f6b7b4e..6039e95a9 100644--- a/services/fusion/tests/test_process_endpoint.py+++ b/services/fusion/tests/test_process_endpoint.py@@ -30,6 +30,7 @@ from app.models.alert import (FusionDecision,RawAlert,)+from app.security.tenant_scope import TenantPrincipal, require_console_or_service_authfrom fastapi import FastAPIfrom httpx import ASGITransport, AsyncClient@@ -91,6 +92,13 @@ def _make_app(worker: Any | None) -> FastAPI:set_worker(worker) if worker is not None else _clear_worker()app = FastAPI()app.include_router(router)+ # `/process` is authenticated now — it was reachable with no credential+ # and it runs the fusion pipeline. These tests are about the pipeline's+ # response envelope, so they supply a resolved principal; the refusal of+ # an anonymous caller is asserted by scripts/check_route_auth.py.+ app.dependency_overrides[require_console_or_service_auth] = lambda: TenantPrincipal(+ tenant_ids=frozenset({UUID("aaaaaaaa-0000-0000-0000-00000000000a")}), subject="test"+ )return appdiff --git a/services/osquery-tls/app/api/v1/endpoints/distributed_status.py b/services/osquery-tls/app/api/v1/endpoints/distributed_status.pyindex 234e92c76..bd80713aa 100644--- a/services/osquery-tls/app/api/v1/endpoints/distributed_status.py+++ b/services/osquery-tls/app/api/v1/endpoints/distributed_status.py@@ -12,8 +12,13 @@ from pydantic import BaseModelfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.db.session import get_db+from app.security.tenant_scope import TenantPrincipal, require_console_or_service_auth, scoped_tenant_or_403from app.services.distributed_queue import get_query_by_id+#: Dual-mode guard: the console reads query status through a Next rewrite,+#: and the tenant comes from the credential rather than the query_id.+ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]+router = APIRouter()@@ -28,8 +33,9 @@ class QueryStatusResponse(BaseModel):async def distributed_status(query_id: str,db: Annotated[AsyncSession, Depends(get_db)],+ principal: ScopedPrincipal,) -> QueryStatusResponse:- dq = await get_query_by_id(db, query_id)+ dq = await get_query_by_id(db, query_id, scoped_tenant_or_403(principal))if dq is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,diff --git a/services/osquery-tls/app/api/v1/endpoints/extensions.py b/services/osquery-tls/app/api/v1/endpoints/extensions.pyindex 43064c49f..0f655f860 100644--- a/services/osquery-tls/app/api/v1/endpoints/extensions.py+++ b/services/osquery-tls/app/api/v1/endpoints/extensions.py@@ -29,7 +29,11 @@ import loggingfrom datetime import UTC, datetime, timedeltafrom typing import Annotated, Any-from fastapi import APIRouter, Query+from fastapi import APIRouter, Depends, Query++from app.security.tenant_scope import TenantPrincipal, require_console_or_service_auth++ScopedPrincipal = Annotated[TenantPrincipal, Depends(require_console_or_service_auth)]log = logging.getLogger(__name__)@@ -109,6 +113,7 @@ def _persistence_baseline_stub(host: str) -> list[dict[str, Any]]:@router.get("/pending-actions")async def get_pending_actions(+ principal: ScopedPrincipal,host_identifier: Annotated[str | None, Query(description="Host identifier")] = None,) -> list[dict[str, Any]]:"""Return pending HITL response actions for the given host."""@@ -118,6 +123,7 @@ async def get_pending_actions(@router.get("/alert-cache")async def get_alert_cache(+ principal: ScopedPrincipal,host_identifier: Annotated[str | None, Query()] = None,since: Annotated[str | None,@@ -138,6 +144,7 @@ async def get_alert_cache(@router.get("/persistence-baseline")async def get_persistence_baseline(+ principal: ScopedPrincipal,host_identifier: Annotated[str | None, Query()] = None,) -> list[dict[str, Any]]:"""Return the approved persistence-mechanism baseline for this host."""diff --git a/services/osquery-tls/app/api/v1/endpoints/packs.py b/services/osquery-tls/app/api/v1/endpoints/packs.pyindex 62587696a..fc4942bd9 100644--- a/services/osquery-tls/app/api/v1/endpoints/packs.py+++ b/services/osquery-tls/app/api/v1/endpoints/packs.py@@ -98,13 +98,13 @@ class PackAssignmentOut(BaseModel):@router.get("/packs", response_model=list[PackOut])-async def list_packs() -> list[PackOut]:+async def list_packs(principal: ScopedPrincipal) -> list[PackOut]:"""Return all packs loaded from the on-disk YAML catalog."""return [PackOut.from_pack(p) for p in get_all_packs()]@router.get("/packs/{pack_id}", response_model=PackOut)-async def get_pack_detail(pack_id: str) -> PackOut:+async def get_pack_detail(pack_id: str, principal: ScopedPrincipal) -> PackOut:"""Return a single pack by id."""pack = get_pack(pack_id)if pack is None:@@ -115,6 +115,7 @@ async def get_pack_detail(pack_id: str) -> PackOut:@router.get("/packs/{pack_id}/render")async def render_pack(pack_id: str,+ principal: ScopedPrincipal,format: Annotated[Literal["osquery-json", "osctrl", "fleetdm"],Query(description="Target render format"),diff --git a/services/osquery-tls/app/services/distributed_queue.py b/services/osquery-tls/app/services/distributed_queue.pyindex 9a22a421f..8fae8c609 100644--- a/services/osquery-tls/app/services/distributed_queue.py+++ b/services/osquery-tls/app/services/distributed_queue.py@@ -55,7 +55,20 @@ async def complete_query(await db.commit()-async def get_query_by_id(db: AsyncSession, query_id: str) -> OsqueryDistributedQuery | None:- """Look up a distributed query by its query_id."""- result = await db.execute(select(OsqueryDistributedQuery).where(OsqueryDistributedQuery.query_id == query_id))+async def get_query_by_id(db: AsyncSession, query_id: str, tenant_id: str | uuid.UUID | None = None) -> OsqueryDistributedQuery | None:+ """Look up a distributed query by its query_id.++ ``osquery_distributed_query`` carries no ``tenant_id`` of its own — it is+ scoped through the node it was sent to — so when a request supplies a+ tenant the lookup joins onto ``osquery_node`` rather than trusting the+ id. Without that join a query_id is a bearer capability for another+ tenant's host telemetry.+ """+ stmt = select(OsqueryDistributedQuery).where(OsqueryDistributedQuery.query_id == query_id)+ if tenant_id is not None:+ # osquery_node.tenant_id is VARCHAR: the rest of this service stores+ # the tenant as a string, so coerce rather than binding a UUID object+ # against a text column and relying on the driver to guess.+ stmt = stmt.join(OsqueryNode, OsqueryNode.id == OsqueryDistributedQuery.node_id).where(OsqueryNode.tenant_id == str(tenant_id))+ result = await db.execute(stmt)return result.scalar_one_or_none()diff --git a/services/osquery-tls/tests/test_distributed.py b/services/osquery-tls/tests/test_distributed.pyindex 6c35fd997..0ff46f136 100644--- a/services/osquery-tls/tests/test_distributed.py+++ b/services/osquery-tls/tests/test_distributed.py@@ -80,8 +80,10 @@ async def test_distributed_write_and_status(client, service_auth):assert write.status_code == 200assert write.json()["node_invalid"] is False- # Internal status endpoint should show completed- status_resp = await client.get(f"/api/v1/osquery/distributed/{query_id}")+ # Internal status endpoint should show completed. It is tenant-scoped+ # now: the results are reached through the node, so the caller has to+ # say which tenant it is acting for.+ status_resp = await client.get(f"/api/v1/osquery/distributed/{query_id}", headers=service_auth)assert status_resp.status_code == 200sdata = status_resp.json()assert sdata["status"] == "completed"@@ -102,6 +104,13 @@ async def test_distributed_enqueue_unknown_host(client, service_auth):@pytest.mark.asyncio-async def test_distributed_status_not_found(client):- resp = await client.get("/api/v1/osquery/distributed/no-such-id")+async def test_distributed_status_not_found(client, service_auth):+ resp = await client.get("/api/v1/osquery/distributed/no-such-id", headers=service_auth)assert resp.status_code == 404+++async def test_distributed_status_refuses_an_anonymous_caller(client):+ """A query_id used to be a bearer capability for another tenant's results."""+ resp = await client.get("/api/v1/osquery/distributed/no-such-id")+ assert resp.status_code == 401diff --git a/services/threatintel/app/main.py b/services/threatintel/app/main.pyindex 25ea7b4a9..b6aa6e8f7 100644--- a/services/threatintel/app/main.py+++ b/services/threatintel/app/main.py@@ -13,11 +13,12 @@ from __future__ import annotationsfrom collections.abc import AsyncGeneratorfrom contextlib import asynccontextmanagerfrom functools import partial+from typing import Annotatedimport redis.asyncio as aioredisimport structlogfrom aiokafka import AIOKafkaProducer-from fastapi import FastAPI+from fastapi import Depends, FastAPIfrom neo4j import AsyncGraphDatabasefrom opensearchpy import AsyncOpenSearchfrom prometheus_client import Counter, make_asgi_app@@ -40,6 +41,7 @@ from app.feeds.handlers import ()from app.feeds.pipeline import ThreatIntelPipelinefrom app.feeds.scheduler import FeedScheduler+from app.security.tenant_scope import TenantPrincipal, require_console_or_service_authfrom app.storage.bloom import RedisBloomFilterfrom app.storage.neo4j import Neo4jStorefrom app.storage.opensearch import OpenSearchStore@@ -310,6 +312,7 @@ async def health() -> dict:@app.get("/api/v1/iocs/search")async def search_iocs(+ principal: Annotated[TenantPrincipal, Depends(require_console_or_service_auth)],value: str | None = None,ioc_type: str | None = None,source: str | None = None,diff --git a/services/threatintel/app/security/__init__.py b/services/threatintel/app/security/__init__.pynew file mode 100644index 000000000..1648dbacd--- /dev/null+++ b/services/threatintel/app/security/__init__.py@@ -0,0 +1 @@+"""Security helpers for this service."""diff --git a/services/threatintel/app/security/tenant_scope.py b/services/threatintel/app/security/tenant_scope.pynew file mode 100644index 000000000..906e37a3c--- /dev/null+++ b/services/threatintel/app/security/tenant_scope.py@@ -0,0 +1,383 @@+"""Resolve which tenant a request may read, from the caller's credential.++Vendored byte-identical into each Python service that needs it, following the+same convention as ``app/core/cors.py`` and ``app/security/service_auth.py``.+Keep the copies in sync — ``scripts/check_vendored_tenant_scope.py`` fails the+build if they drift.++Why this exists+---------------+``/fusion/entity-risk/*`` took the tenant as a query parameter with no auth+dependency on the route, on both the API gateway and the fusion service. The+console reaches fusion *directly* through a Next rewrite when ``FUSION_URL`` is+set, so that parameter was reachable from any browser on the internet, and+naming somebody else's tenant UUID returned their entity-risk queue.++Validating the parameter's *value* does not fix that. A UUID that parses is+still a UUID the caller chose. The scope has to come from somewhere the caller+does not control, which means the credential.++Two credential shapes reach these services, so this module resolves both:++``console`` — the browser's first-party access token, HS256-signed by+ ``services/api`` (``create_access_token``) and carrying a verified+ ``tenant_id`` claim. That claim is authoritative.+``service`` — the shared service bearer token used for service-to-service+ calls. It identifies *a trusted service*, not a tenant, so a caller+ presenting it must also assert which tenant it is acting for, on the+ ``X-AiSOC-Tenant-ID`` header. The assertion is explicit and required: a+ service token with no tenant header resolves to an **empty** scope, and an+ empty scope refuses rather than widening.++That last sentence is the whole design. Every cross-tenant leak this codebase+has had took the same shape — a scope that was absent rather than narrow, and+a read that treated absent as "no filter".++We verify HS256 by hand with the standard library rather than adding a JWT+dependency to five services, exactly as ``services/realtime/src/auth.ts`` does+for the same reason on the Node side. ``services/api`` remains the sole issuer;+this is a read path, like the vendored ``decrypt_dict()`` that lets the+connector scheduler decrypt without owning the write path.++Configuration+-------------+``SECRET_KEY``+ The HS256 secret ``services/api`` signs console tokens with. Without it+ this service cannot verify a console session and will only accept service+ tokens.+``AISOC_SERVICE_TOKEN`` / ``AISOC_<SERVICE>_SERVICE_TOKEN``+ Shared secret for service-to-service calls, resolved by+ ``app.security.service_auth.resolve_token`` where that module exists.+``AISOC_DEV_MODE``+ When set and *no* credential material is configured at all, requests+ resolve to the demo tenant so a local ``docker compose up`` works. This is+ the single canonical dev-mode flag; ``tests/test_security_defaults.py``+ asserts no shortcut is reachable when it is unset.+"""++from __future__ import annotations++import base64+import binascii+import hashlib+import hmac+import json+import logging+import os+import time+import uuid+from dataclasses import dataclass, field++from fastapi import Header, HTTPException, status++#: Set by each vendored copy so the per-service token override resolves.+SERVICE_NAME = "THREATINTEL"++logger = logging.getLogger("aisoc.tenant_scope")++_TRUTHY = {"1", "true", "yes", "on"}++#: Mirrors ``INSECURE_SECRET_KEY_DEFAULTS`` in services/api/app/core/config.py+#: so a placeholder secret is treated as "unset" on this side too. Verifying a+#: token signed with a well-known literal would authenticate anybody who read+#: the repository.+INSECURE_SECRET_DEFAULTS = frozenset(+ {+ "change-me-in-production-at-least-32-chars",+ "dev_secret_key_change_in_production",+ "changeme",+ "secret",+ }+)++#: Deterministic demo tenant, matching ``DEMO_TENANT_ID`` in+#: services/api/app/api/v1/dev_auth.py. Only ever used under AISOC_DEV_MODE.+DEV_TENANT_ID = uuid.UUID("00000000-0000-0000-0000-000000000001")++#: Header a trusted service uses to declare which tenant it is acting for.+TENANT_HEADER = "X-AiSOC-Tenant-ID"++#: 30s clock-skew leeway, matching the Node verifier and common JWT defaults.+_CLOCK_SKEW_SECONDS = 30++#: Refs that mean "the caller did not name a tenant" rather than naming one.+#: Several request models default ``tenant_id`` to the string ``"default"``,+#: which is a placeholder, not a tenant — migration 001 seeds the canonical+#: tenant with that *slug* and the demo seed renames it, so the literal+#: identifies nothing anywhere. Treating it as a request for a tenant called+#: "default" would refuse every caller who simply left the field alone.+PLACEHOLDER_TENANT_REFS = frozenset({"", "default", "none", "null"})+++class TenantScopeError(Exception):+ """A read was attempted without a resolved tenant scope.++ Raised by :func:`resolve_scoped_tenant`. Routes let it surface as a 403;+ it means a query was about to run with no tenant filter, or with one the+ caller is not authorised for.+ """+++@dataclass(frozen=True)+class TenantPrincipal:+ """The tenants one credential may read, and what kind of credential it is.++ ``tenant_ids`` is authoritative and exhaustive. Nothing downstream may+ widen it, and no code path may substitute "all tenants" for an empty one.+ """++ tenant_ids: frozenset[uuid.UUID] = field(default_factory=frozenset)+ subject: str = "anonymous"+ #: True when a service token asserted the tenant rather than a verified+ #: console claim carrying it. Surfaced so logs can tell the two apart.+ delegated: bool = False++ @property+ def is_empty(self) -> bool:+ return not self.tenant_ids++ def covers(self, tenant_id: uuid.UUID) -> bool:+ return tenant_id in self.tenant_ids++ def ordered_ids(self) -> list[uuid.UUID]:+ return sorted(self.tenant_ids)+++EMPTY_PRINCIPAL = TenantPrincipal()+++def resolve_scoped_tenant(+ principal: TenantPrincipal,+ requested: uuid.UUID | str | None = None,+) -> uuid.UUID:+ """The one tenant this request may read, or refuse to name one.++ Intersection only. A ``requested`` tenant inside the principal's scope is+ honoured — that is an MSSP operator narrowing to one managed customer. A+ ``requested`` tenant outside it narrows to nothing and raises, rather than+ reaching outside. Passing ``None`` means "the caller's own tenant", which+ is the common case and the safe default.+ """+ if principal.is_empty:+ raise TenantScopeError("refusing to read with an empty tenant scope")++ if isinstance(requested, str) and requested.strip().lower() in PLACEHOLDER_TENANT_REFS:+ requested = None++ if requested is None:+ if len(principal.tenant_ids) != 1:+ raise TenantScopeError(f"caller reaches {len(principal.tenant_ids)} tenants; the request must name one")+ return next(iter(principal.tenant_ids))++ try:+ wanted = requested if isinstance(requested, uuid.UUID) else uuid.UUID(str(requested))+ except (ValueError, AttributeError, TypeError) as exc:+ raise TenantScopeError("requested tenant is not a UUID") from exc++ if not principal.covers(wanted):+ # Logged at warning with the subject, because a caller reaching for a+ # tenant they do not hold is a security event, not routine noise.+ logger.warning(+ "tenant_scope.refused subject=%s requested=%s scope_size=%d",+ # Sanitised inline rather than through a helper: CodeQL does not+ # track a helper across the call boundary, and `subject` really is+ # attacker-influenced — it carries the JWT `sub` claim.+ str(principal.subject).replace("\r", "").replace("\n", " ")[:128],+ str(wanted).replace("\r", "").replace("\n", " ")[:64],+ len(principal.tenant_ids),+ )+ raise TenantScopeError("requested tenant is outside the caller's authorised scope")+ return wanted+++# ---------------------------------------------------------------------------+# Credential resolution+# ---------------------------------------------------------------------------+++def _dev_mode() -> bool:+ return os.getenv("AISOC_DEV_MODE", "").strip().lower() in _TRUTHY+++def resolve_console_secret() -> str:+ """The HS256 secret console tokens are signed with, or "" when unusable."""+ secret = (os.getenv("SECRET_KEY") or "").strip()+ if not secret or secret in INSECURE_SECRET_DEFAULTS:+ return ""+ return secret+++def resolve_service_token() -> str:+ """Per-service override wins, then the shared platform token."""+ specific = os.getenv(f"AISOC_{SERVICE_NAME}_SERVICE_TOKEN", "").strip()+ if specific:+ return specific+ return os.getenv("AISOC_SERVICE_TOKEN", "").strip()+++def _b64url_decode(segment: str) -> bytes:+ padding = "=" * (-len(segment) % 4)+ return base64.urlsafe_b64decode(segment + padding)+++def verify_console_token(token: str, secret: str) -> dict | None:+ """Verify a first-party HS256 access token. Return claims, or None.++ Mirrors ``verifyRealtimeTicket`` in services/realtime/src/auth.ts. The+ signing side is ``create_access_token`` in services/api/app/core/security.py+ and must stay in sync with the claims checked here.+ """+ if not token or not secret:+ return None+ parts = token.split(".")+ if len(parts) != 3:+ return None+ header_b64, payload_b64, sig_b64 = parts++ try:+ header = json.loads(_b64url_decode(header_b64))+ except (ValueError, binascii.Error, UnicodeDecodeError):+ return None+ # Reject "alg: none" and asymmetric algorithms so a caller cannot downgrade+ # the verification into no verification at all.+ if not isinstance(header, dict) or header.get("alg") != "HS256":+ return None++ expected = hmac.new(+ secret.encode("utf-8"),+ f"{header_b64}.{payload_b64}".encode(),+ hashlib.sha256,+ ).digest()+ try:+ provided = _b64url_decode(sig_b64)+ except (ValueError, binascii.Error):+ return None+ if not hmac.compare_digest(expected, provided):+ return None++ try:+ claims = json.loads(_b64url_decode(payload_b64))+ except (ValueError, binascii.Error, UnicodeDecodeError):+ return None+ if not isinstance(claims, dict):+ return None++ # A refresh token must not buy access; the API sets type="access" on the+ # short-lived one and type="refresh" on the long-lived one.+ if claims.get("type") != "access":+ return None+ exp = claims.get("exp")+ if not isinstance(exp, int | float):+ return None+ if exp + _CLOCK_SKEW_SECONDS < time.time():+ return None+ if not claims.get("tenant_id"):+ return None+ return claims+++def _principal_from_claims(claims: dict) -> TenantPrincipal | None:+ try:+ tenant = uuid.UUID(str(claims["tenant_id"]))+ except (KeyError, ValueError, TypeError):+ return None+ return TenantPrincipal(+ tenant_ids=frozenset({tenant}),+ subject=f"console:{claims.get('sub', 'unknown')}",+ delegated=False,+ )+++async def require_console_or_service_auth(+ authorization: str | None = Header(default=None),+ x_aisoc_tenant_id: str | None = Header(default=None, alias=TENANT_HEADER),+) -> TenantPrincipal:+ """FastAPI dependency. Resolve the caller's tenant scope, or fail closed.++ Order matters only for clarity — the two credential shapes are disjoint. A+ console token carries its own tenant; a service token must declare one.+ """+ console_secret = resolve_console_secret()+ service_token = resolve_service_token()++ if not console_secret and not service_token:+ if _dev_mode():+ return TenantPrincipal(+ tenant_ids=frozenset({DEV_TENANT_ID}),+ subject="dev",+ delegated=False,+ )+ # No credential material configured at all: refuse to serve rather+ # than serve openly. This is the same fail-closed posture as+ # ``require_service_auth``.+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail=(+ "tenant-scoped auth is not configured; set SECRET_KEY and/or "+ f"AISOC_SERVICE_TOKEN (or AISOC_{SERVICE_NAME}_SERVICE_TOKEN) "+ "before exposing this service"+ ),+ )++ if not authorization or not authorization.startswith("Bearer "):+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="missing bearer credential",+ headers={"WWW-Authenticate": "Bearer"},+ )+ token = authorization[len("Bearer ") :].strip()++ # --- console session ---+ if console_secret:+ claims = verify_console_token(token, console_secret)+ if claims is not None:+ principal = _principal_from_claims(claims)+ if principal is not None:+ return principal++ # --- trusted service acting for a declared tenant ---+ if service_token and hmac.compare_digest(token, service_token):+ if not x_aisoc_tenant_id or not x_aisoc_tenant_id.strip():+ # An absent tenant is an empty scope, never every scope.+ logger.warning(+ "tenant_scope.service_token_without_tenant service=%s header=%s",+ SERVICE_NAME,+ TENANT_HEADER,+ )+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail=f"service token must declare the tenant it acts for on {TENANT_HEADER}",+ )+ try:+ tenant = uuid.UUID(x_aisoc_tenant_id.strip())+ except ValueError:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail=f"{TENANT_HEADER} must be a UUID",+ ) from None+ return TenantPrincipal(+ tenant_ids=frozenset({tenant}),+ subject="service",+ delegated=True,+ )++ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="invalid or missing credential",+ headers={"WWW-Authenticate": "Bearer"},+ )+++def scoped_tenant_or_403(+ principal: TenantPrincipal,+ requested: uuid.UUID | str | None = None,+) -> uuid.UUID:+ """:func:`resolve_scoped_tenant`, surfaced to HTTP as 403.++ Routes call this so the refusal reaches the client as a refusal rather+ than a 500, without every route repeating the try/except.+ """+ try:+ return resolve_scoped_tenant(principal, requested)+ except TenantScopeError as exc:+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from excdiff --git a/services/threatintel/tests/test_tenant_scope.py b/services/threatintel/tests/test_tenant_scope.pynew file mode 100644index 000000000..f2c30dded--- /dev/null+++ b/services/threatintel/tests/test_tenant_scope.py@@ -0,0 +1,274 @@+"""Unit tests for the vendored tenant-scope resolver.++Vendored byte-identical into each service that carries+``app/security/tenant_scope.py``, and kept in lockstep by+``scripts/sync_vendored_tenant_scope.py``. The module is the thing that+decides which tenant a request may read, so every copy is tested where it+lives rather than trusting that the one covered by ``tests/isolation`` stands+in for the other five.++The cross-service two-tenant replay lives in+``tests/isolation/test_route_tenant_scope.py``; this file covers the+credential and intersection logic on its own.+"""++from __future__ import annotations++import base64+import hashlib+import hmac+import json+import time+import uuid++import pytest+from app.security import tenant_scope as ts+from fastapi import HTTPException++SECRET = "unit-test-secret-key-at-least-32-characters"+SERVICE_TOKEN = "unit-test-service-token"++TENANT_A = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")+TENANT_B = uuid.UUID("bbbbbbbb-0000-0000-0000-00000000000b")+++def _b64(raw: bytes) -> str:+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()+++def _token(+ tenant: uuid.UUID | None = TENANT_A,+ *,+ secret: str = SECRET,+ alg: str = "HS256",+ token_type: str = "access",+ ttl: int = 600,+ sub: str = "user-1",+) -> str:+ header = _b64(json.dumps({"alg": alg, "typ": "JWT"}, separators=(",", ":")).encode())+ claims: dict[str, object] = {"sub": sub, "type": token_type, "exp": int(time.time()) + ttl}+ if tenant is not None:+ claims["tenant_id"] = str(tenant)+ payload = _b64(json.dumps(claims, separators=(",", ":")).encode())+ sig = _b64(hmac.new(secret.encode(), f"{header}.{payload}".encode(), hashlib.sha256).digest())+ return f"{header}.{payload}.{sig}"++[email protected](autouse=True)+def _configured(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("SECRET_KEY", SECRET)+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)+ monkeypatch.delenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", raising=False)+++# ---------------------------------------------------------------------------+# Token verification+# ---------------------------------------------------------------------------+++def test_valid_token_yields_its_tenant() -> None:+ claims = ts.verify_console_token(_token(), SECRET)+ assert claims is not None and claims["tenant_id"] == str(TENANT_A)+++ ("label", "kwargs"),+ [+ # An `alg: none` header is the classic downgrade: a verifier that+ # reads the header to decide how to verify must refuse anything else.+ ("alg none", {"alg": "none"}),+ ("wrong key", {"secret": "a-completely-different-secret-key-32ch"}),+ # A refresh token is long-lived by design; buying access with it would+ # make the short access-token expiry meaningless.+ ("refresh token", {"token_type": "refresh"}),+ ("expired", {"ttl": -3600}),+ ("no tenant claim", {"tenant": None}),+ ],+)+def test_unacceptable_tokens_are_refused(label: str, kwargs: dict) -> None:+ assert ts.verify_console_token(_token(**kwargs), SECRET) is None, label++[email protected]("malformed", ["", "not-a-jwt", "a.b", "a.b.c.d", "...", "%%%.%%%.%%%"])+def test_malformed_tokens_are_refused(malformed: str) -> None:+ assert ts.verify_console_token(malformed, SECRET) is None+++def test_no_secret_means_no_verification() -> None:+ """An unconfigured secret must not verify anything, least of all everything."""+ assert ts.verify_console_token(_token(), "") is None+++def test_placeholder_secrets_count_as_unset() -> None:+ for placeholder in ts.INSECURE_SECRET_DEFAULTS:+ assert ts.resolve_console_secret.__doc__ # module contract exists+ assert placeholder in ts.INSECURE_SECRET_DEFAULTS+++# ---------------------------------------------------------------------------+# Intersection+# ---------------------------------------------------------------------------+++def _principal(*tenants: uuid.UUID) -> ts.TenantPrincipal:+ return ts.TenantPrincipal(tenant_ids=frozenset(tenants), subject="console:test")+++def test_no_request_tenant_means_the_callers_own() -> None:+ assert ts.resolve_scoped_tenant(_principal(TENANT_A)) == TENANT_A+++def test_a_tenant_inside_scope_is_honoured() -> None:+ assert ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B), TENANT_B) == TENANT_B+++def test_a_tenant_outside_scope_narrows_to_nothing() -> None:+ with pytest.raises(ts.TenantScopeError):+ ts.resolve_scoped_tenant(_principal(TENANT_A), TENANT_B)+++def test_empty_scope_refuses_rather_than_widening() -> None:+ """The invariant every cross-tenant leak in this codebase has broken."""+ with pytest.raises(ts.TenantScopeError):+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL)+ with pytest.raises(ts.TenantScopeError):+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, TENANT_A)+++def test_a_multi_tenant_caller_must_name_one() -> None:+ """Silently picking one of several would be a coin toss over customers."""+ with pytest.raises(ts.TenantScopeError):+ ts.resolve_scoped_tenant(_principal(TENANT_A, TENANT_B))+++def test_a_non_uuid_request_tenant_is_refused() -> None:+ with pytest.raises(ts.TenantScopeError):+ ts.resolve_scoped_tenant(_principal(TENANT_A), "not-a-uuid")++[email protected]("placeholder", ["", " ", "default", "DEFAULT", "none", "null"])+def test_a_placeholder_means_the_caller_did_not_ask(placeholder: str) -> None:+ """A placeholder is the absence of a request, not a tenant named "default".++ Several request models default `tenant_id` to the literal `"default"`.+ That string names no tenant anywhere — migration 001 seeds the canonical+ tenant with it as a *slug* and the demo seed renames that to `demo` — so+ treating it as a requested tenant would refuse every caller who left the+ field at its default.+ """+ assert ts.resolve_scoped_tenant(_principal(TENANT_A), placeholder) == TENANT_A+++def test_a_placeholder_still_cannot_widen_an_empty_scope() -> None:+ with pytest.raises(ts.TenantScopeError):+ ts.resolve_scoped_tenant(ts.EMPTY_PRINCIPAL, "default")+++def test_scoped_tenant_or_403_surfaces_a_refusal_as_403() -> None:+ with pytest.raises(HTTPException) as exc:+ ts.scoped_tenant_or_403(_principal(TENANT_A), TENANT_B)+ assert exc.value.status_code == 403+++# ---------------------------------------------------------------------------+# The dependency+# ---------------------------------------------------------------------------+++# `require_console_or_service_auth` is a FastAPI dependency: its parameters+# are normally resolved by FastAPI from the request. Calling it directly means+# supplying both, including the tenant header as an explicit `None` — leaving+# it out hands the function FastAPI's `Header(...)` sentinel rather than the+# absent value the test means to describe.+++async def test_console_session_resolves_to_its_own_tenant() -> None:+ principal = await ts.require_console_or_service_auth(authorization=f"Bearer {_token()}", x_aisoc_tenant_id=None)+ assert principal.tenant_ids == frozenset({TENANT_A})+ assert principal.delegated is False+++async def test_service_token_must_declare_the_tenant_it_acts_for() -> None:+ """A service credential identifies a service, not a tenant."""+ with pytest.raises(HTTPException) as exc:+ await ts.require_console_or_service_auth(authorization=f"Bearer {SERVICE_TOKEN}", x_aisoc_tenant_id=None)+ assert exc.value.status_code == 403+++async def test_service_token_with_a_declared_tenant_is_delegated() -> None:+ principal = await ts.require_console_or_service_auth(+ authorization=f"Bearer {SERVICE_TOKEN}",+ x_aisoc_tenant_id=str(TENANT_B),+ )+ assert principal.tenant_ids == frozenset({TENANT_B})+ assert principal.delegated is True+++async def test_a_declared_tenant_must_be_a_uuid() -> None:+ with pytest.raises(HTTPException) as exc:+ await ts.require_console_or_service_auth(+ authorization=f"Bearer {SERVICE_TOKEN}",+ x_aisoc_tenant_id="the-big-customer",+ )+ assert exc.value.status_code == 400++[email protected]("header", [None, "", "Basic abc", "Bearer ", "Bearer nonsense"])+async def test_a_missing_or_unrecognised_credential_is_401(header: str | None) -> None:+ with pytest.raises(HTTPException) as exc:+ await ts.require_console_or_service_auth(authorization=header, x_aisoc_tenant_id=None)+ assert exc.value.status_code == 401+++async def test_unconfigured_credentials_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None:+ """No credential material and no dev mode serves 503, never the route."""+ monkeypatch.setenv("SECRET_KEY", "")+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)+ with pytest.raises(HTTPException) as exc:+ await ts.require_console_or_service_auth(authorization="Bearer anything", x_aisoc_tenant_id=None)+ assert exc.value.status_code == 503+++async def test_dev_mode_only_applies_with_nothing_configured(monkeypatch: pytest.MonkeyPatch) -> None:+ """Dev mode is a fallback for an unconfigured stack, not an auth bypass.++ With a secret configured, `AISOC_DEV_MODE` must not let an unauthenticated+ caller through — otherwise setting one flag in the wrong environment opens+ every tenant-scoped route.+ """+ monkeypatch.setenv("AISOC_DEV_MODE", "1")+ monkeypatch.setenv("SECRET_KEY", SECRET)+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)+ with pytest.raises(HTTPException) as exc:+ await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)+ assert exc.value.status_code == 401++ monkeypatch.setenv("SECRET_KEY", "")+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")+ principal = await ts.require_console_or_service_auth(authorization=None, x_aisoc_tenant_id=None)+ assert principal.tenant_ids == frozenset({ts.DEV_TENANT_ID})+++async def test_a_per_service_token_override_wins(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(f"AISOC_{ts.SERVICE_NAME}_SERVICE_TOKEN", "service-specific")+ principal = await ts.require_console_or_service_auth(+ authorization="Bearer service-specific",+ x_aisoc_tenant_id=str(TENANT_A),+ )+ assert principal.delegated is True+ # The shared token must no longer be accepted once an override exists.+ with pytest.raises(HTTPException):+ await ts.require_console_or_service_auth(+ authorization=f"Bearer {SERVICE_TOKEN}",+ x_aisoc_tenant_id=str(TENANT_A),+ )diff --git a/tests/isolation/README.md b/tests/isolation/README.mdindex 17f0be31a..e10ed8f7c 100644--- a/tests/isolation/README.md+++ b/tests/isolation/README.md@@ -31,12 +31,37 @@ intersecting it with the caller's scope. `--self-test` injects a violation ofeach kind plus a stale exemption and asserts all three are caught, because agate nobody has seen fail is indistinguishable from one that cannot.-The resolver is vendored into six services (each is built with its own+The resolver is vendored into eight services (each is built with its owndirectory as its Docker context, the same reason `service_auth.py` and`cors.py` are vendored), so `sync_vendored_tenant_scope.py --check` runsalongside it: a fix that lands in one copy and not the others is a fix innone.+## The two shapes that question could not reach++`test_route_auth_default_deny.py` covers the rest of the surface, because the+gate above asks a *conditional* question and two shapes fall outside it.++**A route that takes no tenant was never in its reach.** 37 routes in+`services/agents` took none, and they included create, delete and *execute* a+response playbook. The suite drives the real routers over ASGI with credential+material configured — so a refusal is about the credential, not about an+unconfigured service — and asserts an anonymous caller is refused on every one+of them, that a valid console session still gets a non-empty response, that a+service token declaring no tenant is a 403, and that forged, expired,+`alg: none` and refresh tokens are each refused. `scripts/check_route_auth.py`+holds the line repo-wide: every route authenticates or appears in one of three+tables with its reason, and an entry that no longer matches an unauthenticated+route fails as stale.++**A route that matches on an id takes no tenant, which is exactly why it was+missing the filter.** `scripts/check_tenant_query_predicates.py` asks the+predicate question instead, deriving both the tenant-scoped models and the+tenant-scoped tables from the tree rather than from a list. The live half+seeds two tenants against a real database and asserts both hold rows *before*+asserting either absence — a scoped read against an empty table passes for the+wrong reason — then has tenant B name tenant A's `query_id` and get nothing.+## Two layers1. **Offline (gated on every PR, `.github/workflows/isolation.yml`).** Assertsdiff --git a/tests/isolation/test_route_auth_default_deny.py b/tests/isolation/test_route_auth_default_deny.pynew file mode 100644index 000000000..be221fdfb--- /dev/null+++ b/tests/isolation/test_route_auth_default_deny.py@@ -0,0 +1,294 @@+"""Default-deny routes, and by-id reads that carry a tenant predicate.++``test_route_tenant_scope.py`` covers the question "where did the tenant come+from" for routes that take one. This file covers the two shapes that question+could not reach.++**Routes with no auth dependency at all.** ``services/agents`` had 37. None of+them took a tenant, so the parameter gate never looked at them, and they+included ``POST /api/v1/playbooks``, ``DELETE /api/v1/playbooks/{id}`` and+``POST /api/v1/playbooks/{id}/run`` — create, delete and *execute* a response+playbook, for a caller holding no credential. Reproduced below against the+real routers over ASGI, with credential material configured, so the result is+not "the service was unconfigured".++**Reads addressed by an id with no tenant predicate.** A ``query_id`` was a+bearer capability for another tenant's osquery results: ``osquery_distributed_+query`` carries no ``tenant_id`` of its own, it is scoped through the node it+was sent to, and the lookup never joined. Seeded here for two tenants against+a real database, with both tenants' rows asserted present before anything is+asserted absent — a scoped read against an empty table passes for the wrong+reason.++Three layers, same as the neighbouring file: live routers, live store, and a+meta-assertion that the repository-wide gates stay green so neither shape can+come back without this suite noticing.+"""++from __future__ import annotations++import subprocess+import sys+import uuid+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]+AGENTS_ROOT = REPO_ROOT / "services" / "agents"+OSQUERY_ROOT = REPO_ROOT / "services" / "osquery-tls"++TENANT_A = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")+TENANT_B = uuid.UUID("bbbbbbbb-0000-0000-0000-00000000000b")++SECRET = "isolation-suite-secret-key-at-least-32-chars"+SERVICE_TOKEN = "isolation-suite-service-token"++# Reuse the token minter from the sibling suite rather than writing a second+# one: two implementations of "what a valid session looks like" drift, and the+# drift shows up as a test that passes against a token the service rejects.+sys.path.insert(0, str(Path(__file__).resolve().parent))+from test_route_tenant_scope import console_token # noqa: E402++# ---------------------------------------------------------------------------+# Layer 1 — services/agents answers nobody without a credential+# ---------------------------------------------------------------------------+++def agents_app(monkeypatch: pytest.MonkeyPatch):+ """The real agents routers, mounted with credential material configured."""+ monkeypatch.setenv("SECRET_KEY", SECRET)+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", SERVICE_TOKEN)+ monkeypatch.delenv("AISOC_DEV_MODE", raising=False)+ monkeypatch.syspath_prepend(str(AGENTS_ROOT))++ pytest.importorskip("httpx")+ from app.api.contextual import router as contextual_router # noqa: PLC0415+ from app.api.copilot import router as copilot_router # noqa: PLC0415+ from app.api.hunt_search import router as hunt_search_router # noqa: PLC0415+ from app.api.playbooks import router as playbooks_router # noqa: PLC0415+ from fastapi import FastAPI # noqa: PLC0415++ app = FastAPI()+ for router in (playbooks_router, copilot_router, hunt_search_router, contextual_router):+ app.include_router(router)+ return app+++#: (method, path, json) for routes that were reachable with no credential.+#: The three playbook entries are the ones that mattered: they create, execute+#: and delete a response playbook.+_AGENT_ROUTES = [+ ("POST", "/api/v1/playbooks", {"id": "probe", "name": "p", "enabled": True, "trigger": {"type": "manual"}, "steps": []}),+ ("GET", "/api/v1/playbooks", None),+ ("POST", "/api/v1/playbooks/probe/run", {"context": {}, "dry_run": True}),+ ("DELETE", "/api/v1/playbooks/probe", None),+ ("GET", "/api/v1/copilot/conversations", None),+ ("POST", "/api/v1/hunt/search", {"query": "*", "limit": 1}),+ ("GET", "/api/v1/contextual/actions", None),+]++[email protected](("method", "path", "body"), _AGENT_ROUTES)+async def test_agents_routes_refuse_an_anonymous_caller(agents_app, method: str, path: str, body: dict | None) -> None:+ """No credential at all — including on the routes that change state."""+ import httpx # noqa: PLC0415++ transport = httpx.ASGITransport(app=agents_app)+ async with httpx.AsyncClient(transport=transport, base_url="http://agents.test") as client:+ resp = await client.request(method, path, json=body)+ assert resp.status_code == 401, f"{method} {path} answered an anonymous caller with {resp.status_code}: {resp.text[:200]}"+++async def test_agents_routes_still_serve_a_real_console_session(agents_app) -> None:+ """The refusal must be about the credential, not about the route.++ A default-deny pass that returns 401 to everybody is indistinguishable+ from one that broke the console, and the console reaches these routes+ directly through a Next rewrite.+ """+ import httpx # noqa: PLC0415++ transport = httpx.ASGITransport(app=agents_app)+ headers = {"Authorization": f"Bearer {console_token(TENANT_A)}"}+ async with httpx.AsyncClient(transport=transport, base_url="http://agents.test") as client:+ listed = await client.get("/api/v1/playbooks", headers=headers)+ actions = await client.get("/api/v1/contextual/actions", headers=headers)++ assert listed.status_code == 200, f"a valid console session was refused: {listed.text[:200]}"+ assert isinstance(listed.json(), list) and listed.json(), "the playbook corpus came back empty — this assertion would be vacuous"+ assert actions.status_code == 200+++async def test_agents_routes_refuse_a_service_token_that_declares_no_tenant(agents_app) -> None:+ """A service token identifies a service, not a tenant. Absent is not all."""+ import httpx # noqa: PLC0415++ transport = httpx.ASGITransport(app=agents_app)+ async with httpx.AsyncClient(transport=transport, base_url="http://agents.test") as client:+ undeclared = await client.get("/api/v1/playbooks", headers={"Authorization": f"Bearer {SERVICE_TOKEN}"})+ declared = await client.get(+ "/api/v1/playbooks",+ headers={"Authorization": f"Bearer {SERVICE_TOKEN}", "X-AiSOC-Tenant-ID": str(TENANT_B)},+ )+ assert undeclared.status_code == 403+ assert declared.status_code == 200+++async def test_agents_routes_refuse_a_forged_or_expired_session(agents_app) -> None:+ import httpx # noqa: PLC0415++ transport = httpx.ASGITransport(app=agents_app)+ forged = console_token(TENANT_A, secret="a-different-secret-key-at-least-32-chars")+ expired = console_token(TENANT_A, ttl=-3600)+ unsigned = console_token(TENANT_A, alg="none")+ refresh = console_token(TENANT_A, token_type="refresh")+ async with httpx.AsyncClient(transport=transport, base_url="http://agents.test") as client:+ for label, token in (("forged", forged), ("expired", expired), ("alg none", unsigned), ("refresh", refresh)):+ resp = await client.get("/api/v1/playbooks", headers={"Authorization": f"Bearer {token}"})+ assert resp.status_code == 401, f"{label} token was accepted ({resp.status_code})"+++# ---------------------------------------------------------------------------+# Layer 2 — a by-id read, seeded for two tenants against a real database+# ---------------------------------------------------------------------------+++async def test_distributed_query_status_is_scoped_through_its_node() -> None:+ """Seed A and B for real, then read A's query_id as B.++ ``osquery_distributed_query`` has no ``tenant_id`` column — it is reached+ through ``osquery_node`` — so the lookup has to join. Before the join it+ matched on ``query_id`` alone, which made the id a bearer capability for+ another tenant's host telemetry.+ """+ pytest.importorskip("aiosqlite")+ # SQLAlchemy's async layer needs greenlet; skip rather than fail where the+ # extra is not installed, the way the Redis-backed suites skip.+ pytest.importorskip("greenlet")++ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine # noqa: PLC0415++ # Every service in this repo roots its package at `app`, so whichever one+ # imported first owns the name for the rest of the session. Swap the+ # binding for the duration rather than relying on collection order — the+ # agents fixture above has already claimed it.+ saved_modules = {name: mod for name, mod in sys.modules.items() if name == "app" or name.startswith("app.")}+ saved_path = list(sys.path)+ for name in saved_modules:+ del sys.modules[name]+ sys.path.insert(0, str(OSQUERY_ROOT))+ try:+ from app.db.base import Base # noqa: PLC0415+ from app.models.distributed_query import OsqueryDistributedQuery # noqa: PLC0415+ from app.models.node import OsqueryNode # noqa: PLC0415+ from app.services.distributed_queue import get_query_by_id # noqa: PLC0415+ finally:+ sys.path[:] = saved_path++ engine = create_async_engine("sqlite+aiosqlite:///:memory:")+ try:+ async with engine.begin() as conn:+ await conn.run_sync(Base.metadata.create_all)+ session_factory = async_sessionmaker(engine, expire_on_commit=False)++ async with session_factory() as db:+ node_a = OsqueryNode(host_identifier="a-dc-01", node_key="key-a", tenant_id=str(TENANT_A))+ node_b = OsqueryNode(host_identifier="b-lap-09", node_key="key-b", tenant_id=str(TENANT_B))+ db.add_all([node_a, node_b])+ await db.flush()+ query_a = OsqueryDistributedQuery(+ node_id=node_a.id,+ query_id="query-owned-by-tenant-a",+ query_text="SELECT * FROM users;",+ status="completed",+ results_json=[{"username": "ceo", "uid": 0}],+ )+ query_b = OsqueryDistributedQuery(+ node_id=node_b.id,+ query_id="query-owned-by-tenant-b",+ query_text="SELECT * FROM processes;",+ status="completed",+ results_json=[{"name": "intern-laptop"}],+ )+ db.add_all([query_a, query_b])+ await db.commit()++ # Non-vacuity first: if neither row exists, every assertion below+ # is trivially true and proves nothing about the scoping.+ own_a = await get_query_by_id(db, "query-owned-by-tenant-a", TENANT_A)+ own_b = await get_query_by_id(db, "query-owned-by-tenant-b", TENANT_B)+ assert own_a is not None, "tenant A seeded no query — the assertions below would be vacuous"+ assert own_b is not None, "tenant B seeded no query — the assertions below would be vacuous"+ assert own_a.results_json == [{"username": "ceo", "uid": 0}]++ # The read that used to succeed.+ leaked = await get_query_by_id(db, "query-owned-by-tenant-a", TENANT_B)+ assert leaked is None, "tenant B read tenant A's distributed-query results by naming its query_id"++ crossed = await get_query_by_id(db, "query-owned-by-tenant-b", TENANT_A)+ assert crossed is None, "tenant A read tenant B's distributed-query results"+ finally:+ await engine.dispose()+ for name in [n for n in sys.modules if n == "app" or n.startswith("app.")]:+ del sys.modules[name]+ sys.modules.update(saved_modules)+++# ---------------------------------------------------------------------------+# Layer 3 — the repository-wide gates+# ---------------------------------------------------------------------------+++def _run_gate(script: str, *args: str) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ [sys.executable, str(REPO_ROOT / "scripts" / script), *args],+ capture_output=True,+ text=True,+ cwd=REPO_ROOT,+ )+++def test_every_route_authenticates_or_records_why_not() -> None:+ result = _run_gate("check_route_auth.py")+ assert result.returncode == 0, f"check_route_auth reported violations:\n{result.stdout}\n{result.stderr}"+++def test_route_auth_gate_detects_injected_drift() -> None:+ result = _run_gate("check_route_auth.py", "--self-test")+ assert result.returncode == 0, f"route-auth gate self-test failed:\n{result.stdout}\n{result.stderr}"+++def test_every_tenant_scoped_query_carries_a_tenant_predicate() -> None:+ result = _run_gate("check_tenant_query_predicates.py")+ assert result.returncode == 0, f"check_tenant_query_predicates reported violations:\n{result.stdout}\n{result.stderr}"+++def test_tenant_predicate_gate_detects_injected_drift() -> None:+ result = _run_gate("check_tenant_query_predicates.py", "--self-test")+ assert result.returncode == 0, f"tenant-predicate gate self-test failed:\n{result.stdout}\n{result.stderr}"+++def test_gates_name_what_they_scanned() -> None:+ """A gate that prints OK without saying what it opened is not evidence.++ Both gates resolve their root from ``git rev-parse`` rather than+ ``__file__`` — a previous gate in this repository would have printed a+ confident OK about a tree it never opened.+ """+ for script, needle in (+ ("check_route_auth.py", "scanned 601 routes"),+ ("check_tenant_query_predicates.py", "statements touch"),+ ):+ result = _run_gate(script)+ assert result.returncode == 0, result.stderr+ assert "scanned" in result.stdout, f"{script} did not say what it scanned"+ if needle.startswith("scanned "):+ # Route count is allowed to move; assert the shape, not the number.+ assert "routes across" in result.stdout and "files under" in result.stdout