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(2.5): collect a real posture, and version it so it can be read at event time

Beenu Arora1ef5c0ea6418
diff --git a/DEPTH_PROGRESS.md b/DEPTH_PROGRESS.md
index aec08e1cf..dc4c64181 100644
--- a/DEPTH_PROGRESS.md
+++ b/DEPTH_PROGRESS.md
@@ -284,6 +284,43 @@ Instead, every selector field, `group-by` and `distinct_by` is checked
against the emitted-field namespace with **no ceiling**, which caught three
invented fields on the first run of the gate.
+### D11 -- The plan says `valid_to`; this schema says `valid_until`
+
+Item 2.5 asks for versioned snapshots with `valid_from` / `valid_to`. The one
+existing table in this database that bounds a fact in time is `identity_edges`
+(migration 018), and it spells the closing column `valid_until`. Adopting the
+plan's spelling would put two names for one concept in one schema, and the
+next person to write a point-in-time query would have to know which table
+they were in before they could write a `WHERE`. The existing spelling wins;
+`posture_snapshots` uses `valid_from` / `valid_until`, and the deviation is
+recorded here rather than made silently.
+
+### D12 -- Eleven API tests are already failing on `main`, and nothing grades them
+
+The full `services/api` suite run for 2.5 reported 4,774 passed and 11 failed.
+All eleven are in `test_alert_list_priority_sort.py` and
+`test_alert_tiles_cover_the_whole_result_set.py`, neither of which this branch
+touches, and all eleven fail identically on a clean `git archive origin/main`
+export with the same error: `list_alerts() missing 1 required positional
+argument: 'http_request'`. The handler grew a `Request` parameter; the two
+test files call it directly and were not updated.
+
+What makes this worth a deviation rather than a footnote is why it is still
+open on a branch-protected `main` with twenty-eight required checks. Both
+files open with "Run against live Postgres: the defect is an `ORDER BY`, and a
+fake session that answers any query cannot tell one ordering from another" --
+and their fixture skips when no database answers. The only job that runs them
+is `Python — Tests`, which sets `DATABASE_URL` to a host with no Postgres
+behind it, so the fixture skips and the job is green. Neither file is named by
+any workflow in `.github/workflows/`, so no live-Postgres job runs them
+either. The suite that exists to prove the priority ordering has therefore
+never graded it, and the signature break has been invisible since it landed.
+
+Fixing them belongs to item 2.6, which wires the priority score and the queue
+ordering these very tests cover; the fix lands there together with a workflow
+that actually runs them against a database, because repairing the assertions
+without that would restore a test nothing executes.
+
## Phase 1: Verdict quality you can publish
- [x] **1.1** Balanced, labelled verdict corpus
@@ -301,7 +338,7 @@ invented fields on the first run of the gate.
- [x] **2.2** Activity projection on every event
- [x] **2.3** Event classification catalogue
- [ ] **2.4** Sessions per principal
-- [ ] **2.5** `__posture_snapshot__` collectors (AWS, Azure, GCP, Workspace, GitHub)
+- [x] **2.5** `__posture_snapshot__` collectors (AWS, Azure, GCP, Workspace, GitHub)
- [ ] **2.6** Use the posture everywhere
- [ ] **2.7** Entity context in CORE (ADR first)
@@ -430,3 +467,4 @@ invented fields on the first run of the gate.
| 2026-10-09 | 3.2 | Ordered and unordered sequences in the windowed engine; all four translatable Sigma correlation types compile, seven refusal reasons recorded. No upstream correlation rule exists in this tree to import (D8), so the corpus is first-party and labelled as such. |
| 2026-10-09 | 4.1 | Reproduced: `check_cloud_native_collection.py` on the unmodified tree reported all three collection paths absent. Implemented `aws_cloudtrail_s3` (SQS-notified S3 objects; management events, data events and VPC flow logs; delete-after-emit), `gcp_pubsub` (REST pull on a log-sink subscription; ack-after-read) and `azure_event_hubs` (Capture blobs over the Data Lake Gen2 JSON API, with a focused Avro OCF reader). Negative controls recorded in the PR: deleting the SQS message before the object is read, acknowledging the Pub/Sub batch before it is built, ignoring the Avro union branch index, and ignoring the flow-log header line each fail a named test, and all were restored. Connectors suite 1014 -> 1098 passed. |
| 2026-10-09 | 3.1 | All 74 decided. 50 translated into `wd-*` rules derived from each original's own clauses and replayed through the real engine (162 assertions); 24 refused with a reason across five kinds. `MAX_UNREACHABLE` 119 → 45, published executable 2,603 → 2,529, windowed 18 → 68. Three findings recorded as D4–D6 below. |
+| 2026-10-11 | 2.5 | Reproduced: `test_posture_snapshot_coverage.py` on the unmodified tree asserted the *gap* — every resolver in `effective_permissions/` was pure and the only production snapshot source returned `{}`, so every live call 412'd and the subsystem had never answered a question about a real estate. Five collectors now exist under `services/connectors/app/connectors/posture/`, reached by a `__posture_snapshot__` sentinel through each connector's `get_resource_config`, and the coverage test is inverted: it now fails when a registered resolver has no declared collector. Building it found three things worth recording. (a) `BaseConnector.get_resource_config` declares `at_ts: str | None = None` while AWS, Okta and GitHub each required a positional `ts`, so a caller written against the base class raised `TypeError` on three of the connectors — standardised, with `test_every_implementation_matches_the_base_signature` holding it. (b) Google Workspace's directory read needs scopes the audit-log credential is not consented for, so the JWT is now built per scope: asking for both in one assertion would have broken alert polling on every tenant that had not pre-consented the new ones. (c) A snapshot is only an answer if you know *when* it was true — an alert is triaged minutes to days after the event, and a single mutable "current posture" row answers "what can this identity do now" while appearing to answer "what could it do when it acted", which is the worse failure because the number looks right. Migration 103 therefore versions snapshots on `valid_from`/`valid_until` (`valid_to` in the plan; `valid_from`/`valid_until` is the existing spelling in migration 018 and two spellings of one concept in one schema is worse than a recorded deviation — D11). Negative controls, both run against live Postgres and both restored: dropping `posture_snapshots_live_idx` leaves `test_a_second_live_row_is_refused_by_the_database` reporting `DID NOT RAISE IntegrityError`, and defeating the content-hash comparison in `save_snapshot` fails `test_unchanged_recollection_does_not_open_a_version` with two distinct row ids — without that comparison an unchanged estate re-collected hourly writes a version an hour and "when did this posture last change" becomes unanswerable because every row is a change. Evidence: 12 posture-store tests against live Postgres with the migration chain applied, 65 across the posture and effective-permission suites, 1,145 connector tests, 4,774 API tests. Eleven API failures are pre-existing on `main` and unrelated — recorded as D12. |
diff --git a/apps/web/src/app/(app)/identity/permissions/EffectivePermissionsView.tsx b/apps/web/src/app/(app)/identity/permissions/EffectivePermissionsView.tsx
index fdab1464b..c8417dac5 100644
--- a/apps/web/src/app/(app)/identity/permissions/EffectivePermissionsView.tsx
+++ b/apps/web/src/app/(app)/identity/permissions/EffectivePermissionsView.tsx
@@ -90,7 +90,7 @@ type ResolverResult = {
};
export type ResolverResultPayload = ResolverResult;
-type SupportedProvider = 'aws' | 'azure' | 'gcp' | 'okta' | 'gws';
+type SupportedProvider = 'aws' | 'azure' | 'gcp' | 'okta' | 'gws' | 'github';
const SUPPORTED_PROVIDERS: SupportedProvider[] = [
'aws',
@@ -98,6 +98,7 @@ const SUPPORTED_PROVIDERS: SupportedProvider[] = [
'gcp',
'okta',
'gws',
+ 'github',
];
function isSupportedProvider(p: string | null): p is SupportedProvider {
@@ -110,6 +111,7 @@ const PROVIDER_LABEL: Record<SupportedProvider, string> = {
gcp: 'GCP',
okta: 'Okta',
gws: 'Workspace',
+ github: 'GitHub',
};
const MAX_RENDERED_DECISIONS = 250;
diff --git a/services/api/app/api/v1/endpoints/effective_permissions.py b/services/api/app/api/v1/endpoints/effective_permissions.py
index a2cc271de..3c73d28a9 100644
--- a/services/api/app/api/v1/endpoints/effective_permissions.py
+++ b/services/api/app/api/v1/endpoints/effective_permissions.py
@@ -59,6 +59,7 @@ 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,
+ CollectedSnapshot,
HttpResourceConfigFetcher,
collect_snapshot,
)
@@ -67,6 +68,7 @@ from app.services.effective_permissions.service import (
cache_result_into_neo4j,
resolve_effective_permissions,
)
+from app.services.posture_store import save_snapshot
logger = logging.getLogger(__name__)
@@ -79,6 +81,44 @@ _INLINE_SNAPSHOT_FLAG = "AISOC_ALLOW_INLINE_SNAPSHOT"
_LIVE_POSTURE_FLAG = "AISOC_EFFECTIVE_PERMISSIONS_LIVE"
+async def _record_snapshot(
+ db: AsyncSession,
+ tenant_id: Any,
+ provider: str,
+ connector_type: str,
+ connector_instance_id: Any,
+ collected: CollectedSnapshot,
+) -> None:
+ """Persist a collected posture as a version, best-effort.
+
+ Deliberately swallowing: a tenant asking "what can this identity do"
+ should get their answer even if the archive write fails. The failure is
+ logged at ``warning`` with the provider named, because a store that has
+ silently stopped accepting versions looks exactly like a tenant who has
+ not collected yet, and the point-in-time read would then answer ``None``
+ for a reason no reader could distinguish from the honest one.
+ """
+ try:
+ await save_snapshot(
+ db,
+ tenant_id=tenant_id,
+ provider=provider,
+ connector_id=connector_type,
+ connector_instance_id=connector_instance_id,
+ snapshot=collected.snapshot,
+ partial=collected.partial,
+ collection_notes=list(collected.notes),
+ )
+ await db.commit()
+ except Exception as exc: # noqa: BLE001 — archiving must not fail the read
+ await db.rollback()
+ logger.warning(
+ "effective_permissions.snapshot_not_recorded provider=%s: %s",
+ provider,
+ str(exc).replace("\n", " ")[:200],
+ )
+
+
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.
@@ -106,8 +146,19 @@ async def _maybe_live_snapshot(db: AsyncSession, tenant_id: Any, provider: str,
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
+ collected = await collect_snapshot(provider, principal_id, fetcher=fetcher)
+ if not collected:
+ return None
+ # Record the version. The resolver below answers from the snapshot in
+ # hand, but an alert is triaged minutes to days after the event it
+ # describes, and "what could this identity do **when it acted**" can
+ # only be answered from a version that was stored while it was true.
+ # Okta is excluded because its snapshot is assembled per principal
+ # rather than per estate — storing one would make the live row mean
+ # "the posture of whoever was looked up last".
+ if provider != "okta":
+ await _record_snapshot(db, tenant_id, provider, connector_type, row.id, collected)
+ return collected.snapshot
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
diff --git a/services/api/app/services/effective_permissions/github.py b/services/api/app/services/effective_permissions/github.py
new file mode 100644
index 000000000..01b916e54
--- /dev/null
+++ b/services/api/app/services/effective_permissions/github.py
@@ -0,0 +1,189 @@
+"""GitHub organisation effective-permissions resolver (depth plan 2.5).
+
+GitHub belongs in this set because it is where the source and the deployment
+credentials live, so "what can this identity do" has a direct blast radius --
+and unlike the three clouds its permission model is small enough to resolve
+completely rather than partially.
+
+Resolution model
+----------------
+
+A principal reaches a repository three ways, and the strongest wins:
+
+1. **Organisation owner.** Admin on every repository in the organisation,
+ regardless of any team or collaborator grant. Collected separately
+ because an owner frequently holds no team grant at all, and a resolver
+ that only read teams would report the most privileged identities in the
+ organisation as having whatever their team happened to give them.
+2. **Team membership.** A team holds a level on a repository and every
+ member inherits it.
+3. **Direct collaborator.** A grant made to the person on one repository.
+
+Snapshot shape::
+
+ {
+ "org": "acme",
+ "principals": [
+ {"id": "alice", "type": "user", "org_role": "member|admin",
+ "teams": ["platform"]},
+ {"id": "team:platform", "type": "team", ...},
+ ],
+ "teams": [{"id": "team:platform", "slug": "platform", "members": ["alice"]}],
+ "repositories": [{"id": "acme/api", "private": true, "archived": false}],
+ "grants": [
+ {"id": "...", "principal_id": "alice" | "team:platform",
+ "repository_id": "acme/api", "level": "push",
+ "via": null | "team:platform" | "organisation-owner"},
+ ],
+ "level_actions": {"push": ["repo.read", ...], ...}
+ }
+
+The level ladder is ordered by the *collector*, not here: it is a property
+of GitHub rather than of this product, and re-deriving it in the resolver
+would be a second place for the ladder to drift. This module reads
+``level_actions`` out of the snapshot for the same reason.
+
+There is no deny in GitHub's model -- access is granted, never subtracted --
+so ``deny_actions`` is always empty, and that is a real property of the
+provider rather than something unimplemented here. An archived repository is
+the one case that *looks* like a deny: writes are refused regardless of the
+grant. It is reported as a note on the decision's provenance rather than as
+a denied action, because the grant genuinely exists and would take effect
+the moment someone unarchives the repository -- which is a single click, and
+is exactly the kind of latent access a reviewer is looking for.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from typing import Any
+
+from app.services.effective_permissions.base import (
+ PolicyChainStep,
+ ResolvedPermission,
+ Resolver,
+ ResolverError,
+ ResolverResult,
+)
+
+#: Weakest to strongest. Mirrors the collector's ladder; the parity test in
+#: ``services/connectors/tests/test_posture_collectors.py`` asserts the two
+#: are equal rather than
+#: trusting this comment.
+LEVELS = ("pull", "triage", "push", "maintain", "admin")
+
+
+def _strongest(*levels: str) -> str:
+ known = [level for level in levels if level in LEVELS]
+ if not known:
+ return ""
+ return max(known, key=LEVELS.index)
+
+
+class GitHubResolver(Resolver):
+ """Resolve what a GitHub principal can do to each repository."""
+
+ provider = "github"
+ coverage = "full"
+
+ def __init__(self, snapshot: dict[str, Any] | None = None) -> None:
+ self._snapshot = snapshot
+
+ def resolve(
+ self,
+ principal_id: str,
+ *,
+ snapshot: dict[str, Any] | None = None,
+ ) -> ResolverResult:
+ snap = snapshot if snapshot is not None else self._snapshot
+ if snap is None:
+ raise ResolverError("GitHubResolver.resolve called without a snapshot")
+
+ principals = {p["id"]: p for p in snap.get("principals", []) if p.get("id")}
+ principal = principals.get(principal_id)
+ if principal is None:
+ raise ResolverError(f"principal {principal_id!r} not present in snapshot")
+
+ level_actions: dict[str, list[str]] = snap.get("level_actions") or {}
+ notes: list[str] = []
+ if not level_actions:
+ # Without the ladder the resolver cannot say what a level
+ # confers. Refusing is correct: inventing a ladder here is how
+ # the product would end up with two that disagree.
+ raise ResolverError(
+ "snapshot carries no level_actions map; the collector owns the GitHub permission "
+ "ladder and a resolver that invented one would be a second source of truth"
+ )
+
+ teams = {t["id"]: t for t in snap.get("teams", []) if t.get("id")}
+ repositories = {r["id"]: r for r in snap.get("repositories", []) if r.get("id")}
+
+ # Every id this principal can be granted through: itself, plus the
+ # teams it belongs to.
+ identities = {principal_id}
+ for slug in principal.get("teams") or []:
+ identities.add(f"team:{slug}")
+ for team_id, team in teams.items():
+ if principal_id in (team.get("members") or []):
+ identities.add(team_id)
+
+ # repository -> (level, winning grant). A principal with two grants
+ # on one repository gets the stronger, which is GitHub's rule.
+ best: dict[str, tuple[str, dict[str, Any]]] = {}
+ chains: dict[str, list[PolicyChainStep]] = {}
+ for grant in snap.get("grants", []):
+ if grant.get("principal_id") not in identities:
+ continue
+ repo_id = grant.get("repository_id")
+ level = grant.get("level")
+ if not repo_id or level not in LEVELS:
+ continue
+ chains.setdefault(repo_id, []).append(
+ PolicyChainStep(
+ kind="grant",
+ id=str(grant.get("id") or f"{grant.get('principal_id')}:{repo_id}"),
+ name=f"{level} via {grant.get('via') or 'direct collaborator'}",
+ effect="allow",
+ via=grant.get("via"),
+ )
+ )
+ current = best.get(repo_id)
+ if current is None or LEVELS.index(level) > LEVELS.index(current[0]):
+ best[repo_id] = (level, grant)
+
+ decisions: list[ResolvedPermission] = []
+ archived: list[str] = []
+ for repo_id, (level, _grant) in sorted(best.items()):
+ repo = repositories.get(repo_id, {})
+ if repo.get("archived"):
+ archived.append(repo_id)
+ decisions.append(
+ ResolvedPermission(
+ principal_id=principal_id,
+ resource_id=repo_id,
+ resource_kind="github:repository",
+ resource_arn=repo_id,
+ actions=tuple(sorted(level_actions.get(level, ()))),
+ # GitHub grants and never subtracts. Empty here is a
+ # property of the provider, not a gap in this resolver.
+ deny_actions=(),
+ policy_chain=tuple(chains.get(repo_id, ())),
+ )
+ )
+
+ if archived:
+ notes.append(
+ f"{len(archived)} repository(ies) are archived, so writes are refused today despite "
+ f"the grant: {', '.join(sorted(archived)[:5])}"
+ + (" and others" if len(archived) > 5 else "")
+ + ". The grant is real and takes effect the moment the repository is unarchived."
+ )
+
+ return ResolverResult(
+ provider=self.provider,
+ principal_id=principal_id,
+ coverage=self.coverage,
+ last_resolved=datetime.now(tz=UTC),
+ decisions=decisions,
+ notes=notes,
+ )
diff --git a/services/api/app/services/effective_permissions/posture_loader.py b/services/api/app/services/effective_permissions/posture_loader.py
index 74ebfa7f4..ca3db57e3 100644
--- a/services/api/app/services/effective_permissions/posture_loader.py
+++ b/services/api/app/services/effective_permissions/posture_loader.py
@@ -17,16 +17,17 @@ 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.
+* **aws / azure / gcp / gws / github** — 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 snapshot we didn't actually collect.
"""
from __future__ import annotations
from collections.abc import Awaitable, Callable
+from dataclasses import dataclass
from typing import Any
import httpx
@@ -44,6 +45,7 @@ PROVIDER_CONNECTOR = {
"azure": "azure_entra",
"gcp": "gcp_scc",
"gws": "google_workspace",
+ "github": "github",
}
# Sentinel resource id: connectors that expose a full reconciled provider
@@ -103,36 +105,71 @@ async def _collect_okta(principal_id: str, fetcher: ResourceConfigFetcher, at_ts
}
+@dataclass(frozen=True)
+class CollectedSnapshot:
+ """A collected snapshot and how complete the collector says it is.
+
+ The gap travels with the data on purpose. An earlier shape returned the
+ bare snapshot dict and dropped ``partial`` and the notes on the floor, so
+ a collection that 403'd halfway through a page of role assignments was
+ indistinguishable from one that read the whole estate -- and the
+ difference is an identity that looks harmless because the policy granting
+ it everything was in the part nobody could read.
+ """
+
+ snapshot: dict[str, Any]
+ partial: bool = False
+ notes: tuple[str, ...] = ()
+
+ def __bool__(self) -> bool:
+ """Truthy only when something was actually collected.
+
+ Callers test this to decide between answering and 412-ing, so an
+ empty snapshot must be falsy however complete the collector claims
+ it was: zero principals means a lost read permission far more often
+ than it means an empty estate.
+ """
+ return bool(self.snapshot)
+
+
async def collect_snapshot(
provider: str,
principal_id: str,
*,
fetcher: ResourceConfigFetcher,
at_ts: str = "",
-) -> dict[str, Any]:
+) -> CollectedSnapshot:
"""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).
+ Returns an empty snapshot 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 {}
+ return CollectedSnapshot({})
try:
if provider == "okta":
- return await _collect_okta(principal_id, fetcher, at_ts)
+ # Assembled here rather than by the connector, and assembled from
+ # reads that either succeed or raise, so there is no partial state
+ # for it to report.
+ return CollectedSnapshot(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
+ notes = cfg.get("collection_notes")
+ return CollectedSnapshot(
+ snapshot=snap,
+ partial=bool(cfg.get("partial")),
+ notes=tuple(str(n) for n in notes) if isinstance(notes, list) else (),
+ )
# 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 {}
+ return CollectedSnapshot(cfg)
+ return CollectedSnapshot({})
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 {}
+ return CollectedSnapshot({})
class HttpResourceConfigFetcher:
diff --git a/services/api/app/services/effective_permissions/service.py b/services/api/app/services/effective_permissions/service.py
index 31d1d83d7..29b5a2316 100644
--- a/services/api/app/services/effective_permissions/service.py
+++ b/services/api/app/services/effective_permissions/service.py
@@ -35,6 +35,7 @@ from app.services.effective_permissions.base import (
chain_ids,
)
from app.services.effective_permissions.gcp import GcpIamResolver
+from app.services.effective_permissions.github import GitHubResolver
from app.services.effective_permissions.gws import GoogleWorkspaceResolver
from app.services.effective_permissions.okta import OktaResolver
@@ -47,6 +48,7 @@ SUPPORTED_PROVIDERS: dict[str, type[Resolver]] = {
"gcp": GcpIamResolver,
"okta": OktaResolver,
"gws": GoogleWorkspaceResolver,
+ "github": GitHubResolver,
}
@@ -62,6 +64,7 @@ _PROVIDER_LOG_TOKENS: dict[str, str] = {
"gcp": "gcp",
"okta": "okta",
"gws": "gws",
+ "github": "github",
}
diff --git a/services/api/app/services/posture_store.py b/services/api/app/services/posture_store.py
new file mode 100644
index 000000000..843d21481
--- /dev/null
+++ b/services/api/app/services/posture_store.py
@@ -0,0 +1,340 @@
+"""Read and write versioned identity-posture snapshots (depth plan 2.5).
+
+Backs migration 103. The table's reason for existing is in its own comment
+block; this module is the only thing that writes it, and it exists to keep
+one invariant true from the application side as well as the index side:
+
+ at most one row per (tenant, provider) has ``valid_until IS NULL``
+
+and to make the point-in-time read the easy call to reach for, so a caller
+asking "what could this identity do" does not quietly get "what can it do
+now" because that query was shorter to write.
+
+Every statement filters on ``tenant_id`` in the ``WHERE`` clause. RLS is
+enabled on the table too, but the query-layer filter is the control being
+relied on here: RLS depends on the session GUC being set, and a path that
+forgets it would read across tenants with the policy still in force.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import uuid
+from dataclasses import dataclass
+from datetime import datetime
+from typing import Any
+
+import structlog
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+logger = structlog.get_logger(__name__)
+
+#: Mirrors the CHECK constraint in migration 103. Declared here as well so a
+#: bad provider is refused with a sentence naming the valid set rather than
+#: an IntegrityError from the driver.
+PROVIDERS: frozenset[str] = frozenset({"aws", "azure", "gcp", "gws", "github", "okta"})
+
+
+def content_hash(snapshot: dict[str, Any]) -> str:
+ """sha256 over a canonical rendering of the snapshot.
+
+ ``sort_keys`` is what makes this stable: two collections of an unchanged
+ estate differ only in dict ordering, and without it every re-collection
+ would look like a posture change and the history would answer "when did
+ this last change" with "every hour".
+ """
+ canonical = json.dumps(snapshot, sort_keys=True, separators=(",", ":"), default=str)
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
+
+
+def counts(snapshot: dict[str, Any]) -> tuple[int, int, int]:
+ """``(principals, resources, policies)`` for one snapshot.
+
+ Counted from the collected document rather than from whatever the
+ collector thought it fetched, so a truncated page shows up as a smaller
+ number instead of agreeing with an optimistic running total.
+
+ It lives here, beside the columns it fills, because the only reader of
+ these three numbers is this table. An earlier draft had it in the
+ connectors package, one import boundary away from the only thing that
+ uses it, which is how a second definition starts.
+ """
+ principals = len(snapshot.get("principals") or ())
+ resources = len(snapshot.get("resources") or ())
+ policies = (
+ len(snapshot.get("policies") or ())
+ + len(snapshot.get("role_definitions") or ())
+ + len(snapshot.get("roles") or ())
+ + len(snapshot.get("admin_roles") or ())
+ )
+ return principals, resources, policies
+
+
+@dataclass(frozen=True)
+class PostureSnapshot:
+ """One version of a provider's posture, and how complete it is."""
+
+ id: uuid.UUID
+ tenant_id: uuid.UUID
+ provider: str
+ connector_id: str
+ snapshot: dict[str, Any]
+ content_hash: str
+ principal_count: int
+ resource_count: int
+ policy_count: int
+ partial: bool
+ collection_notes: list[str]
+ collected_at: datetime
+ valid_from: datetime
+ valid_until: datetime | None
+
+ @property
+ def is_live(self) -> bool:
+ return self.valid_until is None
+
+
+def _row_to_snapshot(row: Any) -> PostureSnapshot:
+ # asyncpg hands back jsonb already decoded; other drivers hand back a
+ # string. Accepting both here keeps every caller from having to know
+ # which one it is on.
+ snapshot = row.snapshot if isinstance(row.snapshot, dict) else json.loads(row.snapshot or "{}")
+ notes = row.collection_notes if isinstance(row.collection_notes, list) else json.loads(row.collection_notes or "[]")
+ return PostureSnapshot(
+ id=row.id if isinstance(row.id, uuid.UUID) else uuid.UUID(str(row.id)),
+ tenant_id=row.tenant_id if isinstance(row.tenant_id, uuid.UUID) else uuid.UUID(str(row.tenant_id)),
+ provider=row.provider,
+ connector_id=row.connector_id,
+ snapshot=snapshot,
+ content_hash=row.content_hash,
+ principal_count=int(row.principal_count or 0),
+ resource_count=int(row.resource_count or 0),
+ policy_count=int(row.policy_count or 0),
+ partial=bool(row.partial),
+ collection_notes=list(notes),
+ collected_at=row.collected_at,
+ valid_from=row.valid_from,
+ valid_until=row.valid_until,
+ )
+
+
+_COLUMNS = """
+ id, tenant_id, provider, connector_id, snapshot, content_hash,
+ principal_count, resource_count, policy_count, partial, collection_notes,
+ collected_at, valid_from, valid_until
+"""
+
+
+async def save_snapshot(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ provider: str,
+ connector_id: str,
+ snapshot: dict[str, Any],
+ principal_count: int | None = None,
+ resource_count: int | None = None,
+ policy_count: int | None = None,
+ partial: bool = False,
+ collection_notes: list[str] | None = None,
+ connector_instance_id: uuid.UUID | None = None,
+ collection_ms: int | None = None,
+) -> PostureSnapshot:
+ """Record a collection, opening a new version only if something changed.
+
+ An unchanged estate re-collected hourly must not write a version an hour,
+ or the history stops being able to answer "when did this posture last
+ change". So an identical ``content_hash`` leaves the live row in force and
+ only refreshes ``collected_at`` — the row's interval is about when the
+ posture was true, and it still is.
+
+ A changed hash closes the live row and inserts the new one. Both
+ statements run in the caller's transaction and the partial unique index
+ would refuse the overlap, so a half-applied supersede cannot leave two
+ live rows behind.
+ """
+ if provider not in PROVIDERS:
+ raise ValueError(f"unknown provider {provider!r}; valid: {sorted(PROVIDERS)}")
+
+ digest = content_hash(snapshot)
+ notes = list(collection_notes or [])
+
+ # Derived unless the caller measured them itself. Defaulting these to 0
+ # would have let a caller that forgot them write "this estate has no
+ # principals", which is the one value an operator reads as "our
+ # credential lost its permissions".
+ derived = counts(snapshot)
+ principal_count = derived[0] if principal_count is None else principal_count
+ resource_count = derived[1] if resource_count is None else resource_count
+ policy_count = derived[2] if policy_count is None else policy_count
+
+ live = await live_snapshot(db, tenant_id=tenant_id, provider=provider)
+ if live is not None and live.content_hash == digest:
+ # Same posture. Record that we looked — and that the partial state
+ # and its reasons may have changed even when the content did not, as
+ # a collection that newly lost read access to half the estate returns
+ # exactly the snapshot it could still see.
+ await db.execute(
+ text(
+ """
+ UPDATE posture_snapshots
+ SET collected_at = NOW(),
+ collection_ms = :collection_ms,
+ partial = :partial,
+ collection_notes = CAST(:collection_notes AS jsonb)
+ WHERE tenant_id = :tenant_id
+ AND id = :id
+ """
+ ),
+ {
+ "tenant_id": str(tenant_id),
+ "id": str(live.id),
+ "collection_ms": collection_ms,
+ "partial": partial,
+ "collection_notes": json.dumps(notes),
+ },
+ )
+ refreshed = await live_snapshot(db, tenant_id=tenant_id, provider=provider)
+ # The row was just updated inside this transaction, so it is there;
+ # returning the pre-update object would hand back stale notes.
+ return refreshed if refreshed is not None else live
+
+ if live is not None:
+ await db.execute(
+ text(
+ """
+ UPDATE posture_snapshots
+ SET valid_until = NOW()
+ WHERE tenant_id = :tenant_id
+ AND id = :id
+ AND valid_until IS NULL
+ """
+ ),
+ {"tenant_id": str(tenant_id), "id": str(live.id)},
+ )
+
+ result = await db.execute(
+ text(
+ f"""
+ INSERT INTO posture_snapshots (
+ tenant_id, provider, connector_id, connector_instance_id,
+ snapshot, content_hash,
+ principal_count, resource_count, policy_count,
+ partial, collection_notes, collection_ms
+ ) VALUES (
+ :tenant_id, :provider, :connector_id, :connector_instance_id,
+ CAST(:snapshot AS jsonb), :content_hash,
+ :principal_count, :resource_count, :policy_count,
+ :partial, CAST(:collection_notes AS jsonb), :collection_ms
+ )
+ RETURNING {_COLUMNS}
+ """
+ ),
+ {
+ "tenant_id": str(tenant_id),
+ "provider": provider,
+ "connector_id": connector_id,
+ "connector_instance_id": str(connector_instance_id) if connector_instance_id else None,
+ "snapshot": json.dumps(snapshot, default=str),
+ "content_hash": digest,
+ "principal_count": principal_count,
+ "resource_count": resource_count,
+ "policy_count": policy_count,
+ "partial": partial,
+ "collection_notes": json.dumps(notes),
+ "collection_ms": collection_ms,
+ },
+ )
+ return _row_to_snapshot(result.fetchone())
+
+
+async def live_snapshot(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ provider: str,
+) -> PostureSnapshot | None:
+ """The version in force now, or ``None`` if this tenant has never collected."""
+ result = await db.execute(
+ text(
+ f"""
+ SELECT {_COLUMNS}
+ FROM posture_snapshots
+ WHERE tenant_id = :tenant_id
+ AND provider = :provider
+ AND valid_until IS NULL
+ LIMIT 1
+ """
+ ),
+ {"tenant_id": str(tenant_id), "provider": provider},
+ )
+ row = result.fetchone()
+ return _row_to_snapshot(row) if row else None
+
+
+async def snapshot_at(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ provider: str,
+ at: datetime,
+) -> PostureSnapshot | None:
+ """The version that was in force at ``at``.
+
+ This is the call a triage path should make. "What can this identity do"
+ and "what could it do when it acted" are different questions, and on an
+ alert raised before someone revoked a role they have different answers —
+ the second being the one that explains the alert.
+
+ Returns ``None`` when no version covers ``at``: an event predating the
+ tenant's first collection has no posture, and saying so is the only
+ honest answer. Falling back to the live snapshot would answer a question
+ nobody asked, in a way no reader could detect.
+ """
+ result = await db.execute(
+ text(
+ f"""
+ SELECT {_COLUMNS}
+ FROM posture_snapshots
+ WHERE tenant_id = :tenant_id
+ AND provider = :provider
+ AND valid_from <= :at
+ AND (valid_until IS NULL OR valid_until > :at)
+ ORDER BY valid_from DESC
+ LIMIT 1
+ """
+ ),
+ {"tenant_id": str(tenant_id), "provider": provider, "at": at},
+ )
+ row = result.fetchone()
+ return _row_to_snapshot(row) if row else None
+
+
+async def snapshot_history(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ provider: str,
+ limit: int = 50,
+) -> list[PostureSnapshot]:
+ """Versions newest first — the drift view.
+
+ Every row here is a real posture change, because an unchanged
+ re-collection extends the live row instead of writing a new one.
+ """
+ result = await db.execute(
+ text(
+ f"""
+ SELECT {_COLUMNS}
+ FROM posture_snapshots
+ WHERE tenant_id = :tenant_id
+ AND provider = :provider
+ ORDER BY valid_from DESC
+ LIMIT :limit
+ """
+ ),
+ {"tenant_id": str(tenant_id), "provider": provider, "limit": max(1, min(limit, 500))},
+ )
+ return [_row_to_snapshot(row) for row in result.fetchall()]
diff --git a/services/api/tests/test_effective_permissions_aws.py b/services/api/tests/test_effective_permissions_aws.py
index b6cb6d274..b8a05bb4c 100644
--- a/services/api/tests/test_effective_permissions_aws.py
+++ b/services/api/tests/test_effective_permissions_aws.py
@@ -465,8 +465,8 @@ def test_phase_4_1_providers_now_report_full_coverage(
assert resolver_cls.coverage == "full"
-def test_supported_providers_contains_all_five() -> None:
- assert set(SUPPORTED_PROVIDERS) == {"aws", "azure", "gcp", "okta", "gws"}
+def test_supported_providers_contains_every_resolver() -> None:
+ assert set(SUPPORTED_PROVIDERS) == {"aws", "azure", "gcp", "okta", "gws", "github"}
def test_resolver_result_serialises_to_dict(snapshot: dict[str, Any]) -> None:
@@ -578,11 +578,7 @@ def test_a_capped_action_is_reported_rather_than_silently_absent(
frank = AwsIamResolver(snapshot=snapshot).resolve("u-frank")
assert "s3:PutObject" in _denies_for(frank, "res-bucket-reports")
- kinds = {
- step.kind
- for decision in frank.decisions
- for step in decision.policy_chain
- }
+ kinds = {step.kind for decision in frank.decisions for step in decision.policy_chain}
assert "permissions-boundary" in kinds
diff --git a/services/api/tests/test_posture_loader.py b/services/api/tests/test_posture_loader.py
index 69112f4c3..a812ee245 100644
--- a/services/api/tests/test_posture_loader.py
+++ b/services/api/tests/test_posture_loader.py
@@ -44,7 +44,7 @@ def _okta_fetcher():
async def test_okta_snapshot_assembled_from_resource_configs():
- snap = await collect_snapshot("okta", "00u-alice", fetcher=_okta_fetcher())
+ snap = (await collect_snapshot("okta", "00u-alice", fetcher=_okta_fetcher())).snapshot
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")
@@ -55,7 +55,7 @@ async def test_okta_snapshot_assembled_from_resource_configs():
async def test_assembled_okta_snapshot_resolves():
- snap = await collect_snapshot("okta", "00u-alice", fetcher=_okta_fetcher())
+ snap = (await collect_snapshot("okta", "00u-alice", fetcher=_okta_fetcher())).snapshot
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}
@@ -70,35 +70,78 @@ async def test_cloud_provider_consumes_reconciled_snapshot():
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
+ collected = await collect_snapshot("aws", "arn:aws:iam::1:user/bob", fetcher=_fetch)
+ assert collected.snapshot == reconciled
+ assert collected.partial is False
+ assert collected.notes == ()
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
+ collected = await collect_snapshot("azure", "u1", fetcher=_fetch)
+ assert "principals" in collected.snapshot
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) == {}
+ assert not 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) == {}
+ assert not await collect_snapshot("okta", "00u-alice", fetcher=_boom)
+ assert not 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) == {}
+ assert not await collect_snapshot("gcp", "[email protected]", fetcher=_fetch)
+
+
+async def test_the_gap_survives_the_hop_from_the_connector():
+ """A collector that could not read half the estate says so in the same
+ envelope as the data, and that has to reach the caller.
+
+ The earlier shape returned the bare snapshot dict and dropped `partial`
+ and the notes on the floor, so a collection that 403'd on a page of role
+ assignments was indistinguishable from one that read everything -- and
+ the difference is an identity that looks harmless because the policy
+ granting it everything was in the page nobody could read.
+ """
+
+ async def _fetch(connector_id, resource_id, at_ts): # noqa: ANN001, ARG001
+ return {
+ "snapshot": {"principals": [{"id": "u1"}]},
+ "partial": True,
+ "collection_notes": ["the second page of role assignments returned 403"],
+ }
+
+ collected = await collect_snapshot("azure", "u1", fetcher=_fetch)
+
+ assert collected.partial is True
+ assert collected.notes == ("the second page of role assignments returned 403",)
+ assert collected.snapshot["principals"] == [{"id": "u1"}]
+
+
+async def test_an_incomplete_collection_that_got_nothing_is_still_nothing():
+ """`partial` does not make an empty snapshot answerable.
+
+ Zero principals means the credential lost its read permission far more
+ often than it means the estate is empty, so the caller must still 412
+ rather than resolve a principal against a document with nothing in it.
+ """
+
+ async def _fetch(connector_id, resource_id, at_ts): # noqa: ANN001, ARG001
+ return {"snapshot": {}, "partial": True, "collection_notes": ["every page 403'd"]}
+
+ collected = await collect_snapshot("gcp", "[email protected]", fetcher=_fetch)
+
+ assert not collected, "an empty snapshot is falsy however complete the collector claims it was"
diff --git a/services/api/tests/test_posture_snapshot_coverage.py b/services/api/tests/test_posture_snapshot_coverage.py
index bceebfc15..7ecc3bd92 100644
--- a/services/api/tests/test_posture_snapshot_coverage.py
+++ b/services/api/tests/test_posture_snapshot_coverage.py
@@ -1,45 +1,47 @@
"""Which providers can resolve permissions *live* must be stated, not implied.
-All five resolvers (AWS, Azure, GCP, Okta, Google Workspace) are implemented
-and report ``coverage: "full"``. That describes the resolver, which is a pure
-function over a provider snapshot — and says nothing about whether a snapshot
-can be obtained.
-
-Only Okta's is assembled from a live connector. The other four expect a
-connector to answer the ``__posture_snapshot__`` sentinel from
-``get_resource_config``, and **no connector implements it**, so with
-``AISOC_EFFECTIVE_PERMISSIONS_LIVE=1`` they return 412 rather than a
-fabricated snapshot.
-
-That is an honest state, but nothing recorded it, so "coverage: full" was the
-only number a reader saw. These tests pin the real shape of the gap: if a
-connector implements the sentinel, the allow-list below must shrink, and if a
-resolver is registered without one, that fails too. The gap is allowed to
-exist; it is not allowed to be invisible.
+A resolver reporting ``coverage: "full"`` describes a pure function over a
+provider snapshot and says nothing about whether a snapshot can be obtained.
+For most of this subsystem's life no connector could produce one for any
+cloud provider, so every live call answered 412 while the endpoint advertised
+full coverage — and nothing in the tree recorded the difference.
+
+Depth-plan 2.5 closed that: all six providers now have a connector that
+answers the ``__posture_snapshot__`` sentinel. These tests hold the closed
+state closed. The *behavioural* proof that each connector really collects
+lives in ``services/connectors/tests/test_posture_collectors.py``, which
+drives ``get_resource_config`` through a stubbed transport; this file can
+only assert the declarations, because ``services/api`` and
+``services/connectors`` both name their top-level package ``app`` and
+importing one in a process shadows the other.
+
+A note on the detector that used to live here, because the lesson outlasted
+it. The previous version read each connector's source and asserted the
+sentinel string was absent, as a reverse check that the documented gap was
+still real. After all five connectors were wired it still passed on four of
+them: a connector that imports the shared ``POSTURE_SNAPSHOT_ID`` constant
+does not contain the literal ``__posture_snapshot__``, so the grep could only
+ever recognise the hardcoded spelling — the one nobody should write. A
+source-reading test cannot notice whether the code runs, and this one could
+not even notice whether it existed.
"""
from __future__ import annotations
import inspect
-from pathlib import Path
-import pytest
from app.services.effective_permissions.posture_loader import (
POSTURE_SNAPSHOT_ID,
PROVIDER_CONNECTOR,
)
from app.services.effective_permissions.service import SUPPORTED_PROVIDERS
-#: Providers whose snapshot cannot yet be collected live, with the reason.
-#: Shrink this as connectors implement the sentinel; never grow it silently.
-NO_LIVE_SNAPSHOT = {
- "aws": "aws_security_hub does not answer __posture_snapshot__",
- "azure": "azure_entra implements no get_resource_config at all",
- "gcp": "gcp_scc treats the id as an SCC finding name, not a posture request",
- "gws": "google_workspace implements no get_resource_config at all",
-}
-
-CONNECTORS_DIR = Path(__file__).resolve().parents[2] / "connectors" / "app" / "connectors"
+#: Providers whose snapshot cannot be collected live, with the reason.
+#: Empty since 2.5. A provider may be added back when a real gap appears,
+#: but never silently: `test_every_registered_resolver_can_collect_a_snapshot`
+#: fails on a resolver that has no declared source at all, and this list is
+#: the only way to record a source that exists and does not work.
+NO_LIVE_SNAPSHOT: dict[str, str] = {}
def test_every_registered_resolver_has_a_snapshot_source_declared() -> None:
@@ -49,31 +51,41 @@ def test_every_registered_resolver_has_a_snapshot_source_declared() -> None:
assert not missing, f"{sorted(missing)} have a resolver but no declared snapshot source"
-def test_the_live_gap_is_exactly_the_four_cloud_providers() -> None:
- """Okta is the only provider assembled end-to-end today."""
- live = set(PROVIDER_CONNECTOR) - set(NO_LIVE_SNAPSHOT)
- assert live == {"okta"}, f"the set of live-capable providers changed to {sorted(live)} — update NO_LIVE_SNAPSHOT and the docs"
+def test_every_registered_resolver_can_collect_a_snapshot() -> None:
+ """The inverse of the gap list, which is the direction that rots.
+
+ Before 2.5 this read "only okta". Keeping the assertion pointed at the
+ *whole* provider set means adding a seventh resolver without a collector
+ fails here rather than shipping as another silent 412.
+ """
+ uncollectable = set(SUPPORTED_PROVIDERS) & set(NO_LIVE_SNAPSHOT)
+ assert not uncollectable, f"{sorted(uncollectable)} cannot collect a live snapshot: " + "; ".join(
+ f"{p}: {NO_LIVE_SNAPSHOT[p]}" for p in sorted(uncollectable)
+ )
[email protected](not CONNECTORS_DIR.is_dir(), reason="services/connectors is not in this checkout")
[email protected]("provider", sorted(NO_LIVE_SNAPSHOT))
-def test_a_provider_on_the_gap_list_really_cannot_collect_a_snapshot(provider: str) -> None:
- """The reverse direction, which is the one that rots.
+def test_the_sentinel_is_spelled_the_same_on_both_sides() -> None:
+ """The API loader and the connectors package each declare the constant.
- A one-directional gate would only check that listed providers stay
- listed. This asserts the listing is still *true*: if the connector starts
- handling the sentinel, the allow-list is stale and must shrink — otherwise
- a capability that now works keeps being reported as missing.
+ They cannot import from one another — two different services, both with
+ a top-level package called ``app`` — so the one thing that stops them
+ drifting to two spellings is this assertion. A mismatch would make every
+ cloud provider 412 again, with each side's unit tests still green.
"""
- connector_id = PROVIDER_CONNECTOR[provider]
- source_file = CONNECTORS_DIR / f"{connector_id}.py"
- if not source_file.is_file():
- pytest.fail(f"{provider} maps to connector '{connector_id}', which has no module at {source_file}")
-
- source = source_file.read_text(encoding="utf-8")
- assert POSTURE_SNAPSHOT_ID not in source, (
- f"{connector_id} now references {POSTURE_SNAPSHOT_ID}, so '{provider}' may be able to "
- f"collect a live snapshot. Remove it from NO_LIVE_SNAPSHOT and update the endpoint docstring."
+ connectors_init = (
+ __import__("pathlib").Path(__file__).resolve().parents[2] / "connectors" / "app" / "connectors" / "posture" / "__init__.py"
+ )
+ if not connectors_init.is_file():
+ # services/connectors is not in every checkout of this service.
+ return
+
+ source = connectors_init.read_text(encoding="utf-8")
+ declared = next(
+ line.split("=", 1)[1].strip().strip('"').strip("'") for line in source.splitlines() if line.startswith("POSTURE_SNAPSHOT_ID")
+ )
+ assert declared == POSTURE_SNAPSHOT_ID, (
+ f"the connectors package declares {declared!r} and the API loader declares "
+ f"{POSTURE_SNAPSHOT_ID!r}; every cloud provider would 412 with both sides green"
)
diff --git a/services/api/tests/test_posture_store.py b/services/api/tests/test_posture_store.py
new file mode 100644
index 000000000..930b1ef46
--- /dev/null
+++ b/services/api/tests/test_posture_store.py
@@ -0,0 +1,391 @@
+"""Versioned posture snapshots, against live Postgres (depth plan 2.5).
+
+Run against a real database on purpose. Every property worth asserting here
+is enforced by the schema rather than by Python — a partial unique index, a
+CHECK constraint, and an interval query — and a fake session that answers
+any query cannot tell a working temporal lookup from a broken one. The
+project has shipped that exact failure before: a store whose tests passed
+against a double while the production table had no writer at all.
+
+What is being pinned, and why each one matters:
+
+* **One live version per provider.** Two rows with ``valid_until IS NULL``
+ make "the current posture" ambiguous and the resolver takes whichever the
+ planner returns first. The index refuses it; this proves the index is
+ really there, not just the application convention.
+
+* **An unchanged re-collection does not open a version.** Otherwise a
+ collector on an hourly schedule writes a version an hour and "when did
+ this posture last change" becomes unanswerable, because every row is a
+ change.
+
+* **A point-in-time read returns the version in force then.** This is the
+ whole reason the table is versioned. An alert is triaged minutes to days
+ after the event, and what the identity can do *now* — after someone
+ revoked the role — is a different question with a different answer.
+
+* **An event predating the first collection returns nothing.** Falling back
+ to the live snapshot would answer a question nobody asked, in a way no
+ reader could detect.
+"""
+
+from __future__ import annotations
+
+import os
+import uuid
+from datetime import UTC, datetime, timedelta
+
+import pytest
+import pytest_asyncio
+from app.services.posture_store import (
+ content_hash,
+ counts,
+ live_snapshot,
+ save_snapshot,
+ snapshot_at,
+ snapshot_history,
+)
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+DSN = os.environ.get("DATABASE_URL", "")
+REQUIRED = os.environ.get("MSSP_ISOLATION_REQUIRED", "").strip() not in ("", "0", "false")
+
+TENANT = uuid.UUID("0c100000-0000-0000-0000-000000001030")
+OTHER_TENANT = uuid.UUID("0c100000-0000-0000-0000-000000001040")
+
+
+@pytest_asyncio.fixture
+async def db():
+ if "postgres" not in DSN and not REQUIRED:
+ pytest.skip("needs a live Postgres with the migration chain applied (integration.yml)")
+ engine = create_async_engine(DSN)
+ try:
+ async with engine.connect() as probe:
+ await probe.execute(text("SELECT 1"))
+ except Exception as exc:
+ await engine.dispose()
+ if REQUIRED:
+ pytest.fail(
+ "MSSP_ISOLATION_REQUIRED is set but no database answered at DATABASE_URL — "
+ f"the posture-store proof did not run: {type(exc).__name__}: {exc}"
+ )
+ pytest.skip(f"no database at DATABASE_URL ({type(exc).__name__}) — runs in integration.yml")
+
+ factory = async_sessionmaker(engine, expire_on_commit=False)
+ async with factory() as session:
+ await _reset(session)
+ try:
+ yield session
+ finally:
+ await _reset(session)
+ await engine.dispose()
+
+
+async def _reset(session) -> None:
+ await session.rollback()
+ for tenant in (TENANT, OTHER_TENANT):
+ await session.execute(
+ text("DELETE FROM posture_snapshots WHERE tenant_id = CAST(:t AS uuid)"),
+ {"t": str(tenant)},
+ )
+ await session.commit()
+
+
+def _snapshot(n_principals: int, *, marker: str = "") -> dict:
+ return {
+ "principals": [{"id": f"arn:aws:iam::1:user/u{i}", "name": f"u{i}"} for i in range(n_principals)],
+ "policies": [],
+ "marker": marker,
+ }
+
+
+async def _save(db, snapshot: dict, **kw):
+ saved = await save_snapshot(
+ db,
+ tenant_id=kw.pop("tenant_id", TENANT),
+ provider=kw.pop("provider", "aws"),
+ connector_id=kw.pop("connector_id", "aws_security_hub"),
+ snapshot=snapshot,
+ principal_count=len(snapshot.get("principals") or []),
+ **kw,
+ )
+ await db.commit()
+ return saved
+
+
+async def test_first_collection_becomes_the_live_version(db) -> None:
+ saved = await _save(db, _snapshot(3))
+
+ assert saved.is_live
+ assert saved.principal_count == 3
+ assert saved.content_hash == content_hash(_snapshot(3))
+
+ live = await live_snapshot(db, tenant_id=TENANT, provider="aws")
+ assert live is not None
+ assert live.id == saved.id
+
+
+async def test_unchanged_recollection_does_not_open_a_version(db) -> None:
+ """Every row in the history must be a real posture change."""
+ first = await _save(db, _snapshot(3))
+ second = await _save(db, _snapshot(3))
+
+ assert second.id == first.id
+ assert len(await snapshot_history(db, tenant_id=TENANT, provider="aws")) == 1
+
+
+async def test_unchanged_recollection_still_records_a_newly_lost_read(db) -> None:
+ """A collection that lost access to half the estate returns exactly the
+ snapshot it can still see, so the content is identical and the *gap* is
+ the only thing that changed. Dropping it would leave a snapshot claiming
+ to be complete."""
+ await _save(db, _snapshot(3))
+
+ refreshed = await _save(
+ db,
+ _snapshot(3),
+ partial=True,
+ collection_notes=["organisation members: HTTP 403 on page 2"],
+ )
+
+ assert refreshed.partial is True
+ assert refreshed.collection_notes == ["organisation members: HTTP 403 on page 2"]
+
+
+async def test_a_changed_estate_opens_a_version_and_closes_the_old_one(db) -> None:
+ first = await _save(db, _snapshot(3))
+ second = await _save(db, _snapshot(4))
+
+ assert second.id != first.id
+ assert second.is_live
+
+ history = await snapshot_history(db, tenant_id=TENANT, provider="aws")
+ assert [s.id for s in history] == [second.id, first.id]
+ assert history[1].valid_until is not None, "the superseded version was never closed"
+
+
+async def test_only_one_version_is_ever_live(db) -> None:
+ """The invariant the whole table rests on, asserted against the database
+ rather than against the writer that is supposed to maintain it."""
+ for n in range(2, 6):
+ await _save(db, _snapshot(n))
+
+ result = await db.execute(
+ text(
+ """
+ SELECT COUNT(*) FROM posture_snapshots
+ WHERE tenant_id = CAST(:t AS uuid) AND provider = 'aws' AND valid_until IS NULL
+ """
+ ),
+ {"t": str(TENANT)},
+ )
+ assert result.scalar_one() == 1
+
+
+async def test_a_second_live_row_is_refused_by_the_database(db) -> None:
+ """The negative control for the index.
+
+ Without it the application convention is the only thing holding the
+ invariant, and a writer that forgets to close the old row leaves two
+ live versions with nothing complaining.
+ """
+ from sqlalchemy.exc import IntegrityError
+
+ await _save(db, _snapshot(3))
+
+ with pytest.raises(IntegrityError):
+ await db.execute(
+ text(
+ """
+ INSERT INTO posture_snapshots
+ (tenant_id, provider, connector_id, snapshot, content_hash)
+ VALUES
+ (CAST(:t AS uuid), 'aws', 'aws_security_hub', CAST('{}' AS jsonb), 'a-different-hash')
+ """
+ ),
+ {"t": str(TENANT)},
+ )
+ await db.rollback()
+
+
+async def test_point_in_time_read_returns_the_version_in_force_then(db) -> None:
+ """The reason the table is versioned at all.
+
+ The cutover instant is taken from the *database* clock and read back,
+ rather than from ``datetime.now()`` here. Mixing the two clocks makes a
+ temporal assertion depend on host/container skew — which on this machine
+ is enough to push ``valid_until`` behind ``valid_from`` and trip the
+ interval CHECK, turning a query test into a clock test.
+ """
+ before = await _save(db, _snapshot(2, marker="before"))
+ # Backdate the first version so the two intervals are an hour apart
+ # rather than milliseconds: an alert triaged "during" a version is the
+ # case being modelled, and two adjacent instants cannot express it.
+ cutover = (
+ await db.execute(
+ text(
+ """
+ UPDATE posture_snapshots
+ SET valid_from = NOW() - INTERVAL '1 hour', valid_until = NOW()
+ WHERE tenant_id = CAST(:t AS uuid) AND id = CAST(:i AS uuid)
+ RETURNING valid_until
+ """
+ ),
+ {"t": str(TENANT), "i": str(before.id)},
+ )
+ ).scalar_one()
+ await db.execute(
+ text(
+ """
+ INSERT INTO posture_snapshots
+ (tenant_id, provider, connector_id, snapshot, content_hash, valid_from)
+ VALUES
+ (CAST(:t AS uuid), 'aws', 'aws_security_hub', CAST(:s AS jsonb), 'after-hash', :c)
+ """
+ ),
+ {"t": str(TENANT), "s": '{"principals": [], "marker": "after"}', "c": cutover},
+ )
+ await db.commit()
+
+ at_event = await snapshot_at(db, tenant_id=TENANT, provider="aws", at=cutover - timedelta(minutes=30))
+ assert at_event is not None
+ assert at_event.snapshot["marker"] == "before", "a point-in-time read returned the posture in force now, not then"
+
+ now = await snapshot_at(db, tenant_id=TENANT, provider="aws", at=cutover + timedelta(minutes=5))
+ assert now is not None
+ assert now.snapshot["marker"] == "after"
+
+ # The boundary itself belongs to the new version: the interval is
+ # [valid_from, valid_until), so an event at the exact cutover instant
+ # must not match both rows.
+ boundary = await snapshot_at(db, tenant_id=TENANT, provider="aws", at=cutover)
+ assert boundary is not None
+ assert boundary.snapshot["marker"] == "after"
+
+
+async def test_an_event_predating_every_collection_has_no_posture(db) -> None:
+ """Returning the live snapshot here would answer a question nobody asked
+ and no reader could detect."""
+ await _save(db, _snapshot(3))
+
+ answer = await snapshot_at(
+ db,
+ tenant_id=TENANT,
+ provider="aws",
+ at=datetime.now(UTC) - timedelta(days=30),
+ )
+ assert answer is None
+
+
+async def test_one_tenants_snapshot_is_invisible_to_another(db) -> None:
+ await _save(db, _snapshot(3))
+ await _save(db, _snapshot(9), tenant_id=OTHER_TENANT)
+
+ mine = await live_snapshot(db, tenant_id=TENANT, provider="aws")
+ theirs = await live_snapshot(db, tenant_id=OTHER_TENANT, provider="aws")
+
+ assert mine is not None and theirs is not None
+ assert mine.principal_count == 3
+ assert theirs.principal_count == 9
+ assert mine.id != theirs.id
+
+
+async def test_providers_version_independently(db) -> None:
+ """Collecting AWS must not close GitHub's live row."""
+ aws = await _save(db, _snapshot(3))
+ gh = await _save(db, _snapshot(5), provider="github", connector_id="github")
+ await _save(db, _snapshot(4))
+
+ assert (await live_snapshot(db, tenant_id=TENANT, provider="github")).id == gh.id
+ assert (await live_snapshot(db, tenant_id=TENANT, provider="aws")).id != aws.id
+
+
+async def test_an_unknown_provider_is_refused_with_a_sentence(db) -> None:
+ with pytest.raises(ValueError, match="unknown provider"):
+ await save_snapshot(
+ db,
+ tenant_id=TENANT,
+ provider="not-a-cloud",
+ connector_id="x",
+ snapshot={},
+ )
+
+
+def test_content_hash_ignores_key_order() -> None:
+ """Two collections of an unchanged estate differ only in dict ordering,
+ and without this every re-collection looks like a posture change."""
+ assert content_hash({"a": 1, "b": [1, 2]}) == content_hash({"b": [1, 2], "a": 1})
+ assert content_hash({"a": 1}) != content_hash({"a": 2})
+
+
+def test_counts_are_read_off_the_collected_document() -> None:
+ """Counting the document rather than a running total is what makes a
+ truncated collection show up as a smaller number instead of agreeing
+ with whatever the collector believed it had fetched."""
+ assert counts(
+ {
+ "principals": [{"id": "a"}, {"id": "b"}],
+ "resources": [{"id": "r"}],
+ "policies": [{"id": "p"}],
+ "role_definitions": [{"id": "rd"}],
+ }
+ ) == (2, 1, 2)
+
+
+async def test_counts_are_derived_when_the_caller_does_not_supply_them(db) -> None:
+ """The columns are filled from the snapshot unless measured separately.
+
+ They used to default to 0, so a caller that forgot them wrote "this
+ estate has no principals" -- the one value an operator reads as "our
+ credential lost its read permission", published about an estate that was
+ read perfectly well.
+ """
+ snapshot = {
+ "principals": [{"id": "a"}, {"id": "b"}, {"id": "c"}],
+ "resources": [{"id": "r"}],
+ "policies": [{"id": "p1"}, {"id": "p2"}],
+ }
+
+ saved = await save_snapshot(
+ db,
+ tenant_id=TENANT,
+ provider="gcp",
+ connector_id="gcp_scc",
+ snapshot=snapshot,
+ )
+
+ assert (saved.principal_count, saved.resource_count, saved.policy_count) == (3, 1, 2)
+
+
+async def test_a_measured_count_is_not_overwritten_by_the_derived_one(db) -> None:
+ """A collector that knows it truncated can say so.
+
+ Deriving unconditionally would discard the one number that is better
+ than the document: a collector that fetched 900 of 1,000 principals and
+ knows it knows something `len()` cannot see.
+ """
+ saved = await save_snapshot(
+ db,
+ tenant_id=TENANT,
+ provider="github",
+ connector_id="github",
+ snapshot={"principals": [{"id": "a"}]},
+ principal_count=900,
+ partial=True,
+ collection_notes=["page 2 of the member list timed out"],
+ )
+
+ assert saved.principal_count == 900
+ assert saved.partial is True
diff --git a/services/connectors/app/connectors/aws_security_hub.py b/services/connectors/app/connectors/aws_security_hub.py
index 2e5674ec1..1349c3fa7 100644
--- a/services/connectors/app/connectors/aws_security_hub.py
+++ b/services/connectors/app/connectors/aws_security_hub.py
@@ -11,6 +11,8 @@ from typing import Any
import structlog
from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field
+from app.connectors.posture import POSTURE_SNAPSHOT_ID
+from app.connectors.posture import aws as aws_posture
logger = structlog.get_logger()
@@ -142,16 +144,34 @@ class AWSSecurityHubConnector(BaseConnector):
# ``{"error": "not recorded"}`` rather than raising — the ingest
# snapshotter then records "no config" rather than failing the path.
- async def get_resource_config(self, resource_id: str, ts: str) -> dict[str, Any]:
+ async def get_resource_config(self, resource_id: str, at_ts: str | None = None) -> dict[str, Any]:
if not resource_id:
return {}
+ if resource_id == POSTURE_SNAPSHOT_ID:
+ collected = await aws_posture.collect(self._boto_session())
+ return collected.to_resource_config()
# boto3 is synchronous; the connector path is async, so we run
# the lookup in a worker thread to avoid blocking the event loop.
# We accept the small thread-pool overhead here because the
# ingest snapshotter caches results aggressively (TTL bucket).
import asyncio
- return await asyncio.to_thread(self._get_resource_config_sync, resource_id, ts)
+ return await asyncio.to_thread(self._get_resource_config_sync, resource_id, at_ts or "")
+
+ def _boto_session(self):
+ """A boto3 Session carrying this instance's credentials.
+
+ The posture collector opens several IAM and Organizations clients, so
+ it takes a session rather than the per-call ``boto3.client(**kwargs)``
+ the finding lookups use.
+ """
+ import boto3
+
+ kwargs: dict[str, Any] = {"region_name": self._region}
+ if self._access_key and self._secret_key:
+ kwargs["aws_access_key_id"] = self._access_key
+ kwargs["aws_secret_access_key"] = self._secret_key
+ return boto3.Session(**kwargs)
def _get_resource_config_sync(self, resource_id: str, ts: str) -> dict[str, Any]:
# Lazy-import boto3 so unit tests that don't exercise this path
diff --git a/services/connectors/app/connectors/azure_entra.py b/services/connectors/app/connectors/azure_entra.py
index c549a2b87..ec6c778b4 100644
--- a/services/connectors/app/connectors/azure_entra.py
+++ b/services/connectors/app/connectors/azure_entra.py
@@ -26,6 +26,8 @@ import httpx
import structlog
from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
+from app.connectors.posture import POSTURE_SNAPSHOT_ID
+from app.connectors.posture import azure as azure_posture
logger = structlog.get_logger()
@@ -197,6 +199,26 @@ class AzureEntraConnector(BaseConnector):
return [self.normalize(e) for e in events]
+ # ------------------------- posture --------------------------
+
+ async def get_resource_config(self, resource_id: str, at_ts: str | None = None) -> dict[str, Any]:
+ """Return the directory posture snapshot for the sentinel id.
+
+ This connector models the identity plane, so the only resource it can
+ describe is the directory itself. Any other id raises rather than
+ returning ``{}``, because a caller asking for a resource that was
+ never collectable should see that, not an empty config that reads as
+ "this resource has no settings".
+ """
+ if resource_id != POSTURE_SNAPSHOT_ID:
+ raise NotImplementedError(
+ f"{self.connector_id} describes the directory, not individual resources; the only id it answers is {POSTURE_SNAPSHOT_ID!r}"
+ )
+ await self._authenticate()
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ collected = await azure_posture.collect(client, self._headers(), tenant_id=self._tenant_id)
+ return collected.to_resource_config()
+
# ----------------------- normalize --------------------------
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
diff --git a/services/connectors/app/connectors/gcp_scc.py b/services/connectors/app/connectors/gcp_scc.py
index efc988c2c..b17ed1d59 100644
--- a/services/connectors/app/connectors/gcp_scc.py
+++ b/services/connectors/app/connectors/gcp_scc.py
@@ -31,6 +31,8 @@ from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
+from app.connectors.posture import POSTURE_SNAPSHOT_ID
+from app.connectors.posture import gcp as gcp_posture
logger = structlog.get_logger()
@@ -236,6 +238,11 @@ class GCPSCCConnector(BaseConnector):
"""Fetch one SCC finding by full resource name (``external_id`` from normalize)."""
if not (resource_id or "").strip():
return {}
+ if resource_id == POSTURE_SNAPSHOT_ID:
+ await self._authenticate()
+ async with httpx.AsyncClient(timeout=60.0) as client:
+ collected = await gcp_posture.collect(client, self._headers(), organization_id=self._organization_id)
+ return collected.to_resource_config()
rid = resource_id.strip()
url = f"{_SCC_BASE}/{rid}"
diff --git a/services/connectors/app/connectors/github.py b/services/connectors/app/connectors/github.py
index 905286496..d0a13fe6e 100644
--- a/services/connectors/app/connectors/github.py
+++ b/services/connectors/app/connectors/github.py
@@ -28,6 +28,8 @@ import httpx
import structlog
from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
+from app.connectors.posture import POSTURE_SNAPSHOT_ID
+from app.connectors.posture import github as github_posture
logger = structlog.get_logger()
@@ -371,9 +373,13 @@ class GitHubConnector(BaseConnector):
#
# We bundle all three into a single dict so the graph writer's
# :Configuration node carries everything the operator needs in one
- # MERGE. ``ts`` is informational — GitHub's REST API doesn't expose
+ # MERGE. ``at_ts`` is informational — GitHub's REST API doesn't expose
# a point-in-time view, so we tag the response ``snapshot_freshness="live"``.
- async def get_resource_config(self, resource_id: str, ts: str) -> dict[str, Any]:
+ async def get_resource_config(self, resource_id: str, at_ts: str | None = None) -> dict[str, Any]:
+ if resource_id == POSTURE_SNAPSHOT_ID:
+ async with httpx.AsyncClient(timeout=60.0) as client:
+ collected = await github_posture.collect(client, self._headers(), self._org)
+ return collected.to_resource_config()
if not resource_id or "/" not in resource_id:
return {"error": "resource_id must be 'owner/repo'"}
owner_repo = resource_id
@@ -428,5 +434,5 @@ class GitHubConnector(BaseConnector):
"branch_protection": protection,
"actions_permissions": actions_perms,
"snapshot_freshness": "live",
- "snapshot_taken_at": ts,
+ "snapshot_taken_at": at_ts,
}
diff --git a/services/connectors/app/connectors/google_workspace.py b/services/connectors/app/connectors/google_workspace.py
index ec20aabae..f5d7e004f 100644
--- a/services/connectors/app/connectors/google_workspace.py
+++ b/services/connectors/app/connectors/google_workspace.py
@@ -33,6 +33,8 @@ from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field, OAuthHints
+from app.connectors.posture import POSTURE_SNAPSHOT_ID, Collected
+from app.connectors.posture import gws as gws_posture
logger = structlog.get_logger()
@@ -40,6 +42,18 @@ _TOKEN_URL = "https://oauth2.googleapis.com/token"
_REPORTS_BASE = "https://admin.googleapis.com/admin/reports/v1/activity"
_SCOPE = "https://www.googleapis.com/auth/admin.reports.audit.readonly"
+# Posture collection reads the directory, which the audit-log scope above
+# does not cover. These are requested as a separate token so an operator who
+# has only authorised the reports scope keeps working alert polling and sees
+# a clear failure on the posture call alone.
+_DIRECTORY_SCOPE = " ".join(
+ (
+ "https://www.googleapis.com/auth/admin.directory.user.readonly",
+ "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly",
+ "https://www.googleapis.com/auth/admin.directory.orgunit.readonly",
+ )
+)
+
_DEFAULT_APPS = ("login", "admin", "drive", "token", "mobile")
_PAGE_SIZE = 500
@@ -104,8 +118,12 @@ class GoogleWorkspaceConnector(BaseConnector):
def __init__(self, admin_email: str, service_account_json: str):
self._admin_email = admin_email
self._sa_info = self._parse_sa(service_account_json)
- self._access_token: str | None = None
- self._token_expiry: float = 0.0
+ # Keyed by scope: audit-log polling and posture collection need
+ # different Google scopes, and a domain-wide-delegation token request
+ # fails outright for any scope the operator has not authorised. One
+ # shared token would therefore make posture collection able to break
+ # alert polling, so each scope holds its own.
+ self._tokens: dict[str, tuple[str, float]] = {}
# --------------------------- auth ---------------------------
@@ -120,14 +138,14 @@ class GoogleWorkspaceConnector(BaseConnector):
raise ValueError(f"service_account_json missing required field: {required}")
return sa
- def _build_jwt(self) -> str:
+ def _build_jwt(self, scope: str = _SCOPE) -> str:
"""Build a JWT with the ``sub`` claim set to the impersonated admin —
this is what makes domain-wide delegation actually work."""
now = int(time.time())
header = {"alg": "RS256", "typ": "JWT"}
claims = {
"iss": self._sa_info["client_email"],
- "scope": _SCOPE,
+ "scope": scope,
"aud": self._sa_info.get("token_uri", _TOKEN_URL),
"iat": now,
"exp": now + 3600,
@@ -149,26 +167,31 @@ class GoogleWorkspaceConnector(BaseConnector):
)
return signing_input.decode("ascii") + "." + _b64url(signature)
- async def _authenticate(self) -> str:
- if self._access_token and time.time() < self._token_expiry - 60:
- return self._access_token
+ async def _authenticate(self, scope: str = _SCOPE) -> str:
+ cached = self._tokens.get(scope)
+ if cached and time.time() < cached[1] - 60:
+ return cached[0]
async with httpx.AsyncClient(timeout=15.0) as client:
resp = await client.post(
self._sa_info.get("token_uri", _TOKEN_URL),
data={
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
- "assertion": self._build_jwt(),
+ "assertion": self._build_jwt(scope),
},
)
resp.raise_for_status()
payload = resp.json()
- self._access_token = payload["access_token"]
- self._token_expiry = time.time() + int(payload.get("expires_in", 3600))
- return self._access_token
+ token = payload["access_token"]
+ self._tokens[scope] = (token, time.time() + int(payload.get("expires_in", 3600)))
+ return token
+
+ def _invalidate(self, scope: str = _SCOPE) -> None:
+ self._tokens.pop(scope, None)
- def _headers(self) -> dict[str, str]:
+ def _headers(self, scope: str = _SCOPE) -> dict[str, str]:
+ token, _ = self._tokens.get(scope, ("", 0.0))
return {
- "Authorization": f"Bearer {self._access_token}",
+ "Authorization": f"Bearer {token}",
"Accept": "application/json",
}
@@ -215,7 +238,7 @@ class GoogleWorkspaceConnector(BaseConnector):
params={"startTime": start_time, "maxResults": _PAGE_SIZE},
)
if resp.status_code == 401:
- self._access_token = None
+ self._invalidate()
await self._authenticate()
resp = await client.get(
f"{_REPORTS_BASE}/users/all/applications/{app_name}",
@@ -240,6 +263,37 @@ class GoogleWorkspaceConnector(BaseConnector):
return [self.normalize(e) for e in events]
+ # ------------------------- posture --------------------------
+
+ async def get_resource_config(self, resource_id: str, at_ts: str | None = None) -> dict[str, Any]:
+ """Return the Workspace directory posture snapshot for the sentinel id.
+
+ This connector reads the Reports API and the directory, neither of
+ which addresses an individual "resource" the way a cloud connector
+ does, so any other id raises rather than returning an empty config
+ that would read as "this resource has no settings".
+ """
+ if resource_id != POSTURE_SNAPSHOT_ID:
+ raise NotImplementedError(
+ f"{self.connector_id} describes the Workspace directory, not individual resources; "
+ f"the only id it answers is {POSTURE_SNAPSHOT_ID!r}"
+ )
+ try:
+ await self._authenticate(_DIRECTORY_SCOPE)
+ except httpx.HTTPStatusError as exc:
+ # Almost always an operator who authorised the reports scope and
+ # not the directory ones. Saying which scopes are missing is the
+ # difference between a two-minute fix and a support thread.
+ collected = Collected(snapshot={})
+ collected.note(
+ f"could not mint a directory token (HTTP {exc.response.status_code}). The service "
+ f"account's domain-wide delegation must also authorise: {_DIRECTORY_SCOPE}"
+ )
+ return collected.to_resource_config()
+ async with httpx.AsyncClient(timeout=60.0) as client:
+ collected = await gws_posture.collect(client, self._headers(_DIRECTORY_SCOPE))
+ return collected.to_resource_config()
+
# ----------------------- normalize --------------------------
# Workspace event names that we always treat as high-severity. These are
diff --git a/services/connectors/app/connectors/okta.py b/services/connectors/app/connectors/okta.py
index 182579dca..e97867b21 100644
--- a/services/connectors/app/connectors/okta.py
+++ b/services/connectors/app/connectors/okta.py
@@ -184,7 +184,7 @@ class OktaConnector(BaseConnector):
# ``resource_id`` is the Okta entity id; we infer the entity type from
# the prefix (the audit log uses canonical id prefixes:
# ``00g*`` group, ``0oa*`` app, ``00p*`` policy, ``00u*`` user).
- async def get_resource_config(self, resource_id: str, ts: str) -> dict[str, Any]:
+ async def get_resource_config(self, resource_id: str, at_ts: str | None = None) -> dict[str, Any]:
if not resource_id:
return {}
prefix = resource_id[:3]
@@ -234,6 +234,6 @@ class OktaConnector(BaseConnector):
"version": payload.get("version"),
"last_updated": payload.get("lastUpdated"),
"snapshot_freshness": "live",
- "snapshot_taken_at": ts,
+ "snapshot_taken_at": at_ts,
"raw": payload,
}
diff --git a/services/connectors/app/connectors/posture/__init__.py b/services/connectors/app/connectors/posture/__init__.py
new file mode 100644
index 000000000..055f69092
--- /dev/null
+++ b/services/connectors/app/connectors/posture/__init__.py
@@ -0,0 +1,68 @@
+"""Identity-posture collection (depth plan 2.5).
+
+A resolver in ``services/api/app/services/effective_permissions/`` is pure:
+hand it a snapshot of an estate's identities, roles and policies and it
+computes what a principal can actually do. Until now the production loader
+returned ``{}`` for every cloud provider, so every live call answered 412 and
+the whole subsystem had never once described a real estate. Okta was the only
+provider assembled, and it was assembled in the API service.
+
+These collectors are the missing half. Each one reads a provider's identity
+plane through the connector that already holds the credential and returns the
+snapshot shape that provider's resolver documents.
+
+Three rules the collectors share, each of which exists because the opposite
+has shipped here before.
+
+**A gap is data, not a log line.** A collector that cannot read part of the
+estate returns what it got with ``partial=True`` and a note naming what was
+missed. The resolver's answer is only as complete as its input, and a triage
+surface that cannot say "this is incomplete, here is why" will render a gap
+as an absence -- an identity that looks harmless because the policy granting
+it everything was in the page that 403'd.
+
+**An empty collection is a real and important state.** Zero principals means
+the credential lost its read permission far more often than it means the
+estate is empty, so an empty snapshot is never silently treated as success.
+
+**Nothing is fabricated.** A collector that cannot reach the provider returns
+no snapshot at all and the endpoint answers 412 exactly as it did before.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+#: Sentinel resource id. ``get_resource_config`` returns the full provider
+#: snapshot for this id rather than one resource's config. Kept here so the
+#: connectors and the API loader cannot drift to two spellings; the API side
+#: declares the same constant and a test asserts they are equal.
+POSTURE_SNAPSHOT_ID = "__posture_snapshot__"
+
+
+@dataclass
+class Collected:
+ """A posture snapshot plus an honest account of what is missing from it."""
+
+ snapshot: dict[str, Any]
+ partial: bool = False
+ notes: list[str] = field(default_factory=list)
+
+ def note(self, message: str) -> None:
+ """Record a gap. Recording one always marks the snapshot partial.
+
+ The two cannot be set separately on purpose: every earlier version of
+ this idea in the tree had a notes list that some callers filled and
+ no caller read, so the flag and the reason are one operation.
+ """
+ self.notes.append(message)
+ self.partial = True
+
+ def to_resource_config(self) -> dict[str, Any]:
+ """The envelope ``get_resource_config`` returns for the sentinel id."""
+ return {
+ "snapshot": self.snapshot,
+ "partial": self.partial,
+ "collection_notes": list(self.notes),
+ }
diff --git a/services/connectors/app/connectors/posture/aws.py b/services/connectors/app/connectors/posture/aws.py
new file mode 100644
index 000000000..26367b39a
--- /dev/null
+++ b/services/connectors/app/connectors/posture/aws.py
@@ -0,0 +1,258 @@
+"""Collect an AWS IAM posture snapshot for the effective-permissions resolver.
+
+Reads the account's identity plane through ``iam:Get*`` / ``iam:List*`` and
+returns the snapshot shape documented in
+``services/api/app/services/effective_permissions/aws.py``.
+
+Why ``GetAccountAuthorizationDetails`` and not twenty List calls
+---------------------------------------------------------------
+One paginated call returns every user, group, role, their inline policies,
+their attached managed policy ARNs, and the managed policy documents
+themselves. The obvious alternative -- list users, then for each user list
+its policies, then fetch each policy -- is O(principals x policies) requests
+against an API with a low request rate, and on an estate of any size it gets
+throttled into a partial snapshot that looks complete.
+
+It also carries ``PermissionsBoundary`` per principal, which is the field
+2.5 exists to model and which several of the per-entity List calls omit.
+
+What this deliberately does not collect
+---------------------------------------
+Resource-based policies and the resource inventory. Enumerating every bucket,
+key and queue in an account is a different and much larger job than reading
+the identity plane, and a snapshot that half-enumerated resources would make
+the resolver's answer *look* resource-aware while silently omitting whatever
+it missed. ``resources`` is therefore empty and the collection says so, so a
+reader sees "identity plane only" rather than a thin answer presented as a
+complete one.
+
+SCPs are read when the caller is in an organisation and has
+``organizations:List*``; a member account without that permission is the
+normal case, not a failure, and is noted rather than retried.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from typing import Any
+from urllib.parse import unquote
+
+import structlog
+
+from app.connectors.posture import Collected
+
+logger = structlog.get_logger()
+
+#: AWS caps a single page at 1000 and most accounts need one or two. The
+#: ceiling exists so a pagination bug cannot spin forever against a provider
+#: that is handing back a cursor it never retires.
+_MAX_PAGES = 50
+
+
+def _policy_document(version: Any) -> dict[str, Any]:
+ """An IAM policy document, which the API returns URL-encoded JSON.
+
+ ``GetAccountAuthorizationDetails`` returns the document as a
+ percent-encoded JSON string, not as a dict. Handing that string to the
+ resolver would make every statement unreadable and every principal look
+ as though it had no permissions at all -- a snapshot that collects
+ cleanly and resolves to nothing.
+ """
+ if isinstance(version, dict):
+ return version
+ if not isinstance(version, str):
+ return {}
+ try:
+ return json.loads(unquote(version))
+ except (ValueError, TypeError):
+ return {}
+
+
+def collect_sync(session: Any, *, account_id: str | None = None) -> Collected:
+ """Collect the snapshot with a synchronous boto3 session.
+
+ Separated from the async wrapper so tests can drive it with a stub
+ client and no event loop.
+ """
+ out = Collected(snapshot={})
+ iam = session.client("iam")
+
+ principals: list[dict[str, Any]] = []
+ groups: list[dict[str, Any]] = []
+ policies: list[dict[str, Any]] = []
+ seen_policies: set[str] = set()
+
+ marker: str | None = None
+ pages = 0
+ try:
+ while pages < _MAX_PAGES:
+ pages += 1
+ kwargs: dict[str, Any] = {"Filter": ["User", "Role", "Group", "LocalManagedPolicy", "AWSManagedPolicy"]}
+ if marker:
+ kwargs["Marker"] = marker
+ page = iam.get_account_authorization_details(**kwargs)
+
+ for policy in page.get("Policies", []):
+ arn = policy.get("Arn")
+ if not arn or arn in seen_policies:
+ continue
+ default_id = policy.get("DefaultVersionId")
+ document: dict[str, Any] = {}
+ for version in policy.get("PolicyVersionList", []):
+ if version.get("VersionId") == default_id or version.get("IsDefaultVersion"):
+ document = _policy_document(version.get("Document"))
+ break
+ seen_policies.add(arn)
+ policies.append(
+ {
+ "id": arn,
+ "name": policy.get("PolicyName") or arn,
+ "kind": "identity",
+ "document": document,
+ }
+ )
+
+ for group in page.get("GroupDetailList", []):
+ gid = group.get("Arn") or group.get("GroupId")
+ if not gid:
+ continue
+ inline = []
+ for entry in group.get("GroupPolicyList", []) or []:
+ name = entry.get("PolicyName")
+ if not name:
+ continue
+ pid = f"inline:group:{group.get('GroupName')}:{name}"
+ if pid not in seen_policies:
+ seen_policies.add(pid)
+ policies.append(
+ {
+ "id": pid,
+ "name": name,
+ "kind": "identity",
+ "document": _policy_document(entry.get("PolicyDocument")),
+ }
+ )
+ inline.append(pid)
+ groups.append(
+ {
+ "id": gid,
+ "name": group.get("GroupName") or gid,
+ "attached_policies": [p["PolicyArn"] for p in group.get("AttachedManagedPolicies", []) if p.get("PolicyArn")],
+ "inline_policies": inline,
+ }
+ )
+
+ group_arn_by_name = {g.get("GroupName"): g.get("Arn") for g in page.get("GroupDetailList", [])}
+
+ for kind, key in (("user", "UserDetailList"), ("role", "RoleDetailList")):
+ for entity in page.get(key, []):
+ arn = entity.get("Arn")
+ if not arn:
+ continue
+ name = entity.get("UserName") or entity.get("RoleName") or arn
+ inline_key = "UserPolicyList" if kind == "user" else "RolePolicyList"
+ inline: list[str] = []
+ for entry in entity.get(inline_key, []) or []:
+ pname = entry.get("PolicyName")
+ if not pname:
+ continue
+ pid = f"inline:{kind}:{name}:{pname}"
+ if pid not in seen_policies:
+ seen_policies.add(pid)
+ policies.append(
+ {
+ "id": pid,
+ "name": pname,
+ "kind": "identity",
+ "document": _policy_document(entry.get("PolicyDocument")),
+ }
+ )
+ inline.append(pid)
+
+ boundary = entity.get("PermissionsBoundary") or {}
+ principals.append(
+ {
+ "id": arn,
+ "arn": arn,
+ "name": name,
+ "type": kind,
+ # Group membership only exists for users. A role
+ # belongs to no group in IAM, and emitting an
+ # empty list for both keeps the resolver's walk
+ # uniform.
+ "groups": [group_arn_by_name.get(g) for g in entity.get("GroupList", []) or [] if group_arn_by_name.get(g)],
+ "attached_policies": [
+ p["PolicyArn"] for p in entity.get("AttachedManagedPolicies", []) or [] if p.get("PolicyArn")
+ ],
+ "inline_policies": inline,
+ # The field 2.5 exists to model. Absent for most
+ # principals, and absent is not the same as
+ # "boundary that allows everything".
+ "permissions_boundary": boundary.get("PermissionsBoundaryArn"),
+ }
+ )
+
+ marker = page.get("Marker") if page.get("IsTruncated") else None
+ if not marker:
+ break
+ else:
+ out.note(
+ f"stopped after {_MAX_PAGES} pages of GetAccountAuthorizationDetails; "
+ f"the identity plane is larger than this collector will read in one pass"
+ )
+ except Exception as exc: # noqa: BLE001 — a partial estate is still useful
+ out.note(f"GetAccountAuthorizationDetails failed after {pages} page(s): {exc}")
+
+ scps: list[str] = []
+ try:
+ org = session.client("organizations")
+ for policy in org.list_policies(Filter="SERVICE_CONTROL_POLICY").get("Policies", []):
+ pid = policy.get("Id")
+ if not pid:
+ continue
+ content = org.describe_policy(PolicyId=pid).get("Policy", {}).get("Content")
+ policies.append(
+ {
+ "id": pid,
+ "name": policy.get("Name") or pid,
+ "kind": "scp",
+ "document": _policy_document(content),
+ }
+ )
+ scps.append(pid)
+ except Exception as exc: # noqa: BLE001
+ # A member account without organizations:List* is the normal case,
+ # not a failure -- but it does change the answer, because without
+ # SCPs the resolver cannot show an action the org blocks. Said out
+ # loud rather than left as a silent absence.
+ out.note(f"service control policies not read ({exc}); org-level denials are not reflected")
+
+ if not principals:
+ out.note(
+ "no IAM principals were returned. On a live account this is far more often a missing "
+ "iam:GetAccountAuthorizationDetails permission than an empty estate"
+ )
+
+ out.snapshot = {
+ "account_id": account_id or "",
+ "principals": principals,
+ "groups": groups,
+ "policies": policies,
+ # Deliberately empty -- see the module docstring. Enumerating every
+ # resource in an account is a different job, and a half-enumerated
+ # list would read as a complete one.
+ "resources": [],
+ "scps": scps,
+ "action_catalogue": {},
+ }
+ out.note(
+ "identity plane only: resource-based policies and the resource inventory are not collected, "
+ "so a grant made by a bucket or key policy will not appear"
+ )
+ return out
+
+
+async def collect(session: Any, *, account_id: str | None = None) -> Collected:
+ """Async wrapper. boto3 is synchronous and this runs on an async path."""
+ return await asyncio.to_thread(collect_sync, session, account_id=account_id)
diff --git a/services/connectors/app/connectors/posture/azure.py b/services/connectors/app/connectors/posture/azure.py
new file mode 100644
index 000000000..d6362d13b
--- /dev/null
+++ b/services/connectors/app/connectors/posture/azure.py
@@ -0,0 +1,169 @@
+"""Collect an Entra ID directory-RBAC posture snapshot.
+
+Returns the shape documented in
+``services/api/app/services/effective_permissions/azure.py``.
+
+Scope, stated plainly
+---------------------
+This reads **Entra ID directory roles** -- the control plane over identities
+themselves (Global Administrator, User Administrator, Privileged Role
+Administrator). It does *not* read Azure resource RBAC, which lives behind a
+different API (``management.azure.com``), a different credential and a
+different consent, and which governs subscriptions and resource groups.
+
+The distinction matters to a reader of the resolver's answer: an identity
+with no directory role may still own a subscription. The collection says so
+in a note rather than leaving a reader to infer that "no permissions found"
+means "harmless", which is the misreading that costs an incident.
+
+Every assignment is emitted at scope ``/`` because a directory role applies
+tenant-wide unless it carries an administrative-unit scope, which is read
+from ``directoryScopeId`` when present.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import structlog
+
+from app.connectors.posture import Collected
+
+logger = structlog.get_logger()
+
+_GRAPH = "https://graph.microsoft.com/v1.0"
+_MAX_PAGES = 50
+
+
+async def _paged(client: Any, url: str, headers: dict[str, str], out: Collected, what: str) -> list[dict[str, Any]]:
+ """Follow Graph's ``@odata.nextLink`` and return every item.
+
+ A truncated read is recorded rather than returned as if complete: a
+ missing page of role assignments is a privileged identity the resolver
+ will report as unprivileged.
+ """
+ items: list[dict[str, Any]] = []
+ next_url: str | None = url
+ pages = 0
+ while next_url and pages < _MAX_PAGES:
+ pages += 1
+ try:
+ resp = await client.get(next_url, headers=headers)
+ except Exception as exc: # noqa: BLE001
+ out.note(f"{what}: request failed after {pages - 1} page(s): {exc}")
+ return items
+ if resp.status_code != 200:
+ out.note(f"{what}: HTTP {resp.status_code} after {pages - 1} page(s)")
+ return items
+ body = resp.json()
+ items.extend(body.get("value") or [])
+ next_url = body.get("@odata.nextLink")
+ if next_url:
+ out.note(f"{what}: stopped after {_MAX_PAGES} pages; the directory is larger than one pass")
+ return items
+
+
+async def collect(client: Any, headers: dict[str, str], *, tenant_id: str = "") -> Collected:
+ out = Collected(snapshot={})
+
+ role_defs = await _paged(client, f"{_GRAPH}/roleManagement/directory/roleDefinitions", headers, out, "role definitions")
+ assignments = await _paged(client, f"{_GRAPH}/roleManagement/directory/roleAssignments", headers, out, "role assignments")
+
+ definitions: list[dict[str, Any]] = []
+ for definition in role_defs:
+ rid = definition.get("id")
+ if not rid:
+ continue
+ actions: list[str] = []
+ not_actions: list[str] = []
+ for permission in definition.get("rolePermissions") or []:
+ actions.extend(permission.get("allowedResourceActions") or [])
+ not_actions.extend(permission.get("excludedResourceActions") or [])
+ definitions.append(
+ {
+ "id": rid,
+ "name": definition.get("displayName") or rid,
+ "permissions": [
+ {
+ "actions": actions,
+ "notActions": not_actions,
+ "dataActions": [],
+ "notDataActions": [],
+ }
+ ],
+ }
+ )
+
+ role_assignments: list[dict[str, Any]] = []
+ principal_ids: set[str] = set()
+ for assignment in assignments:
+ principal_id = assignment.get("principalId")
+ role_definition_id = assignment.get("roleDefinitionId")
+ if not principal_id or not role_definition_id:
+ continue
+ principal_ids.add(principal_id)
+ role_assignments.append(
+ {
+ "id": assignment.get("id") or f"{principal_id}:{role_definition_id}",
+ "principal_id": principal_id,
+ "role_definition_id": role_definition_id,
+ # "/" is tenant-wide. An administrative unit narrows it, and
+ # the resolver's prefix match handles both without a special
+ # case.
+ "scope": assignment.get("directoryScopeId") or "/",
+ }
+ )
+
+ # Only the principals that actually hold a role are resolved. Reading
+ # every user in a directory to answer "what can this one do" is a far
+ # larger and slower collection, and a principal absent from the snapshot
+ # is correctly reported by the resolver as unknown rather than as
+ # unprivileged.
+ principals: list[dict[str, Any]] = []
+ for principal_id in sorted(principal_ids):
+ kind = "user"
+ name = principal_id
+ try:
+ resp = await client.get(f"{_GRAPH}/directoryObjects/{principal_id}", headers=headers)
+ if resp.status_code == 200:
+ obj = resp.json()
+ odata = str(obj.get("@odata.type") or "")
+ if "servicePrincipal" in odata:
+ kind = "servicePrincipal"
+ elif "group" in odata:
+ kind = "group"
+ name = obj.get("displayName") or obj.get("userPrincipalName") or principal_id
+ except Exception as exc: # noqa: BLE001
+ out.note(f"could not type principal {principal_id}: {exc}")
+ principals.append(
+ {
+ "id": principal_id,
+ "object_id": principal_id,
+ "name": name,
+ "type": kind,
+ "groups": [],
+ }
+ )
+
+ if not principals:
+ out.note(
+ "no directory role assignments were returned. On a live tenant this is far more often a "
+ "missing RoleManagement.Read.Directory permission than a tenant with no administrators"
+ )
+
+ out.snapshot = {
+ "tenant_id": tenant_id,
+ "principals": principals,
+ "groups": [],
+ "role_definitions": definitions,
+ "role_assignments": role_assignments,
+ "deny_assignments": [],
+ "resources": [],
+ "action_catalogue": {},
+ }
+ out.note(
+ "Entra directory roles only: Azure resource RBAC (subscriptions, resource groups) is a "
+ "separate API and is not collected, so an identity with no directory role here may still "
+ "own a subscription"
+ )
+ return out
diff --git a/services/connectors/app/connectors/posture/gcp.py b/services/connectors/app/connectors/posture/gcp.py
new file mode 100644
index 000000000..53b66c87f
--- /dev/null
+++ b/services/connectors/app/connectors/posture/gcp.py
@@ -0,0 +1,223 @@
+"""Collect a GCP IAM posture snapshot for one or more projects.
+
+Returns the shape documented in
+``services/api/app/services/effective_permissions/gcp.py``.
+
+Two things worth knowing before reading the answer
+--------------------------------------------------
+**A project's IAM policy is not the whole story.** GCP inherits bindings
+downward from the organisation and folders, so a principal with no binding
+on a project can still hold ``roles/owner`` on its parent folder. This
+collector reads the ancestry via ``projects.getAncestry`` and fetches each
+ancestor's policy when the credential is allowed to, and records a note when
+it is not -- because "no bindings" read off a project alone is exactly the
+answer that makes an owner look like a stranger.
+
+**Role permissions have to be fetched per role.** A binding names
+``roles/storage.admin``; what that expands to lives behind
+``iam.roles.get``. Predefined roles are fetched once and shared across
+projects. A role whose permissions could not be read is emitted with an
+empty permission list *and* a note, never silently dropped -- dropping it
+would remove a grant from the answer entirely, while an empty role at least
+shows up in the provenance chain as something the resolver could not expand.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import structlog
+
+from app.connectors.posture import Collected
+
+logger = structlog.get_logger()
+
+_CRM_V1 = "https://cloudresourcemanager.googleapis.com/v1"
+_CRM_V3 = "https://cloudresourcemanager.googleapis.com/v3"
+_IAM = "https://iam.googleapis.com/v1"
+
+#: Ancestry is org -> folder... -> project and is never deep in practice.
+_MAX_ANCESTORS = 20
+
+#: 500 projects per page, so this covers 5,000 before the note fires.
+_MAX_PROJECT_PAGES = 10
+
+
+def _resource_name(ancestor: dict[str, Any]) -> str | None:
+ rid = ancestor.get("resourceId") or {}
+ kind, value = rid.get("type"), rid.get("id")
+ if not kind or not value:
+ return None
+ return f"//cloudresourcemanager.googleapis.com/{kind}s/{value}"
+
+
+async def _discover_projects(client: Any, headers: dict[str, str], organization_id: str, out: Collected) -> list[str]:
+ """List the active projects under an organisation.
+
+ The SCC connector is configured with an organisation rather than a list
+ of projects, so the set has to be discovered. A failure here is recorded
+ rather than raised: a snapshot of the projects we *could* enumerate is
+ worth more than no snapshot, as long as it says so.
+ """
+ found: list[str] = []
+ page_token: str | None = None
+ for _ in range(_MAX_PROJECT_PAGES):
+ params: dict[str, Any] = {"filter": f"parent.type:organization parent.id:{organization_id}", "pageSize": 500}
+ if page_token:
+ params["pageToken"] = page_token
+ try:
+ resp = await client.get(f"{_CRM_V1}/projects", headers=headers, params=params)
+ except Exception as exc: # noqa: BLE001
+ out.note(f"project discovery under organisation {organization_id} failed: {exc}")
+ return found
+ if resp.status_code != 200:
+ out.note(
+ f"project discovery under organisation {organization_id} returned HTTP {resp.status_code}; "
+ f"this usually means the service account lacks resourcemanager.projects.list"
+ )
+ return found
+ body = resp.json()
+ for project in body.get("projects") or []:
+ pid = project.get("projectId")
+ if pid and project.get("lifecycleState", "ACTIVE") == "ACTIVE":
+ found.append(pid)
+ page_token = body.get("nextPageToken")
+ if not page_token:
+ return found
+ out.note(f"project discovery stopped after {_MAX_PROJECT_PAGES} pages; the organisation has more projects than one pass")
+ return found
+
+
+async def collect(
+ client: Any,
+ headers: dict[str, str],
+ project_ids: list[str] | None = None,
+ *,
+ organization_id: str = "",
+) -> Collected:
+ out = Collected(snapshot={})
+
+ members: dict[str, dict[str, Any]] = {}
+ bindings: list[dict[str, Any]] = []
+ roles: dict[str, dict[str, Any]] = {}
+ resources: list[dict[str, Any]] = []
+
+ project_ids = list(project_ids or [])
+ if not project_ids and organization_id:
+ project_ids = await _discover_projects(client, headers, organization_id, out)
+
+ if not project_ids:
+ out.note("no projects were configured or discovered, so nothing could be collected")
+
+ async def _read_policy(resource_name: str, api_url: str, label: str) -> list[dict[str, Any]]:
+ try:
+ resp = await client.post(api_url, headers=headers, json={})
+ except Exception as exc: # noqa: BLE001
+ out.note(f"{label}: getIamPolicy request failed: {exc}")
+ return []
+ if resp.status_code != 200:
+ out.note(f"{label}: getIamPolicy returned HTTP {resp.status_code}; its bindings are not in this snapshot")
+ return []
+ return resp.json().get("bindings") or []
+
+ for project_id in project_ids:
+ project_resource = f"//cloudresourcemanager.googleapis.com/projects/{project_id}"
+ ancestry: list[str] = [project_resource]
+
+ try:
+ resp = await client.post(f"{_CRM_V1}/projects/{project_id}:getAncestry", headers=headers, json={})
+ if resp.status_code == 200:
+ for ancestor in (resp.json().get("ancestor") or [])[:_MAX_ANCESTORS]:
+ name = _resource_name(ancestor)
+ if name and name not in ancestry:
+ ancestry.append(name)
+ else:
+ out.note(
+ f"project {project_id}: getAncestry returned HTTP {resp.status_code}; inherited "
+ f"organisation and folder bindings are not in this snapshot, so a principal that "
+ f"holds a role on a parent will read as having none here"
+ )
+ except Exception as exc: # noqa: BLE001
+ out.note(f"project {project_id}: getAncestry failed ({exc}); inherited bindings are not reflected")
+
+ resources.append(
+ {
+ "id": project_id,
+ "gcp_id": project_resource,
+ "ancestors": ancestry,
+ "kind": "cloudresourcemanager.googleapis.com/Project",
+ }
+ )
+
+ for resource_name in ancestry:
+ short = resource_name.rsplit("/", 2)
+ if len(short) < 2:
+ continue
+ kind, value = short[-2], short[-1]
+ if kind == "projects":
+ url = f"{_CRM_V1}/projects/{value}:getIamPolicy"
+ else:
+ url = f"{_CRM_V3}/{kind}/{value}:getIamPolicy"
+ for binding in await _read_policy(resource_name, url, f"{kind[:-1]} {value}"):
+ role = binding.get("role")
+ if not role:
+ continue
+ roles.setdefault(role, {"id": role, "name": role, "permissions": []})
+ bindings.append(
+ {
+ "id": f"{resource_name}:{role}",
+ "resource_id": resource_name,
+ "role": role,
+ "members": list(binding.get("members") or []),
+ }
+ )
+ for member in binding.get("members") or []:
+ if ":" not in member:
+ continue
+ member_type, _, identifier = member.partition(":")
+ members.setdefault(
+ identifier,
+ {
+ "id": identifier,
+ "type": member_type,
+ "groups": [],
+ },
+ )
+
+ for role_id, role in roles.items():
+ # A predefined role is `roles/<name>` and a custom one is
+ # `projects/<p>/roles/<name>`; both are full resource names and both
+ # answer the same GET, so there is no branch here on purpose.
+ url = f"{_IAM}/{role_id}"
+ try:
+ resp = await client.get(url, headers=headers)
+ except Exception as exc: # noqa: BLE001
+ out.note(f"role {role_id}: could not be expanded ({exc}); it resolves to no permissions here")
+ continue
+ if resp.status_code != 200:
+ out.note(
+ f"role {role_id}: expansion returned HTTP {resp.status_code}; it appears in the chain "
+ f"with no permissions rather than being dropped from it"
+ )
+ continue
+ role["permissions"] = list(resp.json().get("includedPermissions") or [])
+
+ if not members:
+ out.note(
+ "no IAM members were returned. On a live project this is far more often a missing "
+ "resourcemanager.projects.getIamPolicy permission than a project nobody can access"
+ )
+
+ out.snapshot = {
+ "principals": list(members.values()),
+ "groups": [],
+ "roles": list(roles.values()),
+ "bindings": bindings,
+ "org_policies": [],
+ "resources": resources,
+ }
+ out.note(
+ "organisation policy constraints are not collected, so a constraint that blocks an action "
+ "granted by a binding will not appear as a denial"
+ )
+ return out
diff --git a/services/connectors/app/connectors/posture/github.py b/services/connectors/app/connectors/posture/github.py
new file mode 100644
index 000000000..a952ea81e
--- /dev/null
+++ b/services/connectors/app/connectors/posture/github.py
@@ -0,0 +1,267 @@
+"""Collect a GitHub organisation posture snapshot.
+
+Returns the shape the GitHub resolver in
+``services/api/app/services/effective_permissions/github.py`` consumes.
+
+Why GitHub belongs in this set
+------------------------------
+It is where the source and the deployment credentials live, so "what can
+this identity do" has a direct blast radius -- and unlike the three clouds,
+its permission model is small enough to collect completely rather than
+partially. An org member reaches a repository two ways: a direct
+collaborator grant, or membership of a team that holds one. Both are
+collected.
+
+The modelling decision worth stating: GitHub's permission *levels* (read,
+triage, write, maintain, admin) are ordered, and a principal holding two
+grants on one repository gets the stronger. That ordering is applied here,
+at collection time, because it is a property of GitHub rather than of this
+product, and a resolver that re-derived it would be a second place for the
+ladder to drift.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import structlog
+
+from app.connectors.posture import Collected
+
+logger = structlog.get_logger()
+
+_BASE = "https://api.github.com"
+_MAX_PAGES = 50
+_PER_PAGE = 100
+
+#: Weakest to strongest. A principal holding two grants on one repository
+#: gets the stronger, which is GitHub's rule and not ours.
+_LEVELS = ("pull", "triage", "push", "maintain", "admin")
+
+#: The actions each level confers, named the way GitHub's own documentation
+#: and audit log name them so a reader can match an answer against a log
+#: line without a translation table.
+_LEVEL_ACTIONS: dict[str, tuple[str, ...]] = {
+ "pull": ("repo.read", "repo.clone"),
+ "triage": ("repo.read", "repo.clone", "issues.manage"),
+ "push": ("repo.read", "repo.clone", "issues.manage", "repo.push", "workflow.run"),
+ "maintain": (
+ "repo.read",
+ "repo.clone",
+ "issues.manage",
+ "repo.push",
+ "workflow.run",
+ "repo.manage_settings",
+ ),
+ "admin": (
+ "repo.read",
+ "repo.clone",
+ "issues.manage",
+ "repo.push",
+ "workflow.run",
+ "repo.manage_settings",
+ "repo.manage_access",
+ "repo.delete",
+ "secrets.write",
+ ),
+}
+
+
+def strongest(*levels: str) -> str:
+ """The strongest of the levels given, ignoring any GitHub does not define.
+
+ An unrecognised level is dropped rather than ranked, because guessing
+ where a new GitHub level sits in the ladder would either over- or
+ under-state access, and both are wrong in a way nobody would notice.
+ """
+ known = [level for level in levels if level in _LEVELS]
+ if not known:
+ return ""
+ return max(known, key=_LEVELS.index)
+
+
+def _level_from_permissions(permissions: dict[str, Any] | None) -> str:
+ """Read a level off GitHub's boolean permission block.
+
+ The REST API returns ``{"admin": true, "push": true, ...}`` rather than
+ a single level on several endpoints, and the booleans are cumulative, so
+ the strongest true one is the level.
+ """
+ if not isinstance(permissions, dict):
+ return ""
+ for level in reversed(_LEVELS):
+ if permissions.get(level) is True:
+ return level
+ return ""
+
+
+async def _paged(
+ client: Any,
+ url: str,
+ headers: dict[str, str],
+ out: Collected,
+ what: str,
+) -> list[dict[str, Any]]:
+ items: list[dict[str, Any]] = []
+ for page in range(1, _MAX_PAGES + 1):
+ try:
+ resp = await client.get(url, headers=headers, params={"per_page": _PER_PAGE, "page": page})
+ except Exception as exc: # noqa: BLE001
+ out.note(f"{what}: request failed on page {page}: {exc}")
+ return items
+ if resp.status_code != 200:
+ out.note(f"{what}: HTTP {resp.status_code} on page {page}")
+ return items
+ batch = resp.json()
+ if not isinstance(batch, list) or not batch:
+ return items
+ items.extend(batch)
+ if len(batch) < _PER_PAGE:
+ return items
+ out.note(f"{what}: stopped after {_MAX_PAGES} pages; the organisation is larger than one pass")
+ return items
+
+
+async def collect(client: Any, headers: dict[str, str], org: str) -> Collected:
+ out = Collected(snapshot={})
+ if not org:
+ out.note("no organisation is configured on the connector, so nothing could be collected")
+ out.snapshot = {"org": "", "principals": [], "teams": [], "repositories": [], "grants": []}
+ return out
+
+ members = await _paged(client, f"{_BASE}/orgs/{org}/members", headers, out, "organisation members")
+ teams = await _paged(client, f"{_BASE}/orgs/{org}/teams", headers, out, "teams")
+ repos = await _paged(client, f"{_BASE}/orgs/{org}/repos", headers, out, "repositories")
+
+ # Org owners hold admin on every repository regardless of any team or
+ # collaborator grant, so the role is read separately. Without it the
+ # most privileged identities in the organisation would resolve to
+ # whatever their team happened to grant.
+ owners: set[str] = set()
+ for member in members:
+ login = member.get("login")
+ if not login:
+ continue
+ try:
+ resp = await client.get(f"{_BASE}/orgs/{org}/memberships/{login}", headers=headers)
+ if resp.status_code == 200 and resp.json().get("role") == "admin":
+ owners.add(login)
+ elif resp.status_code != 200:
+ out.note(
+ f"membership role for {login} returned HTTP {resp.status_code}; if they are an "
+ f"organisation owner their admin access over every repository is not reflected"
+ )
+ except Exception as exc: # noqa: BLE001
+ out.note(f"membership role for {login} could not be read: {exc}")
+
+ team_members: dict[str, list[str]] = {}
+ grants: list[dict[str, Any]] = []
+
+ for team in teams:
+ slug = team.get("slug")
+ if not slug:
+ continue
+ logins = [
+ m["login"]
+ for m in await _paged(client, f"{_BASE}/orgs/{org}/teams/{slug}/members", headers, out, f"team {slug} members")
+ if m.get("login")
+ ]
+ team_members[slug] = logins
+ for repo in await _paged(client, f"{_BASE}/orgs/{org}/teams/{slug}/repos", headers, out, f"team {slug} repositories"):
+ full_name = repo.get("full_name")
+ level = _level_from_permissions(repo.get("permissions"))
+ if not full_name or not level:
+ continue
+ grants.append(
+ {
+ "id": f"team:{slug}:{full_name}",
+ "principal_id": f"team:{slug}",
+ "repository_id": full_name,
+ "level": level,
+ "via": f"team:{slug}",
+ }
+ )
+
+ repositories: list[dict[str, Any]] = []
+ for repo in repos:
+ full_name = repo.get("full_name")
+ if not full_name:
+ continue
+ repositories.append(
+ {
+ "id": full_name,
+ "name": repo.get("name") or full_name,
+ "private": bool(repo.get("private")),
+ "archived": bool(repo.get("archived")),
+ }
+ )
+ for collaborator in await _paged(
+ client,
+ f"{_BASE}/repos/{full_name}/collaborators",
+ headers,
+ out,
+ f"collaborators on {full_name}",
+ ):
+ login = collaborator.get("login")
+ level = _level_from_permissions(collaborator.get("permissions"))
+ if not login or not level:
+ continue
+ grants.append(
+ {
+ "id": f"user:{login}:{full_name}",
+ "principal_id": login,
+ "repository_id": full_name,
+ "level": level,
+ "via": None,
+ }
+ )
+
+ for login in sorted(owners):
+ for repo in repositories:
+ grants.append(
+ {
+ "id": f"owner:{login}:{repo['id']}",
+ "principal_id": login,
+ "repository_id": repo["id"],
+ "level": "admin",
+ "via": "organisation-owner",
+ }
+ )
+
+ principals: list[dict[str, Any]] = [
+ {
+ "id": m["login"],
+ "name": m["login"],
+ "type": "user",
+ "org_role": "admin" if m["login"] in owners else "member",
+ "teams": sorted(slug for slug, logins in team_members.items() if m["login"] in logins),
+ }
+ for m in members
+ if m.get("login")
+ ]
+ principals.extend(
+ {
+ "id": f"team:{slug}",
+ "name": slug,
+ "type": "team",
+ "org_role": "team",
+ "teams": [],
+ }
+ for slug in sorted(team_members)
+ )
+
+ if not principals:
+ out.note(
+ f"no members were returned for organisation {org!r}. On a live organisation this is far "
+ f"more often a token without the read:org scope than an organisation with no members"
+ )
+
+ out.snapshot = {
+ "org": org,
+ "principals": principals,
+ "teams": [{"id": f"team:{slug}", "slug": slug, "members": sorted(logins)} for slug, logins in sorted(team_members.items())],
+ "repositories": repositories,
+ "grants": grants,
+ "level_actions": {level: list(actions) for level, actions in _LEVEL_ACTIONS.items()},
+ }
+ return out
diff --git a/services/connectors/app/connectors/posture/gws.py b/services/connectors/app/connectors/posture/gws.py
new file mode 100644
index 000000000..15ea06ce9
--- /dev/null
+++ b/services/connectors/app/connectors/posture/gws.py
@@ -0,0 +1,171 @@
+"""Collect a Google Workspace admin posture snapshot.
+
+Returns the shape documented in
+``services/api/app/services/effective_permissions/gws.py``.
+
+Workspace has the smallest admin model of the five providers: a user holds
+role assignments, each role is a bag of privilege strings, and an assignment
+is scoped either customer-wide or to an org unit. All three come from the
+Admin SDK Directory API.
+
+The one trap worth naming: the API identifies an org-unit-scoped assignment
+by ``orgUnitId``, not by path, while the resolver matches on an OU *path*
+prefix (an assignment on ``/Eng`` covering a user in ``/Eng/Platform``). The
+ids are therefore resolved to paths here, once, rather than leaving the
+resolver to compare an id against a path -- a comparison that never matches
+and would silently report every OU-scoped administrator as having no reach.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import structlog
+
+from app.connectors.posture import Collected
+
+logger = structlog.get_logger()
+
+_DIRECTORY = "https://admin.googleapis.com/admin/directory/v1"
+_MAX_PAGES = 50
+
+
+async def _paged(
+ client: Any,
+ url: str,
+ headers: dict[str, str],
+ key: str,
+ out: Collected,
+ what: str,
+ params: dict[str, Any] | None = None,
+) -> list[dict[str, Any]]:
+ items: list[dict[str, Any]] = []
+ token: str | None = None
+ pages = 0
+ while pages < _MAX_PAGES:
+ pages += 1
+ query = dict(params or {})
+ if token:
+ query["pageToken"] = token
+ try:
+ resp = await client.get(url, headers=headers, params=query)
+ except Exception as exc: # noqa: BLE001
+ out.note(f"{what}: request failed after {pages - 1} page(s): {exc}")
+ return items
+ if resp.status_code != 200:
+ out.note(f"{what}: HTTP {resp.status_code} after {pages - 1} page(s)")
+ return items
+ body = resp.json()
+ items.extend(body.get(key) or [])
+ token = body.get("nextPageToken")
+ if not token:
+ return items
+ out.note(f"{what}: stopped after {_MAX_PAGES} pages; the directory is larger than one pass")
+ return items
+
+
+async def collect(client: Any, headers: dict[str, str], *, customer: str = "my_customer") -> Collected:
+ out = Collected(snapshot={})
+
+ roles = await _paged(client, f"{_DIRECTORY}/customer/{customer}/roles", headers, "items", out, "admin roles")
+ assignments = await _paged(
+ client,
+ f"{_DIRECTORY}/customer/{customer}/roleassignments",
+ headers,
+ "items",
+ out,
+ "role assignments",
+ )
+ org_units = await _paged(
+ client,
+ f"{_DIRECTORY}/customer/{customer}/orgunits",
+ headers,
+ "organizationUnits",
+ out,
+ "org units",
+ params={"type": "all"},
+ )
+
+ # orgUnitId arrives with an "id:" prefix in assignments and without it in
+ # the org-unit listing. Both spellings are indexed so a prefix mismatch
+ # cannot silently drop an assignment's scope.
+ path_by_ou_id: dict[str, str] = {}
+ for unit in org_units:
+ ou_id = unit.get("orgUnitId")
+ path = unit.get("orgUnitPath")
+ if not ou_id or not path:
+ continue
+ path_by_ou_id[ou_id] = path
+ if ou_id.startswith("id:"):
+ path_by_ou_id[ou_id[3:]] = path
+ else:
+ path_by_ou_id[f"id:{ou_id}"] = path
+
+ admin_roles: list[dict[str, Any]] = []
+ for role in roles:
+ rid = role.get("roleId")
+ if not rid:
+ continue
+ admin_roles.append(
+ {
+ "id": str(rid),
+ "name": role.get("roleName") or str(rid),
+ "privileges": [p.get("privilegeName") for p in role.get("rolePrivileges") or [] if p.get("privilegeName")],
+ }
+ )
+
+ role_assignments: list[dict[str, Any]] = []
+ principal_ids: set[str] = set()
+ for assignment in assignments:
+ assigned_to = assignment.get("assignedTo")
+ role_id = assignment.get("roleId")
+ if not assigned_to or not role_id:
+ continue
+ principal_ids.add(str(assigned_to))
+ scope_type = assignment.get("scopeType") or "CUSTOMER"
+ ou_id = assignment.get("orgUnitId")
+ ou_path = path_by_ou_id.get(str(ou_id)) if ou_id else None
+ if scope_type == "ORG_UNIT" and ou_id and ou_path is None:
+ out.note(
+ f"assignment {assignment.get('roleAssignmentId')} is scoped to org unit {ou_id}, "
+ f"whose path could not be read; its reach is reported as org-wide, which "
+ f"over-states it rather than silently dropping the assignment"
+ )
+ role_assignments.append(
+ {
+ "id": str(assignment.get("roleAssignmentId") or f"{assigned_to}:{role_id}"),
+ "principal_id": str(assigned_to),
+ "role_id": str(role_id),
+ "scope_type": "CUSTOMER" if ou_path is None else scope_type,
+ "ou_path": ou_path or "/",
+ }
+ )
+
+ principals: list[dict[str, Any]] = []
+ for principal_id in sorted(principal_ids):
+ ou_path = "/"
+ name = principal_id
+ try:
+ resp = await client.get(f"{_DIRECTORY}/users/{principal_id}", headers=headers)
+ if resp.status_code == 200:
+ user = resp.json()
+ ou_path = user.get("orgUnitPath") or "/"
+ name = user.get("primaryEmail") or principal_id
+ except Exception as exc: # noqa: BLE001
+ out.note(f"could not read org unit for principal {principal_id}: {exc}")
+ principals.append({"id": principal_id, "name": name, "ou_path": ou_path})
+
+ if not principals:
+ out.note(
+ "no admin role assignments were returned. On a live tenant this is far more often a "
+ "missing admin.directory.rolemanagement.readonly scope, or a service account without "
+ "domain-wide delegation, than a tenant with no administrators"
+ )
+
+ out.snapshot = {
+ "principals": principals,
+ "admin_roles": admin_roles,
+ "role_assignments": role_assignments,
+ "resources": [],
+ }
+ return out
diff --git a/services/connectors/tests/test_posture_collectors.py b/services/connectors/tests/test_posture_collectors.py
new file mode 100644
index 000000000..56e9595c3
--- /dev/null
+++ b/services/connectors/tests/test_posture_collectors.py
@@ -0,0 +1,574 @@
+"""The posture collectors, driven through the connectors that own them.
+
+Why these tests go through ``get_resource_config`` rather than calling the
+collector functions directly
+---------------------------------------------------------------------------
+The gap these collectors close was not "nobody wrote a collector". It was
+that the resolver subsystem had no way to *obtain* a snapshot, so every live
+call answered 412 while the endpoint reported ``coverage: "full"``. A test
+that calls ``posture.azure.collect`` proves a function works; it does not
+prove the connector routes the sentinel to it, which is the half that was
+missing. So the cloud tests go in through ``connector.get_resource_config(
+POSTURE_SNAPSHOT_ID)`` — the exact call the API's posture loader makes.
+
+The test this replaces searched connector *source* for the sentinel string,
+and passed on all four cloud connectors after they were wired, because a
+connector that imports the shared constant does not contain the literal. A
+detector that only recognises the hardcoded spelling recognises the wrong
+one, and a source-reading test can never notice the code does not run.
+
+Three properties are asserted per provider, matching the three rules the
+collectors are written to:
+
+* a reachable provider yields a snapshot in the shape its resolver reads;
+* an unreadable part of the estate comes back ``partial`` with a note naming
+ what was missed, never as a smaller snapshot that looks complete;
+* an empty collection is partial with a reason, because zero principals
+ means a lost read permission far more often than an empty estate.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import pytest
+from app.connectors.azure_entra import AzureEntraConnector
+from app.connectors.github import GitHubConnector
+from app.connectors.posture import POSTURE_SNAPSHOT_ID, Collected
+
+
+class FakeResponse:
+ def __init__(self, status_code: int, payload: Any = None) -> None:
+ self.status_code = status_code
+ self._payload = payload if payload is not None else {}
+ self.text = json.dumps(self._payload)
+
+ def json(self) -> Any:
+ return self._payload
+
+
+class FakeClient:
+ """Routes a request by substring match against a table of responses.
+
+ Substring rather than exact match because the collectors build URLs with
+ page tokens and query parameters; a test pinning whole URLs would fail
+ on a pagination change that broke nothing. Longest fragment wins so a
+ specific route can sit alongside a general one.
+ """
+
+ def __init__(self, routes: dict[str, Any], default: Any = None) -> None:
+ self._routes = routes
+ self._default = default if default is not None else FakeResponse(404, {"message": "no stub route"})
+ self.requested: list[str] = []
+
+ def _match(self, url: str) -> Any:
+ best: tuple[int, Any] | None = None
+ for fragment, response in self._routes.items():
+ if fragment in url and (best is None or len(fragment) > best[0]):
+ best = (len(fragment), response)
+ return best[1] if best else self._default
+
+ async def get(self, url: str, headers: Any = None, params: Any = None) -> Any:
+ self.requested.append(url)
+ return self._match(url)
+
+ async def post(self, url: str, headers: Any = None, json: Any = None) -> Any:
+ self.requested.append(url)
+ return self._match(url)
+
+ async def __aenter__(self) -> FakeClient:
+ return self
+
+ async def __aexit__(self, *exc: object) -> None:
+ return None
+
+
+class FakeHttpx:
+ """Stands in for the ``httpx`` module a connector imported.
+
+ The connectors open their own ``httpx.AsyncClient(...)`` inside the
+ method under test, so the seam is the module attribute rather than the
+ client object. ``HTTPStatusError`` is carried through because one
+ connector catches it by name.
+ """
+
+ HTTPStatusError = __import__("httpx").HTTPStatusError
+
+ def __init__(self, client: FakeClient) -> None:
+ self._client = client
+
+ def AsyncClient(self, *args: Any, **kwargs: Any) -> FakeClient: # noqa: N802 — mirrors httpx
+ return self._client
+
+
+async def _noop(*args: Any, **kwargs: Any) -> str:
+ """Stands in for a connector's ``_authenticate`` so no token is minted."""
+ return "test-token"
+
+
+# --------------------------------------------------------------------------
+# Collected: the contract every collector reports its gaps through
+# --------------------------------------------------------------------------
+
+
+def test_noting_a_gap_marks_the_snapshot_partial() -> None:
+ """The flag and the reason are one operation on purpose.
+
+ Earlier versions of this idea in the tree had a notes list that some
+ callers filled and no caller read. Being able to set them separately is
+ exactly what lets a snapshot carry a reason and still report complete.
+ """
+ collected = Collected(snapshot={"principals": []})
+ assert collected.partial is False
+ assert collected.notes == []
+
+ collected.note("the second page of role assignments returned 403")
+
+ assert collected.partial is True
+ assert collected.notes == ["the second page of role assignments returned 403"]
+
+
+def test_envelope_carries_the_gap_alongside_the_snapshot() -> None:
+ """``partial`` travelling in the same envelope as the data is what lets
+ a triage surface render "incomplete, here is why" instead of rendering
+ a gap as an absence."""
+ collected = Collected(snapshot={"principals": []})
+ collected.note("page 2 of 7 returned 403")
+
+ envelope = collected.to_resource_config()
+
+ assert envelope["snapshot"] == {"principals": []}
+ assert envelope["partial"] is True
+ assert envelope["collection_notes"] == ["page 2 of 7 returned 403"]
+
+
+# --------------------------------------------------------------------------
+# Azure (Entra ID directory roles)
+# --------------------------------------------------------------------------
+
+
+def _entra(monkeypatch: pytest.MonkeyPatch, client: FakeClient) -> AzureEntraConnector:
+ from app.connectors import azure_entra
+
+ monkeypatch.setattr(azure_entra, "httpx", FakeHttpx(client))
+ connector = AzureEntraConnector("tenant-1", "client-1", "secret-1")
+ monkeypatch.setattr(connector, "_authenticate", _noop)
+ return connector
+
+
+async def test_entra_sentinel_returns_a_resolver_shaped_snapshot(monkeypatch: pytest.MonkeyPatch) -> None:
+ client = FakeClient(
+ {
+ "roleDefinitions": FakeResponse(
+ 200,
+ {
+ "value": [
+ {
+ "id": "role-ga",
+ "displayName": "Global Administrator",
+ "rolePermissions": [
+ {
+ "allowedResourceActions": ["microsoft.directory/users/delete"],
+ "excludedResourceActions": [],
+ }
+ ],
+ }
+ ]
+ },
+ ),
+ "roleAssignments": FakeResponse(
+ 200,
+ {"value": [{"id": "ra-1", "principalId": "user-1", "roleDefinitionId": "role-ga"}]},
+ ),
+ "directoryObjects/user-1": FakeResponse(200, {"@odata.type": "#microsoft.graph.user", "displayName": "Ada"}),
+ }
+ )
+ connector = _entra(monkeypatch, client)
+
+ envelope = await connector.get_resource_config(POSTURE_SNAPSHOT_ID)
+ snapshot = envelope["snapshot"]
+
+ assert [p["id"] for p in snapshot["principals"]] == ["user-1"]
+ assert snapshot["principals"][0]["name"] == "Ada"
+ assert snapshot["principals"][0]["type"] == "user"
+ assert snapshot["role_definitions"][0]["permissions"][0]["actions"] == ["microsoft.directory/users/delete"]
+ # Tenant-wide unless an administrative unit narrows it.
+ assert snapshot["role_assignments"][0]["scope"] == "/"
+
+
+async def test_entra_types_a_service_principal_distinctly(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A service principal holding a directory role is the shape that gets
+ missed in review, so the type has to survive collection."""
+ client = FakeClient(
+ {
+ "roleDefinitions": FakeResponse(200, {"value": []}),
+ "roleAssignments": FakeResponse(200, {"value": [{"id": "ra-2", "principalId": "sp-9", "roleDefinitionId": "role-ga"}]}),
+ "directoryObjects/sp-9": FakeResponse(200, {"@odata.type": "#microsoft.graph.servicePrincipal", "displayName": "ci-deployer"}),
+ }
+ )
+ connector = _entra(monkeypatch, client)
+
+ snapshot = (await connector.get_resource_config(POSTURE_SNAPSHOT_ID))["snapshot"]
+
+ assert snapshot["principals"][0]["type"] == "servicePrincipal"
+ assert snapshot["principals"][0]["name"] == "ci-deployer"
+
+
+async def test_entra_truncated_assignment_read_is_partial(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A missing page of role assignments is a privileged identity the
+ resolver would otherwise report as unprivileged."""
+ client = FakeClient(
+ {
+ "roleDefinitions": FakeResponse(200, {"value": []}),
+ "roleAssignments": FakeResponse(403, {"error": {"message": "Insufficient privileges"}}),
+ }
+ )
+ connector = _entra(monkeypatch, client)
+
+ envelope = await connector.get_resource_config(POSTURE_SNAPSHOT_ID)
+
+ assert envelope["partial"] is True
+ assert any("role assignments" in note and "403" in note for note in envelope["collection_notes"])
+
+
+async def test_entra_records_the_resource_rbac_boundary(monkeypatch: pytest.MonkeyPatch) -> None:
+ """An identity with no directory role may still own a subscription.
+
+ A reader who takes "no permissions found" for "harmless" has made the
+ misreading that costs an incident, so the snapshot states the limit of
+ its own scope rather than leaving it to be inferred.
+ """
+ client = FakeClient(
+ {
+ "roleDefinitions": FakeResponse(200, {"value": []}),
+ "roleAssignments": FakeResponse(200, {"value": []}),
+ }
+ )
+ connector = _entra(monkeypatch, client)
+
+ envelope = await connector.get_resource_config(POSTURE_SNAPSHOT_ID)
+ notes = " ".join(envelope["collection_notes"]).lower()
+
+ assert envelope["partial"] is True
+ assert "resource rbac" in notes
+ assert "subscription" in notes
+
+
+async def test_entra_refuses_a_non_sentinel_resource_id(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Returning ``{}`` would read as "this resource has no settings"."""
+ connector = _entra(monkeypatch, FakeClient({}))
+ with pytest.raises(NotImplementedError):
+ await connector.get_resource_config("some-directory-object-id")
+
+
+# --------------------------------------------------------------------------
+# GitHub
+# --------------------------------------------------------------------------
+
+
+def _github(monkeypatch: pytest.MonkeyPatch, client: FakeClient) -> GitHubConnector:
+ from app.connectors import github as github_connector
+
+ monkeypatch.setattr(github_connector, "httpx", FakeHttpx(client))
+ return GitHubConnector("acme", "token")
+
+
+async def test_github_org_owner_gets_admin_on_every_repository(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Without the membership read, the most privileged identities in an
+ organisation resolve to whatever their team happened to grant."""
+ client = FakeClient(
+ {
+ "/orgs/acme/members": FakeResponse(200, [{"login": "owner-ann"}, {"login": "dev-bob"}]),
+ "/orgs/acme/teams/platform/members": FakeResponse(200, [{"login": "dev-bob"}]),
+ "/orgs/acme/teams/platform/repos": FakeResponse(200, [{"full_name": "acme/api", "permissions": {"pull": True, "push": True}}]),
+ "/orgs/acme/teams": FakeResponse(200, [{"slug": "platform"}]),
+ "/orgs/acme/repos": FakeResponse(200, [{"full_name": "acme/api", "name": "api"}, {"full_name": "acme/web", "name": "web"}]),
+ "/orgs/acme/memberships/owner-ann": FakeResponse(200, {"role": "admin"}),
+ "/orgs/acme/memberships/dev-bob": FakeResponse(200, {"role": "member"}),
+ "/collaborators": FakeResponse(200, []),
+ }
+ )
+ connector = _github(monkeypatch, client)
+
+ snapshot = (await connector.get_resource_config(POSTURE_SNAPSHOT_ID))["snapshot"]
+
+ owner_grants = {(g["repository_id"], g["level"]) for g in snapshot["grants"] if g["principal_id"] == "owner-ann"}
+ assert owner_grants == {("acme/api", "admin"), ("acme/web", "admin")}
+
+ team_grants = {(g["repository_id"], g["level"]) for g in snapshot["grants"] if g["principal_id"] == "team:platform"}
+ assert team_grants == {("acme/api", "push")}
+
+ ann = next(p for p in snapshot["principals"] if p["id"] == "owner-ann")
+ assert ann["org_role"] == "admin"
+
+
+async def test_github_cumulative_permission_block_reads_as_the_strongest_level(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """GitHub returns ``{"admin": true, "push": true, "pull": true}`` rather
+ than one level, and the booleans are cumulative — so the strongest true
+ one is the answer, not the first."""
+ client = FakeClient(
+ {
+ "/orgs/acme/members": FakeResponse(200, []),
+ "/orgs/acme/teams": FakeResponse(200, []),
+ "/orgs/acme/repos": FakeResponse(200, [{"full_name": "acme/api", "name": "api"}]),
+ "/repos/acme/api/collaborators": FakeResponse(
+ 200,
+ [{"login": "dev-bob", "permissions": {"pull": True, "triage": True, "push": True, "admin": True}}],
+ ),
+ }
+ )
+ connector = _github(monkeypatch, client)
+
+ snapshot = (await connector.get_resource_config(POSTURE_SNAPSHOT_ID))["snapshot"]
+
+ assert [g["level"] for g in snapshot["grants"]] == ["admin"]
+
+
+async def test_github_unreadable_membership_is_a_note_not_a_silent_demotion(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A 403 on the membership read must not quietly turn an owner into a
+ member — that under-states the blast radius of the account holding the
+ most of it."""
+ client = FakeClient(
+ {
+ "/orgs/acme/members": FakeResponse(200, [{"login": "owner-ann"}]),
+ "/orgs/acme/teams": FakeResponse(200, []),
+ "/orgs/acme/repos": FakeResponse(200, []),
+ "/orgs/acme/memberships/owner-ann": FakeResponse(403, {"message": "Forbidden"}),
+ }
+ )
+ connector = _github(monkeypatch, client)
+
+ envelope = await connector.get_resource_config(POSTURE_SNAPSHOT_ID)
+ notes = " ".join(envelope["collection_notes"])
+
+ assert envelope["partial"] is True
+ assert "owner-ann" in notes
+ assert "403" in notes
+
+
+async def test_github_empty_org_is_partial_with_a_scope_hint(monkeypatch: pytest.MonkeyPatch) -> None:
+ client = FakeClient(
+ {
+ "/orgs/acme/members": FakeResponse(200, []),
+ "/orgs/acme/teams": FakeResponse(200, []),
+ "/orgs/acme/repos": FakeResponse(200, []),
+ }
+ )
+ connector = _github(monkeypatch, client)
+
+ envelope = await connector.get_resource_config(POSTURE_SNAPSHOT_ID)
+
+ assert envelope["partial"] is True
+ assert "read:org" in " ".join(envelope["collection_notes"])
+
+
+async def test_github_still_answers_a_repo_resource_id(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The sentinel is an addition, not a replacement: the pre-existing
+ per-repository config read has to keep working."""
+ client = FakeClient({"/repos/acme/api": FakeResponse(404, {"message": "Not Found"})})
+ connector = _github(monkeypatch, client)
+
+ result = await connector.get_resource_config("acme/api")
+
+ assert result.get("snapshot_freshness") == "unavailable"
+
+
+# --------------------------------------------------------------------------
+# The contract every implementation has to keep
+# --------------------------------------------------------------------------
+
+
+def test_every_implementation_matches_the_base_signature() -> None:
+ """``at_ts`` is optional in the base class and three connectors required
+ a second positional ``ts``.
+
+ Nothing broke, because both call sites happened to pass positionally —
+ but the base's own docstring tells a caller that omitting the timestamp
+ means "latest known", and following that advice raised TypeError on
+ AWS, Okta and GitHub. A contract that only works if you read the
+ implementations is not a contract.
+ """
+ import inspect
+
+ from app.connectors import CONNECTOR_REGISTRY
+ from app.connectors.base import BaseConnector
+
+ expected = inspect.signature(BaseConnector.get_resource_config)
+ drifted: list[str] = []
+ for connector_id, cls in sorted(CONNECTOR_REGISTRY.items()):
+ impl = cls.__dict__.get("get_resource_config")
+ if impl is None:
+ continue
+ if inspect.signature(impl) != expected:
+ drifted.append(f"{connector_id}: {inspect.signature(impl)}")
+
+ assert not drifted, "get_resource_config signatures differ from BaseConnector's:\n " + "\n ".join(drifted)
+
+
+# --------------------------------------------------------------------------
+# AWS
+# --------------------------------------------------------------------------
+
+
+class FakeIam:
+ def __init__(self, pages: list[dict[str, Any]]) -> None:
+ self._pages = pages
+ self.calls = 0
+
+ def get_account_authorization_details(self, **kwargs: Any) -> dict[str, Any]:
+ page = self._pages[min(self.calls, len(self._pages) - 1)]
+ self.calls += 1
+ return page
+
+
+class FakeSession:
+ def __init__(self, clients: dict[str, Any]) -> None:
+ self._clients = clients
+
+ def client(self, name: str, **kwargs: Any) -> Any:
+ if name not in self._clients:
+ raise RuntimeError(f"no stub client for {name!r}")
+ return self._clients[name]
+
+
+_EMPTY_IAM_PAGE: dict[str, Any] = {
+ "UserDetailList": [],
+ "GroupDetailList": [],
+ "RoleDetailList": [],
+ "Policies": [],
+ "IsTruncated": False,
+}
+
+
+async def test_aws_collects_users_groups_and_the_default_policy_version() -> None:
+ from app.connectors.posture import aws as aws_posture
+
+ iam = FakeIam(
+ [
+ {
+ "UserDetailList": [
+ {
+ "Arn": "arn:aws:iam::111122223333:user/ada",
+ "UserName": "ada",
+ "GroupList": ["engineers"],
+ "AttachedManagedPolicies": [{"PolicyArn": "arn:aws:iam::aws:policy/ReadOnlyAccess"}],
+ }
+ ],
+ "GroupDetailList": [{"Arn": "arn:aws:iam::111122223333:group/engineers", "GroupName": "engineers"}],
+ "RoleDetailList": [],
+ "Policies": [
+ {
+ "Arn": "arn:aws:iam::aws:policy/ReadOnlyAccess",
+ "PolicyName": "ReadOnlyAccess",
+ "DefaultVersionId": "v2",
+ "PolicyVersionList": [
+ {
+ "VersionId": "v1",
+ "Document": {"Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]},
+ },
+ {
+ "VersionId": "v2",
+ "Document": {"Statement": [{"Effect": "Allow", "Action": "s3:GetObject", "Resource": "*"}]},
+ },
+ ],
+ }
+ ],
+ "IsTruncated": False,
+ }
+ ]
+ )
+
+ collected = await aws_posture.collect(FakeSession({"iam": iam}))
+ snapshot = collected.snapshot
+
+ ada = next(p for p in snapshot["principals"] if p["id"].endswith("user/ada"))
+ assert ada["attached_policies"] == ["arn:aws:iam::aws:policy/ReadOnlyAccess"]
+ assert ada["groups"] == ["arn:aws:iam::111122223333:group/engineers"]
+
+ policy = next(p for p in snapshot["policies"] if p["id"].endswith("ReadOnlyAccess"))
+ # The non-default version is the one that grants s3:*; reading it would
+ # over-state what the principal can do.
+ assert policy["document"]["Statement"][0]["Action"] == "s3:GetObject"
+
+
+async def test_aws_carries_the_permissions_boundary_through() -> None:
+ """The field 2.5 exists to model. Absent is not the same as "a boundary
+ that allows everything", so it has to arrive at the resolver."""
+ from app.connectors.posture import aws as aws_posture
+
+ iam = FakeIam(
+ [
+ {
+ **_EMPTY_IAM_PAGE,
+ "UserDetailList": [
+ {
+ "Arn": "arn:aws:iam::111122223333:user/frank",
+ "UserName": "frank",
+ "PermissionsBoundary": {"PermissionsBoundaryArn": "arn:aws:iam::111122223333:policy/DevBoundary"},
+ },
+ {"Arn": "arn:aws:iam::111122223333:user/gina", "UserName": "gina"},
+ ],
+ }
+ ]
+ )
+
+ snapshot = (await aws_posture.collect(FakeSession({"iam": iam}))).snapshot
+ by_name = {p["name"]: p for p in snapshot["principals"]}
+
+ assert by_name["frank"]["permissions_boundary"] == "arn:aws:iam::111122223333:policy/DevBoundary"
+ assert by_name["gina"]["permissions_boundary"] is None
+
+
+async def test_aws_missing_organizations_access_is_recorded() -> None:
+ """Service control policies cap everything beneath them, so a collection
+ that could not read them must say so — otherwise a principal the SCP
+ blocks resolves as able to act."""
+ from app.connectors.posture import aws as aws_posture
+
+ class DeniedOrgs:
+ def list_policies(self, **kwargs: Any) -> dict[str, Any]:
+ raise RuntimeError("AccessDeniedException: organizations:ListPolicies")
+
+ collected = await aws_posture.collect(FakeSession({"iam": FakeIam([_EMPTY_IAM_PAGE]), "organizations": DeniedOrgs()}))
+
+ assert collected.partial is True
+ assert any("service control policies not read" in note for note in collected.notes)
+
+
+async def test_aws_empty_estate_names_the_likely_permission() -> None:
+ from app.connectors.posture import aws as aws_posture
+
+ collected = await aws_posture.collect(FakeSession({"iam": FakeIam([_EMPTY_IAM_PAGE])}))
+
+ assert collected.partial is True
+ assert any("GetAccountAuthorizationDetails" in note for note in collected.notes)
+
+
+async def test_aws_records_that_resource_policies_are_not_collected() -> None:
+ """A grant made by a bucket or key policy will not appear, and the
+ snapshot says so rather than reading as a complete picture."""
+ from app.connectors.posture import aws as aws_posture
+
+ collected = await aws_posture.collect(FakeSession({"iam": FakeIam([_EMPTY_IAM_PAGE])}))
+
+ assert any("resource-based policies" in note for note in collected.notes)