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(ai-estate): depth 6.2 — endpoint discovery with no new agent (#1305)

Beenu Arora601b485a0a70
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d3dcbceac..0dbdeba0b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -714,6 +714,16 @@ jobs:
run: python3 scripts/check_ai_asset_inventory.py --self-test
- name: AI asset inventory gate
run: python3 scripts/check_ai_asset_inventory.py
+ # Depth 6.2. The endpoint half, and the rule that carries it is
+ # NAMESPACE: the four endpoint connectors put their process fields in
+ # the connector payload under `raw_data`, and the canonical OCSF
+ # profile maps none of them — so a classifier reading `process.name`
+ # finds None on every real source while its unit tests pass against
+ # events built in the shape it expects.
+ - name: AI endpoint discovery gate — self-test
+ run: python3 scripts/check_ai_endpoint_discovery.py --self-test
+ - name: AI endpoint discovery gate
+ run: python3 scripts/check_ai_endpoint_discovery.py
# One layer in from the name: the profile gate asks whether a connector
# reaches a normalization path, this asks which OCSF class it reaches
# when it gets there. The class uid divided by a thousand is the
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cfc173f50..2e93a0080 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -191,6 +191,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Endpoint discovery of the AI estate, with no new agent** (depth plan 6.2).
+ `packs/aisoc-ai-estate.yaml` finds coding agents and MCP server processes,
+ the configuration files the popular MCP clients read, AI IDE extensions and
+ model-provider credential files, through the osquery agent a fleet already
+ runs. `apps/docs/docs/concepts/ai-estate-discovery.md` records what each
+ source can **and cannot** see, which is the half that makes an empty column
+ readable: a device missing from a provider-audit row is not a finding,
+ because no provider audit log has ever carried one.
+
+ The finding that made this a fix as well as a feature: the endpoint branch
+ of the recorder read `process.name` off the OCSF event, and the canonical
+ OCSF profile carries `title`, `external_id` and the identity aliases and
+ nothing else. `fleetdm`, `osctrl`, `auditd` and `windows_event` all put
+ their process fields in the connector payload under `raw_data`, so that
+ branch found `None` on every endpoint source this product has and could
+ never have produced one row — while its own tests passed, because they
+ built events in the shape the module expected. It now reconstructs the same
+ flat namespace `DetectionEngine._raw_fields` does, and
+ `scripts/check_ai_endpoint_discovery.py` makes reading it a rule.
+
+ Recorded rather than implied: `crowdstrike`, `sentinelone` and
+ `azure_defender` poll the vendor's own **detections**, not raw process
+ telemetry, so they cannot supply a process start. An operator running an
+ EDR and nothing else has a coverage gap here, not a quiet estate, and the
+ documentation says so in a callout.
+
- **An AI-estate inventory built from observation rather than registration**
(depth plan 6.1). `aisoc_ai_assets` (migration `105`, tenant-scoped with
forced row-level security) holds every AI app, coding agent, MCP server,
diff --git a/DEPTH_PROGRESS.md b/DEPTH_PROGRESS.md
index 204dd08c5..1ac499a4e 100644
--- a/DEPTH_PROGRESS.md
+++ b/DEPTH_PROGRESS.md
@@ -438,7 +438,51 @@ invented fields on the first run of the gate.
provider audit log never carries either — so `discovery_source` is stored
per row and the page prints what each source can and cannot see, because
an unlinked device and an unlinkable one are different facts.
-- [ ] **6.2** Endpoint discovery with no new agent
+- [x] **6.2** Endpoint discovery with no new agent. Reproduced:
+ `services/fusion/tests/test_ai_endpoint_discovery.py` was written first and
+ **13 of its 16 cases failed** on the tree as 6.1 left it, driving payloads
+ in the shapes `windows_event`, `auditd`, `fleetdm` and `osctrl` actually
+ emit — read out of each connector's own `normalize()` rather than invented.
+
+ **The root cause is the one this repository keeps paying for, in its second
+ form.** 6.1's endpoint branch read `process.name` off the OCSF event. The
+ canonical OCSF profile maps `title`, `external_id` and the identity aliases
+ and *nothing else*; all four endpoint connectors put their process fields in
+ the connector payload, which `services/ingest` stores as a JSON string under
+ `raw_data`. So the branch resolved `None` on every real source and could
+ never have produced one row — and its own unit tests passed throughout,
+ because they built events in the shape the module expected. The recorder now
+ reconstructs the same flat namespace `DetectionEngine._raw_fields` does, and
+ `PROCESS_FIELDS` / `COMMAND_LINE_FIELDS` name each connector's own spelling.
+
+ Built: `packs/aisoc-ai-estate.yaml` (5 queries — coding-agent processes, MCP
+ server processes, MCP client configuration files, AI IDE extensions,
+ provider key files; loaded through the real `pack_loader`, 5 packs -> 6),
+ `SOURCE_CAPABILITIES` declaring what each of the five discovery sources sees
+ *and* cannot see, `apps/docs/docs/concepts/ai-estate-discovery.md`, and
+ `scripts/check_ai_endpoint_discovery.py` (6 rules, self-test injects one
+ violation each). Fusion suite 683 -> 700.
+
+ Negative controls: an ordinary process (`falcon-sensor`, `osqueryd`,
+ `nginx`, `chrome`, `MsMpEng.exe`, `node`), an unrelated IDE extension
+ (`esbenp.prettier-vscode`) and an unrelated `package.json` each produce no
+ asset, and an endpoint sighting is asserted to carry no model or provider —
+ because filling those from a default would make the inventory assert
+ something no source observed. The gate's own self-test re-injects the
+ original defect (`fields = _connector_fields(ocsf)` -> `fields = dict(ocsf)`)
+ and requires NAMESPACE to catch it; writing it found the same
+ read-your-own-docstring blind spot a second time, now fixed by stripping the
+ docstring before matching.
+
+ **Honest limit, and the reason the claim row is PARTIAL:** `crowdstrike`,
+ `sentinelone` and `azure_defender` poll the vendor's own **detections**, not
+ process telemetry — `crowdstrike.py` reads `/detects/queries/detects/v1` —
+ so they cannot supply a process start, and the plan's wording that endpoint
+ discovery comes from them is not satisfiable with the connectors this tree
+ has. The documentation says so in a callout rather than leaving a reader to
+ assume their EDR covers it. Separately, no osquery agent runs in CI: the
+ pack is asserted to load and to select the columns the recorder reads, but
+ no test has watched a real `osqueryd` execute one of its queries.
- [ ] **6.3** Provider coverage beyond OpenAI and Anthropic
- [ ] **6.4** Agent identity and baselines (parity 6.7)
- [ ] **6.5** AI rule pack
@@ -482,5 +526,7 @@ invented fields on the first run of the gate.
| 2026-10-09 | 3.3 | Identity privilege (18 rules) and a per-tenant first-seen store (2) built; 5 rules were never unreachable (gate operator drift, D9); 18 retired with a reason (D10). `MAX_UNREACHABLE` 45 → 2, the two remaining both needing the 3.4 baseline. Two matcher operators three shipped rules already used were implemented. |
| 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-11 | 6.2 | Reproduced: 13 of 16 new cases failed, driving the shapes the four endpoint connectors actually emit. Root cause was 6.1's endpoint branch reading `process.name` off OCSF, which the canonical profile never populates — it found `None` on every real source while its own tests passed. Fixed by reconstructing the connector namespace. Shipped the osquery pack (5 queries, packs 5 -> 6), the source-capability table, the operator doc and a 6-rule gate. Fusion suite 683 -> 700. Claim row is PARTIAL: no osquery agent runs in CI, and the EDR connectors return vendor detections rather than process telemetry, so the plan's "CrowdStrike, Defender, SentinelOne" wording is not satisfiable with these connectors. |
+| 2026-10-11 | 6.2 | Reproduced: 13 of 16 new cases failed, driving the shapes the four endpoint connectors actually emit. Root cause was 6.1's endpoint branch reading `process.name` off OCSF, which the canonical profile never populates — it found `None` on every real source while its own tests passed. Fixed by reconstructing the connector namespace. Shipped the osquery pack (5 queries, packs 5 -> 6), the source-capability table, the operator doc and a 6-rule gate. Fusion suite 683 -> 700. Claim row is PARTIAL: no osquery agent runs in CI, and the EDR connectors return vendor detections rather than process telemetry, so the plan's "CrowdStrike, Defender, SentinelOne" wording is not satisfiable with these connectors. |
| 2026-10-11 | 6.1 | Reproduced: the new gate reported nine problems across five of eight rules on the unmodified tree. Built `aisoc_ai_assets` (migration 105), its routes behind a new `ai_estate:*` permission pair, the fusion recorder that writes it on the default profile, the `AIAsset` graph label with `OPERATES`/`HOSTS` edges, and the `/ai-estate` page. Two negative controls against a real PostgreSQL: reverting `NULLS NOT DISTINCT` turns one provider-key row into three, and a `USING (true)` policy leaks across tenants. Claim matrix 302 -> 303 rows, 300 GATED. Writing the gate found two blind spots in the gate itself. |
| 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. |
diff --git a/ROADMAP.md b/ROADMAP.md
index 0ed1c578e..aeb5272c3 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -45,7 +45,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
-The claim-to-gate matrix stands at **303 rows — 300 GATED / 3 PARTIAL / 0 NO GATE**. Three rows are PARTIAL. "The retention window a tenant chooses is the one the lake honours" stays PARTIAL until a live ClickHouse test watches a row survive past the old 90-day boundary. "Cloud-native collection" stays PARTIAL until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification. And "SSO completes a sign-in": fix pass 4.1 drove both handlers end to end against real Postgres and real signed assertions, and it stays PARTIAL until the containerised-IdP leg of `sso-live.yml` has been observed to pass, because the identity providers in that suite are trust material this repository authors. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
+The claim-to-gate matrix stands at **304 rows — 300 GATED / 4 PARTIAL / 0 NO GATE**. Four rows are PARTIAL. "The retention window a tenant chooses is the one the lake honours" stays PARTIAL until a live ClickHouse test watches a row survive past the old 90-day boundary. "Cloud-native collection" stays PARTIAL until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification. And "SSO completes a sign-in": fix pass 4.1 drove both handlers end to end against real Postgres and real signed assertions, and it stays PARTIAL until the containerised-IdP leg of `sso-live.yml` has been observed to pass, because the identity providers in that suite are trust material this repository authors. "Endpoint discovery of the AI estate" stays PARTIAL until a containerised osquery runs `packs/aisoc-ai-estate.yaml` end to end: the pack is asserted to load and to select the columns the recorder classifies on, but no test has watched a real `osqueryd` execute one of its queries against a real filesystem. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
## v4.0 — Shipped
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index fb5e360ec..ef13f1440 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -34,7 +34,7 @@ and says so.
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
The last row is the one worth reading first. It is the honest index: 300 rows
-`GATED`, 3 `PARTIAL`, and a ratchet that refuses to let a row sit at
+`GATED`, 4 `PARTIAL`, and a ratchet that refuses to let a row sit at
`NO GATE`. Re-read the figure from the table rather than from here — a count
copied into prose goes stale in silence, which is why
`scripts/readme_gates.py` cross-checks this sentence against the matrix.
diff --git a/apps/docs/docs/concepts/ai-estate-discovery.md b/apps/docs/docs/concepts/ai-estate-discovery.md
new file mode 100644
index 000000000..b814dc8a5
--- /dev/null
+++ b/apps/docs/docs/concepts/ai-estate-discovery.md
@@ -0,0 +1,135 @@
+---
+sidebar_position: 9
+title: Discovering the AI estate
+description: How AiSOC finds AI apps, coding agents, MCP servers, IDE extensions, provider keys and OAuth grants — and exactly what each source cannot see.
+---
+
+# Discovering the AI estate
+
+AiSOC builds its AI inventory from telemetry it already collects. There is no
+new agent to deploy: the three discovery paths are an SDK or gateway you may
+already route AI traffic through, the endpoint agent your fleet already runs,
+and your model provider's own audit log.
+
+The inventory lives at **AI Estate** in the console and in the
+`aisoc_ai_assets` table. It records what AiSOC *observed*, which is
+deliberately different from `/api/v1/mcp-servers`, which records what an
+operator *declared*. The row that matters in an AI governance review is the
+one present in the first and absent from the second.
+
+## What each source can and cannot see
+
+This is the part worth reading before you plan coverage. The three sources
+see genuinely different things, and the gaps are not symmetric — so a column
+on the inventory page being empty can mean "nobody is accountable for this"
+or "this source has never been able to tell us", and only the first is a
+finding.
+
+### AI runtime telemetry
+
+**Connectors:** the `ai_gateway` connector, and the `ai-runtime` /
+`ai-finding` inbox templates that `packages/aisoc-ai-sdk` posts to.
+
+| Sees | Cannot see |
+| --- | --- |
+| The agent's identity and name | The device, unless the app itself reports a hostname |
+| The model and the provider | Anything about an agent that is not instrumented and does not route through a gateway |
+| Which tools were invoked, and against which resources | A process that never called a model |
+| The human the agent acted for, when there is one | |
+| Which secret *shapes* a prompt contained, without the prompt ever leaving the process | |
+
+### Endpoint telemetry
+
+**Connectors:** `fleetdm`, `osctrl`, `auditd`, `windows_event`.
+
+| Sees | Cannot see |
+| --- | --- |
+| The device | Which model was called |
+| The binary and its full command line | Which tools were invoked |
+| Whether an agent was started with its permission prompts disabled | What a prompt contained |
+| MCP client configuration files — evidence a server is *wired in* | An agent running anywhere with no endpoint agent |
+| AI IDE extension directories, with publisher and version | |
+| Model-provider credential files sitting on a laptop | |
+
+:::caution The EDR connectors do not supply this
+`crowdstrike`, `sentinelone` and `azure_defender` poll the **vendor's own
+detections**, not raw process telemetry — `crowdstrike.py` reads
+`/detects/queries/detects/v1`, which returns judgements. They are classed as
+OCSF Security Findings for that reason, and they cannot supply a process
+start.
+
+Endpoint discovery therefore comes from osquery (through FleetDM or osctrl),
+from `auditd` on Linux, and from Windows event forwarding. If you run an EDR
+and nothing else, this half of the inventory will be empty, and that is a
+coverage gap rather than a quiet estate.
+:::
+
+### Provider and directory audit logs
+
+**Connectors:** `llm_usage`, and the Workspace / Entra audit streams.
+
+| Sees | Cannot see |
+| --- | --- |
+| The provider account and organisation | Any device, ever |
+| Who minted or used an API key | Which application used the key |
+| Role, logging and MFA changes | Anything about a key minted outside the audited organisation |
+| Which AI application was granted OAuth access, and the scopes | What the application did with the grant |
+
+## The osquery pack
+
+`packs/aisoc-ai-estate.yaml` is the endpoint half. Assign it to a tenant the
+same way as any other pack, or render it for direct import:
+
+```
+GET /api/v1/osquery/packs/aisoc-ai-estate/render?format=osctrl
+GET /api/v1/osquery/packs/aisoc-ai-estate/render?format=fleetdm
+```
+
+Five queries:
+
+| Query | Interval | What it answers |
+| --- | --- | --- |
+| `coding_agent_processes` | 5 min | Which coding agents are running, and with what command line |
+| `mcp_server_processes` | 5 min | Which local MCP servers are running |
+| `mcp_client_configurations` | 1 hour | Which MCP clients are configured, and where |
+| `ai_ide_extensions` | 1 hour | Which AI assistant extensions are installed, with version |
+| `provider_key_files` | 1 hour | Whether model-provider credential material sits on this laptop |
+
+Three design decisions worth knowing, because each is a trade-off rather than
+an oversight:
+
+**Process names are an explicit list, not a pattern.** A `LIKE '%agent%'`
+would match half an EDR estate, and a false positive here puts somebody's
+antivirus on a security review. The cost is that an agent not on the list is
+invisible to the process queries — though it still appears through the SDK
+path and, if it is an editor extension, through the extension query.
+
+**Configuration file *contents* are never collected.** An MCP configuration
+routinely holds bearer tokens for third-party servers. The file's presence,
+path and mtime are the evidence; an inventory has no business holding the
+credentials.
+
+**Every query is severity `info`.** Discovering that a developer runs a
+coding agent is inventory, not a finding. What makes a row interesting is the
+risk the inventory computes from it — nobody accountable, permission prompts
+disabled, an unvetted install source — and that judgement lives in one place
+rather than being duplicated into a pack.
+
+## How a row is linked to a person and a device
+
+Each source contributes what it has, and a later sighting never erases what
+an earlier one learned:
+
+- **Person** comes from `actor.user.name` on runtime telemetry, the acting
+ user on an endpoint event, or the account on a provider audit record.
+- **Device** comes from the endpoint hostname. Runtime telemetry supplies it
+ only when the instrumented app reports one, and a provider audit log never
+ does.
+- **Permissions** are a snapshot of what the effective-permissions resolver
+ returned for the linked person at the last sighting, rather than a join, so
+ a later permission change does not rewrite history.
+
+When a source did not supply a link, the console renders **"not learned"** in
+the colour of a finding rather than a blank cell, and the tooltip names what
+that source is blind to. An asset nobody is accountable for is the row this
+inventory exists to surface.
diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.ts
index f0e423059..cc6b246ce 100644
--- a/apps/docs/sidebars.ts
+++ b/apps/docs/sidebars.ts
@@ -28,6 +28,7 @@ const sidebars: SidebarsConfig = {
"concepts/python-detections",
"concepts/windowed-detections",
"concepts/ai-estate",
+ "concepts/ai-estate-discovery",
"concepts/groundedness",
"concepts/live-actions",
"concepts/retro-hunts",
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index b4d396b2b..6081b7810 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -15,6 +15,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Connectors: live Test connection | README L168 | `ci.yml` connectors matrix (`test_conformance.py` — every connector implements the async `test_connection` contract) + `connector_conformance.py --check` published matrix + `test_live_vendor_smoke.py` (Phase D3 — mock-server conformance: `test_connection()` + paginated `fetch_alerts()` HTTP path exercised against realistic vendor payloads) | core | GATED | - |
| Cloud telemetry is collected the way a real estate emits it: a CloudTrail organisation trail on S3 notified over SQS (management events, data events and VPC flow logs), a Pub/Sub subscription on a Cloud Logging sink, and an Event Hub's Capture output | `apps/docs/docs/connectors/{aws-cloudtrail-s3,gcp-pubsub,azure-event-hubs}.md`; depth plan 4.1 | `ci.yml :: python-lint` (`check_cloud_native_collection.py --self-test` then the gate: each of the three is registered in `_CONNECTOR_CLASSES`, declares a resumable cursor, declares a bounded `collection_budget` carrying the sentence that says where the overflow goes, and ships vendor-shaped fixtures, a setup guide and a marketplace manifest. The self-test injects one violation per rule into a copy of the real tree and requires each to be caught, and refuses both an absent and an empty tree) + `ci.yml` connectors matrix (`test_aws_cloudtrail_s3.py`, `test_gcp_pubsub.py`, `test_azure_event_hubs.py`, `test_avro_ocf.py` — 83 cases driving recorded vendor payloads through each connector: the SNS and raw S3 notification envelopes, a CloudTrail object carrying management and data events, an S3 flow-log object with its header line, a Pub/Sub pull response with base64 `LogEntry` payloads, and a binary Avro capture file. Acknowledgement ordering is pinned by failure injection rather than described, because an ack before the batch is in hand loses it permanently) | core | PARTIAL (no vendor account of any kind is reachable from CI, so every payload here is recorded or synthesised rather than live. Two consequences are stated rather than implied: the Azure capture fixture was built from the Avro specification rather than taken from a running Event Hub, so a decoder and a fixture that share an author share a misreading; and the Data Lake Gen2 listing path has never been exercised against a real storage account. Returns to GATED when a recorded capture from a live hub replaces the synthesised one) | a live-vendor fixture for Azure Capture |
| The AI estate AiSOC reports is one it observed, not one somebody typed in: AI apps, coding agents, MCP servers, IDE extensions, provider keys and OAuth grants, each with the person and device behind it | depth plan 6.1; `apps/web/src/components/ai-estate/AiEstateView.tsx` | `ci.yml :: python-lint` (`check_ai_asset_inventory.py --self-test` then the gate: eight rules, of which WRITER is the load-bearing one — the fusion consumer must call the recorder on the raw-events branch *and* the service must construct it at startup, because an unconstructed recorder is a `None` every call site skips in silence and the page would render "no AI estate" to a tenant that has one. The self-test injects one violation per rule into a copy of the real tree and requires each to be caught, and refuses an empty tree) + `ai-estate-live.yml` (a fixture estate of a coding agent, an MCP server and a provider key written by the real recorder into a real PostgreSQL with every migration applied, read back as the DML-only `aisoc_app` role so the RLS policy actually applies; two negative controls re-inject real defects — reverting `NULLS NOT DISTINCT` turns one provider-key row into three, and a policy of `USING (true)` lets one tenant read another's estate — and each must fail the suite) + `ci.yml :: python-test` (fusion `test_ai_asset_recorder.py`, 21 cases, including the negative control that an ordinary process is not an AI asset and the mirror tests comparing the fusion and API risk scorers on shared cases) + `ci.yml` ingest Go tests (`internal/graph/ai_estate_test.go`) | core | GATED | — |
+| The AI estate is discovered on the endpoint with no new agent, and every source states what it cannot see | depth plan 6.2; `apps/docs/docs/concepts/ai-estate-discovery.md`; `packs/aisoc-ai-estate.yaml` | `ci.yml :: python-lint` (`check_ai_endpoint_discovery.py --self-test` then the gate: six rules, of which NAMESPACE is load-bearing — the four endpoint connectors put their process fields in the connector payload under `raw_data` and the canonical OCSF profile maps none of them, so a classifier reading `process.name` finds `None` on every real source while its own tests pass against events built in the shape it expects. CAPABILITIES requires every discovery source to declare a non-empty `cannot_see`, checked in both directions against `DISCOVERY_SOURCES`) + `ci.yml :: python-test` (fusion `test_ai_endpoint_discovery.py`, 16 cases driving the shapes `windows_event`, `auditd`, `fleetdm` and `osctrl` actually emit, read out of each connector's own `normalize()`; negative controls assert that an ordinary process, an unrelated IDE extension and an unrelated JSON file produce nothing, and that an endpoint asset never claims a model) | core | PARTIAL (no osquery agent runs in CI, so the pack is asserted to load through the real `pack_loader` and its queries are asserted to select the columns the recorder classifies on — but no test has ever watched a real osqueryd execute one of them against a real filesystem. The paths were taken from each MCP client's published configuration documentation rather than from a running install. Returns to GATED when a containerised osquery runs the pack and the rows reach the recorder) | an osquery container in CI running the pack end to end |
| Investigation Ledger stores every step | README L61, L169 | `ci.yml :: Python — Lint & Type-check` (`check_ledger_replay_contract.py` — response model ↔ console type, client requests ↔ router decorators, and `seq` ordering/uniqueness, each in both directions) + `ci.yml :: Python — Tests` (`test_investigation_replay.py`, 37 cases over `/replay`, `/events`, `/explain`; removing `ORDER BY seq` fails five of them) | core | GATED | — |
| Public eval harness gates every PR | README L62, L77 | `ci.yml :: p1-eval` | core | GATED (but suites are self-consistency; see reality report) | Phase 4 |
| Alert-reduction is a real measurement | README / benchmark page | `ci.yml :: python-test` (fusion) runs `test_alert_reduction_real.py`, which groups a 1 000-alert stream with `RawAlert.correlation_key()` — the method `Correlator` actually calls — and bounds the ratio on both sides, because a floor alone is satisfied by a key that collapses everything into one incident | core | GATED | the legacy suite's 75.3% stays published for continuity and is labelled as not describing this product; the measurement is still a synthetic workload, as the benchmark page states |
@@ -314,9 +315,9 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- Total: 303
+- Total: 304
- GATED: 300
-- PARTIAL: 3
+- PARTIAL: 4
- NO GATE: 0
Counts come from `scripts/check_claim_gate_matrix.py`, which is also the gate. Recompute
diff --git a/packs/README.md b/packs/README.md
index 133128c1e..f6a84c389 100644
--- a/packs/README.md
+++ b/packs/README.md
@@ -57,6 +57,7 @@ Use `GET /api/v1/osquery/packs/{pack_id}/render?format=osctrl|fleetdm|osquery-js
| `aisoc-attck-persistence` | Cron, systemd, launchd, Run key persistence | linux, darwin | T1547, T1543 |
| `aisoc-attck-defense-evasion` | Disabled services, cleared logs | linux, darwin | T1562, T1070 |
| `aisoc-inventory-baseline` | OS/kernel/package inventory (info) | linux, darwin, windows | — |
+| `aisoc-ai-estate` | Coding agents, MCP servers and their client configs, AI IDE extensions, provider key files | linux, darwin, windows | T1059, T1176, T1552.001 |
## Contributing
diff --git a/packs/aisoc-ai-estate.yaml b/packs/aisoc-ai-estate.yaml
new file mode 100644
index 000000000..166eb9ade
--- /dev/null
+++ b/packs/aisoc-ai-estate.yaml
@@ -0,0 +1,171 @@
+id: aisoc-ai-estate
+name: AiSOC AI Estate Discovery
+version: 1.0.0
+platforms: [linux, darwin, windows]
+description: |
+ Finds the AI estate on an endpoint using the osquery agent a fleet already
+ runs — depth plan 6.2, "endpoint discovery with no new agent".
+
+ Three things this pack looks for, because they are three different kinds of
+ evidence and a governance review needs all three:
+
+ * **Running coding agents and MCP server processes.** A process listing
+ answers "what is executing right now", and carries the command line,
+ which is the only place a disabled-permission-prompt flag ever appears.
+ * **MCP client configuration files.** A configuration says a server is
+ *wired in*, which survives a reboot and survives a process listing that
+ happened to miss the window. Every path below is taken from the client's
+ own published configuration documentation.
+ * **AI IDE extension directories.** An extension is installed software with
+ repository access and, in several cases, shell access.
+
+ Results land in `aisoc_ai_assets` through the fleetdm / osctrl connectors
+ and the fusion recorder, which classifies each row by the columns selected
+ here — `name`, `path`, `cmdline`, `directory`. **Changing a selected column
+ name breaks the classification silently**, so the queries below select the
+ columns the recorder reads rather than the minimum osquery needs.
+
+ Severity is `info` throughout, deliberately. Discovering that a developer
+ runs a coding agent is inventory, not a finding; what makes a row
+ interesting is the risk the inventory computes from it (nobody accountable,
+ permission prompts disabled, an unvetted source), and that judgement
+ belongs in one place rather than duplicated into a pack.
+
+queries:
+ coding_agent_processes:
+ sql: >
+ SELECT p.name AS name, p.path AS path, p.cmdline AS cmdline,
+ p.uid AS uid, p.start_time AS start_time, u.username AS username
+ FROM processes p
+ LEFT JOIN users u ON p.uid = u.uid
+ WHERE p.name IN (
+ 'claude', 'codex', 'aider', 'goose', 'continue', 'opencode',
+ 'gemini', 'copilot', 'copilot-language-server', 'amazonq', 'cline',
+ 'claude.exe', 'codex.exe', 'aider.exe', 'gemini.exe', 'cline.exe'
+ )
+ interval: 300
+ severity: info
+ description: >
+ Coding agents running on this host, with the command line. An explicit
+ name list rather than a LIKE on '%agent%', which matches half an EDR
+ estate and would put somebody's antivirus on an AI inventory.
+ mitre: [T1059]
+ references:
+ - https://attack.mitre.org/techniques/T1059/
+
+ mcp_server_processes:
+ sql: >
+ SELECT p.name AS name, p.path AS path, p.cmdline AS cmdline,
+ p.uid AS uid, p.start_time AS start_time, u.username AS username
+ FROM processes p
+ LEFT JOIN users u ON p.uid = u.uid
+ WHERE p.name LIKE 'mcp-server%%'
+ OR p.name LIKE 'mcp_server%%'
+ OR p.name LIKE 'mcp-proxy%%'
+ interval: 300
+ severity: info
+ description: >
+ Local MCP servers. A prefix rather than a substring: '%mcp%' matches
+ mcpelauncher, and a false positive here puts a game launcher on a
+ security review.
+ mitre: [T1059]
+ references:
+ - https://modelcontextprotocol.io/
+
+ mcp_client_configurations:
+ sql: >
+ SELECT path, directory, filename, uid, mtime, size
+ FROM file
+ WHERE path LIKE '/Users/%%/Library/Application Support/Claude/claude_desktop_config.json'
+ OR path LIKE '/Users/%%/.claude.json'
+ OR path LIKE '/home/%%/.claude.json'
+ OR path LIKE '/Users/%%/.cursor/mcp.json'
+ OR path LIKE '/home/%%/.cursor/mcp.json'
+ OR path LIKE '/Users/%%/.codeium/windsurf/mcp_config.json'
+ OR path LIKE '/home/%%/.codeium/windsurf/mcp_config.json'
+ OR path LIKE '/Users/%%/Library/Application Support/Code/User/mcp.json'
+ OR path LIKE '/home/%%/.config/Code/User/mcp.json'
+ OR path LIKE '/Users/%%/.continue/config.json'
+ OR path LIKE '/home/%%/.continue/config.json'
+ OR path LIKE '/Users/%%/.aws/amazonq/mcp.json'
+ OR path LIKE '/home/%%/.aws/amazonq/mcp.json'
+ OR path LIKE '/Users/%%/.gemini/settings.json'
+ OR path LIKE '/home/%%/.gemini/settings.json'
+ OR path LIKE '/Users/%%/.codex/config.toml'
+ OR path LIKE '/home/%%/.codex/config.toml'
+ interval: 3600
+ severity: info
+ description: >
+ Configuration files the popular MCP clients read. Each path comes from
+ that client's own published documentation. The file's presence is the
+ evidence; its contents are deliberately not collected, because an MCP
+ configuration routinely carries bearer tokens for third-party servers
+ and an inventory has no business holding them.
+ mitre: [T1543]
+ references:
+ - https://modelcontextprotocol.io/docs/develop/connect-local-servers
+
+ ai_ide_extensions:
+ sql: >
+ SELECT path, directory, filename, uid, mtime
+ FROM file
+ WHERE (
+ path LIKE '/Users/%%/.vscode/extensions/%%/package.json'
+ OR path LIKE '/home/%%/.vscode/extensions/%%/package.json'
+ OR path LIKE '/Users/%%/.vscode-insiders/extensions/%%/package.json'
+ OR path LIKE '/Users/%%/.cursor/extensions/%%/package.json'
+ OR path LIKE '/home/%%/.cursor/extensions/%%/package.json'
+ OR path LIKE '/Users/%%/.windsurf/extensions/%%/package.json'
+ )
+ AND (
+ directory LIKE '%%github.copilot%%'
+ OR directory LIKE '%%continue.continue%%'
+ OR directory LIKE '%%codeium.codeium%%'
+ OR directory LIKE '%%amazonwebservices.amazon-q-vscode%%'
+ OR directory LIKE '%%tabnine.tabnine-vscode%%'
+ OR directory LIKE '%%sourcegraph.cody-ai%%'
+ OR directory LIKE '%%google.geminicodeassist%%'
+ OR directory LIKE '%%anthropic.claude-code%%'
+ )
+ interval: 3600
+ severity: info
+ description: >
+ AI assistant extensions installed in an editor. Filtered to a named set
+ rather than listing every extension: an editor has hundreds and a
+ handful are AI, and listing all of them would turn the AI inventory
+ into a package manifest.
+ mitre: [T1176]
+ references:
+ - https://attack.mitre.org/techniques/T1176/
+
+ provider_key_files:
+ sql: >
+ SELECT path, directory, filename, uid, mtime, size
+ FROM file
+ WHERE path LIKE '/Users/%%/.config/anthropic/%%'
+ OR path LIKE '/home/%%/.config/anthropic/%%'
+ OR path LIKE '/Users/%%/.openai/%%'
+ OR path LIKE '/home/%%/.openai/%%'
+ OR path LIKE '/Users/%%/.config/gcloud/application_default_credentials.json'
+ interval: 3600
+ severity: info
+ description: >
+ Model-provider credential material sitting on a laptop. The file's
+ presence and its mtime only; contents are never collected. A key on an
+ endpoint is the row that links a provider key to a device, which no
+ provider audit log can ever supply.
+ mitre: [T1552.001]
+ references:
+ - https://attack.mitre.org/techniques/T1552/001/
+
+file_paths:
+ mcp_client_config:
+ - /Users/%/Library/Application Support/Claude/claude_desktop_config.json
+ - /Users/%/.cursor/mcp.json
+ - /home/%/.cursor/mcp.json
+ - /Users/%/.codeium/windsurf/mcp_config.json
+ - /home/%/.continue/config.json
+ ai_ide_extensions:
+ - /Users/%/.vscode/extensions/%%
+ - /home/%/.vscode/extensions/%%
+ - /Users/%/.cursor/extensions/%%
diff --git a/scripts/check_ai_endpoint_discovery.py b/scripts/check_ai_endpoint_discovery.py
new file mode 100644
index 000000000..62fe43698
--- /dev/null
+++ b/scripts/check_ai_endpoint_discovery.py
@@ -0,0 +1,433 @@
+#!/usr/bin/env python3
+"""Endpoint discovery of the AI estate, with no new agent.
+
+Depth plan 6.2.
+
+The defect this gate exists to prevent
+--------------------------------------
+The endpoint branch of the AI-asset recorder read `process.name` off the OCSF
+event. The canonical OCSF profile carries `title`, `external_id` and the
+identity aliases and **nothing else**, so that field is `None` for every
+endpoint source this product has — `fleetdm`, `osctrl`, `auditd` and
+`windows_event` all put their process fields in the connector payload under
+`raw_data`. The module imported, the unit tests passed against events built
+in the shape the module expected, and endpoint discovery could never have
+produced one row on a real deployment.
+
+So the first rule is not "is there a classifier" but **"does it read the
+namespace the connectors actually produce"**, and the second is that each of
+those four connectors' own field names is recognised. Both are checked by
+parsing the recorder rather than by calling it, so the gate runs on a bare
+interpreter before any service venv exists.
+
+Why the capability table is a rule
+----------------------------------
+The plan asks, in words, to *record what each source can and cannot see*. A
+table listing only what a source provides reads as complete coverage. The
+blind spots are the half an analyst needs when a column on the inventory page
+is empty, because "no device" and "this source has never carried a device"
+are different facts and only one of them is a finding. The rule therefore
+requires **both** halves for every source, and checks the set in both
+directions: every source the recorder can emit must be in the table, and
+every source in the table must be one the recorder can emit.
+
+Usage:
+ python3 scripts/check_ai_endpoint_discovery.py
+ python3 scripts/check_ai_endpoint_discovery.py --self-test
+"""
+
+from __future__ import annotations
+
+import argparse
+import ast
+import re
+import shutil
+import sys
+import tempfile
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+
+RECORDER_PATH = Path("services/fusion/app/services/ai_asset_recorder.py")
+PACK_PATH = Path("packs/aisoc-ai-estate.yaml")
+PACK_README = Path("packs/README.md")
+DOC_PATH = Path("apps/docs/docs/concepts/ai-estate-discovery.md")
+
+READ_PATHS = (RECORDER_PATH, PACK_PATH, PACK_README, DOC_PATH)
+
+#: Field names the four endpoint connectors put a process in. Read out of
+#: each connector's own `normalize()`, not assumed:
+#:
+#: windows_event -> `process_name` at the top level, `Image` lifted out of
+#: `EventData` into `raw_event`
+#: auditd -> `exe`
+#: fleetdm -> the osquery row's columns, flattened; `name` and `path`
+#: for the `processes` table
+REQUIRED_PROCESS_FIELDS = ("process_name", "Image", "exe", "name", "path")
+
+#: Command-line field names, same sources. The command line is where a
+#: disabled-permission-prompt flag appears and nowhere else.
+REQUIRED_COMMAND_FIELDS = ("CommandLine", "cmdline", "argv")
+
+#: The MCP clients depth 6.2 names as "popular". Each must be recognised by
+#: the configuration file it reads.
+REQUIRED_MCP_CLIENTS = ("Claude Desktop", "Cursor", "Windsurf", "VS Code", "Continue", "Amazon Q")
+
+#: Queries the osquery pack must carry. Named individually because a pack
+#: with four of the five is silently partial.
+REQUIRED_PACK_QUERIES = (
+ "coding_agent_processes",
+ "mcp_server_processes",
+ "mcp_client_configurations",
+ "ai_ide_extensions",
+)
+
+#: Columns the recorder classifies on. A pack that stops selecting one of
+#: these keeps running and stops producing assets, with nothing to say so.
+REQUIRED_PACK_COLUMNS = ("name", "path", "cmdline", "directory")
+
+
+def _read(root: Path, rel: Path) -> str:
+ path = root / rel
+ return path.read_text(encoding="utf-8") if path.is_file() else ""
+
+
+def _module(source: str) -> ast.Module | None:
+ try:
+ return ast.parse(source)
+ except SyntaxError:
+ return None
+
+
+def _assigned_collection(tree: ast.Module, name: str) -> list[str]:
+ """String literals in a module-level assignment to `name`."""
+ for node in tree.body:
+ if not isinstance(node, ast.Assign | ast.AnnAssign):
+ continue
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
+ if not any(isinstance(t, ast.Name) and t.id == name for t in targets):
+ continue
+ if node.value is None:
+ return []
+ return [n.value for n in ast.walk(node.value) if isinstance(n, ast.Constant) and isinstance(n.value, str)]
+ return []
+
+
+def _function_body(tree: ast.Module, name: str) -> str:
+ """The function's code, with its docstring removed.
+
+ Dropping the docstring is not tidiness. `check_gate_coverage.py` counted a
+ gate named only in a docstring as invoked and reported "all reachable"
+ while the gate ran in no workflow at all; a rule here that matched a
+ function's own prose would pass on a body that had stopped calling the
+ thing the prose describes — which is precisely the injection the
+ self-test performs.
+ """
+ for node in ast.walk(tree):
+ if isinstance(node, ast.AsyncFunctionDef | ast.FunctionDef) and node.name == name:
+ body = list(node.body)
+ if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant) and isinstance(body[0].value.value, str):
+ body = body[1:]
+ return "\n".join(ast.unparse(stmt) for stmt in body)
+ return ""
+
+
+# ---------------------------------------------------------------------------
+# Rules
+# ---------------------------------------------------------------------------
+
+
+def _check_namespace(root: Path) -> list[str]:
+ """The endpoint branch reads the connector payload, not only OCSF."""
+ source = _read(root, RECORDER_PATH)
+ if not source:
+ return [f"NAMESPACE: {RECORDER_PATH} is absent."]
+ tree = _module(source)
+ if tree is None:
+ return [f"NAMESPACE: {RECORDER_PATH} does not parse."]
+
+ failures: list[str] = []
+ reconstructor = _function_body(tree, "_connector_fields")
+ if not reconstructor:
+ return [
+ f"NAMESPACE: {RECORDER_PATH} has no _connector_fields. Every endpoint field this item "
+ f"needs lives in the connector payload under raw_data, and the canonical OCSF profile maps "
+ f"none of them, so a reader without this finds None on every real source."
+ ]
+ for needle, why in (
+ ("raw_data", "the connector payload is stored there as a JSON string by services/ingest"),
+ ("raw_event", "connectors nest the untouched vendor payload one level deeper"),
+ ):
+ if needle not in reconstructor:
+ failures.append(f"NAMESPACE: _connector_fields never reads {needle!r} — {why}.")
+
+ endpoint = _function_body(tree, "_from_endpoint")
+ if not endpoint:
+ failures.append(f"NAMESPACE: {RECORDER_PATH} has no _from_endpoint, so nothing classifies endpoint telemetry.")
+ elif "_connector_fields" not in endpoint:
+ failures.append(
+ "NAMESPACE: _from_endpoint does not call _connector_fields, so it is reading OCSF slots the "
+ "endpoint connectors never populate. This is the exact defect the item reproduced."
+ )
+ return failures
+
+
+def _check_fields(root: Path) -> list[str]:
+ """Each endpoint connector's own field names are recognised."""
+ source = _read(root, RECORDER_PATH)
+ tree = _module(source) if source else None
+ if tree is None:
+ return []
+ failures: list[str] = []
+ process_fields = set(_assigned_collection(tree, "PROCESS_FIELDS"))
+ for field in REQUIRED_PROCESS_FIELDS:
+ if field not in process_fields:
+ failures.append(
+ f"FIELDS: PROCESS_FIELDS does not include {field!r}. One of the four endpoint "
+ f"connectors puts its executable there and will contribute nothing."
+ )
+ command_fields = set(_assigned_collection(tree, "COMMAND_LINE_FIELDS"))
+ for field in REQUIRED_COMMAND_FIELDS:
+ if field not in command_fields:
+ failures.append(
+ f"FIELDS: COMMAND_LINE_FIELDS does not include {field!r}. The command line is the only "
+ f"place a disabled-permission-prompt flag appears."
+ )
+ return failures
+
+
+def _check_clients(root: Path) -> list[str]:
+ """Every MCP client the plan names is recognised by its config file."""
+ source = _read(root, RECORDER_PATH)
+ tree = _module(source) if source else None
+ if tree is None:
+ return []
+ declared = set(_assigned_collection(tree, "MCP_CLIENT_CONFIGS"))
+ missing = [client for client in REQUIRED_MCP_CLIENTS if client not in declared]
+ if missing:
+ return [
+ f"CLIENTS: MCP_CLIENT_CONFIGS does not recognise {', '.join(missing)}. A configuration file is "
+ f"the evidence that a server is wired in, which survives a reboot and a process listing that "
+ f"missed the window."
+ ]
+ if not _assigned_collection(tree, "AI_IDE_EXTENSIONS"):
+ return ["CLIENTS: AI_IDE_EXTENSIONS is empty, so no IDE extension can ever be inventoried."]
+ return []
+
+
+def _check_capabilities(root: Path) -> list[str]:
+ """Every source declares what it sees AND what it cannot, both ways."""
+ source = _read(root, RECORDER_PATH)
+ tree = _module(source) if source else None
+ if tree is None:
+ return []
+ failures: list[str] = []
+
+ sources = set(_assigned_collection(tree, "DISCOVERY_SOURCES"))
+ if not sources:
+ return ["CAPABILITIES: DISCOVERY_SOURCES is absent, so there is nothing to describe."]
+
+ table: dict[str, str] = {}
+ for node in tree.body:
+ targets = node.targets if isinstance(node, ast.Assign) else ([node.target] if isinstance(node, ast.AnnAssign) else [])
+ if not any(isinstance(t, ast.Name) and t.id == "SOURCE_CAPABILITIES" for t in targets):
+ continue
+ value = node.value
+ if isinstance(value, ast.Dict):
+ for key, entry in zip(value.keys, value.values, strict=False):
+ if isinstance(key, ast.Constant) and isinstance(key.value, str):
+ table[key.value] = ast.unparse(entry)
+ if not table:
+ return ["CAPABILITIES: SOURCE_CAPABILITIES is absent. The plan asks, in words, to record what each source can and cannot see."]
+
+ for missing in sorted(sources - set(table)):
+ failures.append(f"CAPABILITIES: discovery source {missing!r} has no entry, so a reader cannot tell what it is blind to.")
+ for extra in sorted(set(table) - sources):
+ failures.append(f"CAPABILITIES: {extra!r} is described and is not a discovery source any row can carry.")
+
+ for name, entry in sorted(table.items()):
+ # The half that matters, and the half that is easy to omit.
+ if "cannot_see" not in entry:
+ failures.append(f"CAPABILITIES: {name!r} declares no cannot_see. No real source sees everything.")
+ elif re.search(r"cannot_see\s*=\s*\(\s*\)", entry):
+ failures.append(f"CAPABILITIES: {name!r} declares an empty cannot_see, which claims it is blind to nothing.")
+ if "connectors" not in entry:
+ failures.append(f"CAPABILITIES: {name!r} names no connector, so nothing says where its rows come from.")
+ return failures
+
+
+def _check_pack(root: Path) -> list[str]:
+ """The osquery pack exists, is indexed, and selects what the recorder reads."""
+ pack = _read(root, PACK_PATH)
+ if not pack:
+ return [
+ f"PACK: {PACK_PATH} is absent. The plan requires an osquery pack for MCP client "
+ f"configuration files and IDE extension directories, so a fleet already running osquery "
+ f"gets this with no new agent."
+ ]
+ failures: list[str] = []
+ for query in REQUIRED_PACK_QUERIES:
+ if f"{query}:" not in pack:
+ failures.append(f"PACK: {PACK_PATH} has no {query!r} query, so that evidence is never collected.")
+ for column in REQUIRED_PACK_COLUMNS:
+ if column not in pack:
+ failures.append(
+ f"PACK: {PACK_PATH} never selects {column!r}. The recorder classifies on it, so a pack "
+ f"that stops selecting it keeps running and stops producing assets with nothing to say so."
+ )
+ # A pack nobody can find is a pack nobody assigns.
+ if "aisoc-ai-estate" not in _read(root, PACK_README):
+ failures.append(f"PACK: {PACK_README} does not list the pack in its curated table, so nobody discovers it.")
+ return failures
+
+
+def _check_doc(root: Path) -> list[str]:
+ doc = _read(root, DOC_PATH)
+ if not doc:
+ return [f"DOC: {DOC_PATH} is absent. What each source can and cannot see has to be readable by an operator, not only by a test."]
+ failures: list[str] = []
+ if "cannot see" not in doc.lower():
+ failures.append(f"DOC: {DOC_PATH} never says what a source cannot see, which is the half that makes an empty column readable.")
+ for connector in ("fleetdm", "osctrl", "auditd", "windows_event"):
+ if connector not in doc:
+ failures.append(f"DOC: {DOC_PATH} does not mention {connector}, one of the four sources endpoint discovery reads.")
+ # The honest limit. CrowdStrike, SentinelOne and Defender poll the
+ # vendor's own *detections*, not raw process telemetry, so they cannot
+ # supply a process start — and a reader who assumes otherwise concludes
+ # their EDR is covering this when it is not.
+ if "detections" not in doc.lower():
+ failures.append(
+ f"DOC: {DOC_PATH} does not record that the EDR connectors return vendor detections rather than "
+ f"process telemetry. A reader would assume their EDR covers this."
+ )
+ return failures
+
+
+RULES = (
+ ("NAMESPACE", _check_namespace),
+ ("FIELDS", _check_fields),
+ ("CLIENTS", _check_clients),
+ ("CAPABILITIES", _check_capabilities),
+ ("PACK", _check_pack),
+ ("DOC", _check_doc),
+)
+
+
+def evaluate(root: Path) -> list[str]:
+ failures: list[str] = []
+ for _, rule in RULES:
+ failures.extend(rule(root))
+ return failures
+
+
+# ---------------------------------------------------------------------------
+# Self-test
+# ---------------------------------------------------------------------------
+
+INJECTIONS: tuple[tuple[str, Path, str, str], ...] = (
+ # The original defect: read OCSF instead of the connector namespace.
+ ("NAMESPACE", RECORDER_PATH, "fields = _connector_fields(ocsf)", "fields = dict(ocsf)"),
+ ("FIELDS", RECORDER_PATH, '"process_name", "Image", "exe"', '"process_name", "Image"'),
+ ("CLIENTS", RECORDER_PATH, '"Windsurf"', '"Windsurf_TYPO"'),
+ ("CAPABILITIES", RECORDER_PATH, '"endpoint": SourceCapability(', '"endpoint_TYPO": SourceCapability('),
+ ("PACK", PACK_PATH, "mcp_client_configurations:", "mcp_client_configurations_disabled:"),
+ # Renamed, not suffixed: `windows_event_TYPO` still contains
+ # `windows_event`, so a suffix injection would be caught by a gate doing
+ # nothing at all.
+ ("DOC", DOC_PATH, "windows_event", "wef-forwarding"),
+)
+
+
+def _materialise(dest: Path) -> None:
+ for rel in READ_PATHS:
+ src = REPO_ROOT / rel
+ if not src.is_file():
+ continue
+ (dest / rel).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(src, dest / rel)
+
+
+def _apply(root: Path, target: Path, old: str, new: str) -> bool:
+ path = root / target
+ if not path.is_file():
+ return False
+ text = path.read_text(encoding="utf-8")
+ if old not in text:
+ return False
+ path.write_text(text.replace(old, new), encoding="utf-8")
+ return True
+
+
+def _self_test() -> int:
+ print(f"{Path(__file__).name} --self-test\n")
+ results: list[tuple[str, bool]] = []
+
+ clean = Path(tempfile.mkdtemp(prefix="ai-endpoint-clean-"))
+ try:
+ _materialise(clean)
+ baseline = evaluate(clean)
+ results.append(("the unmodified tree passes", not baseline))
+ for line in baseline:
+ print(f" baseline: {line}")
+ finally:
+ shutil.rmtree(clean, ignore_errors=True)
+
+ for rule_name, target, old, new in INJECTIONS:
+ tmp = Path(tempfile.mkdtemp(prefix="ai-endpoint-"))
+ try:
+ _materialise(tmp)
+ if not _apply(tmp, target, old, new):
+ results.append((f"{rule_name}: injection applies", False))
+ continue
+ caught = any(line.startswith(f"{rule_name}:") for line in evaluate(tmp))
+ results.append((f"{rule_name}: catches {old!r} -> {new!r}", caught))
+ finally:
+ shutil.rmtree(tmp, ignore_errors=True)
+
+ empty = Path(tempfile.mkdtemp(prefix="ai-endpoint-empty-"))
+ try:
+ results.append(("refuses an empty tree rather than reporting it clean", bool(evaluate(empty))))
+ finally:
+ shutil.rmtree(empty, ignore_errors=True)
+
+ ok = True
+ for description, passed in results:
+ ok &= passed
+ print(f" {'PASS' if passed else 'FAIL'} {description}")
+ print()
+ if not ok:
+ print(f"{Path(__file__).name}: self-test FAILED")
+ return 1
+ print(f"{Path(__file__).name}: self-test OK")
+ return 0
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--self-test", action="store_true", help="inject one violation per rule and require each to be caught")
+ args = parser.parse_args()
+ if args.self_test:
+ return _self_test()
+
+ if not (REPO_ROOT / "services" / "fusion").is_dir():
+ print("check_ai_endpoint_discovery: no fusion service — nothing to render a verdict about.", file=sys.stderr)
+ return 2
+
+ failures = evaluate(REPO_ROOT)
+ if failures:
+ print("Endpoint discovery of the AI estate (depth plan 6.2) is incomplete:\n", file=sys.stderr)
+ for line in failures:
+ print(f" - {line}", file=sys.stderr)
+ print(f"\n{len(failures)} problem(s) across {len(RULES)} rule(s).", file=sys.stderr)
+ return 1
+
+ print(
+ f"OK — endpoint discovery reads the connector namespace, recognises "
+ f"{len(REQUIRED_MCP_CLIENTS)} MCP clients, ships an osquery pack with "
+ f"{len(REQUIRED_PACK_QUERIES)} queries, and records what each source cannot see."
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/services/fusion/app/services/ai_asset_recorder.py b/services/fusion/app/services/ai_asset_recorder.py
index 29247d9c2..b79f265f0 100644
--- a/services/fusion/app/services/ai_asset_recorder.py
+++ b/services/fusion/app/services/ai_asset_recorder.py
@@ -45,6 +45,7 @@ rather than mysterious.
from __future__ import annotations
import json
+import re
import time
from collections.abc import Callable
from dataclasses import dataclass, field
@@ -78,14 +79,105 @@ CODING_AGENT_PROCESSES: dict[str, str] = {
"cline": "Cline",
}
-#: Process names that mean an MCP server is running locally.
+#: Process names that mean an MCP server is running locally. Matched as a
+#: prefix on the executable's base name, never as a substring anywhere: `uvx`
+#: as a substring matches nothing useful and `mcp` as one matches `mcpelauncher`.
MCP_SERVER_PROCESSES: tuple[str, ...] = (
"mcp-server",
"mcp_server",
"mcp-proxy",
- "uvx",
)
+#: Configuration files the popular MCP clients read, and the client each
+#: belongs to. Depth plan 6.2 names these explicitly, and they are a
+#: different kind of evidence from a running process: a config file says a
+#: server is *wired in*, which survives a reboot and survives a `ps` that
+#: happened to miss the window.
+#:
+#: Matched on a path suffix rather than an absolute path, because every one
+#: of them sits under a per-user home directory whose shape differs across
+#: macOS, Linux and Windows. Each entry was taken from the client's own
+#: published configuration documentation.
+MCP_CLIENT_CONFIGS: tuple[tuple[str, str], ...] = (
+ ("/claude/claude_desktop_config.json", "Claude Desktop"),
+ ("/.claude.json", "Claude Code"),
+ ("/.cursor/mcp.json", "Cursor"),
+ ("/.codeium/windsurf/mcp_config.json", "Windsurf"),
+ ("/code/user/mcp.json", "VS Code"),
+ ("/.vscode/mcp.json", "VS Code"),
+ ("/.continue/config.json", "Continue"),
+ ("/.aws/amazonq/mcp.json", "Amazon Q"),
+ ("/.gemini/settings.json", "Gemini CLI"),
+ ("/.codex/config.toml", "Codex CLI"),
+ ("/.config/zed/settings.json", "Zed"),
+)
+
+#: Directories an editor keeps its extensions in. The path under one of these
+#: carries `<publisher>.<name>-<version>`, which is where the extension's
+#: identity comes from.
+IDE_EXTENSION_DIRS: tuple[str, ...] = (
+ "/.vscode/extensions/",
+ "/.vscode-insiders/extensions/",
+ "/.vscode-server/extensions/",
+ "/.cursor/extensions/",
+ "/.windsurf/extensions/",
+)
+
+#: Extension publishers and names that are AI assistants. Deliberately a
+#: named list: an editor has hundreds of extensions and six of them are AI,
+#: so listing all of them would turn the AI inventory into a package manifest
+#: and make the column that matters unreadable.
+AI_IDE_EXTENSIONS: dict[str, str] = {
+ "github.copilot": "GitHub",
+ "github.copilot-chat": "GitHub",
+ "continue.continue": "Continue",
+ "codeium.codeium": "Codeium",
+ "amazonwebservices.amazon-q-vscode": "Amazon",
+ "tabnine.tabnine-vscode": "Tabnine",
+ "sourcegraph.cody-ai": "Sourcegraph",
+ "google.geminicodeassist": "Google",
+ "anthropic.claude-code": "Anthropic",
+}
+
+#: Command-line flags that disable an agent's permission prompts. The single
+#: highest-signal attribute an endpoint source can supply, and the only place
+#: it appears: an agent started this way takes no human confirmation before
+#: acting.
+NO_PROMPT_FLAGS: tuple[str, ...] = (
+ "--dangerously-skip-permissions",
+ "--yolo",
+ "--auto-approve",
+ "--no-confirm",
+ "--yes-always",
+ "--full-auto",
+)
+
+#: Connector fields that carry an executable's name or path, in the order
+#: they are consulted. Read from each connector's own `normalize()` rather
+#: than assumed: `windows_event` sets `process_name` and lifts `Image` out of
+#: `EventData`; `auditd` emits `exe`; an osquery row's columns arrive under
+#: whatever the query selected, which for `processes` is `name` and `path`.
+#:
+#: This list is the item. The OCSF canonical field map carries `title`,
+#: `external_id` and the identity aliases and nothing else, so a reader
+#: looking for `process.name` on the OCSF event finds `None` for every
+#: endpoint source this product has.
+PROCESS_FIELDS: tuple[str, ...] = ("process_name", "Image", "exe", "name", "path", "process")
+
+#: Connector fields carrying a command line, same reasoning.
+COMMAND_LINE_FIELDS: tuple[str, ...] = ("CommandLine", "cmdline", "cmd_line", "command_line", "argv")
+
+#: Connector fields carrying a file path, for the config-file and extension
+#: evidence. `path` doubles as a process path, which is why the file rules
+#: run only when the process rules have already declined.
+FILE_PATH_FIELDS: tuple[str, ...] = ("path", "file_path", "target_path", "filename")
+
+#: Connector fields carrying the device, in order.
+DEVICE_FIELDS: tuple[str, ...] = ("hostname", "host_hostname", "computer", "Computer", "device_name", "host")
+
+#: Connector fields carrying the acting user, in order.
+PRINCIPAL_FIELDS: tuple[str, ...] = ("username", "user", "actor", "TargetUserName", "SubjectUserName", "user_name")
+
#: The six kinds. Mirrors `app.models.ai_asset.AI_ASSET_KINDS` in the API
#: service; the two cannot import each other because both package their code
#: as a top-level ``app``, which is the same reason the capability vocabulary
@@ -106,6 +198,75 @@ ALL_KINDS = (
KIND_OAUTH_GRANT,
)
+#: Every discovery source a row may carry. Mirrors the CHECK constraint in
+#: `105_ai_assets.sql` and `AI_ASSET_SOURCES` in the API model.
+DISCOVERY_SOURCES: tuple[str, ...] = ("ai_runtime", "endpoint", "provider_audit", "oauth_audit", "declared")
+
+
+@dataclass(frozen=True)
+class SourceCapability:
+ """What one discovery source can and cannot see.
+
+ Depth plan 6.2 asks for this in words — *record what each source can and
+ cannot see* — and the second half is the half that matters. A table
+ listing only what a source provides reads as complete coverage; the blind
+ spots are what an analyst needs when a column on the inventory page is
+ empty, because "no device" and "this source has never carried a device"
+ are different facts and only one of them is a finding.
+ """
+
+ sees: tuple[str, ...]
+ cannot_see: tuple[str, ...]
+ connectors: tuple[str, ...]
+
+
+SOURCE_CAPABILITIES: dict[str, SourceCapability] = {
+ "ai_runtime": SourceCapability(
+ sees=("agent identity", "model", "provider", "tool names", "the human it acted for", "prompt secret shapes"),
+ cannot_see=(
+ "the device, unless the app reports a hostname",
+ "anything about an agent that is not instrumented",
+ "a process that never called a model",
+ ),
+ connectors=("ai_gateway", "inbox ai-runtime template", "inbox ai-finding template"),
+ ),
+ "endpoint": SourceCapability(
+ sees=(
+ "the device",
+ "the binary and its command line",
+ "whether permission prompts were disabled",
+ "MCP client configuration files",
+ "IDE extension directories",
+ ),
+ cannot_see=(
+ "which model was called",
+ "which tools were invoked",
+ "what the prompt contained",
+ "an agent running somewhere with no endpoint agent",
+ ),
+ connectors=("fleetdm", "osctrl", "auditd", "windows_event"),
+ ),
+ "provider_audit": SourceCapability(
+ sees=("the provider account", "who minted or used a key", "role and logging changes"),
+ cannot_see=(
+ "any device",
+ "which application used the key",
+ "anything about a key minted outside the audited organisation",
+ ),
+ connectors=("llm_usage",),
+ ),
+ "oauth_audit": SourceCapability(
+ sees=("the application that was granted access", "the scopes granted", "who consented"),
+ cannot_see=("any device", "what the application did with the grant", "a grant made in an unaudited directory"),
+ connectors=("llm_usage", "google_workspace", "azure_entra"),
+ ),
+ "declared": SourceCapability(
+ sees=("whatever an operator wrote down",),
+ cannot_see=("anything nobody declared, which is the population this inventory exists to find",),
+ connectors=("console",),
+ ),
+}
+
_UPSERT_SQL = """
INSERT INTO aisoc_ai_assets (
tenant_id, kind, external_id, display_name, vendor, discovery_source,
@@ -213,14 +374,76 @@ def classify(message: dict[str, Any]) -> list[_Sighting]:
if source_type in ("ai-runtime", "ai-finding", "AI Runtime", "AI Guardrail"):
out.extend(_from_ai_telemetry(tenant_id, ocsf, now))
- elif ocsf.get("class_uid") == 1007:
- out.extend(_from_process_activity(tenant_id, ocsf, now))
elif source_type in ("llm_usage", "AI / LLM Usage Audit"):
out.extend(_from_provider_audit(tenant_id, ocsf, now))
+ elif ocsf.get("class_uid") == 1007:
+ out.extend(_from_endpoint(tenant_id, ocsf, now))
return out
+def _connector_fields(ocsf: dict[str, Any]) -> dict[str, Any]:
+ """The flat namespace the connector actually produced.
+
+ `services/ingest` stores the connector's own normalized dict as a JSON
+ **string** under `ocsf["raw_data"]`, and the canonical OCSF field map
+ carries `title`, `external_id` and the identity aliases and nothing else.
+ So every endpoint field this module needs — `exe`, `process_name`,
+ `Image`, `CommandLine`, an osquery row's columns — exists only here.
+
+ This is the same reconstruction `DetectionEngine._raw_fields` performs,
+ and for the same reason: 663 of 825 loaded rules once matched on fields
+ that were not visible because nothing merged this namespace back. It is
+ reimplemented rather than imported only because the detection engine
+ loads the whole compiled ruleset at import time, which this module has no
+ business doing; `test_ai_endpoint_discovery.py` asserts the two agree.
+ """
+ raw = ocsf.get("raw_data")
+ decoded: dict[str, Any] | None = None
+ if isinstance(raw, dict):
+ decoded = raw
+ elif isinstance(raw, str) and raw.strip():
+ try:
+ parsed = json.loads(raw)
+ except (ValueError, TypeError):
+ # One malformed payload must not raise out of the consumer's hot
+ # path. An event we cannot read evidences no AI asset, which is
+ # the safe direction for an inventory.
+ return {}
+ if isinstance(parsed, dict):
+ decoded = parsed
+ if decoded is None:
+ return ocsf
+
+ nested = decoded.get("raw_event")
+ if isinstance(nested, dict):
+ merged = {k: v for k, v in nested.items() if isinstance(k, str)}
+ # Connector-normalized keys win on collision: the connector has
+ # already made a deliberate decision about `severity` or `hostname`
+ # and a vendor field of the same name must not override it.
+ merged.update(decoded)
+ return merged
+ return decoded
+
+
+def _first(fields: dict[str, Any], names: tuple[str, ...]) -> str | None:
+ """First non-empty value among `names`, flattened if it is a list.
+
+ `auditd` emits `argv` as a list, so a caller asking for a command line
+ gets the joined vector rather than a repr.
+ """
+ for name in names:
+ value = fields.get(name)
+ if isinstance(value, list):
+ joined = " ".join(str(v) for v in value if v)
+ if joined.strip():
+ return joined.strip()[:1000]
+ text = _text(value)
+ if text:
+ return text
+ return None
+
+
def _from_ai_telemetry(tenant_id: str, ocsf: dict[str, Any], now: float) -> list[_Sighting]:
"""SDK and gateway spans: the agent, its model, and any MCP server."""
agent_id = _text(_nested(ocsf, "actor", "process", "name"))
@@ -284,62 +507,174 @@ def _from_ai_telemetry(tenant_id: str, ocsf: dict[str, Any], now: float) -> list
return out
-def _from_process_activity(tenant_id: str, ocsf: dict[str, Any], now: float) -> list[_Sighting]:
- """EDR and osquery process telemetry: the device and the binary.
+def _from_endpoint(tenant_id: str, ocsf: dict[str, Any], now: float) -> list[_Sighting]:
+ """EDR, syscall and osquery telemetry: the device, the binary, the files.
+
+ Depth plan 6.2, and the rule the whole branch rests on: every field here
+ is read out of the **connector's** namespace through `_connector_fields`,
+ not off the OCSF event. The canonical profile maps `title`, `external_id`
+ and the identity aliases and nothing else, so an earlier version of this
+ function reading `process.name` found `None` for `fleetdm`, `osctrl`,
+ `auditd` and `windows_event` alike — every endpoint source this product
+ has — and endpoint discovery could never have produced a single row.
+
+ Three kinds of evidence, in order, because the first match wins and a
+ process path is also a file path:
- Depth 6.2 supplies the osquery half and widens the match tables; this
- reads whatever an EDR connector already normalizes to class 1007.
+ 1. A known coding-agent binary.
+ 2. A local MCP server process.
+ 3. A file: an MCP client's configuration, or an AI IDE extension.
+
+ One deliberate restraint: nothing here sets a model or a provider.
+ Endpoint telemetry cannot see either, and filling them in from a default
+ would make the inventory assert something no source observed.
"""
- name = _text(_nested(ocsf, "process", "name")) or _text(_nested(ocsf, "actor", "process", "name"))
- cmdline = _text(_nested(ocsf, "process", "cmd_line")) or ""
- device = _text(_nested(ocsf, "device", "name")) or _text(_nested(ocsf, "src_endpoint", "hostname"))
- principal = _text(_nested(ocsf, "actor", "user", "name"))
- if not name:
- return []
+ fields = _connector_fields(ocsf)
+ device = _first(fields, DEVICE_FIELDS) or _text(_nested(ocsf, "device", "name")) or _text(_nested(ocsf, "src_endpoint", "hostname"))
+ principal = _first(fields, PRINCIPAL_FIELDS) or _text(_nested(ocsf, "actor", "user", "name"))
+ cmdline = _first(fields, COMMAND_LINE_FIELDS) or ""
+
+ # The connector namespace first, then OCSF's own nested slots. Both
+ # exist: the four endpoint connectors populate only the former, while a
+ # producer posting OCSF directly through `/alerts/submit` populates only
+ # the latter, and reading one of the two is how this branch came to find
+ # nothing on every real source.
+ process = _first(fields, PROCESS_FIELDS) or _text(_nested(ocsf, "process", "name")) or _text(_nested(ocsf, "actor", "process", "name"))
+ cmdline = cmdline or _text(_nested(ocsf, "process", "cmd_line")) or ""
+ if process:
+ sighting = _process_sighting(tenant_id, process, cmdline, device, principal, now)
+ if sighting is not None:
+ return [sighting]
+
+ for candidate in (_first(fields, FILE_PATH_FIELDS), _text(fields.get("directory"))):
+ if not candidate:
+ continue
+ sighting = _file_sighting(tenant_id, candidate, device, principal, now)
+ if sighting is not None:
+ return [sighting]
+ return []
+
+
+def _process_sighting(tenant_id: str, name: str, cmdline: str, device: str | None, principal: str | None, now: float) -> _Sighting | None:
base = _basename(name)
+ lowered = cmdline.lower()
if base in CODING_AGENT_PROCESSES:
attributes: dict[str, Any] = {"process": base}
# The flag an agent is started with to stop asking. Read from the
- # command line because that is the only place it appears; an agent
- # running this way takes no human confirmation before acting.
- lowered = cmdline.lower()
- if any(flag in lowered for flag in ("--dangerously-skip-permissions", "--yolo", "--auto-approve", "--no-confirm")):
+ # command line because that is the only place it ever appears.
+ if any(flag in lowered for flag in NO_PROMPT_FLAGS):
attributes["permission_prompts_disabled"] = True
- return [
- _Sighting(
- tenant_id=tenant_id,
- kind=KIND_CODING_AGENT,
- external_id=base,
- device=device,
- display_name=name,
- vendor=CODING_AGENT_PROCESSES[base],
- discovery_source="endpoint",
- principal=principal,
- attributes=attributes,
- count=1,
- first_seen=now,
- last_seen=now,
- )
- ]
+ if cmdline:
+ attributes["cmd_line"] = cmdline[:255]
+ return _Sighting(
+ tenant_id=tenant_id,
+ kind=KIND_CODING_AGENT,
+ external_id=base,
+ device=device,
+ display_name=name,
+ vendor=CODING_AGENT_PROCESSES[base],
+ discovery_source="endpoint",
+ principal=principal,
+ attributes=attributes,
+ count=1,
+ first_seen=now,
+ last_seen=now,
+ )
- if any(token in base for token in MCP_SERVER_PROCESSES):
- return [
- _Sighting(
+ # Prefix, not substring. `mcp` as a substring matches `mcpelauncher`, and
+ # a false positive here puts a game launcher on a security review.
+ if any(base.startswith(token) for token in MCP_SERVER_PROCESSES):
+ attributes = {"process": base}
+ if cmdline:
+ attributes["cmd_line"] = cmdline[:255]
+ return _Sighting(
+ tenant_id=tenant_id,
+ kind=KIND_MCP_SERVER,
+ external_id=base,
+ device=device,
+ display_name=name,
+ discovery_source="endpoint",
+ principal=principal,
+ attributes=attributes,
+ count=1,
+ first_seen=now,
+ last_seen=now,
+ )
+ return None
+
+
+def _file_sighting(tenant_id: str, path: str, device: str | None, principal: str | None, now: float) -> _Sighting | None:
+ """An MCP client configuration file, or an AI IDE extension directory.
+
+ A file is a different kind of evidence from a process: it says a server
+ or an extension is *wired in*, which survives a reboot and survives a
+ process listing that happened to miss the window.
+ """
+ lowered = path.replace("\\", "/").lower()
+
+ for suffix, client in MCP_CLIENT_CONFIGS:
+ if lowered.endswith(suffix):
+ return _Sighting(
tenant_id=tenant_id,
kind=KIND_MCP_SERVER,
- external_id=base,
+ # Keyed on the client, not the file: two laptops with Cursor
+ # configured are two assets, and the same laptop's file moving
+ # between releases is still one.
+ external_id=f"{client} MCP configuration",
device=device,
- display_name=name,
+ display_name=f"{client} MCP configuration",
discovery_source="endpoint",
principal=principal,
- attributes={"process": base, "cmd_line": cmdline[:255]} if cmdline else {"process": base},
+ attributes={"mcp_client": client, "config_path": path[:255]},
count=1,
first_seen=now,
last_seen=now,
)
- ]
- return []
+
+ for directory in IDE_EXTENSION_DIRS:
+ if directory not in lowered:
+ continue
+ remainder = lowered.split(directory, 1)[1]
+ folder = remainder.split("/", 1)[0]
+ identifier, version = _split_extension_folder(folder)
+ vendor = AI_IDE_EXTENSIONS.get(identifier)
+ # An editor has hundreds of extensions and a handful are AI. Listing
+ # all of them would turn this into a package manifest and make the
+ # column that matters unreadable.
+ if vendor is None:
+ return None
+ attributes = {"extension": identifier}
+ if version:
+ attributes["version"] = version
+ return _Sighting(
+ tenant_id=tenant_id,
+ kind=KIND_IDE_EXTENSION,
+ external_id=identifier,
+ device=device,
+ display_name=identifier,
+ vendor=vendor,
+ discovery_source="endpoint",
+ principal=principal,
+ attributes=attributes,
+ count=1,
+ first_seen=now,
+ last_seen=now,
+ )
+ return None
+
+
+def _split_extension_folder(folder: str) -> tuple[str, str | None]:
+ """`publisher.name-1.2.3` -> `("publisher.name", "1.2.3")`.
+
+ Split on the last hyphen followed by a digit, because a publisher or an
+ extension name may itself contain hyphens (`sourcegraph.cody-ai`) and
+ splitting on the first would truncate the identifier.
+ """
+ match = re.search(r"^(.*?)-(\d[\w.+-]*)$", folder)
+ if match:
+ return match.group(1), match.group(2)
+ return folder, None
def _from_provider_audit(tenant_id: str, ocsf: dict[str, Any], now: float) -> list[_Sighting]:
diff --git a/services/fusion/tests/test_ai_asset_recorder.py b/services/fusion/tests/test_ai_asset_recorder.py
index 0f4b69618..2a0ca302a 100644
--- a/services/fusion/tests/test_ai_asset_recorder.py
+++ b/services/fusion/tests/test_ai_asset_recorder.py
@@ -13,6 +13,7 @@ the recurring defect here is a test double more capable than the real source.
from __future__ import annotations
import importlib.util
+import json
from pathlib import Path
from typing import Any
@@ -62,20 +63,48 @@ def runtime_event(**overrides: Any) -> dict[str, Any]:
def process_event(name: str, cmd_line: str = "", hostname: str = "ada-mbp") -> dict[str, Any]:
- """An OCSF Process Activity event, the class EDR telemetry normalizes to."""
+ """A process-activity event in the shape the endpoint connectors emit.
+
+ `services/ingest` stores the connector's own normalized dict as a JSON
+ string under `raw_data`, and the canonical OCSF field map carries almost
+ nothing else — so `exe`, `process_name` and a command line live only
+ here. An earlier version of this helper built a nested `process.name`
+ instead, which no endpoint connector in this product produces; see
+ `test_ai_endpoint_discovery.py` for the four real shapes.
+ """
+ payload: dict[str, Any] = {"source": "auditd", "syscall": "execve", "exe": name, "hostname": hostname, "actor": "[email protected]"}
+ if cmd_line:
+ payload["cmdline"] = cmd_line
return {
"tenant_id": TENANT,
"ocsf_event": {
"class_uid": 1007,
"class_name": "Process Activity",
- "source_type": "crowdstrike_falcon",
- "process": {"name": name, "cmd_line": cmd_line},
+ "source_type": "auditd",
+ "raw_data": json.dumps(payload),
"device": {"name": hostname},
"actor": {"user": {"name": "[email protected]"}},
},
}
+def ocsf_native_process_event(name: str, hostname: str = "ada-mbp") -> dict[str, Any]:
+ """The other shape: OCSF posted directly, with no connector payload.
+
+ Kept as its own helper and its own case because both shapes reach this
+ code and reading only one of them is the defect 6.2 reproduced.
+ """
+ return {
+ "tenant_id": TENANT,
+ "ocsf_event": {
+ "class_uid": 1007,
+ "class_name": "Process Activity",
+ "process": {"name": name},
+ "device": {"name": hostname},
+ },
+ }
+
+
# ---------------------------------------------------------------------------
# Classification
# ---------------------------------------------------------------------------
@@ -117,7 +146,7 @@ def test_process_activity_finds_a_coding_agent_with_a_device_and_no_model():
This is why `discovery_source` is stored: an analyst reading a row with no
model needs to know whether it is missing or unknowable.
"""
- sightings = classify(process_event("claude", "claude --resume"))
+ sightings = classify(process_event("/usr/local/bin/claude", "claude --resume"))
assert len(sightings) == 1
assert sightings[0].kind == "coding_agent"
assert sightings[0].discovery_source == "endpoint"
@@ -125,9 +154,14 @@ def test_process_activity_finds_a_coding_agent_with_a_device_and_no_model():
assert "models" not in sightings[0].attributes
+def test_an_ocsf_native_process_event_is_read_too():
+ sightings = classify(ocsf_native_process_event("/usr/local/bin/claude"))
+ assert [s.kind for s in sightings] == ["coding_agent"]
+
+
@pytest.mark.parametrize("flag", ["--dangerously-skip-permissions", "--yolo", "--auto-approve", "--no-confirm"])
def test_permission_prompts_disabled_is_read_from_the_command_line(flag: str):
- sightings = classify(process_event("claude", f"claude {flag} -p 'refactor'"))
+ sightings = classify(process_event("/usr/local/bin/claude", f"claude {flag} -p 'refactor'"))
assert sightings[0].attributes["permission_prompts_disabled"] is True
diff --git a/services/fusion/tests/test_ai_endpoint_discovery.py b/services/fusion/tests/test_ai_endpoint_discovery.py
new file mode 100644
index 000000000..1e8c627ce
--- /dev/null
+++ b/services/fusion/tests/test_ai_endpoint_discovery.py
@@ -0,0 +1,268 @@
+"""Endpoint discovery of AI assets, from sources that already exist.
+
+Depth plan 6.2: *known coding-agent processes, MCP server processes and the
+configuration files that popular MCP clients read*, from EDR process telemetry
+and osquery, **with no new agent**.
+
+Every payload below is the shape the connector in question actually emits,
+read out of its `normalize()` rather than invented:
+
+* `windows_event` puts `process_name` at the top level and lifts `Image` and
+ `CommandLine` out of `EventData` into `raw_event`.
+* `auditd` emits a flat `syscall` / `exe` / `argv` / `path` record.
+* `fleetdm` and `osctrl` flatten the osquery row's columns to the top level.
+
+That distinction is the whole item. The OCSF canonical field map carries
+`title`, `external_id` and the identity aliases and **nothing else**, so a
+reader that looks for `process.name` on the OCSF event finds `None` for every
+one of these sources — which is what 6.1's endpoint branch did, and what the
+first test here reproduced before it was fixed.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import pytest
+from app.services.ai_asset_recorder import classify
+
+TENANT = "11111111-1111-1111-1111-111111111111"
+
+
+def ingest_event(connector_type: str, payload: dict[str, Any], class_uid: int = 1007) -> dict[str, Any]:
+ """Wrap a connector payload the way `services/ingest` publishes it.
+
+ `normalizer.go` runs `json.Marshal(raw.Payload)` into `ocsf["raw_data"]`
+ as a **string**, and the canonical profile maps almost nothing else. An
+ event built any other way would be testing a pipeline this product does
+ not have.
+ """
+ ocsf: dict[str, Any] = {
+ "class_uid": class_uid,
+ "class_name": "Process Activity",
+ "source_type": connector_type,
+ "metadata": {"product": {"name": connector_type, "vendor_name": connector_type}},
+ "raw_data": json.dumps(payload),
+ }
+ if payload.get("hostname"):
+ ocsf["device"] = {"name": payload["hostname"]}
+ if payload.get("username") or payload.get("actor"):
+ ocsf["actor"] = {"user": {"name": payload.get("username") or payload.get("actor")}}
+ return {"tenant_id": TENANT, "ocsf_event": ocsf}
+
+
+# ---------------------------------------------------------------------------
+# EDR and syscall process telemetry
+# ---------------------------------------------------------------------------
+
+
+def test_windows_event_process_creation_finds_a_coding_agent():
+ """Sysmon event 1 / Security 4688, as `windows_event.normalize()` emits it."""
+ event = ingest_event(
+ "windows_event",
+ {
+ "source": "windows_event",
+ "event_type": "windows.microsoft-windows-sysmon/operational.1",
+ "hostname": "WIN-DEV-02",
+ "username": "CONTOSO\\ada",
+ "process_name": "C:\\Users\\ada\\AppData\\Local\\Programs\\claude\\claude.exe",
+ "raw_event": {
+ "EventID": "1",
+ "Image": "C:\\Users\\ada\\AppData\\Local\\Programs\\claude\\claude.exe",
+ "CommandLine": "claude.exe --dangerously-skip-permissions -p refactor",
+ "Computer": "WIN-DEV-02",
+ },
+ },
+ )
+ sightings = classify(event)
+ assert [s.kind for s in sightings] == ["coding_agent"]
+ assert sightings[0].device == "WIN-DEV-02"
+ assert sightings[0].discovery_source == "endpoint"
+ # The flag is only ever on the command line, and it is the single
+ # highest-signal attribute an endpoint source can supply: an agent
+ # started this way takes no human confirmation before acting.
+ assert sightings[0].attributes["permission_prompts_disabled"] is True
+
+
+def test_auditd_execve_finds_a_coding_agent():
+ """A flat auditd record: `syscall`, `exe`, `argv`."""
+ event = ingest_event(
+ "auditd",
+ {
+ "source": "auditd",
+ "syscall": "execve",
+ "exe": "/usr/local/bin/aider",
+ "argv": ["aider", "--yes-always", "main.py"],
+ "hostname": "build-07",
+ "actor": "ada",
+ },
+ )
+ sightings = classify(event)
+ assert [s.kind for s in sightings] == ["coding_agent"]
+ assert sightings[0].vendor == "Aider"
+ assert sightings[0].device == "build-07"
+
+
+def test_osquery_process_row_finds_a_coding_agent():
+ """A FleetDM scheduled-query row; columns are flattened to the top level."""
+ event = ingest_event(
+ "fleetdm",
+ {
+ "source": "fleetdm",
+ "event_type": "osquery_query_row",
+ "hostname": "ada-mbp",
+ "name": "codex",
+ "path": "/opt/homebrew/bin/codex",
+ "cmdline": "codex --auto-approve",
+ "uid": "501",
+ },
+ )
+ sightings = classify(event)
+ assert [s.kind for s in sightings] == ["coding_agent"]
+ assert sightings[0].vendor == "OpenAI"
+ assert sightings[0].attributes["permission_prompts_disabled"] is True
+
+
+def test_an_mcp_server_process_is_found_on_the_endpoint():
+ event = ingest_event(
+ "osctrl",
+ {
+ "source": "osctrl",
+ "hostname": "ada-mbp",
+ "name": "mcp-server-filesystem",
+ "path": "/usr/local/bin/mcp-server-filesystem",
+ "cmdline": "mcp-server-filesystem /Users/ada",
+ },
+ )
+ sightings = classify(event)
+ assert [s.kind for s in sightings] == ["mcp_server"]
+ assert sightings[0].device == "ada-mbp"
+
+
+def test_an_ordinary_process_row_is_not_an_ai_asset():
+ """The negative control.
+
+ A substring heuristic on "agent" or "server" would put every EDR sensor
+ and every web daemon on an AI inventory, and a false positive here is a
+ name on a governance review that somebody acts on.
+ """
+ for name in ("falcon-sensor", "osqueryd", "nginx", "chrome", "MsMpEng.exe", "node"):
+ event = ingest_event("fleetdm", {"source": "fleetdm", "hostname": "h", "name": name, "path": f"/usr/bin/{name}"})
+ assert classify(event) == [], name
+
+
+# ---------------------------------------------------------------------------
+# Configuration files the MCP clients read
+# ---------------------------------------------------------------------------
+
+
+ ("path", "client"),
+ [
+ ("/Users/ada/Library/Application Support/Claude/claude_desktop_config.json", "Claude Desktop"),
+ ("/Users/ada/.cursor/mcp.json", "Cursor"),
+ ("/home/ada/.codeium/windsurf/mcp_config.json", "Windsurf"),
+ ("/home/ada/.config/Code/User/mcp.json", "VS Code"),
+ ("/home/ada/.continue/config.json", "Continue"),
+ ("/Users/ada/.aws/amazonq/mcp.json", "Amazon Q"),
+ ],
+)
+def test_an_mcp_client_configuration_file_is_an_mcp_server_asset(path: str, client: str):
+ """The file is the evidence that a server is configured, and where.
+
+ A configuration file is a different kind of evidence from a running
+ process: it says a server is *wired in*, which survives a reboot and a
+ `ps` that happened to miss the window.
+ """
+ event = ingest_event(
+ "fleetdm",
+ {"source": "fleetdm", "hostname": "ada-mbp", "path": path, "directory": path.rsplit("/", 1)[0], "uid": "501"},
+ )
+ sightings = classify(event)
+ assert [s.kind for s in sightings] == ["mcp_server"], path
+ assert sightings[0].attributes["mcp_client"] == client
+ assert sightings[0].attributes["config_path"] == path
+
+
+def test_an_ide_extension_directory_is_an_extension_asset():
+ event = ingest_event(
+ "fleetdm",
+ {
+ "source": "fleetdm",
+ "hostname": "ada-mbp",
+ "path": "/Users/ada/.vscode/extensions/github.copilot-1.250.0/package.json",
+ "directory": "/Users/ada/.vscode/extensions/github.copilot-1.250.0",
+ },
+ )
+ sightings = classify(event)
+ assert [s.kind for s in sightings] == ["ide_extension"]
+ assert sightings[0].external_id == "github.copilot"
+ assert sightings[0].attributes["version"] == "1.250.0"
+
+
+def test_an_unrelated_ide_extension_is_not_an_ai_asset():
+ """An editor has hundreds of extensions and six of them are AI.
+
+ Listing all of them would make the AI inventory a package manifest, and
+ the column that matters — "what AI is running here" — unreadable.
+ """
+ event = ingest_event(
+ "fleetdm",
+ {
+ "source": "fleetdm",
+ "hostname": "ada-mbp",
+ "path": "/Users/ada/.vscode/extensions/esbenp.prettier-vscode-11.0.0/package.json",
+ "directory": "/Users/ada/.vscode/extensions/esbenp.prettier-vscode-11.0.0",
+ },
+ )
+ assert classify(event) == []
+
+
+def test_an_unrelated_json_file_is_not_an_mcp_configuration():
+ event = ingest_event(
+ "fleetdm",
+ {"source": "fleetdm", "hostname": "ada-mbp", "path": "/Users/ada/project/package.json"},
+ )
+ assert classify(event) == []
+
+
+# ---------------------------------------------------------------------------
+# What each source can and cannot see
+# ---------------------------------------------------------------------------
+
+
+def test_every_discovery_source_declares_what_it_cannot_see():
+ """The plan asks for this in words: *record what each source can and cannot see.*
+
+ Both directions, because a one-directional check is this repository's
+ dominant gate failure: every source the recorder can emit must appear in
+ the table, and every source in the table must be one the recorder can
+ emit.
+ """
+ from app.services.ai_asset_recorder import DISCOVERY_SOURCES, SOURCE_CAPABILITIES
+
+ assert set(SOURCE_CAPABILITIES) == set(DISCOVERY_SOURCES)
+ for source, capability in SOURCE_CAPABILITIES.items():
+ assert capability.sees, source
+ # The half that matters. A table listing only what a source provides
+ # reads as complete coverage; the blind spots are what an analyst
+ # needs when a column is empty.
+ assert capability.cannot_see, f"{source} declares no blind spot, which no real source has"
+ assert capability.connectors, source
+
+
+def test_an_endpoint_asset_never_claims_a_model():
+ """Endpoint telemetry cannot see which model an agent called.
+
+ Asserting the absence rather than trusting the table: a recorder that
+ filled this in from a default would make the inventory assert something
+ no source observed.
+ """
+ event = ingest_event(
+ "auditd",
+ {"source": "auditd", "syscall": "execve", "exe": "/usr/local/bin/aider", "argv": ["aider"], "hostname": "h"},
+ )
+ sighting = classify(event)[0]
+ assert "models" not in sighting.attributes
+ assert "provider" not in sighting.attributes