Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(phase-C2): live posture-snapshot loader for effective permissions (#457)

Beenu Arorabba6771e3a2d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 36faa6855..e4119c20a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Phase C2 — Effective Permissions now resolves against a live posture snapshot.** The resolver is pure (snapshot → effective access), but the only production snapshot source was `_default_snapshot_loader` returning `{}` — so every live "what can this principal do?" call 412'd with "no policy snapshot ingested yet". New `services/api/app/services/effective_permissions/posture_loader.py` collects a real snapshot via the connector's `get_resource_config` read path: a new `POST /connectors/{id}/resource_config` endpoint (same vault-decrypt trust model as `/test` and federated `/query`) exposes it, and `HttpResourceConfigFetcher` + `collect_snapshot` assemble the resolver's snapshot. Coverage is explicit and honest — **Okta** is fully assembled here (user → groups → assigned apps → admin roles, then resolved), while **aws/azure/gcp/gws** consume a connector-provided *reconciled* snapshot (sentinel resource id `__posture_snapshot__`); a provider whose connector hasn't implemented that still 412s (we never fabricate a cloud snapshot). Wired into the endpoint behind `AISOC_EFFECTIVE_PERMISSIONS_LIVE` (default off → prior behaviour preserved), fail-soft to the 412 path on any collection error. 7 API unit tests + the connectors suite (751 passed). Claim-to-gate matrix +1 GATED (25 GATED / 10 PARTIAL / 1 NO GATE).
- **Phase C4 — related alerts now auto-collapse into one ordered attack chain at fuse time.** Correlation grouped alerts into incidents by shared entity and the API could compute a chain per case on demand, but nothing formed/extended a chain **as alerts arrived** — so an analyst saw N separate alerts instead of "step 3 of an intrusion on host X that began 20m ago". New `services/fusion/app/services/attack_chain_grouper.py`: for each entity an alert touches (host/user/ip) it looks up (or mints) a stable `chain_id` in Redis with a rolling window, so a follow-on alert on the same entity — or a *different* entity sharing an IP — joins the same chain. Members are ordered by MITRE kill-chain stage (initial-access → … → impact), so the assignment's `position`/`stage` reflect where in the intrusion this alert sits, not its arrival order. The fusion engine attaches the assignment to `FusedAlert.enrichments["attack_chain"]` (chain_id, position, stage, prior_alert_ids, member_count) for the UI + triage agent. Fail-soft (Redis miss/outage ⇒ no assignment). 8 unit tests; full fusion suite 130 passed at 65% coverage. Claim-to-gate matrix +1 GATED (24 GATED / 10 PARTIAL / 1 NO GATE).
- **Phase B4 — Business Context Rules now run on the live path (environment-specific noise reduction).** A leading AI-SOC differentiator — suppress alerts during a maintenance window, bump severity for production assets, route cloud alerts to the cloud team — existed as an engine + authoring UI in `services/api` but only ran in a dry-run preview; it never touched a live alert. New `services/agents/app/workers/business_context.py` applies the same `when`/`then` semantics (dotted-path fields + `eq/ne/lt/gt/contains/in/exists/...` comparators + `all/any/not`; effects `set_severity` / `route_to` / `tag` / `suppress`) in the auto-triage worker's post-fusion → pre-triage seam. A **suppress** rule drops the alert **before any triage spend**; severity/route/tag mutations flow into the alert the agent reasons over. Rules load from `AISOC_BUSINESS_CONTEXT_RULES_FILE` (mtime-reloaded), gated by `AISOC_BUSINESS_CONTEXT_ENABLED` (default on), fail-soft (bad/missing file ⇒ no rules applied, never an error into triage). The agents image can't import `services/api`, so the evaluator is a faithful, independently-tested re-implementation of the same documented semantics (unifying both call sites is a follow-up). 15 unit tests (`test_business_context_hotpath.py`, added to the CI agents gate). Claim-to-gate matrix +1 GATED (23 GATED / 10 PARTIAL / 1 NO GATE).
- **Phase B3 — rollback is real, actions are post-verified, and approval SLA timers survive restarts.** Three "honest response" gaps closed. (1) **Real rollback:** every executor's `rollback()` previously returned a bare `True` — logging "rolling back" without calling the vendor. New `services/actions/app/services/rollback.py` performs the **real** reverse via the same clients (isolate→`lift_containment`/`unisolate_machine`, block_ip→`unblock_ip`/`unblock_ip_zone`, disable_user→`enable_user`/`unsuspend_user`, suspend_session→`unsuspend_user`) and returns an honest `RollbackResult` (`reversed_` / `simulated` / `supported`) — never a fake success; a failed reverse is reported, not hidden. `autonomy_safety.REVERSIBLE_ACTIONS` now imports from this module (single source of truth) and `test_rollback.py` gates the two sets so an action can't be declared reversible without a real reverse. (2) **Post-action verification:** new `services/actions/app/services/verification.py` re-queries the vendor to confirm the effect is actually present (`VERIFIED` / `FAILED` / honest `UNVERIFIED` when no probe or no creds) — a probe error is never a false `VERIFIED`. (3) **Durable approvals:** `services/slack-bot/app/services/timer_store.py` adds a Postgres-backed `TimerStore`; the `ApprovalTimeoutScheduler` persists pending SLA timers and `recover()` re-arms them on startup (firing overdue ones promptly), so a bot restart can no longer strand a forgotten approval forever. Fail-soft to in-memory when no DB. 25 new tests across actions + slack-bot. Claim-to-gate matrix +1 GATED (22 GATED / 10 PARTIAL / 1 NO GATE).
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 8a14d540d..8865e5e50 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -43,10 +43,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Rollback is real (not "return True"), post-action verified, and approvals are restart-durable | README (response / rollback) | `ci.yml` actions job (`test_rollback.py` — real vendor reverse calls, honest simulated/failed states, REVERSIBLE_ACTIONS gated against the actual reverse impls; `test_verification.py` — re-queries vendor, never a false VERIFIED) + slack-bot job (`test_timer_store.py` — pending SLA timers persist + recover across restart) | GATED | - |
| Environment-specific noise reduction (business context) applied post-fusion → pre-triage | README (noise reduction) | `ci.yml` agents job (`test_business_context_hotpath.py` — YAML when/then rules mutate severity/route/tags and suppress before any triage spend, wired into `FusedAlertTriageWorker.triage`; `AISOC_BUSINESS_CONTEXT_ENABLED` gate) | GATED | - |
| Related alerts auto-collapse into one ordered attack chain at fuse time | README (attack chains) | `ci.yml` fusion job (`test_attack_chain_grouper.py` — shared-entity alerts join one chain within the window, members ordered by MITRE kill-chain stage, cross-entity link via shared IP; wired into `fusion_engine.process` → `enrichments.attack_chain`) | GATED | - |
+| Effective Permissions resolves against a live posture snapshot (not empty stub) | README (effective permissions) | `ci.yml` api job (`test_posture_loader.py` — assembles the Okta resolver snapshot from connector `get_resource_config` calls and resolves it; cloud providers consume a connector-provided reconciled snapshot; failures degrade to empty, never fabricated) + connectors `/connectors/{id}/resource_config` endpoint | GATED | - |
## Summary
-- GATED: 24
+- GATED: 25
- PARTIAL: 10
- NO GATE: 1 (progressively closed through Phases 2–11 and A1–A4: insecure-defaults, secret/IaC scanning, signed releases, cross-store isolation, DAC candidate-rule + imported-count honesty, connector live-test, OpenAPI breaking-change, ClickHouse lake population (A1), live-stream detection (A2), default cold-boot stack (A3), and the behavioral-model fusion (A4). The **last** NO GATE row — wet-eval live-agent scoreboard tables — closes in Phase 4c/E1, which needs a budgeted live-agent run)
diff --git a/services/api/app/api/v1/endpoints/effective_permissions.py b/services/api/app/api/v1/endpoints/effective_permissions.py
index 3ce122146..6b1f29676 100644
--- a/services/api/app/api/v1/endpoints/effective_permissions.py
+++ b/services/api/app/api/v1/endpoints/effective_permissions.py
@@ -36,10 +36,21 @@ import os
from typing import Any
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, status
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.endpoints.auth import get_current_user
+from app.core.config import settings
+from app.db.database import get_db
+from app.models.connector import Connector
from app.models.tenant import User
+from app.security.credential_vault import get_vault
from app.services.effective_permissions.base import ResolverError
+from app.services.effective_permissions.posture_loader import (
+ PROVIDER_CONNECTOR,
+ HttpResourceConfigFetcher,
+ collect_snapshot,
+)
from app.services.effective_permissions.service import (
SUPPORTED_PROVIDERS,
cache_result_into_neo4j,
@@ -52,6 +63,43 @@ router = APIRouter(prefix="/identity", tags=["identity-effective-permissions"])
# Sentinel for the "dry-run with inline snapshot" feature flag. Off by default.
_INLINE_SNAPSHOT_FLAG = "AISOC_ALLOW_INLINE_SNAPSHOT"
+# Phase C2 — live posture collection via the connectors service. Off by default
+# so a deployment without connectors keeps the prior 412 "no snapshot" behaviour.
+_LIVE_POSTURE_FLAG = "AISOC_EFFECTIVE_PERMISSIONS_LIVE"
+
+
+async def _maybe_live_snapshot(db: AsyncSession, tenant_id: Any, provider: str, principal_id: str) -> dict[str, Any] | None:
+ """Collect a live posture snapshot from the tenant's connector, or None.
+
+ Gated by ``AISOC_EFFECTIVE_PERMISSIONS_LIVE=1``. Looks up the enabled
+ connector instance backing ``provider``, decrypts its ``auth_config`` via
+ the vault, and asks the connectors service for the posture snapshot. Any
+ failure returns None so the caller falls back to the 412 "no snapshot" path.
+ """
+ if os.getenv(_LIVE_POSTURE_FLAG, "0") != "1":
+ return None
+ connector_type = PROVIDER_CONNECTOR.get(provider)
+ if connector_type is None:
+ return None
+ try:
+ row = (
+ await db.execute(
+ select(Connector).where(
+ Connector.tenant_id == tenant_id,
+ Connector.connector_type == connector_type,
+ Connector.is_enabled.is_(True),
+ )
+ )
+ ).scalar_one_or_none()
+ if row is None:
+ return None
+ auth = get_vault().decrypt_dict(row.auth_config or {})
+ fetcher = HttpResourceConfigFetcher(settings.CONNECTORS_SERVICE_URL, auth, row.connector_config or {})
+ snapshot = await collect_snapshot(provider, principal_id, fetcher=fetcher)
+ return snapshot or None
+ except Exception as exc: # noqa: BLE001 — live collection is best-effort
+ logger.warning("effective_permissions.live_snapshot_failed: %s", str(exc).replace("\n", " ")[:200])
+ return None
@router.get(
@@ -90,7 +138,8 @@ async def get_effective_permissions(
"Optional base64-encoded JSON snapshot for dry-run resolution. " "Only honoured when AISOC_ALLOW_INLINE_SNAPSHOT=1 is set."
),
),
- _user: User = Depends(get_current_user),
+ current_user: User = Depends(get_current_user),
+ db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
"""Resolve and return the effective-permissions envelope.
@@ -119,6 +168,12 @@ async def get_effective_permissions(
detail=f"snapshot_b64 is not valid base64-encoded JSON: {exc}",
) from exc
+ # Phase C2 — when no inline snapshot was supplied, try live posture
+ # collection from the tenant's connector (gated by
+ # AISOC_EFFECTIVE_PERMISSIONS_LIVE). Falls through to the 412 path on miss.
+ if snapshot is None:
+ snapshot = await _maybe_live_snapshot(db, current_user.tenant_id, provider, principal_id)
+
try:
result = resolve_effective_permissions(
provider=provider,
diff --git a/services/api/app/services/effective_permissions/posture_loader.py b/services/api/app/services/effective_permissions/posture_loader.py
new file mode 100644
index 000000000..dd6d13e39
--- /dev/null
+++ b/services/api/app/services/effective_permissions/posture_loader.py
@@ -0,0 +1,167 @@
+"""Live posture-snapshot collection for effective permissions (Phase C2).
+
+The resolver (`resolve_effective_permissions`) is pure: it takes a *snapshot*
+dict and computes a principal's effective access. Until now the only snapshot
+source was an inline dev-only base64 blob — the production loader
+(`_default_snapshot_loader`) returned `{}`, so every live call 412'd with "no
+policy snapshot ingested yet". This module collects a real snapshot from the
+configured connector via its `get_resource_config` read path.
+
+Transport: the API service owns the credential vault, so it decrypts a
+connector instance's `auth_config` and POSTs it to the connectors service's
+`/connectors/{id}/resource_config` endpoint (same trust model as `/test` and
+federated `/query`). A pluggable `ResourceConfigFetcher` keeps the assembly
+logic unit-testable without a live connectors service.
+
+Coverage is explicit and honest:
+
+* **okta** — fully assembled here: fetch the user, then its groups and assigned
+ apps, and build the resolver's `principals/groups/apps/admin_roles` snapshot.
+* **aws / azure / gcp / gws** — consume a connector-provided *reconciled*
+ snapshot: the connector returns the full provider snapshot for the sentinel
+ resource id `__posture_snapshot__`. Connectors that haven't implemented that
+ yet surface as "no snapshot" (the endpoint still 412s, same as before) — so
+ we never fabricate a cloud snapshot we didn't actually collect.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+import httpx
+import structlog
+
+logger = structlog.get_logger()
+
+# (connector_id, resource_id, at_ts) -> resource config dict.
+ResourceConfigFetcher = Callable[[str, str, str], Awaitable[dict[str, Any]]]
+
+# Provider -> the connector_id whose get_resource_config backs its posture.
+PROVIDER_CONNECTOR = {
+ "okta": "okta",
+ "aws": "aws_security_hub",
+ "azure": "azure_entra",
+ "gcp": "gcp_scc",
+ "gws": "google_workspace",
+}
+
+# Sentinel resource id: connectors that expose a full reconciled provider
+# snapshot return it from get_resource_config for this id.
+POSTURE_SNAPSHOT_ID = "__posture_snapshot__"
+
+
+async def _collect_okta(principal_id: str, fetcher: ResourceConfigFetcher, at_ts: str) -> dict[str, Any]:
+ """Assemble the Okta resolver snapshot for one user principal."""
+ user_cfg = await fetcher("okta", principal_id, at_ts)
+ raw = user_cfg.get("raw") or user_cfg
+ # Okta user payload carries group + app assignments under the profile /
+ # embedded blocks; we accept a few shapes so the connector can evolve.
+ group_ids = list(raw.get("group_ids") or user_cfg.get("group_ids") or [])
+ assigned_apps = list(raw.get("assigned_apps") or user_cfg.get("assigned_apps") or [])
+ admin_roles_direct = list(raw.get("admin_roles") or user_cfg.get("admin_roles") or [])
+
+ groups: list[dict[str, Any]] = []
+ admin_roles: dict[str, dict[str, Any]] = {}
+ apps: dict[str, dict[str, Any]] = {}
+
+ for gid in group_ids:
+ gcfg = await fetcher("okta", gid, at_ts)
+ graw = gcfg.get("raw") or gcfg
+ groups.append(
+ {
+ "id": gid,
+ "name": gcfg.get("name") or graw.get("name") or gid,
+ "admin_roles": list(graw.get("admin_roles") or []),
+ "assigned_apps": list(graw.get("assigned_apps") or []),
+ }
+ )
+ for r in graw.get("admin_role_defs") or []:
+ if isinstance(r, dict) and r.get("id"):
+ admin_roles.setdefault(r["id"], {"id": r["id"], "privileges": list(r.get("privileges") or [])})
+
+ for aid in {*assigned_apps, *(a for g in groups for a in g["assigned_apps"])}:
+ acfg = await fetcher("okta", aid, at_ts)
+ apps[aid] = {"id": aid, "name": acfg.get("name") or aid}
+
+ for r in raw.get("admin_role_defs") or []:
+ if isinstance(r, dict) and r.get("id"):
+ admin_roles.setdefault(r["id"], {"id": r["id"], "privileges": list(r.get("privileges") or [])})
+
+ return {
+ "principals": [
+ {
+ "id": principal_id,
+ "groups": group_ids,
+ "assigned_apps": assigned_apps,
+ "admin_roles": admin_roles_direct,
+ }
+ ],
+ "groups": groups,
+ "admin_roles": list(admin_roles.values()),
+ "apps": list(apps.values()),
+ }
+
+
+async def collect_snapshot(
+ provider: str,
+ principal_id: str,
+ *,
+ fetcher: ResourceConfigFetcher,
+ at_ts: str = "",
+) -> dict[str, Any]:
+ """Collect a resolver snapshot for ``provider``/``principal_id``.
+
+ Returns an empty dict when nothing could be collected (the endpoint then
+ surfaces the same 412 as before — we never fabricate a snapshot).
+ """
+ connector_id = PROVIDER_CONNECTOR.get(provider)
+ if connector_id is None:
+ return {}
+ try:
+ if provider == "okta":
+ return await _collect_okta(principal_id, fetcher, at_ts)
+ # Cloud providers: consume a connector-provided reconciled snapshot.
+ cfg = await fetcher(connector_id, POSTURE_SNAPSHOT_ID, at_ts)
+ snap = cfg.get("snapshot") if isinstance(cfg, dict) else None
+ if isinstance(snap, dict) and snap:
+ return snap
+ # Some connectors may already return the snapshot at the top level.
+ if isinstance(cfg, dict) and any(k in cfg for k in ("principals", "users", "policies", "role_assignments")):
+ return cfg
+ return {}
+ except Exception as exc: # noqa: BLE001 — collection failure => empty (412), never a crash
+ logger.warning("posture_loader.collect_failed", provider=provider, error=str(exc))
+ return {}
+
+
+class HttpResourceConfigFetcher:
+ """Fetch resource configs from the connectors service over HTTP.
+
+ The API layer decrypts the connector instance's ``auth_config`` (vault) and
+ passes the plaintext here; the connectors service never sees vault tokens
+ (same trust model as ``/test`` and federated ``/query``).
+ """
+
+ def __init__(self, base_url: str, auth_config: dict[str, Any], connector_config: dict[str, Any] | None = None) -> None:
+ self._base = base_url.rstrip("/")
+ self._auth = auth_config
+ self._config = connector_config or {}
+
+ async def __call__(self, connector_id: str, resource_id: str, at_ts: str) -> dict[str, Any]:
+ url = f"{self._base}/connectors/{connector_id}/resource_config"
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ resp = await client.post(
+ url,
+ json={
+ "auth_config": self._auth,
+ "connector_config": self._config,
+ "resource_id": resource_id,
+ "at_ts": at_ts,
+ },
+ )
+ if resp.status_code != 200:
+ logger.info("posture_loader.fetch_non_200", connector_id=connector_id, status=resp.status_code)
+ return {}
+ body = resp.json()
+ return body.get("config") if isinstance(body, dict) else {}
diff --git a/services/api/tests/test_posture_loader.py b/services/api/tests/test_posture_loader.py
new file mode 100644
index 000000000..69112f4c3
--- /dev/null
+++ b/services/api/tests/test_posture_loader.py
@@ -0,0 +1,104 @@
+"""Phase C2 — effective-permissions live posture-loader tests.
+
+Proves the loader assembles a resolver-ready Okta snapshot from connector
+`get_resource_config` calls (user → groups → apps → admin roles), that the
+assembled snapshot actually resolves, that cloud providers consume a
+connector-provided reconciled snapshot, and that collection failures degrade
+to an empty dict (→ 412), never a crash or a fabricated snapshot.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.services.effective_permissions.okta import OktaResolver
+from app.services.effective_permissions.posture_loader import POSTURE_SNAPSHOT_ID, collect_snapshot
+
+pytestmark = pytest.mark.asyncio
+
+
+def _okta_fetcher():
+ """A fake get_resource_config for one user, one group, one app, one role."""
+ data = {
+ "00u-alice": {
+ "raw": {
+ "group_ids": ["00g-admins"],
+ "assigned_apps": [],
+ "admin_roles": [],
+ }
+ },
+ "00g-admins": {
+ "name": "Admins",
+ "raw": {
+ "admin_roles": ["role-super"],
+ "assigned_apps": ["0oa-console"],
+ "admin_role_defs": [{"id": "role-super", "privileges": ["okta.users.manage", "okta.groups.manage"]}],
+ },
+ },
+ "0oa-console": {"name": "Okta Admin Console"},
+ }
+
+ async def _fetch(connector_id, resource_id, at_ts): # noqa: ANN001, ARG001
+ return data.get(resource_id, {})
+
+ return _fetch
+
+
+async def test_okta_snapshot_assembled_from_resource_configs():
+ snap = await collect_snapshot("okta", "00u-alice", fetcher=_okta_fetcher())
+ assert [p["id"] for p in snap["principals"]] == ["00u-alice"]
+ assert snap["principals"][0]["groups"] == ["00g-admins"]
+ group = next(g for g in snap["groups"] if g["id"] == "00g-admins")
+ assert "role-super" in group["admin_roles"]
+ assert "0oa-console" in group["assigned_apps"]
+ assert any(r["id"] == "role-super" for r in snap["admin_roles"])
+ assert any(a["id"] == "0oa-console" for a in snap["apps"])
+
+
+async def test_assembled_okta_snapshot_resolves():
+ snap = await collect_snapshot("okta", "00u-alice", fetcher=_okta_fetcher())
+ result = OktaResolver().resolve("00u-alice", snapshot=snap)
+ # Alice inherits the super-admin role via the Admins group → has privileges.
+ perms = {d.permission if hasattr(d, "permission") else d for d in result.decisions}
+ assert result.decisions # non-empty: she resolved to real permissions
+ assert any("okta.users.manage" in str(p) for p in perms)
+
+
+async def test_cloud_provider_consumes_reconciled_snapshot():
+ reconciled = {"principals": [{"id": "arn:aws:iam::1:user/bob"}], "policies": [], "resources": []}
+
+ async def _fetch(connector_id, resource_id, at_ts): # noqa: ANN001, ARG001
+ assert resource_id == POSTURE_SNAPSHOT_ID
+ return {"snapshot": reconciled}
+
+ snap = await collect_snapshot("aws", "arn:aws:iam::1:user/bob", fetcher=_fetch)
+ assert snap == reconciled
+
+
+async def test_cloud_provider_top_level_snapshot_shape():
+ async def _fetch(connector_id, resource_id, at_ts): # noqa: ANN001, ARG001
+ return {"principals": [{"id": "u1"}], "policies": []}
+
+ snap = await collect_snapshot("azure", "u1", fetcher=_fetch)
+ assert "principals" in snap
+
+
+async def test_unknown_provider_returns_empty():
+ async def _fetch(connector_id, resource_id, at_ts): # noqa: ANN001, ARG001
+ return {"anything": True}
+
+ assert await collect_snapshot("mystery", "p", fetcher=_fetch) == {}
+
+
+async def test_fetch_error_degrades_to_empty():
+ async def _boom(connector_id, resource_id, at_ts): # noqa: ANN001, ARG001
+ raise RuntimeError("connectors service down")
+
+ assert await collect_snapshot("okta", "00u-alice", fetcher=_boom) == {}
+ assert await collect_snapshot("aws", "x", fetcher=_boom) == {}
+
+
+async def test_empty_cloud_snapshot_returns_empty():
+ async def _fetch(connector_id, resource_id, at_ts): # noqa: ANN001, ARG001
+ return {"snapshot": {}}
+
+ assert await collect_snapshot("gcp", "[email protected]", fetcher=_fetch) == {}
diff --git a/services/connectors/app/api/router.py b/services/connectors/app/api/router.py
index f29b5165f..e7660e385 100644
--- a/services/connectors/app/api/router.py
+++ b/services/connectors/app/api/router.py
@@ -71,6 +71,22 @@ class TestConnectionRequest(BaseModel):
)
+class ResourceConfigRequest(BaseModel):
+ """Fetch one resource's live configuration (Phase C2).
+
+ Same trust model as ``TestConnectionRequest``: the API service decrypts
+ ``auth_config`` before forwarding here. ``resource_id`` is the vendor-native
+ id (Okta group/app id, ARN, Azure object id, …); ``at_ts`` is an optional
+ point-in-time (ISO-8601) — connectors that can't time-travel return their
+ latest and mark ``snapshot_freshness``.
+ """
+
+ auth_config: dict[str, Any] = PydField(default_factory=dict)
+ connector_config: dict[str, Any] = PydField(default_factory=dict)
+ resource_id: str = PydField(..., description="Vendor-native resource id to fetch.")
+ at_ts: str = PydField(default="", description="Optional ISO-8601 point-in-time.")
+
+
class FederatedQueryRequest(BaseModel):
"""Run a unified query against a single connector instance.
@@ -269,6 +285,42 @@ async def test_connector_connection(connector_id: str, payload: TestConnectionRe
return result
[email protected]("/connectors/{connector_id}/resource_config")
+async def get_resource_config(connector_id: str, payload: ResourceConfigRequest):
+ """Fetch one resource's live configuration (Phase C2 posture collection).
+
+ Trust boundary matches ``/test`` and ``/query``: the API service has
+ already decrypted ``auth_config`` against the vault; the connector instance
+ lives only for this request. Connectors that don't implement
+ ``get_resource_config`` return 501.
+ """
+ cls = CONNECTOR_REGISTRY.get(connector_id)
+ if cls is None:
+ raise HTTPException(status_code=404, detail=f"Connector '{connector_id}' not found")
+
+ kwargs = {**payload.auth_config, **payload.connector_config}
+ try:
+ connector = cls(**kwargs)
+ except TypeError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail=f"connector config does not match schema: {exc}",
+ ) from exc
+
+ try:
+ config = await connector.get_resource_config(payload.resource_id, payload.at_ts)
+ except NotImplementedError as exc:
+ raise HTTPException(status_code=status.HTTP_501_NOT_IMPLEMENTED, detail=str(exc)) from exc
+ except Exception as exc: # noqa: BLE001
+ logger.exception("connector.resource_config.runtime_error", connector_id=_safe_log_val(connector_id))
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail="Resource-config fetch failed. Check connector configuration and connectivity.",
+ ) from exc
+
+ return {"connector_id": connector_id, "resource_id": payload.resource_id, "config": config}
+
+
@router.post("/connectors/{connector_id}/query")
async def run_federated_query(connector_id: str, payload: FederatedQueryRequest):
"""Translate a ``UnifiedQuery`` and run it against the connector's backend.