Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(connectors): scope the resource-config route to the caller's own tenant (#1496)
Beenu Arora85ce5f59d5f5
diff --git a/.github/workflows/connector-tenant-scope-live.yml b/.github/workflows/connector-tenant-scope-live.ymlnew file mode 100644index 000000000..06875c9ef--- /dev/null+++ b/.github/workflows/connector-tenant-scope-live.yml@@ -0,0 +1,172 @@+# The connectors resource-config route, against real Postgres and a real vendor socket.+#+# Why this exists+# ---------------+# GET /api/v1/connectors/instances/{id}/resource-config decrypts a saved+# instance's vendor credential with the platform vault and spends it on an+# authenticated vendor call. It resolved that instance from the caller-supplied+# path id against *every* tenant's rows: the handler declared no principal, so+# the TenantPrincipal the router-level Depends had already resolved was thrown+# away, and the lookup underneath carried no tenant predicate. Any authenticated+# caller of any role could therefore have the platform read another tenant's+# cloud posture using that tenant's own credential, with the vendor-side audit+# trail naming the victim (GHSA-h4g5-39vv-pqfv).+#+# RLS is not a second line here. `connectors` carries a policy, but the+# connectors engine binds no `app.current_tenant_id`, so the policy's+# `OR current_tenant_id() IS NULL` arm fails open and the query-layer predicate+# is the only control.+#+# Why live, and why the vendor is a socket+# ----------------------------------------+# The finding is not "a row came back" — it is "the platform decrypted somebody+# else's secret and paid a vendor with it". The only way to assert that is to+# ask the vendor which credential it was paid with, so the vendor is a real HTTP+# server and the whole decrypt -> construct -> authenticate path runs. A mock+# that answers whatever it is asked cannot be asked that question.+#+# No `paths:` filter. A path filter here would mean the gate skips on exactly+# the pull request that reshapes the auth dependency it exists to protect.+name: Connector tenant scope (live)++on:+ push:+ branches: [main]+ pull_request:+ workflow_dispatch:++concurrency:+ # Keyed per commit on push and per pull request on PRs, never on `github.ref`+ # alone: that shape cancels the run for the commit before it, and a required+ # check that was cancelled never graded the commit it is reported against.+ group: connector-tenant-scope-live-${{ github.event_name }}-${{ github.event.pull_request.number || github.sha }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++permissions:+ contents: read++jobs:+ connector-tenant-scope-live:+ name: resource-config reaches only the caller's own tenant+ runs-on: ubuntu-latest+ timeout-minutes: 25++ env:+ # The runtime role, not the owner: a superuser ignores every RLS policy+ # even under FORCE ROW LEVEL SECURITY, so grading isolation as `aisoc`+ # would grade nothing.+ CONNECTOR_DSN: postgresql+asyncpg://aisoc_app:aisoc_app_ci_only@localhost:5432/aisoc+ PGPASSWORD: aisoc_ci_only+ AISOC_CONNECTORS_DISABLE_SCHEDULER: "1"+ # This proof owns its loopback vendor fixture. Keep the exception exact;+ # AISOC_SSRF_ALLOW_PRIVATE intentionally cannot admit loopback.+ AISOC_SSRF_ALLOW_HOSTS: 127.0.0.1+ SUITE: ../../tests/isolation/test_connector_resource_config_tenant_scope_live.py++ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7++ - name: Start PostgreSQL with registry fallback+ uses: ./.github/actions/start-postgres+ with:+ password: aisoc_ci_only++ - uses: actions/setup-python@e9d6f990972a57673cdb72ec29e19d42ba28880f # v6+ with:+ python-version: "3.11"++ # The service's own lockfile, not a hand-curated pip list: a suite that+ # drives the real application pulls in the real application's whole+ # import chain, and a set that differs from the lock tests software+ # nobody ships.+ - name: Install connectors from its lockfile+ working-directory: services/connectors+ run: |+ set -euo pipefail+ python -m pip install --quiet --upgrade pip "poetry==2.4.1"+ poetry config virtualenvs.create false+ poetry install --no-root --no-interaction+ python -m pip install --quiet pytest pytest-asyncio++ - name: Apply every migration, in order+ run: |+ set -euo pipefail+ for f in services/api/migrations/*.sql; do+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -f "$f"+ done++ - name: Give the runtime role its password+ run: |+ set -euo pipefail+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "ALTER ROLE aisoc_app WITH PASSWORD 'aisoc_app_ci_only';"+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "GRANT USAGE ON SCHEMA public TO aisoc_app;"++ # Proves the role the suite grades through cannot see around a policy.+ # Without it, a future change to the DSN could silently move this whole+ # job onto the owner and every isolation assertion would still pass.+ - name: Refuse to grade isolation as a role that bypasses RLS+ run: |+ set -euo pipefail+ privileged=$(psql -h localhost -U aisoc -d aisoc -tAc \+ "SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = 'aisoc_app';")+ if [ "$privileged" != "f" ]; then+ echo "FAIL: aisoc_app is SUPERUSER or BYPASSRLS, so this job would grade nothing."+ exit 1+ fi+ echo "OK: aisoc_app is neither SUPERUSER nor BYPASSRLS."++ - name: Mint a credential key for the vault+ run: |+ KEY=$(python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())")+ echo "AISOC_CREDENTIAL_KEY=$KEY" >> "$GITHUB_ENV"++ - name: A caller reaches its own tenant's instance and no other+ working-directory: services/connectors+ env:+ ISOLATION_CONNECTOR_DSN: ${{ env.CONNECTOR_DSN }}+ run: python -m pytest "$SUITE" -v --tb=short++ # The negative control, and it re-injects the real defect.+ #+ # The tenant predicate in `fetch_enabled_connector_for_tenant` is the+ # load-bearing half of the fix: without it the lookup is by id across+ # every tenant again, which is exactly what shipped. Removing it must+ # make this suite fail. If it does not, the suite is not driving the+ # production lookup and its green tick means nothing — which is worth+ # failing the build over, because the alternative is a check that+ # certifies tenant isolation while being blind to it.+ #+ # The guard above the edit is the part that keeps this honest over time:+ # if the predicate is ever reshaped so the string is not found, this+ # control fails loudly rather than passing by editing nothing.+ - name: The gate fails when the tenant predicate is removed+ working-directory: services/connectors+ env:+ ISOLATION_CONNECTOR_DSN: ${{ env.CONNECTOR_DSN }}+ run: |+ set -euo pipefail+ cp app/db/connector_repo.py /tmp/connector_repo.bak+ restore() { cp /tmp/connector_repo.bak app/db/connector_repo.py; }+ trap restore EXIT+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/db/connector_repo.py")+ s = p.read_text()+ needle = " connectors_table.c.tenant_id == tenant_id,\n"+ if needle not in s:+ print("FAIL: the tenant predicate this control removes is not there to remove.")+ print(" The lookup has been reshaped and this control proves nothing.")+ sys.exit(1)+ p.write_text(s.replace(needle, "", 1))+ PY+ if python -m pytest "$SUITE" -q >/dev/null 2>&1; then+ echo "FAIL: the suite passed with the tenant predicate removed."+ echo " It is not grading the production lookup."+ exit 1+ fi+ echo "OK: removing the tenant predicate makes the suite fail, as it must."+ restore+ trap - EXIT+ python -m pytest "$SUITE" -qdiff --git a/scripts/check_tenant_query_predicates.py b/scripts/check_tenant_query_predicates.pyindex d27b3d4c9..71f7cceeb 100644--- a/scripts/check_tenant_query_predicates.py+++ b/scripts/check_tenant_query_predicates.py@@ -66,6 +66,40 @@ Structural signals only, because a naming convention is exactly what drifts:Anything else is a finding, and must be on the ratchet with a reason.+Two arms, because a statement has no opinion about who calls it+---------------------------------------------------------------+The rule above asks whether a statement filters on a tenant. That is not+sufficient on its own, and GHSA-h4g5-39vv-pqfv is the proof: the connectors+scheduler's "every enabled instance, across every tenant" sweep is correctly+unscoped and correctly ratcheted — and a *request handler* was calling it,+picking one caller's row out of every tenant's by string-comparing an id, then+decrypting that row's vendor credential and spending it. Both halves read as+correct in isolation. Measured, with the Core-table rule below in place but+without this second arm, the gate reported OK on the vulnerable tree.++So the second arm asks: **which HTTP route handlers reach a statement that+carries no tenant predicate?** A sweep's exemption is earned by there being no+caller whose tenant it could have filtered on; a request handler has one, so+reaching it retires the justification. ``ROUTE_REACHABLE`` records the pairs+where a request legitimately may — pre-auth lookups, opaque-capability reads,+administrative surfaces that are cross-tenant by design, and handlers that+validated the key against the caller's tenant first — and it is a ratchet in+both directions like the other.++Two things it deliberately is not. It resolves a call through the importing+module rather than by bare name: a name-only pass invented five call paths+that do not exist, and a gate that fabricates findings gets switched off. And+it does not flag a *worker* calling the same sweep, because that caller is the+reason the exemption exists.++A third blind spot, found while measuring this and **not** closed here, is+recorded so it is not rediscovered as news: ``_TENANT_IN_SQL`` matches+``tenant_id`` anywhere in a raw statement, including the projection, so+``SELECT tenant_id, secret FROM t WHERE id = :id`` reads as scoped. The one+statement in this tree that relies on it (``scheduler.py``'s tenant+enumeration) is legitimately cross-tenant, so nothing is currently wrong —+but the rule is weaker than it looks.+Both directions---------------The dominant failure shape in this repository is the one-directional gate: it@@ -427,6 +461,41 @@ RATCHET: dict[str, str] = {"the sweep worker's 'which rooms are open' discovery, the same cross-tenant working-set ""shape as report_scheduler.run_once; sync_war_room then handles one room at a time"),+ # ── services/connectors, visible to this gate for the first time ────────+ # These six are not new queries. They are the six statements the Core-table+ # blindness hid (see build_inventory), surfacing together the moment the+ # gate could see the table at all. Each was read before being recorded.+ "services/connectors/app/db/connector_repo.py::fetch_enabled_connectors::connectors_table": (+ "the connector scheduler's working set: 'which instances are enabled', across every tenant, "+ "which cannot presuppose a tenant — the same discover-a-working-set shape as "+ "hunt_scheduler.run_once and oauth_refresh._select_due_connectors above. A tenant missing "+ "from it is a customer whose connectors silently stop ingesting. Its only two callers are "+ "ConnectorScheduler.reload_jobs and _poll_one, neither reachable from a request; the "+ "docstring now says a request handler must not call it, and the route that did "+ "(GHSA-h4g5-39vv-pqfv) takes fetch_enabled_connector_for_tenant, which filters in SQL"+ ),+ "services/connectors/app/db/connector_repo.py::record_poll_success::connectors_table": (+ "writes the poll outcome back to the row the sweep above already selected, by primary key — "+ "the same shape and the same reasoning as oauth_refresh._refresh_one. Sole caller is "+ "ConnectorScheduler (scheduler.py:875) passing an id from its own enumeration; no request "+ "input reaches it"+ ),+ "services/connectors/app/db/connector_repo.py::record_poll_failure::connectors_table": (+ "the failure counterpart of record_poll_success, keyed on the same swept primary key; sole caller scheduler.py:1111"+ ),+ "services/connectors/app/db/connector_repo.py::record_checkpoint::connectors_table": (+ "persists the ingest cursor onto the swept row by primary key; sole caller "+ "ConnectorScheduler._record_checkpoint (scheduler.py:950), which is handed target.id from "+ "the poll it just completed"+ ),+ "services/connectors/app/db/connector_repo.py::record_backfill_run::connectors_table": (+ "stamps the backfill timestamp on the swept row by primary key; sole caller "+ "ConnectorScheduler._record_backfill_run (scheduler.py:902)"+ ),+ "services/connectors/app/db/connector_repo.py::record_schema_drift::connectors_table": (+ "records a confirmed drift on the swept row by primary key; sole caller scheduler.py:926, "+ "which compares the fingerprint of the poll it just performed"+ ),}#: Raising this is a deliberate act with a diff attached. Appending to RATCHET@@ -495,7 +564,15 @@ RATCHET: dict[str, str] = {# in one run. The policy's unbound-session arm (fixed in the same train) is# what admits the runner's GUC-less session at the database; this entry is# what records the query-layer decision.-MAX_RATCHET = 54+# 54 -> 60 (GHSA-h4g5-39vv-pqfv): the six `services/connectors` statements this+# gate could not previously see. They are not six new exemptions earned by+# argument — they are six statements that had been exempt by accident, because+# the table they query is a SQLAlchemy Core `Table` and entity detection only+# matched declarative class names. The count going up here is the gate getting+# *stricter*: the statement that had to be fixed rather than recorded,+# `fetch_enabled_connectors` called from a request handler, is absent from the+# list because the route now uses a sibling that filters in SQL.+MAX_RATCHET = 60# ---------------------------------------------------------------------------@@ -506,9 +583,21 @@ MAX_RATCHET = 54@dataclassclass Inventory:models: dict[str, str] = field(default_factory=dict) # class name -> table+ #: SQLAlchemy **Core** ``Table`` objects: the variable a statement names+ #: (``connectors_table``) -> the table it maps (``connectors``). Kept+ #: separate from ``models`` because the two are discovered differently and+ #: reporting which one matched is what makes a finding checkable.+ core_tables: dict[str, str] = field(default_factory=dict)tables: set[str] = field(default_factory=set) # tables with a tenant_id columnrls_tables: set[str] = field(default_factory=set) # tables with an RLS policy+ def entities(self) -> set[str]:+ """Every name a statement can use to reach a tenant-scoped table."""+ return set(self.models) | set(self.core_tables)++ def table_for(self, entity: str) -> str:+ return self.models.get(entity) or self.core_tables.get(entity, entity)+def _skipped(path: Path, root: Path) -> bool:rel = path.relative_to(root)@@ -561,6 +650,47 @@ def build_inventory(root: Path) -> Inventory:if "tenant_id" in fields and table is not None:inv.models[node.name] = table+ # SQLAlchemy **Core** tables, which the declarative scan above cannot+ # see because they are an assignment rather than a class.+ #+ # This was a hole wide enough to drive a cross-tenant credential read+ # through. `services/connectors` addresses the `connectors` table as+ # `connectors_table = Table("connectors", metadata, Column(...))` and+ # queries it as `select(connectors_table.c.id, ...)`. The entity match+ # below is against *names appearing inside the select()*, and that name+ # is `connectors_table` — which was in neither `models` nor `tables`,+ # so six statements in that file, including the unscoped read behind+ # GHSA-h4g5-39vv-pqfv, were skipped before any predicate was examined.+ # The gate printed OK over the whole service: not because it excluded+ # it, but because it could not see a single one of its queries.+ for node in ast.walk(tree):+ if not isinstance(node, ast.Assign) or len(node.targets) != 1:+ continue+ target = node.targets[0]+ call = node.value+ if not (isinstance(target, ast.Name) and isinstance(call, ast.Call)):+ continue+ func = call.func+ name = func.id if isinstance(func, ast.Name) else func.attr if isinstance(func, ast.Attribute) else None+ if name != "Table" or not call.args:+ continue+ first = call.args[0]+ if not (isinstance(first, ast.Constant) and isinstance(first.value, str)):+ continue+ # Only a table that declares a tenant column, matching the rule+ # the declarative branch applies. A Core table without one is not+ # tenant-scoped and nothing here should claim it is.+ declares_tenant = any(+ isinstance(arg, ast.Call)+ and (getattr(arg.func, "id", None) or getattr(arg.func, "attr", None)) == "Column"+ and arg.args+ and isinstance(arg.args[0], ast.Constant)+ and arg.args[0].value == "tenant_id"+ for arg in call.args+ )+ if declares_tenant:+ inv.core_tables[target.id] = first.value+# Four services manage their own schema through alembic rather than this# chain of .sql files, so a glob that only saw the latter reported their# twelve tenant-scoped tables as unprotected however many policies they@@ -588,6 +718,7 @@ def build_inventory(root: Path) -> Inventory:inv.rls_tables.add(m.group(1).strip('"').split(".")[-1])inv.tables |= {t for t in inv.models.values() if t}+ inv.tables |= {t for t in inv.core_tables.values() if t}return inv@@ -959,8 +1090,9 @@ def _scan_orm(if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in STATEMENT_FUNCS):continueentities: set[str] = set()+ known = inv.entities()for arg in node.args:- entities |= _names(arg) & inv.models.keys()+ entities |= _names(arg) & knownif not entities:continuetotal += 1@@ -1041,7 +1173,7 @@ def _scan_orm(if fn is not None and (_tenant_validated_keys(fn, auth_names, parents, module_fns) & resolved):continue- table = inv.models.get(entity, entity)+ table = inv.table_for(entity)# Scoped by an RLS context on the connection. Only counts on a table# that actually carries a policy: setting the GUC against a table with# no policy scopes nothing at all.@@ -1177,6 +1309,268 @@ def _scan_sql(return findings, total, rls_scoped+# ---------------------------------------------------------------------------+# Route reachability+# ---------------------------------------------------------------------------+#+# Why a second arm exists at all+# ------------------------------+# The ratchet exempts a *statement*, and a statement has no opinion about who+# calls it. That is the gap GHSA-h4g5-39vv-pqfv went through, and it is worth+# stating exactly, because the obvious reading of the advisory is wrong:+# `services/connectors` was never excluded from this scan, and adding the+# Core-table rule above does not catch the vulnerability either. Measured: with+# that rule alone the gate reports OK on the vulnerable tree, because+# `fetch_enabled_connectors` is a legitimate cross-tenant sweep and is+# correctly ratcheted as one — while a *request handler* was calling it.+#+# "The scheduler legitimately iterates every tenant; a request handler does+# not" is the whole rule. A sweep's exemption is earned by there being no+# caller whose tenant it could have filtered on, so the exemption evaporates+# the moment an HTTP route reaches it — and nothing noticed, because both+# halves looked correct in isolation.+#+# Measured on `main`: 39 handler -> unscoped-statement pairs, every one of them+# a pre-auth credential lookup, a deliberately cross-tenant admin surface or an+# opaque-capability read that is *designed* to be called from a request. The+# vulnerable tree had 40. The fortieth is the finding.++#: Decorator attributes that mark an HTTP route handler.+ROUTE_DECORATOR_METHODS = frozenset({"get", "post", "put", "patch", "delete", "head", "options"})++#: Handlers that may reach a cross-tenant statement, and why *a request* may.+#:+#: Distinct from ``RATCHET``, which says why the statement needs no predicate.+#: These two questions came apart in GHSA-h4g5-39vv-pqfv and the entry has to+#: answer the second one: not "why is this query unscoped" but "why is it+#: correct for an HTTP caller to reach it". Every pair below was read before it+#: was recorded, and they fall into four shapes that are all *designed* for a+#: request — unlike a sweep, whose exemption exists precisely because no+#: request reaches it.+#: Shorthands so a key fits a line. The gate compares whole keys, so these are+#: joined back into exactly the paths `scan_route_reachability` emits.+_EP = "services/api/app/api/v1/endpoints"+_SV = "services/api/app/services"+_OSQ = "services/osquery-tls/app"++ROUTE_REACHABLE: dict[str, str] = {+ # -- pre-auth: the lookup that assigns the tenant ------------------------+ f"{_EP}/auth.py::login -> {_EP}/auth.py::login": ("sign-in by email: there is no tenant yet, and this query is what resolves one"),+ f"{_EP}/auth.py::refresh_token -> {_EP}/auth.py::refresh_token": (+ "refresh presents a signed token, not a tenant; the row it names assigns one"+ ),+ f"{_EP}/passkeys.py::passkey_authenticate_begin -> {_EP}/passkeys.py::passkey_authenticate_begin": (+ "pre-auth WebAuthn: resolves who is signing in from the email they typed"+ ),+ f"{_EP}/passkeys.py::passkey_authenticate_finish -> {_EP}/passkeys.py::passkey_authenticate_finish": (+ "pre-auth WebAuthn: the owner of the verified credential is what assigns the tenant"+ ),+ f"{_EP}/passkeys.py::passkey_authenticate_finish -> {_EP}/passkeys.py::_consume_challenge": (+ "single-use WebAuthn challenge matched on its own high-entropy value, before any session exists"+ ),+ f"{_EP}/passkeys.py::passkey_register_finish -> {_EP}/passkeys.py::_consume_challenge": (+ "the same single-use challenge, on the registration leg"+ ),+ f"{_EP}/mfa.py::webauthn_verify -> {_EP}/passkeys.py::_consume_challenge": (+ "the same single-use challenge, reused by the step-up verifier"+ ),+ f"{_EP}/oauth.py::oauth_callback -> {_EP}/oauth.py::oauth_callback": (+ "matched on the 32-byte single-use state nonce, which is itself the credential"+ ),+ # -- the row is addressed by an opaque capability and yields its own tenant+ "services/honeytokens/app/api/routes.py::webhook_trigger -> services/honeytokens/app/api/routes.py::webhook_trigger": (+ "canary callback: the token id is the capability and the row supplies its own tenant; "+ "the caller is whoever tripped the token and holds no session"+ ),+ f"{_OSQ}/api/v1/endpoints/config.py::get_config -> {_OSQ}/services/node_registry.py::mark_seen": (+ "node_key is the agent's enrolment credential; the heartbeat writes the row that key resolved"+ ),+ f"{_OSQ}/api/v1/endpoints/distributed_read.py::distributed_read -> {_OSQ}/services/node_registry.py::mark_seen": (+ "the same node_key heartbeat, on the distributed-read leg"+ ),+ f"{_OSQ}/api/v1/endpoints/distributed_write.py::distributed_write -> {_OSQ}/services/node_registry.py::mark_seen": (+ "the same node_key heartbeat, on the distributed-write leg"+ ),+ f"{_OSQ}/api/v1/endpoints/log.py::log -> {_OSQ}/services/node_registry.py::mark_seen": (+ "the same node_key heartbeat, on the log-submission leg"+ ),+ f"{_EP}/replay.py::get_public_replay -> {_EP}/replay.py::get_public_replay": (+ "a published replay is deliberately public; the slug is the capability"+ ),+ f"{_EP}/war_rooms.py::channel_decision -> {_EP}/war_rooms.py::channel_decision": (+ "the chat bot presents the shared service token and a war-room id, holds no tenant, and the "+ "handler binds the RLS context to the row's own tenant before acting"+ ),+ # -- cross-tenant by design, behind an administrative permission ---------+ f"{_EP}/tenants.py::create_user -> {_EP}/tenants.py::create_user": (+ "platform-admin provisioning: creates users across tenants by design"+ ),+ f"{_EP}/tenants.py::update_user -> {_EP}/tenants.py::update_user": (+ "platform-admin user administration, authorised by the admin role rather than a tenant"+ ),+ f"{_EP}/rbac.py::set_primary_role -> {_EP}/rbac.py::set_primary_role": (+ "mirrors the granted role onto a user id this endpoint already validated against the caller's tenant"+ ),+ f"{_EP}/usage.py::export_organization_month -> {_SV}/org_scope.py::resolve_portfolio_scope": (+ "the MSSP portfolio resolver answers 'which tenants may this operator see', so it cannot "+ "presuppose one; it is bounded by org_id + user_id"+ ),+ f"{_EP}/mssp.py::list_effective_rules_for_child -> {_SV}/mssp_rule_resolver.py::resolve_effective_rules": (+ "MSSP rule packs are cross-tenant by construction, bounded by a pack_id from the verified portfolio"+ ),+ f"{_EP}/mssp.py::count_effective_rules_for_child -> {_SV}/mssp_rule_resolver.py::resolve_effective_rules": (+ "the count beside the list above, same bound"+ ),+ f"{_EP}/detection_rules.py::hunt -> {_SV}/mssp_rule_resolver.py::resolve_effective_rules": (+ "resolves the effective rule set for the caller's own tenant through the same portfolio bound"+ ),+ f"{_EP}/replay.py::publish_replay -> {_EP}/replay.py::_unique_slug": (+ "slug-collision probe across all replays; a tenant-scoped check would mint duplicate public slugs"+ ),+ # -- the handler validated the key against the caller's tenant first -----+ f"{_EP}/war_rooms.py::sync -> {_SV}/war_room.py::sync_war_room": (+ "the handler loads the room WHERE id = :id AND tenant_id = :tenant_id, 404s on a miss and "+ "passes current_user.tenant_id in, so the sweep function is reached only with a room this "+ "request already proved it owns"+ ),+ f"{_EP}/investigations.py::get_run -> {_EP}/investigations.py::_fetch_model_costs": (+ "costs are keyed on a run_id that _fetch_run already checked against the caller's tenant"+ ),+ f"{_EP}/admin_users.py::delete_user -> {_EP}/admin_users.py::_end_sessions": (+ "keyed on a user id that came out of this module's tenant-scoped SELECT earlier in the request"+ ),+ f"{_EP}/admin_users.py::delete_user -> {_EP}/admin_users.py::_guard_last_admin": (+ "counts admins holding that already-validated user's roles, and only ever denies the operation"+ ),+ f"{_EP}/admin_users.py::patch_status -> {_EP}/admin_users.py::_end_sessions": "same validated user id, status leg",+ f"{_EP}/admin_users.py::patch_status -> {_EP}/admin_users.py::_guard_last_admin": "same last-admin guard, status leg",+ f"{_EP}/admin_users.py::add_role -> {_EP}/admin_users.py::_end_sessions": "same validated user id, role-grant leg",+ f"{_EP}/admin_users.py::remove_role -> {_EP}/admin_users.py::_end_sessions": "same validated user id, role-revoke leg",+ f"{_EP}/admin_users.py::remove_role -> {_EP}/admin_users.py::_guard_last_admin": "same last-admin guard, role-revoke leg",+ f"{_EP}/admin_users.py::set_roles -> {_EP}/admin_users.py::_end_sessions": "same validated user id, role-replace leg",+ f"{_EP}/admin_users.py::set_roles -> {_EP}/admin_users.py::_guard_last_admin": "same last-admin guard, role-replace leg",+}++#: Shrink-only, exactly like MAX_RATCHET. 34 is what `main` measured once the+#: fixed route stopped reaching the scheduler's sweep; the vulnerable tree+#: measured 35.+MAX_ROUTE_REACHABLE = 34++#: How far to follow calls out of a handler. Four frames covers+#: handler -> service -> repository with room to spare.+_REACH_DEPTH = 4+++@dataclass(frozen=True)+class ReachFinding:+ handler_path: str+ handler: str+ target_path: str+ target: str++ @property+ def key(self) -> str:+ return f"{self.handler_path}::{self.handler} -> {self.target_path}::{self.target}"+++def _module_to_path(module: str, service: str) -> str | None:+ """``app.db.connector_repo`` in service ``connectors`` -> its file path.++ Resolution is by import rather than by bare name on purpose. A pass that+ matched any function of the same name anywhere in the service reported+ ``saml_login -> auth.login`` and ``identity_context_for_triage ->+ bootstrap_admin.bootstrap``: two name collisions, neither a call. A gate+ that invents findings gets switched off, which costs more than the gate+ was worth.+ """+ if not module.startswith("app"):+ return None+ return f"services/{service}/{module.replace('.', '/')}.py"+++def _imported_names(tree: ast.AST, rel: str, service: str) -> dict[str, str]:+ """``local name -> defining module's path``, for ``from app.x import y``."""+ out: dict[str, str] = {}+ for node in ast.walk(tree):+ if not isinstance(node, ast.ImportFrom) or node.level or not node.module:+ continue+ path = _module_to_path(node.module, service)+ if path is None:+ continue+ for alias in node.names:+ out[alias.asname or alias.name] = path+ return out+++def scan_route_reachability(root: Path, findings: list[Finding]) -> list[ReachFinding]:+ """Handlers that reach a function owning a statement with no tenant predicate."""+ unscoped = {(f.path, f.function) for f in findings}+ if not unscoped:+ return []++ defined: set[tuple[str, str]] = set()+ called: dict[tuple[str, str], set[str]] = {}+ imports: dict[str, dict[str, str]] = {}+ handlers: list[tuple[str, str, str]] = [] # (path, name, service)++ for py in _python_files(root):+ rel = py.relative_to(root).as_posix()+ if not rel.startswith("services/"):+ continue+ service = rel.split("/")[1]+ try:+ tree = ast.parse(py.read_text(encoding="utf-8", errors="ignore"))+ except SyntaxError:+ continue+ imports[rel] = _imported_names(tree, rel, service)+ for node in ast.walk(tree):+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):+ continue+ defined.add((rel, node.name))+ names: set[str] = set()+ for sub in ast.walk(node):+ if not isinstance(sub, ast.Call):+ continue+ func = sub.func+ name = func.id if isinstance(func, ast.Name) else func.attr if isinstance(func, ast.Attribute) else None+ if name:+ names.add(name)+ called[(rel, node.name)] = names+ for deco in node.decorator_list:+ if isinstance(deco, ast.Call) and isinstance(deco.func, ast.Attribute) and deco.func.attr in ROUTE_DECORATOR_METHODS:+ handlers.append((rel, node.name, service))+ break++ def resolve(name: str, from_path: str) -> tuple[str, str] | None:+ if (from_path, name) in defined:+ return (from_path, name)+ target = imports.get(from_path, {}).get(name)+ if target is not None and (target, name) in defined:+ return (target, name)+ return None++ out: list[ReachFinding] = []+ for path, handler, _service in handlers:+ seen: set[tuple[str, str]] = set()+ frontier = [(path, handler)]+ for _ in range(_REACH_DEPTH):+ nxt: list[tuple[str, str]] = []+ for node_key in frontier:+ if node_key in seen:+ continue+ seen.add(node_key)+ if node_key in unscoped:+ out.append(ReachFinding(path, handler, node_key[0], node_key[1]))+ for name in called.get(node_key, ()):+ resolved = resolve(name, node_key[0])+ if resolved is not None and resolved not in seen:+ nxt.append(resolved)+ frontier = nxt+ if not frontier:+ break+ return sorted(set(out), key=lambda r: r.key)++@dataclassclass ScanResult:findings: list[Finding]@@ -1243,6 +1637,20 @@ def partition(findings: list[Finding]) -> tuple[list[Finding], list[str]]:return unratcheted, stale+def partition_reach(reach: list[ReachFinding]) -> tuple[list[ReachFinding], list[str]]:+ """Return (unallowed handler->statement pairs, stale allowlist keys).++ Both directions, for the same reason the statement ratchet runs both: an+ entry whose pair has gone — the handler stopped calling it, or the+ statement gained a predicate — is a justification that has lapsed, and one+ that keeps passing reads like a decision somebody made.+ """+ seen = {r.key for r in reach}+ unallowed = [r for r in reach if r.key not in ROUTE_REACHABLE]+ stale = sorted(k for k in ROUTE_REACHABLE if k not in seen)+ return unallowed, stale++def _print_inventory(findings: list[Finding], inv: Inventory, files: int, statements: int, rls_scoped: int = 0) -> None:print(f"Tenant-predicate inventory — scanned {files} files under {SERVICES_DIR}")print(f" tenant-scoped ORM models : {len(inv.models)}")@@ -1459,6 +1867,74 @@ CREATE POLICY widgets_tenant ON widgetsUSING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);"""+#: SQLAlchemy **Core** tables, the shape that was invisible. The module declares+#: its own table rather than importing a declarative model, so nothing here+#: matches a class name — which is exactly the condition under which six+#: statements in `services/connectors` were skipped before any predicate was+#: looked at.+_CORE_TABLE_DECL = """+from sqlalchemy import Boolean, Column, MetaData, String, Table+from sqlalchemy.dialects.postgresql import UUID++metadata = MetaData()++widgets_table = Table(+ "widgets",+ metadata,+ Column("id", UUID(as_uuid=True), primary_key=True),+ Column("tenant_id", UUID(as_uuid=True), nullable=False),+ Column("is_enabled", Boolean, nullable=False),+ Column("name", String(255)),+)++gadgets_table = Table(+ "gadgets_no_tenant",+ metadata,+ Column("id", UUID(as_uuid=True), primary_key=True),+ Column("name", String(255)),+)+"""++_CORE_UNSCOPED = """+from sqlalchemy import select+from app.core_tables import widgets_table++async def fetch(connection, widget_id):+ stmt = select(widgets_table.c.id, widgets_table.c.name).where(widgets_table.c.id == widget_id)+ return (await connection.execute(stmt)).first()+"""++_CORE_SCOPED = """+from sqlalchemy import select+from app.core_tables import widgets_table++async def fetch(connection, widget_id, tenant_id):+ stmt = select(widgets_table.c.id, widgets_table.c.name).where(+ widgets_table.c.id == widget_id,+ widgets_table.c.tenant_id == tenant_id,+ )+ return (await connection.execute(stmt)).first()+"""++_CORE_UPDATE_UNSCOPED = """+from sqlalchemy import update+from app.core_tables import widgets_table++async def touch(connection, widget_id):+ await connection.execute(update(widgets_table).where(widgets_table.c.id == widget_id).values(seen=True))+"""++#: A Core table that declares no tenant column is not tenant-scoped, and the+#: rule must not claim it is. Without this control the detector could be+#: "any Table(...)", which would report every lookup table in the tree.+_CORE_TABLE_WITHOUT_TENANT = """+from sqlalchemy import select+from app.core_tables import gadgets_table++async def fetch(connection, gadget_id):+ return (await connection.execute(select(gadgets_table.c.id).where(gadgets_table.c.id == gadget_id))).first()+"""+_DOCSTRING_ONLY = '''"""Widget helpers.@@ -1503,6 +1979,34 @@ def _self_test() -> int:# The RLS-context rule, on both sides of its condition.("control: RLS context bound on a table that has a policy", {"r.py": _RLS_CONTEXT_ON_COVERED_TABLE}, 0, _PROBE_MIGRATION),("drift E: RLS context bound on a table with no policy", {"r.py": _RLS_CONTEXT_ON_UNCOVERED_TABLE}, 1, _PROBE_MIGRATION),+ # SQLAlchemy Core tables. The whole family was invisible, so each arm+ # is exercised: the read that was the vulnerability, the write shape+ # beside it, the scoped form that must stay clean, and a Core table+ # with no tenant column that must not be claimed at all.+ (+ "drift G: Core-table by-id read with no tenant predicate",+ {"core_tables.py": _CORE_TABLE_DECL, "r.py": _CORE_UNSCOPED},+ 1,+ None,+ ),+ (+ "drift H: Core-table by-id update with no tenant predicate",+ {"core_tables.py": _CORE_TABLE_DECL, "r.py": _CORE_UPDATE_UNSCOPED},+ 1,+ None,+ ),+ (+ "control: Core-table read carrying a tenant predicate",+ {"core_tables.py": _CORE_TABLE_DECL, "r.py": _CORE_SCOPED},+ 0,+ None,+ ),+ (+ "control: a Core table declaring no tenant column is not tenant-scoped",+ {"core_tables.py": _CORE_TABLE_DECL, "r.py": _CORE_TABLE_WITHOUT_TENANT},+ 0,+ None,+ ),]failures = 0@@ -1517,6 +2021,7 @@ def _self_test() -> int:failures += 1print(f" [{'PASS' if ok else 'FAIL'}] {label}: {got} finding(s), want {want} (scanned {files} files)")+ failures += _self_test_route_reachability()failures += _self_test_stale_ratchet()failures += _self_test_ratchet_ceiling()failures += _self_test_empty_corpus()@@ -1524,9 +2029,16 @@ def _self_test() -> int:if failures:print(f"\nself-test FAILED: {failures} case(s) did not behave as specified", file=sys.stderr)return 1+ # Counted rather than written down. The previous wording said "ten+ # controls" and was already wrong by the time anybody read it, which is+ # the same stale-figure-in-prose problem this gate exists to prevent.+ drifts = sum(1 for _label, _src, want, _mig in cases if want)+ controls = len(cases) - driftsprint(- "\nself-test passed: drift detected in both directions, ten controls clear, a stale ratchet "- "entry is dropped, and each of the three ways the corpus can empty is refused."+ f"\nself-test passed: {drifts} injected drifts detected and {controls} controls clear in the statement "+ f"scan, the route-reachability arm detects the advisory's shape without flagging the worker that "+ f"shape exists for, a stale ratchet entry is dropped, and each of the {len(_EMPTY_CORPUS_CASES)} ways "+ "the corpus can empty is refused.")return 0@@ -1580,6 +2092,104 @@ def _self_test_empty_corpus() -> int:return failures+#: A repository module with both shapes side by side, so the reachability rule+#: is exercised on both sides of its condition rather than only the failing one.+_REACH_REPO = """+from sqlalchemy import select+from app.core_tables import widgets_table++async def fetch_all_widgets(connection):+ stmt = select(widgets_table.c.id, widgets_table.c.name).where(widgets_table.c.is_enabled.is_(True))+ return (await connection.execute(stmt)).fetchall()++async def fetch_widget_for_tenant(connection, widget_id, tenant_id):+ stmt = select(widgets_table.c.id, widgets_table.c.name).where(+ widgets_table.c.id == widget_id,+ widgets_table.c.tenant_id == tenant_id,+ )+ return (await connection.execute(stmt)).first()+"""++#: The vulnerability's exact shape: a handler serving one caller out of a+#: cross-tenant working set.+_REACH_ROUTE_UNSCOPED = """+from fastapi import APIRouter+from app.repo import fetch_all_widgets++router = APIRouter()+[email protected]("/widgets/{widget_id}")+async def read_widget(widget_id, connection):+ rows = await fetch_all_widgets(connection)+ return next((r for r in rows if str(r.id) == widget_id), None)+"""++#: The fixed shape, which must stay clean or the rule is unusable.+_REACH_ROUTE_SCOPED = """+from fastapi import APIRouter+from app.repo import fetch_widget_for_tenant++router = APIRouter()+[email protected]("/widgets/{widget_id}")+async def read_widget(widget_id, connection, principal):+ return await fetch_widget_for_tenant(connection, widget_id, principal.tenant_id)+"""++#: A worker calling the same cross-tenant sweep. It must NOT be reported:+#: the sweep's exemption is exactly for callers like this one, and a rule that+#: flagged it would be telling every scheduler in the tree to scope a query+#: that cannot be scoped.+_REACH_WORKER = """+from app.repo import fetch_all_widgets++async def poll_everything(connection):+ for row in await fetch_all_widgets(connection):+ print(row)+"""+++def _self_test_route_reachability() -> int:+ """Prove the second arm detects the advisory's shape, and only that shape.++ The statement ratchet alone cannot: measured against the vulnerable tree it+ reported OK, because the sweep was correctly ratcheted and the defect was+ *who called it*.+ """+ cases: tuple[tuple[str, dict[str, str], int], ...] = (+ (+ "drift I: a route handler serving one caller from a cross-tenant sweep",+ {"core_tables.py": _CORE_TABLE_DECL, "repo.py": _REACH_REPO, "routes.py": _REACH_ROUTE_UNSCOPED},+ 1,+ ),+ (+ "control: a route handler calling the by-id-and-tenant sibling",+ {"core_tables.py": _CORE_TABLE_DECL, "repo.py": _REACH_REPO, "routes.py": _REACH_ROUTE_SCOPED},+ 0,+ ),+ (+ "control: a worker calling the same sweep is what the exemption is for",+ {"core_tables.py": _CORE_TABLE_DECL, "repo.py": _REACH_REPO, "worker.py": _REACH_WORKER},+ 0,+ ),+ )++ failures = 0+ with tempfile.TemporaryDirectory(prefix="predicates_reach_") as tmp:+ for i, (label, sources, want) in enumerate(cases):+ root = Path(tmp) / f"reach{i}"+ _write_probe(root, sources)+ result = scan(root=root)+ reach = scan_route_reachability(root, result.findings)+ got = len(reach)+ if got == want:+ print(f" [PASS] {label}: {got} finding(s), want {want}")+ else:+ print(f" [FAIL] {label}: {got} finding(s), want {want} — {[r.key for r in reach]}")+ failures += 1+ return failures++def _self_test_stale_ratchet() -> int:"""Strip a live ratchet entry's justification and assert it stops protecting.@@ -1615,11 +2225,18 @@ def _self_test_stale_ratchet() -> int:def _self_test_ratchet_ceiling() -> int:+ failures = 0if 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+ failures += 1+ else:+ print(f" [PASS] ratchet ceiling: {len(RATCHET)}/{MAX_RATCHET} entries")+ if len(ROUTE_REACHABLE) > MAX_ROUTE_REACHABLE:+ print(f" [FAIL] route-reachability ceiling: {len(ROUTE_REACHABLE)} exceeds MAX_ROUTE_REACHABLE={MAX_ROUTE_REACHABLE}")+ failures += 1+ else:+ print(f" [PASS] route-reachability ceiling: {len(ROUTE_REACHABLE)}/{MAX_ROUTE_REACHABLE} entries")+ return failures# ---------------------------------------------------------------------------@@ -1725,12 +2342,44 @@ def main(argv: list[str] | None = None) -> int: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:+ # Second arm: who can *reach* a cross-tenant statement. A sweep's exemption+ # is earned by having no caller, so an HTTP route reaching one retires the+ # justification — which is the shape GHSA-h4g5-39vv-pqfv had, with both+ # halves looking correct in isolation.+ reach = scan_route_reachability(REPO_ROOT, findings)+ unallowed, stale_reach = partition_reach(reach)++ if len(ROUTE_REACHABLE) > MAX_ROUTE_REACHABLE:+ print(+ f"\nFAIL: {len(ROUTE_REACHABLE)} route-reachability entries exceeds MAX_ROUTE_REACHABLE={MAX_ROUTE_REACHABLE}.",+ file=sys.stderr,+ )+ print(" It only shrinks. Scope the query rather than raising the ceiling.", file=sys.stderr)+ return 1++ if stale_reach:+ print(f"\nFAIL: {len(stale_reach)} route-reachability entry/entries no longer describe a real call path.", file=sys.stderr)+ print(" Remove them — a lapsed justification that still passes reads like a decision.", file=sys.stderr)+ for key in stale_reach:+ print(f" - {key}", file=sys.stderr)++ if unallowed:+ print(+ f"\nFAIL: {len(unallowed)} HTTP route handler(s) reach a statement that carries no tenant predicate.",+ file=sys.stderr,+ )+ print(" A cross-tenant sweep is exempt because nothing calls it with a tenant to filter on.", file=sys.stderr)+ print(" A request handler has one. Scope the read, or record why a request may reach it.", file=sys.stderr)+ for item in unallowed:+ print(f" - {item.key}", file=sys.stderr)++ if stale or unratcheted or stale_reach or unallowed:return 1print(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."+ f"or is one of {len(RATCHET)} ratcheted exceptions that still holds; "+ f"and every one of the {len(reach)} route->unscoped-statement paths is a recorded exception.")return 0diff --git a/services/connectors/app/api/router.py b/services/connectors/app/api/router.pyindex e670a6d48..312763d14 100644--- a/services/connectors/app/api/router.py+++ b/services/connectors/app/api/router.py@@ -26,6 +26,7 @@ service's lifespan), not in this router.from __future__ import annotationsimport re+import uuidfrom typing import Anyimport structlog@@ -35,12 +36,16 @@ from pydantic import Field as PydFieldfrom app.connectors import CONNECTOR_REGISTRY, list_connector_schemasfrom app.connectors.base import Capability-from app.db.connector_repo import fetch_enabled_connectors+from app.db.connector_repo import fetch_enabled_connector_for_tenantfrom app.db.engine import get_enginefrom app.federated.query import QueryError, parse_unified_queryfrom app.security.credential_vault import CredentialVaultError, get_vaultfrom app.security.egress import EgressRefused, refuse_internal_destinations-from app.security.tenant_scope import require_console_or_service_auth+from app.security.tenant_scope import (+ TenantPrincipal,+ require_console_or_service_auth,+ scoped_tenant_or_403,+)logger = structlog.get_logger()#: Default-deny. Everything on this router either reads the connector@@ -62,6 +67,16 @@ _CTRL_RE = re.compile(r"[\x00-\x1f\x7f]")#: working connector into a 422. Mirrors the filter in ``ConnectorScheduler``._SCHEDULER_ONLY_CONFIG_KEYS = frozenset({"poll_interval_seconds", "checkpoint", "filter_rules"})+#: One answer for "no such instance", "not enabled" and "belongs to another+#: tenant", with the requested id deliberately **not** echoed back.+#:+#: Distinguishing those cases is what made this route an existence oracle over+#: every tenant's connector ids: a 403 on a real id beside a 404 on an invented+#: one enumerates the estate without reading a single row. A constant also+#: keeps a caller-supplied string out of the response body, and costs the+#: caller nothing — they already know which id they sent.+_NO_SUCH_INSTANCE = "no enabled connector instance"+def _connector_kwargs(connector_config: dict[str, Any]) -> dict[str, Any]:return {k: v for k, v in connector_config.items() if k not in _SCHEDULER_ONLY_CONFIG_KEYS}@@ -368,6 +383,7 @@ async def get_instance_resource_config(instance_id: str,resource_id: str = Query(..., description="Vendor-native resource id"),ts: str | None = Query(None, description="Point in time (RFC 3339)"),+ principal: TenantPrincipal = Depends(require_console_or_service_auth),):"""Fetch a resource's configuration for a **saved connector instance**.@@ -382,11 +398,28 @@ async def get_instance_resource_config(`ConnectorScheduler` does at poll time, so the caller needs no secrets.That also means the ingest service never handles credentials, which is thereason the original contract could not simply be renamed into place.++ Because it decrypts a stored credential and spends it on an authenticated+ vendor call, the instance has to be resolved **inside the caller's tenant**+ (GHSA-h4g5-39vv-pqfv). ``principal`` is declared as a parameter rather than+ left to the router-level dependency: the router's ``Depends`` authenticates+ either way, but a dependency whose result is never bound hands it nowhere,+ which is how the tenant came to be known and then not used."""+ tenant_id = scoped_tenant_or_403(principal)++ try:+ wanted = uuid.UUID(instance_id)+ except ValueError:+ # Not a UUID, so it identifies nothing. Answered exactly as "no such+ # instance" rather than 422, so malformed, absent and someone else's+ # are one answer — see the comment on ``_NO_SUCH_INSTANCE``.+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=_NO_SUCH_INSTANCE) from None+try:engine = get_engine()async with engine.begin() as conn:- instances = await fetch_enabled_connectors(conn)+ target = await fetch_enabled_connector_for_tenant(conn, wanted, tenant_id)except Exception as exc: # noqa: BLE001 — surfaced as 503, never silentlogger.exception("connector.resource_config.instance_load_failed")raise HTTPException(@@ -394,12 +427,14 @@ async def get_instance_resource_config(detail="could not load connector instances",) from exc- target = next((i for i in instances if str(i.id) == instance_id), None)if target is None:- raise HTTPException(- status_code=status.HTTP_404_NOT_FOUND,- detail=f"no enabled connector instance '{_safe_log_val(instance_id)}'",+ logger.info(+ "connector.resource_config.not_found tenant=%s instance=%s subject=%s",+ _safe_log_val(str(tenant_id)),+ _safe_log_val(instance_id),+ _safe_log_val(principal.subject),)+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=_NO_SUCH_INSTANCE)cls = CONNECTOR_REGISTRY.get(target.connector_type)if cls is None:diff --git a/services/connectors/app/db/connector_repo.py b/services/connectors/app/db/connector_repo.pyindex 3c6a5ef58..df99fb334 100644--- a/services/connectors/app/db/connector_repo.py+++ b/services/connectors/app/db/connector_repo.py@@ -119,8 +119,56 @@ class ConnectorInstance:last_backfill_at: datetime | None = None+def _instance_from_row(row: Any) -> ConnectorInstance:+ """Map one result row onto the dataclass.++ Shared by both readers below so the eighteen field assignments — the part+ that actually drifts when a column is added — exist once.+ """+ return ConnectorInstance(+ id=row.id,+ tenant_id=row.tenant_id,+ name=row.name,+ connector_type=row.connector_type,+ is_enabled=row.is_enabled,+ auth_config=row.auth_config or {},+ connector_config=row.connector_config or {},+ health_status=row.health_status,+ last_sync=row.last_sync,+ events_ingested=row.events_ingested,+ events_dropped=row.events_dropped,+ error_count=row.error_count,+ schema_fingerprint=row.schema_fingerprint,+ last_schema_drift_at=row.last_schema_drift_at,+ last_drift_details=row.last_drift_details,+ last_outage_at=row.last_outage_at,+ last_backfill_at=row.last_backfill_at,+ )+++# The column list below is spelled out at each ``select()`` rather than shared+# through a module-level tuple, and that is deliberate rather than careless.+# ``scripts/check_tenant_query_predicates.py`` identifies which table a+# statement reaches from the names appearing inside the ``select(...)`` call+# itself; behind a ``*_COLUMNS`` splat the statement names no table and becomes+# invisible to the gate. Queries on this table being invisible is precisely how+# the unscoped read below went unnoticed, so the duplication buys the one thing+# worth more than brevity here: both statements are scannable.++async def fetch_enabled_connectors(connection: Any) -> list[ConnectorInstance]:- """Return every connector instance with ``is_enabled = True``.+ """Every enabled instance, **across every tenant**.++ Deliberately unscoped, and the only legitimate caller is+ ``ConnectorScheduler``: its job is to poll every tenant's sources, so it+ cannot presuppose a tenant, and a tenant missing from its working set is a+ customer whose connectors silently stop ingesting.++ **A request handler must not call this.** Serving one caller's request from+ a cross-tenant working set is how a saved instance belonging to somebody+ else got resolved, decrypted and spent (GHSA-h4g5-39vv-pqfv). Handlers take+ :func:`fetch_enabled_connector_for_tenant`, which asks the database for the+ one row the caller is entitled to instead of filtering afterwards.``connection`` must be a SQLAlchemy ``AsyncConnection``. We accept ``Any``in the type hint to avoid forcing every caller to import the async@@ -147,29 +195,57 @@ async def fetch_enabled_connectors(connection: Any) -> list[ConnectorInstance]:).where(connectors_table.c.is_enabled.is_(True))result = await connection.execute(stmt)- rows = result.fetchall()- return [- ConnectorInstance(- id=row.id,- tenant_id=row.tenant_id,- name=row.name,- connector_type=row.connector_type,- is_enabled=row.is_enabled,- auth_config=row.auth_config or {},- connector_config=row.connector_config or {},- health_status=row.health_status,- last_sync=row.last_sync,- events_ingested=row.events_ingested,- events_dropped=row.events_dropped,- error_count=row.error_count,- schema_fingerprint=row.schema_fingerprint,- last_schema_drift_at=row.last_schema_drift_at,- last_drift_details=row.last_drift_details,- last_outage_at=row.last_outage_at,- last_backfill_at=row.last_backfill_at,- )- for row in rows- ]+ return [_instance_from_row(row) for row in result.fetchall()]+++async def fetch_enabled_connector_for_tenant(+ connection: Any,+ connector_id: uuid.UUID,+ tenant_id: uuid.UUID,+) -> ConnectorInstance | None:+ """The one enabled instance with this id **that this tenant owns**, or ``None``.++ The tenant is part of the lookup rather than a check applied to its result.+ That distinction is the fix: filtering after a cross-tenant fetch means the+ row — including its ``auth_config`` ciphertext — has already been read into+ the process, and every past instance of this bug class in this codebase has+ been a scope that was absent rather than narrow.++ ``None`` covers both "no such instance" and "not yours", and callers must+ keep answering them identically. Telling them apart turns a lookup into an+ oracle enumerating which connector ids exist in other tenants.++ ``tenant_id`` must come from the authenticated principal — a console+ token's verified claim or the header a service token is required to+ declare — never from a value the caller is free to assert.+ """+ stmt = select(+ connectors_table.c.id,+ connectors_table.c.tenant_id,+ connectors_table.c.name,+ connectors_table.c.connector_type,+ connectors_table.c.is_enabled,+ connectors_table.c.auth_config,+ connectors_table.c.connector_config,+ connectors_table.c.health_status,+ connectors_table.c.last_sync,+ connectors_table.c.events_ingested,+ connectors_table.c.events_dropped,+ connectors_table.c.error_count,+ connectors_table.c.schema_fingerprint,+ connectors_table.c.last_schema_drift_at,+ connectors_table.c.last_drift_details,+ connectors_table.c.last_outage_at,+ connectors_table.c.last_backfill_at,+ ).where(+ connectors_table.c.is_enabled.is_(True),+ connectors_table.c.id == connector_id,+ connectors_table.c.tenant_id == tenant_id,+ )++ result = await connection.execute(stmt)+ row = result.first()+ return _instance_from_row(row) if row is not None else Noneasync def record_poll_success(@@ -312,6 +388,7 @@ async def record_schema_drift(__all__ = ["ConnectorInstance","connectors_table",+ "fetch_enabled_connector_for_tenant","fetch_enabled_connectors","metadata","record_backfill_run",diff --git a/tests/isolation/test_connector_resource_config_tenant_scope_live.py b/tests/isolation/test_connector_resource_config_tenant_scope_live.pynew file mode 100644index 000000000..3f7d4dcf6--- /dev/null+++ b/tests/isolation/test_connector_resource_config_tenant_scope_live.py@@ -0,0 +1,378 @@+"""``GET /connectors/instances/{id}/resource-config`` may only reach the caller's own tenant.++What was wrong+--------------+The handler took ``(instance_id, resource_id, ts)`` and **no principal**. The+router authenticates (``dependencies=[Depends(require_console_or_service_auth)]``+in ``services/connectors/app/api/router.py``), but a dependency that is never+declared as a handler parameter hands its result nowhere, so the resolved+``TenantPrincipal`` was discarded and nothing downstream knew who was asking.++The lookup underneath was global as well: ``fetch_enabled_connectors`` is+``select(...).where(is_enabled)`` with no tenant predicate, and the handler then+picked its row out of every tenant's instances with+``next(i for i in instances if str(i.id) == instance_id)``. Ownership was never+compared. The connectors engine binds no ``app.current_tenant_id``, so the+``connectors`` RLS policy's ``OR current_tenant_id() IS NULL`` arm fails open and+the predicate is the only control there is.++The consequence is worse than reading a row. ``router.py`` decrypts that row's+``auth_config`` with the platform vault, constructs the vendor client and makes+an authenticated call — so the platform spent **the victim's** cloud credential+on the attacker's behalf and returned the vendor's answer, with the vendor-side+audit trail naming the victim.++What this asserts+-----------------+Both halves, because either alone leaves the hole open:++* the row is selected **by (id, tenant)**, so another tenant's instance is not+ found at all rather than found and then filtered; and+* the tenant comes from the **authenticated principal** — a console token's+ verified claim, or the header a service token must declare — never from+ anything else the caller sends.++Non-ownership resolves as **404, not 403**. A 403 would still answer "this id+exists somewhere", which turns the route into an existence oracle over every+tenant's connector ids; the miss and the cross-tenant hit are required to be+byte-identical.++The positive controls are as load-bearing as the refusals. A route that+refuses everything passes every negative assertion while being broken, and+"stuck closed" reads as working caution — so each tenant must still reach its+*own* instance and the vendor must still see that tenant's own credential.++Why live+--------+The vendor is a real socket rather than a patched method, so the decrypt →+construct → authenticate path runs and the test can ask the vendor *which+credential it was paid with*. That question is the whole finding, and a mock+that answers whatever it is asked cannot be asked it.+"""++from __future__ import annotations++import base64+import hashlib+import hmac+import json+import os+import threading+import time+import uuid+from http.server import BaseHTTPRequestHandler, HTTPServer++import httpx+import pytest+import pytest_asyncio++# Skipped as a *module*, not only in the fixture: the offline isolation job+# collects this directory with no stores running, and a test that does not take+# the fixture would otherwise run and fail there — a failure about the harness,+# reported against a capability.+pytestmark = [+ pytest.mark.asyncio(loop_scope="module"),+ pytest.mark.skipif(+ not os.environ.get("ISOLATION_CONNECTOR_DSN", "").strip(),+ reason="ISOLATION_CONNECTOR_DSN is not set; this suite needs live infrastructure",+ ),+]++SECRET = "isolation-console-secret-at-least-32-characters"+SERVICE_TOKEN = "isolation-shared-service-token"++TENANT_A = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000000a")+TENANT_B = uuid.UUID("bbbbbbbb-0000-0000-0000-00000000000b")++#: Okta ids are prefix-typed; ``00u`` is a user, which is the branch+#: ``OktaConnector.get_resource_config`` takes.+RESOURCE_ID = "00uRESOURCE0001"++TOKEN_A = "tenant-a-own-okta-token"+TOKEN_B = "tenant-b-victim-okta-token"+++def _dsn() -> str:+ value = os.environ.get("ISOLATION_CONNECTOR_DSN", "").strip()+ if not value:+ pytest.skip("ISOLATION_CONNECTOR_DSN is not set; this suite needs a live Postgres")+ return value+++def _b64(raw: bytes) -> str:+ return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()+++def console_token(tenant: uuid.UUID, *, role: str = "viewer") -> str:+ """A console access token, signed the way ``services/api`` signs one.++ Minted here rather than by importing the API, because both services name+ their top-level package ``app`` and importing one shadows the other. The+ construction is byte-compatible with ``create_access_token`` and the+ *verifier* on the path is the real one, which is the half that matters:+ ``require_console_or_service_auth`` -> ``verify_console_token``.+ """+ header = _b64(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())+ claims = {+ "sub": f"user-{tenant}",+ "tenant_id": str(tenant),+ "role": role,+ "type": "access",+ "exp": int(time.time()) + 600,+ }+ 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}"+++class _Vendor(BaseHTTPRequestHandler):+ """A real HTTP server standing in for Okta, recording what it was paid with."""++ seen: list[dict[str, str]] = []++ def do_GET(self) -> None: # noqa: N802+ auth = self.headers.get("Authorization", "")+ presented = auth[len("SSWS ") :] if auth.startswith("SSWS ") else auth+ _Vendor.seen.append({"path": self.path, "credential": presented})+ body = json.dumps(+ {+ "id": self.path.rsplit("/", 1)[-1],+ "status": "ACTIVE",+ "profile": {"login": "[email protected]"},+ "_authenticated_with": presented,+ }+ ).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *_args) -> None: # noqa: ANN002+ """Quiet: the default handler prints to stderr on every request."""++[email protected](scope="module")+def vendor():+ server = HTTPServer(("127.0.0.1", 0), _Vendor)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ yield f"http://127.0.0.1:{server.server_port}"+ server.shutdown()++[email protected](scope="module", autouse=True)+def _env():+ """Production posture, and the credentials both auth shapes need.++ ``ENVIRONMENT=production`` deliberately: ``development`` is in+ ``AUTH_BYPASS_ENVIRONMENTS`` and would resolve a demo principal inside the+ one suite whose whole subject is that the tenant comes from the credential.+ """+ previous = {+ k: os.environ.get(k)+ for k in (+ "ENVIRONMENT",+ "SECRET_KEY",+ "AISOC_SERVICE_TOKEN",+ "AISOC_DEV_MODE",+ "AISOC_DEV_AUTH_BYPASS",+ "AISOC_CONNECTORS_DISABLE_SCHEDULER",+ )+ }+ os.environ["ENVIRONMENT"] = "production"+ os.environ["SECRET_KEY"] = SECRET+ os.environ["AISOC_SERVICE_TOKEN"] = SERVICE_TOKEN+ os.environ["AISOC_CONNECTORS_DISABLE_SCHEDULER"] = "1"+ os.environ.pop("AISOC_DEV_MODE", None)+ os.environ.pop("AISOC_DEV_AUTH_BYPASS", None)+ yield+ for key, value in previous.items():+ if value is None:+ os.environ.pop(key, None)+ else:+ os.environ[key] = value+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def engine():+ pytest.importorskip("asyncpg")+ from sqlalchemy.ext.asyncio import create_async_engine++ created = create_async_engine(_dsn(), future=True)+ yield created+ await created.dispose()+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def instances(engine, vendor): # noqa: ANN001+ """One enabled Okta instance per tenant, written the way the console writes one.++ Both point at the same stub vendor and differ only in their credential, so+ "whose secret was spent" is answerable from the vendor's own log rather+ than inferred from which row came back.+ """+ import sqlalchemy+ from app.security.credential_vault import get_vault++ vault = get_vault()+ ids = {TENANT_A: uuid.uuid4(), TENANT_B: uuid.uuid4()}+ async with engine.begin() as conn:+ for tenant, token in ((TENANT_A, TOKEN_A), (TENANT_B, TOKEN_B)):+ await conn.execute(+ sqlalchemy.text(+ "INSERT INTO tenants (id, name, slug, is_active) VALUES (CAST(:i AS uuid), :n, :s, true) ON CONFLICT (id) DO NOTHING"+ ),+ {"i": str(tenant), "n": f"T-{tenant}", "s": f"t-{tenant}"},+ )+ auth = vault.encrypt_dict({"domain": vendor, "api_token": token})+ assert str(auth["api_token"]).startswith("vault:v1:"), "the credential must be ciphertext at rest"+ await conn.execute(+ sqlalchemy.text(+ "INSERT INTO connectors (id, tenant_id, name, connector_type, category, is_enabled, "+ "auth_config, connector_config, health_status, tags, events_ingested, events_dropped, error_count) "+ "VALUES (CAST(:i AS uuid), CAST(:t AS uuid), :n, 'okta', 'iam', true, "+ "CAST(:a AS jsonb), CAST('{}' AS jsonb), 'healthy', CAST('[]' AS jsonb), 0, 0, 0) "+ "ON CONFLICT (id) DO NOTHING"+ ),+ {"i": str(ids[tenant]), "t": str(tenant), "n": f"okta-{tenant}", "a": json.dumps(auth)},+ )+ yield ids+ async with engine.begin() as conn:+ for value in ids.values():+ await conn.execute(+ sqlalchemy.text("DELETE FROM connectors WHERE id = CAST(:i AS uuid)"),+ {"i": str(value)},+ )+++@pytest_asyncio.fixture(loop_scope="module")+async def client(engine): # noqa: ANN001+ """The real connectors ASGI application, over the real request pipeline."""+ from app.db.engine import set_engine+ from app.main import app as application++ set_engine(engine)+ transport = httpx.ASGITransport(app=application)+ async with httpx.AsyncClient(transport=transport, base_url="http://connectors") as http:+ yield http+ set_engine(None)+++def _url(instance_id: uuid.UUID) -> str:+ return f"/api/v1/connectors/instances/{instance_id}/resource-config?resource_id={RESOURCE_ID}"+++# ---------------------------------------------------------------------------+# The finding+# ---------------------------------------------------------------------------+++async def test_a_console_token_cannot_read_another_tenants_instance(client, instances): # noqa: ANN001+ """The reported defect: a tenant-A viewer read tenant B's instance and got 200."""+ _Vendor.seen.clear()++ response = await client.get(+ _url(instances[TENANT_B]),+ headers={"Authorization": f"Bearer {console_token(TENANT_A)}"},+ )++ assert response.status_code == 404, f"tenant A reached tenant B's instance: {response.status_code} {response.text[:300]}"+++async def test_the_victims_credential_is_never_decrypted_or_spent(client, instances): # noqa: ANN001+ """Not merely "no row returned": the victim's secret must not be used at all.++ Asserted against the vendor's own record of the credential presented to it,+ because the sink is an authenticated vendor call made with a decrypted+ ``auth_config`` — a refusal that still spent the secret would be no fix.+ """+ _Vendor.seen.clear()++ await client.get(+ _url(instances[TENANT_B]),+ headers={"Authorization": f"Bearer {console_token(TENANT_A)}"},+ )++ spent = [call["credential"] for call in _Vendor.seen]+ assert TOKEN_B not in spent, f"the platform spent tenant B's credential for tenant A: {spent}"+ assert spent == [], f"the refused request reached the vendor at all: {spent}"+++async def test_a_service_token_cannot_name_one_tenant_and_read_another(client, instances): # noqa: ANN001+ """The declared tenant must bound the read, not merely accompany it."""+ _Vendor.seen.clear()++ response = await client.get(+ _url(instances[TENANT_B]),+ headers={+ "Authorization": f"Bearer {SERVICE_TOKEN}",+ "X-AiSOC-Tenant-ID": str(TENANT_A),+ },+ )++ assert response.status_code == 404, f"a service token declaring tenant A read tenant B: {response.status_code}"+ assert TOKEN_B not in [c["credential"] for c in _Vendor.seen]+++async def test_a_foreign_instance_is_indistinguishable_from_one_that_does_not_exist(client, instances): # noqa: ANN001+ """404 rather than 403, so the route stops being an existence oracle.++ A 403 on a real id and a 404 on an invented one lets an unauthorised caller+ enumerate which connector ids exist across every tenant. The two answers+ must be the same answer.+ """+ headers = {"Authorization": f"Bearer {console_token(TENANT_A)}"}++ foreign = await client.get(_url(instances[TENANT_B]), headers=headers)+ absent = await client.get(_url(uuid.uuid4()), headers=headers)++ assert foreign.status_code == absent.status_code == 404+ assert foreign.json() == absent.json(), f"a foreign instance is distinguishable from an absent one: {foreign.json()} vs {absent.json()}"+++# ---------------------------------------------------------------------------+# Positive controls — the route must still work, or "fixed" means "broken"+# ---------------------------------------------------------------------------+++async def test_each_tenant_still_reaches_its_own_instance_with_its_own_credential(client, instances): # noqa: ANN001+ """Stuck-closed reads as working caution, so this is the half that catches it."""+ for tenant, token in ((TENANT_A, TOKEN_A), (TENANT_B, TOKEN_B)):+ _Vendor.seen.clear()++ response = await client.get(+ _url(instances[tenant]),+ headers={"Authorization": f"Bearer {console_token(tenant)}"},+ )++ assert response.status_code == 200, f"tenant {tenant} lost access to its own instance: {response.text[:300]}"+ assert response.json()["resource_id"] == RESOURCE_ID+ assert [c["credential"] for c in _Vendor.seen] == [token], (+ f"tenant {tenant}'s own read was made with the wrong credential: {_Vendor.seen}"+ )+++async def test_a_service_token_still_acts_for_the_tenant_it_declares(client, instances): # noqa: ANN001+ """Delegation is the mechanism the scheduler and the API both rely on."""+ _Vendor.seen.clear()++ response = await client.get(+ _url(instances[TENANT_B]),+ headers={+ "Authorization": f"Bearer {SERVICE_TOKEN}",+ "X-AiSOC-Tenant-ID": str(TENANT_B),+ },+ )++ assert response.status_code == 200, f"a correctly-scoped service call was refused: {response.text[:300]}"+ assert [c["credential"] for c in _Vendor.seen] == [TOKEN_B]+++async def test_an_unauthenticated_caller_is_refused_before_any_lookup(client, instances): # noqa: ANN001+ """The router-level guard still applies; this pins it from the route's side."""+ _Vendor.seen.clear()++ response = await client.get(_url(instances[TENANT_B]))++ assert response.status_code == 401+ assert _Vendor.seen == []