Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(1.3): HR and device context connectors, synced on schedule, cited in triage (#1589)
Beenu Arorad42b7e5f5d53
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 02c764ec0..31845c1ec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,50 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **HR and managed-device context, kept current by a connector on a+ schedule** (depth plan wave 2, item 1.3). Three new connectors --+ BambooHR, Rippling and Microsoft Intune -- feed employment status, start+ and last-day dates, manager, department, worker type, device owner,+ compliance state, OS version, encryption and threat-defence agent state+ into triage.++ What was absent, measured: 88 registered connectors and not one of them+ HR or MDM, and `import_context` with exactly one production caller, a+ manual POST route. A tenant's HR context was only ever as current as the+ last file somebody uploaded.++ The wiring is the half that makes it real. The connector scheduler calls+ the workforce sync on every poll, in its own `try`, modelled on the+ vulnerability sync beside it: a context sync that fails must not cost the+ poll its events.++ Migration 131 puts the context in Postgres so it exists on CORE. The graph+ import stays and is richer, but Neo4j is a `full`-profile service, so on+ the deployment `make up` produces the HR dimension did not exist at all+ and every triage input reading it was silently dead.++ Tenure, departing-within-30-days, contractor status and device compliance+ are derived and cited in the confidence basis as well as rendered in the+ prompt, because a fact in one and not the other is either invisible to a+ reviewer or absent from the model. Every absence keeps its direction: a+ missing start date is not a new joiner, a missing end date is not+ "staying", an unmapped employment type is not an employee, and a device+ the MDM never evaluated is not a compliant one.++ Data minimisation is in the request and in the schema rather than in a+ filter. All three vendors return compensation, date of birth and home+ address; none is requested, and migration 131 has no column that could+ hold one. The BambooHR directory endpoint, which would have been the+ obvious single read, is deliberately not used for the facts: its own+ reference says it never includes employment status or history in any+ configuration and excludes former employees entirely, which removes every+ field this item needs and the whole population it exists to see.++ **Not built:** Workday and Kandji, recorded as blocked with exactly what+ each needs rather than built against an invented payload shape.++### Added+- **Anonymizer and hosting classes stamped on public addresses at ingest**(depth plan wave 2, item 1.6). An event's source address now carries`tor_exit` or `hosting_provider` where a pinned local dataset has a recorddiff --git a/DEPTH2_PROGRESS.md b/DEPTH2_PROGRESS.mdindex e9a2e0174..90f7f90f6 100644--- a/DEPTH2_PROGRESS.md+++ b/DEPTH2_PROGRESS.md@@ -42,6 +42,22 @@ from now on; `DEPTH_PROGRESS.md` gains a cross-reference rather than a tick.| 9.6 remainder (device evidence) | wave 2 Phase 9.2 | maintainer-blocked at hand-over || Phase 10 close | wave 2 Phase 10 | wave 2's Phase 10 closes both |+## Lane B status (sources: 1.3, 1.6, 8.1 to 8.4)++| Item | State | Where |+|---|---|---|+| 1.6 Anonymizer and hosting classes at ingest | **done**, in review | PR #1586 |+| 1.3 HR and device context | **done for three of six connectors**, in review | PR #1589 |+| 8.1 CNAPP depth | not started, gap reproduced | item log |+| 8.2 NDR connectors | not started; ExtraHop buildable, Corelight blocked | item log |+| 8.3 Enrichment per tenant, cited | not started, gap reproduced | item log |+| 8.4 Scale and deployment evidence | **blocked, recorded with exactly what is needed** | item log |++Every row above has its reproduction recorded in the item log as a command+or a failing test, including the ones that were not built: a gap nobody+reproduced is a rumour, and the three not-started items are written up so+the next lane starts from evidence rather than from the plan's prose.+## Migration and ADR numbers claimedClaim a number here, push the claim, then write the file. Two lanes once@@ -339,11 +355,306 @@ Not done because landing 1.6 and 1.3 unblocks Lane C, and a half-wiredper-tenant path would have been worse than an honest gap. Nothing shippeddepends on it; the three classes simply carry no records.+### D5 - Workday and Kandji are blocked; three of the six named sources are built++Item 1.3 names six connectors. Three are built against public references+verified on 2026-11-01 and cited by URL in each module: BambooHR, Rippling+and Microsoft Intune. Three are not, for different reasons.++**Workday.** `community.workday.com/sites/default/files/file-hosting/restapi/`+answers 200, but the Staffing REST surface a tenant actually exposes is+per-tenant and the report-as-a-service shape most deployments use is defined+by the customer's own report definition, not by a fixed schema. There is no+public response document from which an honest mock payload can be written.+**Needed:** a Workday sandbox tenant, or one recorded (redacted) response+from `Get_Workers` or from a customer's staffing RaaS report.++**Kandji.** `api-docs.kandji.io` answers 200 and the landing page documents+the base URL, the token header, the rate limit and the response codes. The+device-list response's field names are rendered client-side and could not be+extracted. **Needed:** one recorded (redacted) `GET /api/v1/devices`+response, or the field list from the vendor's device-detail page.++**Jamf Pro.** `developer.jamf.com/jamf-pro/reference/get_v1-computers-inventory`+answers 200 and the field names *are* verified -- `general.name`,+`operatingSystem.version`, `operatingSystem.fileVault2Status`,+`diskEncryption.fileVault2Enabled`, `userAndLocation.username`,+`userAndLocation.email`, `security.firewallEnabled` -- so unlike the other+two this one is **not blocked on the vendor**. It is not built in this pass+for time, and `plugins/jamf-mdm` stays a manifest without a connector class.+The promotion is a known quantity: one module in the shape of+`microsoft_intune.py` reading `GET /v1/computers-inventory` with+`section=GENERAL§ion=OPERATING_SYSTEM§ion=DISK_ENCRYPTION§ion=USER_AND_LOCATION§ion=SECURITY`.++Recorded rather than built against an invented shape, which is the plan's own+rule for exactly these vendors.++### D6 - HR and MDM connectors get no ingest profile, and the first evidence for that was the wrong test++**Corrected after CI.** The conclusion held; the evidence did not, which is+the half worth recording.++These three connectors publish no events at all. `fetch_alerts` returns an+empty list on each by design: an HR system reports slowly-changing state,+not security events, and their output is context the scheduler writes to+`workforce_members` and `workforce_devices`, never to ingest. A+`connectorProfiles` entry would be an entry nothing can reach.++What was wrong was the check behind it. The original entry said `go test+./internal/normalizer/` passed and cited+`TestConnectorTypeCanonicalTargetsAreDeclaredAndUnshadowed`, which asserts+that every *alias target* is declared and asks nothing about a connector+having a profile. The test that does ask is+`TestEveryDeclaredConnectorHasAnOCSFDecision`, and it failed in CI:++ connector "bamboohr" has no entry in connectorOCSFClass: its events+ take the 2001 default, which is always promoted, and nothing records+ that as a decision++`connectorOCSFClass` exists precisely to separate "decided to take the+generic path" from "nobody looked", and a connector with no entry reads as+the second. All three now carry a `genericReason` naming what they are.++The lesson is the one this programme keeps paying for: a local suite+passing is not evidence that the specific question was asked. The original+entry named a test by title and did not read what it asserted.++### D7 - Zero check runs was a conflicted PR, not a saturated pool, and the two look identical from outside++**Corrected.** This entry first recorded the wrong cause, and the+correction is worth more to the next lane than the original observation+was.++What was true: the head commit of each Lane B branch returned+`total_count: 0` check runs. What was wrong: attributing that to the shared+runner pool because 19 runs were queued and 18 in progress at the same+moment. The pool had in fact drained to a single queued run.++**The real cause.** Wave 0 was squash-merged into `main`, so `main` and the+Lane B base `depth2/wave0-kickoff` each carried `DEPTH2_PROGRESS.md` and+`plans/aisoc_depth_wave2.plan.md` by different histories - an add/add+conflict. Both pull requests were therefore `mergeStateStatus: DIRTY`, and+**GitHub cannot compute a merge ref for a conflicted pull request, so it+creates no check runs at all**. Zero runs was the conflict, not the queue.++**The one call that tells the two apart**, which is the durable half of+this entry:++```bash+gh pr view <n> --repo beenuar/AiSOC --json mergeStateStatus -q .mergeStateStatus+```++* `DIRTY` - the merge ref cannot be computed. **Nothing can be graded**,+ and no amount of waiting or re-pushing will change that. Merge the base+ in and the runs appear.+* `BLOCKED` or `UNSTABLE` with `total_count: 0` - the pull request is+ gradeable and the runs have genuinely not started. That is the pool.++A queue snapshot alone cannot distinguish them, because a busy queue is the+ordinary state of this repository and is true at the same moment either way.+Checking the queue first is what produced the wrong answer here.++**Standing rule for this lane from now on:** after any push, read+`mergeStateStatus` before concluding anything about the pool.++Resolved by merging `origin/main` into both branches, keeping both sides of+the tracker. Measured immediately afterwards: 108 check runs on+`depth2/lane-b-sources` and 109 on `depth2/lane-b-workforce`, against zero+before.+## Item logOne entry per item as it lands: what failed before, the change, the negativecontrol, and the measurement delta.+### 8.1 CNAPP depth - Lane B - NOT STARTED, gap reproduced++**Reproduced, recorded as commands rather than asserted.**++`services/connectors/app/connectors/wiz.py` declares exactly one GraphQL+operation, `query IssuesTable`. There is no vulnerability query, no+configuration-finding query, no secrets query and no runtime-detection+query. The four sibling cloud-security connectors each read one endpoint+and it is their alert stream in every case:++| Connector | The one read it makes |+|---|---|+| `orca` | two `GET`s against the alerts API |+| `prisma_cloud` | two `POST`s against the search API |+| `lacework` | `GET /api/v2/Alerts` |+| `sysdig` | `GET /api/v1/secureEvents` |++So the gap is real on all five and is as the plan describes it.++**What remains, scoped:** extend the Wiz connector to vulnerabilities,+configuration findings, secrets and runtime detections where the vendor API+offers them; record the same depth check for the other four; surface the+findings as **triage context keyed on the resource the alert touched**,+not as alerts by default. The triage-context half is the part that needs a+design decision rather than a read: a CNAPP finding on a resource is an+input to a verdict about an event on that resource, which means a lookup+keyed on resource identity at triage time, in the shape+`services/agents/app/context/identity.py` uses for principals.++**Risk the plan already names:** Wiz's newer GraphQL surfaces are behind a+customer tenant. Verify each field against the vendor's current public+reference before writing it, and record BLOCKED rather than inventing a+payload shape, exactly as D5 does for Workday and Kandji.++### 8.2 NDR connectors - Lane B - NOT STARTED, one half blocked++**Reproduced.** `ls services/connectors/app/connectors/ | grep -iE+"extrahop|corelight"` returns nothing. The two network connectors that+exist are `zeek_suricata` and `darktrace`.++**Reference availability, measured 2026-11-01:**++| Vendor | Public reference | Verdict |+|---|---|---|+| ExtraHop RevealX 360 | `https://docs.extrahop.com/current/rest-api-guide/` answers **200** | buildable |+| Corelight | `https://docs.corelight.com/` answers **401** | **BLOCKED** |++So ExtraHop is a build and Corelight is not. **Corelight needs** either a+documentation account, or one recorded (redacted) detection payload plus the+endpoint and auth shape, before an honest mock can be written. Corelight's+*Zeek output* is open and is already covered by the `zeek_suricata`+connector, which is a different thing from the sensor's own detection API+and must not be passed off as it.++### 8.3 Enrichment per tenant, cited - Lane B - NOT STARTED, gap reproduced++**Reproduced, and the gap is wider than the plan states.**++`services/enrichment` is a **Go** service, not Python. Measured on this+tree:++ * `grep -c tenant` over `internal/enricher/enricher.go` and+ `internal/config/config.go` returns **0** and **0**. There is no+ per-tenant dimension anywhere in the service, so per-tenant opt-in is+ absent rather than partial.+ * No reference to the credential vault anywhere under+ `services/enrichment/`. Keys are per-deployment environment variables.+ * `RATE_LIMIT_RPS` and `RATE_LIMIT_BURST` are parsed in `config.go` lines+ 59-60, assigned to struct fields at lines 92-93, and **read by nothing+ else in the service**. The plan's "reads and never enforces" reproduces+ exactly.+ * `URLSCAN_API_KEY` is a config field (`config.go:71`) with no client.+ * No enrichment result is cited in the ledger.++**What remains, and the one design decision it needs.** The per-tenant+opt-in is a console settings surface with the tenant's own key in the+credential vault, which `services/api` owns the write path for. A Go+service cannot hold that write path, so either the enrichment service+learns to read vault tokens through a vendored read-path `decrypt_dict`+(the pattern `services/connectors` already uses), or the fan-out moves+behind an API route that resolves the tenant's credentials first. That+choice should be made explicitly rather than discovered during+implementation.++The rate limiter needs a test that proves it **refuses**, per the brief: a+limiter asserted only on the allowed path is indistinguishable from no+limiter.++### 8.4 Scale and deployment evidence - Lane B - **BLOCKED**, which is the correct outcome++The plan's own text allows for this: "published with hardware, date and+commit, **or recorded as blocked with exactly what is needed**". Both halves+are blocked on hardware nobody here has, and neither is blocked on code.++**4.4, the cloud-hardware run.** Already stated honestly on+`apps/docs/docs/operations/performance.md` under "No cloud-hardware run+exists yet, and that is a gap", re-read on 2026-11-01 and still accurate.+Every figure on that page comes from an 18-core Apple-silicon laptop, a+6-CPU Linux VM on it, or a kind cluster on the same machine. The target is+a sustained 5,000 events/s through detection at p95 under 2 s on one+documented instance size.++**Needed:** a cloud account and one named instance type. Nothing else. The+harness already records the hardware fingerprint, the load shape and the+commit into every result file, and `scripts/check_perf_results.py` already+refuses a result that drops any of them. The command that produces the row+is published on that page and is reproduced here so this entry stands alone:++```bash+python3 scripts/perf/load_harness.py \+ --target compose --events 500000 --workers 32 --batch 100 \+ --alert-every 100 --target-eps 5000 --drain-timeout 1800 \+ --assert-benign-alert-rate-max 0.001 \+ --out docs/perf/results/<date>-<instance-type>-realistic-mix.json+```++**4.5, the managed-cluster run.** The only cluster evidence in the tree is+the three-node **kind** run of 2026-09-27, and the page already says what+that does and does not prove: "kind nodes are containers on the same+kernel, so this is not two machines' worth of anything". A kind run is not+a managed-cluster run and must not be published as one.++**Needed:** a managed Kubernetes cluster (EKS, GKE or AKS) with at least+three worker nodes and a load balancer, plus permission to install the+chart into it. The first depth plan recorded the same requirement as+maintainer action M3; this entry carries it forward rather than restating+it as new.++**What was deliberately not done:** no figure was produced by extrapolation+from the laptop runs. A laptop VM's disk, network and CPU scheduling are not+an instance type's, and a number derived that way becomes a promise nobody+can keep. "Not measured" with the exact requirement is the honest record,+and it is the record this item asks for.++### 1.3 HR and device context - Lane B++**Reproduced.** On the current tree:++ ModuleNotFoundError: No module named 'app.connectors.bamboohr'++and the state behind it, measured rather than asserted: 88 connectors in+`_CONNECTOR_CLASSES`, none HR and none MDM; `import_context` with exactly+one production caller, the manual POST at+`services/api/app/api/v1/endpoints/graph.py:725`.++**Shipped.**++| Piece | Where |+|---|---|+| HR connectors | `bamboohr`, `rippling` |+| MDM connector | `microsoft_intune` |+| Capabilities | `PULL_WORKFORCE`, `PULL_DEVICE_INVENTORY` |+| Context store | `services/connectors/app/workforce.py`, migration `131` |+| Scheduler caller | `ConnectorScheduler._sync_workforce_context`, on every poll |+| CORE read | `services/api/app/services/workforce_context.py`, merged into `/graph/identity-context` |+| Triage derivations | `derive_employment_facts` and `_render_device_line` in `services/agents/app/context/identity.py` |+| Citations | `identity.basis` names departed, departing, contractor and device counts |+| Marketplace | three `plugins/<id>/plugin.yaml`, index regenerated |+| Docs | three pages generated, all three in the sidebar |+| Count | regenerated, not edited: 87 -> **90** |++**Negative control.** Removing the `_sync_workforce_context` call from+`_poll_one` fails `test_the_scheduler_calls_a_workforce_sync_on_every_poll`+with the reason stated: the connector would be registered, configured,+polled and silently ignored. Removing each derived fact from+`render_for_prompt` fails its paired prompt assertion, and removing it from+`basis` fails its paired citation assertion, which is why both halves are+asserted for all four facts.++**Numbers, from the generators.**++| Figure | Value | Source |+|---|---|---|+| Registered connectors | 87 -> **90** | `generate_connector_count.py --check` |+| Connector docs | 90 documented, 41 generated / 49 hand-written | `generate_connector_docs.py --check` |+| Marketplace plugins | 80 -> **83** | `build_marketplace.py` |+| Claim matrix | 335/330/5 -> **336/331/5** | `check_claim_gate_matrix.py` |++**One trap avoided and worth recording.** `generate_connector_docs._slug`+writes the hyphenated filename for a connector with no existing page, so+`microsoft_intune` documents at `/docs/connectors/microsoft-intune`. The+connector's `docs_url` was written with the underscore first and would have+404'd; corrected before commit and verified against the generated sidebar+entry.++**Deviations:** D5 (Workday and Kandji blocked, Jamf deferred with its shape+recorded), D6 (no ingest profile, with the reason and the check).+### 1.1 Effective permissions everywhere — shipped**Reproduced first.** `services/api/tests/test_identity_privilege_reproduction.py`@@ -804,7 +1115,6 @@ classify from.**Shipped.**-| Piece | Where ||---|---|| Downloader | `scripts/fetch_ip_class_dataset.py` || Pinned snapshot | `services/ingest/internal/activity/ipclass/data/` (21,726 records) |@@ -832,7 +1142,6 @@ Restored, the suite passes again.**Numbers, from the generators.**-| Figure | Value | Source ||---|---|---|| Dataset records | 21,726 | `check_ip_class_dataset.py` || `tor_exit` records | 1,228 | same |diff --git a/README.md b/README.mdindex 6c3a8610c..a29f6f30b 100644--- a/README.md+++ b/README.md@@ -90,7 +90,7 @@ curl -X POST http://localhost:8081/v1/ingest/batch \"title":"Encoded PowerShell from Office","host":"WIN-FIN-01"}]}'```-Or pull, by configuring one of **87 click-and-connect data connectors** in **Settings → Connectors**+Or pull, by configuring one of **90 click-and-connect data connectors** in **Settings → Connectors**— Splunk, Sentinel, Elastic, CrowdStrike, Okta, AWS and Kubernetes audit among those withvendor-specific normalization and setup docs([coverage](https://beenuar.github.io/AiSOC/docs/connectors/api-coverage)). Without a vendor profilediff --git a/RELEASES.md b/RELEASES.mdindex 1934b42d4..3ef17e1c9 100644--- a/RELEASES.md+++ b/RELEASES.md@@ -723,7 +723,7 @@ The full inventory (every file, env-var, and test count) lives under `[7.6.0]` i- First community contribution merged: [#135](https://github.com/beenuar/AiSOC/pull/135) (UEBA env-var alignment, closes [#134](https://github.com/beenuar/AiSOC/issues/134)). Every UEBA variable accepts both unprefixed (`DATABASE_URL`) and legacy (`UEBA_DATABASE_URL`) forms; unprefixed wins.**Stage 2 / Stage 3 platform additions** — landed alongside the architectural foundation above.-- **Wazuh Indexer ingest connector** — polls `wazuh-alerts-*` over HTTPX, paginates time-windowed queries, retries on 5xx; collapses Wazuh severity into the AiSOC ladder. Docs: [`apps/docs/docs/connectors/wazuh.md`](apps/docs/docs/connectors/wazuh.md). The connector registry now declares **87 first-party connectors**.+- **Wazuh Indexer ingest connector** — polls `wazuh-alerts-*` over HTTPX, paginates time-windowed queries, retries on 5xx; collapses Wazuh severity into the AiSOC ladder. Docs: [`apps/docs/docs/connectors/wazuh.md`](apps/docs/docs/connectors/wazuh.md). The connector registry now declares **90 first-party connectors**.- **auditd `file_tail` connector + `aisoc.rules` profile** — replaces the host-agent dependency for Linux endpoint visibility; 4 new detections pivot on the bundled `aisoc_*` audit keys. Docs: [`apps/docs/docs/connectors/auditd.md`](apps/docs/docs/connectors/auditd.md).- **Live Actions dispatcher** — generic vendor/capability surface so plugins can register executors against the in-tree taxonomy (`isolate_host`, `disable_user`, `block_ip`, …) without forking. Unknown pairs return a typed `LiveActionResult(FAILED, "executor_not_found")` — never a 500. Docs: [`apps/docs/docs/concepts/live-actions.md`](apps/docs/docs/concepts/live-actions.md).- **Deterministic NL → ES|QL / KQL / SPL translator** — replaces the template fallback in `/nl_query` with an IR + grammar validator; 50-pair gold eval set scores 100% syntactic, 100% semantic. Air-gapped by default; optional `gpt-4o-mini` enhancement falls back deterministically.@@ -732,7 +732,7 @@ The full inventory (every file, env-var, and test count) lives under `[7.6.0]` i- **Azure Container Apps + Postgres Flexible Server Terraform skeleton** — file-for-file mirror of the GCP skeleton for teams standardised on Azure. Container Apps for the three customer-visible services, VNet-integrated Postgres 16 + Azure Cache for Redis on private endpoints, Key Vault for secrets, ACR for images, and per-service user-assigned managed identities so each app pulls its own image and reads only its own secrets. Docs: [`apps/docs/docs/deployment/azure.md`](apps/docs/docs/deployment/azure.md).- **Blameless case post-mortem endpoint** — `GET /api/v1/cases/{case_id}/postmortem?format=json|html` produces a deterministic retrospective covering contributing factors, detection timing/gaps, response phases, blast radius, and action items. Analyst handles are explicitly redacted from the narrative. Docs: [`apps/docs/docs/operations/case-reports.md`](apps/docs/docs/operations/case-reports.md).- **Per-rule cross-fire FP gate** — `services/agents/tests/test_detection_fp_rate.py` replays every rule's `match_when` against every *other* rule's positive fixture; current corpus 816 native rules, worst FPR 0.49% (5% ceiling). Wired into `scripts/run_evals.py` as `suites.detection_fp_rate`.-- **Operator-facing documentation refresh** — new pages for [notifications](apps/docs/docs/operations/notifications.md), [plugin lifecycle](apps/docs/docs/plugins/lifecycle.md), and [credentials / vault rotation](apps/docs/docs/operations/credentials.md); v2.2 architecture diagram and the corrected **87-connector count** (now including Wazuh Indexer + auditd `file_tail`) rolled through every surface.+- **Operator-facing documentation refresh** — new pages for [notifications](apps/docs/docs/operations/notifications.md), [plugin lifecycle](apps/docs/docs/plugins/lifecycle.md), and [credentials / vault rotation](apps/docs/docs/operations/credentials.md); v2.2 architecture diagram and the corrected **90-connector count** (now including Wazuh Indexer + auditd `file_tail`) rolled through every surface.The full inventory (with file paths, env-var changes, and test counts) lives in the `[7.4.0]` section of [`CHANGELOG.md`](CHANGELOG.md).diff --git a/ROADMAP.md b/ROADMAP.mdindex 83ecb1683..c32989201 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 **335 rows — 330 GATED / 5 PARTIAL / 0 NO GATE**. Five rows are PARTIAL, each naming what closes it: "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; and "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real; and "every automatic closure of a production alert is checked against the current policy, grant and stop controls" until the live suite that proves it against real Postgres has been observed to pass on `main` rather than only in the pull request that added it. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. 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. 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 **336 rows — 331 GATED / 5 PARTIAL / 0 NO GATE**. Five rows are PARTIAL, each naming what closes it: "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; and "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real; and "every automatic closure of a production alert is checked against the current policy, grant and stop controls" until the live suite that proves it against real Postgres has been observed to pass on `main` rather than only in the pull request that added it. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. 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. 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@@ -483,7 +483,7 @@ Terraform skeleton equivalent to the existing AWS module.off `auditd_key` for sudoers / SSH / kernel-module / systemdtampering. 444-test full connectors suite green (excluding`test_scheduler.py` which needs the `apscheduler` dev dep).-- [x] Connector registry now declares **87 first-party connectors**;+- [x] Connector registry now declares **90 first-party connectors**;`pnpm marketplace:sync` rebuilt `marketplace/index.json` +`apps/web/public/marketplace/index.json`.diff --git a/apps/docs/docs/architecture.md b/apps/docs/docs/architecture.mdindex 3a621a6a6..3b804b45b 100644--- a/apps/docs/docs/architecture.md+++ b/apps/docs/docs/architecture.md@@ -61,7 +61,7 @@ curl -X POST http://localhost:8081/v1/ingest/batch \polls a vendor API on a schedule, decrypts that tenant's stored credentialsthrough the vault at poll time, and forwards the result to the same ingestendpoint. It runs in **CORE**, so a default install can pull as well as receive.-The registry is **now 87 connectors** — that figure is generated from+The registry is **now 90 connectors** — that figure is generated from`services/connectors/app/connectors/__init__.py` by[`scripts/generate_connector_count.py`](https://github.com/beenuar/AiSOC/blob/main/scripts/generate_connector_count.py),which fails CI if this sentence disagrees with the tree.diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex 6cf5fa29d..45c48bf36 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 330 rows+The last row is the one worth reading first. It is the honest index: 331 rows`GATED`, 5 `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 countcopied into prose goes stale in silence, which is whydiff --git a/apps/docs/docs/connectors/api-coverage.md b/apps/docs/docs/connectors/api-coverage.mdindex 5034de5f6..255fbdfc2 100644--- a/apps/docs/docs/connectors/api-coverage.md+++ b/apps/docs/docs/connectors/api-coverage.md@@ -27,7 +27,7 @@ This page is the canonical "what works where" reference. It is generated from thWhen a capability is not listed for a connector, the connector simply does not support it today — it is **not** a misconfiguration to surface. Adding a capability requires an explicit code change in that connector's `capabilities()` classmethod and matching method implementation.-## Coverage table — 87 connectors+## Coverage table — 90 connectorsThe matrix below is grouped by category. `OAuth (hosted)` indicates the connector is wired into the hosted OAuth marketplace flow (no client secret in tenant config). `Federated search` means the connector participates in the federated-query planner.diff --git a/apps/docs/docs/connectors/bamboohr.md b/apps/docs/docs/connectors/bamboohr.mdnew file mode 100644index 000000000..17528d5b9--- /dev/null+++ b/apps/docs/docs/connectors/bamboohr.md@@ -0,0 +1,47 @@+---+title: BambooHR+description: Connect BambooHR to AiSOC.+---++# BambooHR++{/* Generated by scripts/generate_connector_docs.py from the connector's+ schema(). Edit the schema, not this block. Prose between the HUMAN+ NOTES markers below is preserved across regeneration. */}++Employment status, start and last-day dates, manager, department and worker type from BambooHR, as triage context. Read-only; no personal or compensation data is stored.++- **Connector id:** `bamboohr`+- **Category:** hr++## Configuration++| Field | Label | Type | Required | Default | Notes |+|-------|-------|------|----------|---------|-------|+| `subdomain` | Company subdomain | string | yes | — | The first label of your BambooHR URL: acme.bamboohr.com -> acme. |+| `api_key` | API key | secret | yes | — | **encrypted at rest** · Generated from your BambooHR profile under API Keys. Needs directory and employee read access. |+| `max_employees` | Maximum employees per sync | number | no | `5000` | A ceiling on the per-employee reads one sync will make. |++:::note Credential handling+`api_key` is encrypted at rest by the credential vault before the row is written, and decrypted only at poll time. The value is never logged and never returned by the API — a read of the saved connector shows the field as set, not its contents. See [credential vault](../operations/credentials.md).+:::++## Capabilities++- `pull_workforce`++## Setup++1. In the console, go to **Connectors → Add connector** and pick **BambooHR**.+2. Fill in the fields above and run **Test connection**. The test is read-only and does not save anything.+3. Save. Polling starts on a jittered schedule within about a minute; the connector row shows `last_sync` once the first poll completes.++:::tip If `last_sync` stays empty+The first poll is the honest signal that the credential works. A connector that saves cleanly and never syncs usually means the credential lacks a scope the vendor requires for reads — check the connectors service log for the vendor's own error, which is passed through verbatim rather than summarised.+:::++<!-- BEGIN HUMAN NOTES -->++_Vendor-specific setup notes go here: which console page issues the credential, which scopes to grant, rate limits, and anything the schema cannot express. This section is preserved when the page is regenerated._++<!-- END HUMAN NOTES -->diff --git a/apps/docs/docs/connectors/endpoint-decision-matrix.md b/apps/docs/docs/connectors/endpoint-decision-matrix.mdindex 8730be165..c213cbde4 100644--- a/apps/docs/docs/connectors/endpoint-decision-matrix.md+++ b/apps/docs/docs/connectors/endpoint-decision-matrix.md@@ -189,7 +189,7 @@ can ingest today.## Related-- [Connectors overview](/docs/connectors) — the full 87-connector catalog.+- [Connectors overview](/docs/connectors) — the full 90-connector catalog.- [Hello, connector tutorial](/docs/connectors/hello-connector) — write yourown if none of these fit.- [Detection coverage](/docs/detections/coverage) — which endpoint detectionsdiff --git a/apps/docs/docs/connectors/index.md b/apps/docs/docs/connectors/index.mdindex fcf431746..8c28da0e8 100644--- a/apps/docs/docs/connectors/index.md+++ b/apps/docs/docs/connectors/index.md@@ -18,7 +18,7 @@ If your tool isn't in the catalog, see [Universal capture](/docs/connectors/univ## Catalog-The catalog ships with **87 connectors** out of the box, registered in [`services/connectors/app/connectors/__init__.py`](https://github.com/beenuar/AiSOC/blob/main/services/connectors/app/connectors/__init__.py). The list below is grouped by category; only a subset has dedicated walkthrough pages today (linked entries) — the rest follow the same schema-driven wizard described under [Adding a connector](#adding-a-connector).+The catalog ships with **90 connectors** out of the box, registered in [`services/connectors/app/connectors/__init__.py`](https://github.com/beenuar/AiSOC/blob/main/services/connectors/app/connectors/__init__.py). The list below is grouped by category; only a subset has dedicated walkthrough pages today (linked entries) — the rest follow the same schema-driven wizard described under [Adding a connector](#adding-a-connector).### Identitydiff --git a/apps/docs/docs/connectors/microsoft-intune.md b/apps/docs/docs/connectors/microsoft-intune.mdnew file mode 100644index 000000000..ad698ea65--- /dev/null+++ b/apps/docs/docs/connectors/microsoft-intune.md@@ -0,0 +1,47 @@+---+title: Microsoft Intune+description: Connect Microsoft Intune to AiSOC.+---++# Microsoft Intune++{/* Generated by scripts/generate_connector_docs.py from the connector's+ schema(). Edit the schema, not this block. Prose between the HUMAN+ NOTES markers below is preserved across regeneration. */}++Device owner, compliance state, OS version, encryption and threat-defence agent state from Microsoft Intune, as triage context. Read-only.++- **Connector id:** `microsoft_intune`+- **Category:** mdm++## Configuration++| Field | Label | Type | Required | Default | Notes |+|-------|-------|------|----------|---------|-------|+| `tenant_id` | Directory (tenant) ID | string | yes | — | — |+| `client_id` | Application (client) ID | string | yes | — | — |+| `client_secret` | Client secret | secret | yes | — | **encrypted at rest** · The app registration needs the application permission DeviceManagementManagedDevices.Read.All, granted with admin consent. |++:::note Credential handling+`client_secret` is encrypted at rest by the credential vault before the row is written, and decrypted only at poll time. The value is never logged and never returned by the API — a read of the saved connector shows the field as set, not its contents. See [credential vault](../operations/credentials.md).+:::++## Capabilities++- `pull_device_inventory`++## Setup++1. In the console, go to **Connectors → Add connector** and pick **Microsoft Intune**.+2. Fill in the fields above and run **Test connection**. The test is read-only and does not save anything.+3. Save. Polling starts on a jittered schedule within about a minute; the connector row shows `last_sync` once the first poll completes.++:::tip If `last_sync` stays empty+The first poll is the honest signal that the credential works. A connector that saves cleanly and never syncs usually means the credential lacks a scope the vendor requires for reads — check the connectors service log for the vendor's own error, which is passed through verbatim rather than summarised.+:::++<!-- BEGIN HUMAN NOTES -->++_Vendor-specific setup notes go here: which console page issues the credential, which scopes to grant, rate limits, and anything the schema cannot express. This section is preserved when the page is regenerated._++<!-- END HUMAN NOTES -->diff --git a/apps/docs/docs/connectors/rippling.md b/apps/docs/docs/connectors/rippling.mdnew file mode 100644index 000000000..c74a4763f--- /dev/null+++ b/apps/docs/docs/connectors/rippling.md@@ -0,0 +1,46 @@+---+title: Rippling+description: Connect Rippling to AiSOC.+---++# Rippling++{/* Generated by scripts/generate_connector_docs.py from the connector's+ schema(). Edit the schema, not this block. Prose between the HUMAN+ NOTES markers below is preserved across regeneration. */}++Employment status, start and end dates, manager, department and worker type from Rippling, as triage context. Read-only; compensation and personal data are never requested.++- **Connector id:** `rippling`+- **Category:** hr++## Configuration++| Field | Label | Type | Required | Default | Notes |+|-------|-------|------|----------|---------|-------|+| `api_token` | API token | secret | yes | — | **encrypted at rest** · A Rippling API token or installed-app access token carrying the workers.read scope. |+| `base_url` | API base URL | string | no | `https://rest.ripplingapis.com` | Override only if Rippling has given you a different regional host. |++:::note Credential handling+`api_token` is encrypted at rest by the credential vault before the row is written, and decrypted only at poll time. The value is never logged and never returned by the API — a read of the saved connector shows the field as set, not its contents. See [credential vault](../operations/credentials.md).+:::++## Capabilities++- `pull_workforce`++## Setup++1. In the console, go to **Connectors → Add connector** and pick **Rippling**.+2. Fill in the fields above and run **Test connection**. The test is read-only and does not save anything.+3. Save. Polling starts on a jittered schedule within about a minute; the connector row shows `last_sync` once the first poll completes.++:::tip If `last_sync` stays empty+The first poll is the honest signal that the credential works. A connector that saves cleanly and never syncs usually means the credential lacks a scope the vendor requires for reads — check the connectors service log for the vendor's own error, which is passed through verbatim rather than summarised.+:::++<!-- BEGIN HUMAN NOTES -->++_Vendor-specific setup notes go here: which console page issues the credential, which scopes to grant, rate limits, and anything the schema cannot express. This section is preserved when the page is regenerated._++<!-- END HUMAN NOTES -->diff --git a/apps/docs/docs/detections/coverage.md b/apps/docs/docs/detections/coverage.mdindex 8d9647752..5304f593b 100644--- a/apps/docs/docs/detections/coverage.md+++ b/apps/docs/docs/detections/coverage.md@@ -10,7 +10,7 @@ sidebar_position: 2# Detection Coverage-Generated: `2026-11-01T11:45:50Z`+Generated: `2026-11-01T19:20:24Z`This page is a **curated selection**, not the size of the corpus.It picks the highest-scoring rules per threat family from the setdiff --git a/apps/docs/docs/intro.md b/apps/docs/docs/intro.mdindex 339b28065..30cb53a41 100644--- a/apps/docs/docs/intro.md+++ b/apps/docs/docs/intro.md@@ -50,7 +50,7 @@ for the full list.## Capabilities-- **Click-and-connect cloud connectors** — pick from a **87-connector** catalog spanning EDR, SIEM, cloud, IAM, SaaS, VCS, network, ITSM, vuln, and email-security sources (CrowdStrike, SentinelOne, Cortex XDR, Splunk, Microsoft Sentinel, AWS Security Hub, Defender XDR, GCP Cloud Audit, GCP SCC, M365, Entra ID, Azure Activity, Google Workspace, Okta, Duo Security, Cloudflare, Tailscale, GitHub, Wiz, Snyk, Zscaler, Proofpoint, ServiceNow, Jira, 1Password, **Wazuh Indexer**, **auditd `file_tail`**, and 25 more — see [Architecture](./architecture)). Fill a schema-driven form, click `Test connection` for a live auth round-trip, and `Save & enable`. Secrets are encrypted at the application layer with a Fernet [`CredentialVault`](./operations/credentials) before they hit Postgres; an in-process APScheduler polls each enabled instance and pushes normalized OCSF events through to the ingest spine. Setup walkthroughs: [docs/connectors](./connectors).+- **Click-and-connect cloud connectors** — pick from a **90-connector** catalog spanning EDR, SIEM, cloud, IAM, SaaS, VCS, network, ITSM, vuln, and email-security sources (CrowdStrike, SentinelOne, Cortex XDR, Splunk, Microsoft Sentinel, AWS Security Hub, Defender XDR, GCP Cloud Audit, GCP SCC, M365, Entra ID, Azure Activity, Google Workspace, Okta, Duo Security, Cloudflare, Tailscale, GitHub, Wiz, Snyk, Zscaler, Proofpoint, ServiceNow, Jira, 1Password, **Wazuh Indexer**, **auditd `file_tail`**, and 25 more — see [Architecture](./architecture)). Fill a schema-driven form, click `Test connection` for a live auth round-trip, and `Save & enable`. Secrets are encrypted at the application layer with a Fernet [`CredentialVault`](./operations/credentials) before they hit Postgres; an in-process APScheduler polls each enabled instance and pushes normalized OCSF events through to the ingest spine. Setup walkthroughs: [docs/connectors](./connectors).- **Investigation Ledger** — every prompt, response, evidence citation, and tool call the agent emits is logged step-by-step and replayable on each case.- **Public eval harness** — alert reduction, measured against `RawAlert.correlation_key()` on a fixed noisy stream (a legacy in-test suite grouping on different dimensions is retained for continuity and does not describe this product), plus MITRE-tactic, investigation-completeness, and response-quality substrate self-consistency gates. Reproducible with one command and run in CI on every PR. The [eval harness page](./benchmark) documents what each suite does and does not measure.- **Ambient Copilot** — context-aware next-action suggestions on every alert, case, rule, and playbook page; one click runs the right agent tool with the right payload.diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex cdb156128..eda5ddfa6 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -105,6 +105,7 @@ const sidebars: SidebarsConfig = {"connectors/azure-defender","connectors/azure-entra","connectors/azure-event-hubs",+ "connectors/bamboohr","connectors/box","connectors/carbon-black","connectors/chronicle",@@ -140,6 +141,7 @@ const sidebars: SidebarsConfig = {"connectors/lacework","connectors/llm_usage","connectors/m365-audit",+ "connectors/microsoft-intune","connectors/microsoft-sentinel","connectors/mimecast","connectors/netskope",@@ -155,6 +157,7 @@ const sidebars: SidebarsConfig = {"connectors/qradar","connectors/qualys","connectors/rapid7-insightidr",+ "connectors/rippling","connectors/salesforce","connectors/securonix","connectors/sentinelone",diff --git a/apps/docs/static/llms-full.txt b/apps/docs/static/llms-full.txtindex 662fb5b51..7c3c0fab9 100644--- a/apps/docs/static/llms-full.txt+++ b/apps/docs/static/llms-full.txt@@ -172,12 +172,14 @@ Contribution guide: https://beenuar.github.io/AiSOC/docs/contributing/guidelines## Connectors-87 first-party connectors ship in the repository, by category:+90 first-party connectors ship in the repository, by category:- `ai`: 1- `cloud`: 18- `edr`: 10+- `hr`: 2- `iam`: 7+- `mdm`: 1- `ndr`: 2- `network`: 7- `saas`: 22diff --git a/apps/docs/static/llms.txt b/apps/docs/static/llms.txtindex c0afec7d6..decdece5f 100644--- a/apps/docs/static/llms.txt+++ b/apps/docs/static/llms.txt@@ -3,7 +3,7 @@<!-- Generated by scripts/generate_llms_txt.py. Do not edit by hand; run the script and commit the result. -->> AiSOC is an open-source, self-hostable AI Security Operations Center. It ingests-> security telemetry from 87 first-party connectors, normalises it to OCSF,+> security telemetry from 90 first-party connectors, normalises it to OCSF,> correlates it into alerts, and runs LLM agents that triage and investigate them.> Every agent decision is written to an investigation ledger, so the reasoning> behind a verdict can be replayed step by step. MIT licensed. Current version 21.0.0.@@ -54,7 +54,7 @@ Key facts a summary should get right:## Core capabilities-- [Connectors](https://beenuar.github.io/AiSOC/docs/connectors): 87 first-party integrations with per-connector setup guides.+- [Connectors](https://beenuar.github.io/AiSOC/docs/connectors): 90 first-party integrations with per-connector setup guides.- [Detections](https://beenuar.github.io/AiSOC/docs/detections/coverage): detection content, authoring modes, and MITRE ATT&CK coverage.- [Console](https://beenuar.github.io/AiSOC/docs/console/investigation-rail): the analyst workbench and investigation rail.- [Concepts](https://beenuar.github.io/AiSOC/docs/concepts/automation-maturity): the L0–L4 automation maturity model.diff --git a/apps/web/public/marketplace/curated.json b/apps/web/public/marketplace/curated.jsonindex aafc38173..9cbce3733 100644--- a/apps/web/public/marketplace/curated.json+++ b/apps/web/public/marketplace/curated.json@@ -1,7 +1,7 @@{"$schema": "https://aisoc.example.com/schemas/curated/v1.json","version": "1.0.0",- "generated": "2026-11-01T11:45:50Z",+ "generated": "2026-11-01T19:20:24Z","stats": {"considered": 2510,"eligible": 2499,diff --git a/apps/web/public/marketplace/index.json b/apps/web/public/marketplace/index.jsonindex faeeeddb5..d119ef249 100644--- a/apps/web/public/marketplace/index.json+++ b/apps/web/public/marketplace/index.json@@ -1,7 +1,7 @@{"$schema": "https://example.com/schemas/marketplace/v1.json","version": "1.0.0",- "generated": "2026-11-01T11:45:43Z",+ "generated": "2026-11-01T19:20:18Z","categories": [{"id": "playbooks",@@ -20,29 +20,29 @@}],"stats": {- "total": 7187,+ "total": 7190,"playbooks": 88,"playbook_packs": 63,"detections": 7019,- "plugins": 80,- "verified": 1066,+ "plugins": 83,+ "verified": 1069,"community": 1,"by_tier": {"beta": 7,"community": 1,"imported": 6113,- "stable": 1066+ "stable": 1069},"detections_by_tier": {"community": 1,"imported": 6113,"stable": 905},- "executable": 2702,+ "executable": 2705,"quarantined": 4485,"executable_detections": 2534,"reference_only_detections": 4485,- "not_a_detection": 168+ "not_a_detection": 171},"mitre_coverage": {"unique_techniques": 391,@@ -238551,6 +238551,32 @@"path": "plugins/azure-event-hubs/plugin.yaml","sha256": "985bb360b3ecb9cb252c48a84b321d85dfb454e9ac4483ef62353a0373d8fd10"},+ {+ "id": "bamboohr",+ "type": "plugin",+ "name": "BambooHR Connector",+ "description": "Employment status, start and last-day dates, manager, department and worker type from BambooHR, as triage context. Read-only. The employee endpoint is read with an explicit field list, so compensation, date of birth and home address are never requested, let alone stored.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "hr",+ "workforce",+ "identity",+ "context",+ "bamboohr"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/bamboohr.py",+ "min_aisoc_version": "21.0.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/bamboohr/plugin.yaml",+ "sha256": "c058cbc9927c18df427ae672d3c80930ed5b8c9437d2f6c2c8ada75b06382d6f"+ },{"id": "box","type": "plugin",@@ -239343,6 +239369,33 @@"path": "plugins/m365-audit/plugin.yaml","sha256": "ea68a64d4da29f71904de2452bff2d1e9d775f79938b24370bcd2f9a0c9a3722"},+ {+ "id": "microsoft_intune",+ "type": "plugin",+ "name": "Microsoft Intune Connector",+ "description": "Managed device context from Microsoft Intune through Microsoft Graph: device owner, compliance state, OS version, encryption and threat-defence agent state. Read-only; the app registration needs only the Read.All permission.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "mdm",+ "device",+ "compliance",+ "endpoint",+ "intune",+ "microsoft"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/microsoft_intune.py",+ "min_aisoc_version": "21.0.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/microsoft_intune/plugin.yaml",+ "sha256": "08595b41af02b6e3e2e7bcf0ae6b982e7fee7f3889fe881788a737540b98849a"+ },{"id": "mimecast","type": "plugin",@@ -239750,6 +239803,32 @@"path": "plugins/rapid7-insightidr/plugin.yaml","sha256": "d3eebd528cc17c4984879f33b71ae14af8a85fd317e715383e0ccee1ee916461"},+ {+ "id": "rippling",+ "type": "plugin",+ "name": "Rippling Connector",+ "description": "Employment status, start and end dates, manager, department and worker type from Rippling. Read-only. Only the department and employment-type relationships are expanded, so compensation and personal data are never fetched.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "hr",+ "workforce",+ "identity",+ "context",+ "rippling"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/rippling.py",+ "min_aisoc_version": "21.0.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/rippling/plugin.yaml",+ "sha256": "8499ceabc071dac745b545856a5e784b77fabf105229123f5a57d3454af2baf2"+ },{"id": "salesforce","type": "plugin",diff --git a/apps/web/src/data/connector-count.json b/apps/web/src/data/connector-count.jsonindex b3d430503..3ddd63b3a 100644--- a/apps/web/src/data/connector-count.json+++ b/apps/web/src/data/connector-count.json@@ -1,10 +1,12 @@{- "count": 87,+ "count": 90,"categories": {"ai": 1,"cloud": 18,"edr": 10,+ "hr": 2,"iam": 7,+ "mdm": 1,"ndr": 2,"network": 7,"saas": 22,diff --git a/apps/web/src/data/corpus-stats.json b/apps/web/src/data/corpus-stats.jsonindex 8531271e8..b181043cf 100644--- a/apps/web/src/data/corpus-stats.json+++ b/apps/web/src/data/corpus-stats.json@@ -3,10 +3,10 @@"windowed": 76,"onDisk": 7019,"quarantined": 4485,- "plugins": 80,+ "plugins": 83,"playbookPacks": 63,"playbooks": 88,- "marketplaceItems": 7187,+ "marketplaceItems": 7190,"categories": {"application": 78,"cloud": 235,diff --git a/docs/architecture/SYSTEM_DESIGN.md b/docs/architecture/SYSTEM_DESIGN.mdindex a0eef4af3..246aece31 100644--- a/docs/architecture/SYSTEM_DESIGN.md+++ b/docs/architecture/SYSTEM_DESIGN.md@@ -20,7 +20,7 @@ This document describes the end-to-end architecture of the AiSOC platform after┌─────────────────┐ ┌──────────────────────┐│ services/api │ │ services/connectors ││ inbox tokens + │ │ APScheduler poll │- │ HMAC webhooks │ │ 87 connector classes│+ │ HMAC webhooks │ │ 90 connector classes││ CEF / HEC / DNS│ │ push_case + status │└────────┬────────┘ └──────────┬───────────┘│ │@@ -91,7 +91,7 @@ This document describes the end-to-end architecture of the AiSOC platform after| `services/enrichment` | Go 1.21 | Per-IOC TTL-cached enrichment lookups | n/a || `services/fusion` | Python 3.11 | Simhash dedup → correlation → ML scoring → publish fused alerts | Background ML retrain on feedback || `services/api` | Python 3.11 | REST + WS, RBAC, case mgmt, rule engine, graph queries, ITSM webhook inbox, case fan-out | Schema migrations on boot |-| `services/connectors` | Python 3.11 | 87 connector classes, APScheduler poll, `push_case` / `push_status_change` for Jira & ServiceNow | CredentialVault decrypt at poll time |+| `services/connectors` | Python 3.11 | 90 connector classes, APScheduler poll, `push_case` / `push_status_change` for Jira & ServiceNow | CredentialVault decrypt at poll time || `services/agents` | Python 3.11 | LangGraph multi-agent investigation runs | Loads full ATT&CK STIX bundle on boot, optional Qdrant embed || `services/actions` | Python 3.11 | SOAR action execution with blast-radius gating | Approval workflows || `services/threatintel` | Python 3.11 | IOC/actor search API | APScheduler poll loop for TAXII/MISP/OTX/KEV |@@ -315,7 +315,7 @@ The following subsystems were added on top of the v2 design described above. The### 12.1 Connector Platform (`services/connectors`)-A first-class, in-process polling tier with **87 registered connector classes** spanning seven categories — `edr`, `siem`, `cloud`, `iam`, `saas`, `vcs`, `network`. Every connector subclasses `BaseConnector` and declares:+A first-class, in-process polling tier with **90 registered connector classes** spanning seven categories — `edr`, `siem`, `cloud`, `iam`, `saas`, `vcs`, `network`. Every connector subclasses `BaseConnector` and declares:* `schema()` — self-describing `ConnectorSchema(name, label, category, fields, oauth, default_poll_interval_seconds)` consumed by the web console for the connect form.* `capabilities()` — tuple of `Capability` enum values (`PULL_ALERTS`, `PUSH_CASE`, `PUSH_STATUS`, `FEDERATED_SEARCH`, …) that the orchestrator inspects at runtime.diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 90a8560d4..57a198d30 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -343,11 +343,12 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| A retro-hunt can be rehearsed over history with mutations withheld at the write boundary: dry-run sweeps run exactly as live (and still consume the sweep budget, because the scan happened) while matches come back as recorded proposals — no alert opens, no sighting row lands, no dedup counter moves | `services/api/app/services/retro_hunt/service.py`; `RETRO_HUNT_DRY_RUN` in `services/api/app/core/config.py` | `ci.yml :: Python — Tests` (api `test_retro_hunt.py` — `test_dry_run_records_the_proposal_and_writes_nothing` and `test_dry_run_does_not_mutate_an_existing_sighting` against a write-spying session, with `test_a_real_sweep_still_opens_the_alert` as the negative control proving the same sweep without the flag adds both rows) | core | GATED | — || The unsupported-claim detector gating auto-closure is measured, not merely asserted: a 16-case hand-annotated corpus pins its confusion matrix exactly in both directions, with the known miss recorded by id | `services/agents/app/confidence/claim_support.py`; `services/agents/tests/test_claim_support_measured.py` | `ci.yml :: Python — Tests` (agents `test_claim_support_measured.py` — TP 7 / FP 0 / FN 1 / TN 8 pinned exactly so a new miss and a new catch both fail until the pins move in the same commit; the recorded miss must stay missed or the test names the promotion; the zero-false-positive set covers negation, evidence-anchored approval and first-party context support — the analyst language production cannot afford to flag. The measurement found and drove a real fix: the MAINTENANCE claim pattern knew "scheduled scan" while the support keys did not) | core | GATED | regression-grade, stated in the corpus itself: the annotator authored the cases and had read the detector, so this is the tuned-corpus rate; an audit-grade rate needs cases authored by someone who has not read the patterns || Every public source address carries the anonymizer or hosting class a pinned local dataset gives it, with the dataset version that answered | `apps/docs/docs/operations/ip-classification.md`; `docs/decisions/0018-ip-class-dataset-provenance.md`; depth plan wave 2 item 1.6 | `ci.yml` ingest Go job (`internal/normalizer/ipclass_stamp_test.go`, driving the real `Normalize` rather than the classifier, so a classifier with no caller cannot satisfy it: a Tor exit relay and a cloud range read out of the committed dataset are classified, a documentation range and an unlisted public address are not, and no private address is ever classified) + `ci.yml :: Python — Tests` (fusion, `test_ip_class_projection.py`, 9 cases: the nested ingest stamp reaches the flat namespace the matcher reads, an unstamped event gains no key, a fixture carrying only a `src_ip` classifies through the vendored loader, the two agree on one address, and `enrich` does not consult the dataset when no rule asks) + `ci.yml :: python-lint` (`check_ip_class_dataset.py --self-test` then the gate: manifest digest and record count against the committed file, downloader and manifest naming the same sources, the class vocabulary agreeing across the downloader, the loader and the manifest, the vendored copy in sync, and **the Go classifier and the Python one returning identical answers over 400 sampled addresses**) | core | GATED | **Three of the five classes ship with no records.** `vpn`, `public_proxy` and `residential_proxy` have no redistributable source - the widely cited community list carries no licence file, verified as a 404 on its default branch - so they are tenant-supplied only, and tenant-supplied lists are **not yet implemented**. An unclassified address therefore means the dataset had no entry and never that the address is ordinary: the column is NULL, the rail renders nothing and no surface says "not an anonymizer". Measured at the pinned snapshot: 21,726 records, 1,228 `tor_exit` and 20,498 `hosting_provider` across 8 sources |+| A tenant's HR and managed-device context is kept current by a connector on a schedule, reaches triage on CORE, and is cited in the confidence basis | `apps/docs/docs/connectors/bamboohr.md`; `apps/docs/docs/connectors/rippling.md`; `apps/docs/docs/connectors/microsoft-intune.md`; depth plan wave 2 item 1.3 | `ci.yml :: Python — Tests` (connectors, `test_workforce_context.py`: registration in `_CONNECTOR_CLASSES`, every credential field declared `secret`, **the scheduler's poll path calling the workforce sync** -- the half that makes it real, because `import_context` had exactly one production caller and it was a manual POST -- and every vendor read replayed against a recorded, vendor-shaped payload through a mock transport with the request shape asserted as well as the parsed result, since a reader that does not name a column cannot recover it with an adapter) + `ci.yml :: Python — Tests` (agents, `test_identity_employment_facts.py`, 22 cases: tenure, departure proximity, contractor status and device compliance each asserted in **both** the prompt and the confidence basis, because a fact in one and not the other is either invisible to a reviewer or absent from the model; plus the direction of every absence -- a missing start date is not a new joiner, a missing end date is not "staying", an unmapped employment type is not an employee, and a device the MDM never evaluated is not a compliant one) + `ci.yml :: python-lint` (`check_rls_policy_shape.py`, `check_route_tenant_scope.py`, `check_tenant_query_predicates.py` over migration 131's two tables) | core | GATED | **No live vendor tenant has been exercised.** Every read is asserted against the vendor's current public reference, cited by URL in each connector module and verified on 2026-11-01; the shapes are recorded and synthetic, not captured from a live account. Workday and Kandji are **not built** and are recorded as blocked in `DEPTH2_PROGRESS.md` with what each needs. Data minimisation is in the request and the schema rather than in a filter: every one of these vendors returns compensation and personal data, none is requested, and migration 131 has no column that could hold one |## Summary-- Total: 335-- GATED: 330+- Total: 336+- GATED: 331- PARTIAL: 5- NO GATE: 0diff --git a/docs/connectors/conformance-matrix.md b/docs/connectors/conformance-matrix.mdindex 61820065c..46654fd87 100644--- a/docs/connectors/conformance-matrix.md+++ b/docs/connectors/conformance-matrix.md@@ -6,7 +6,7 @@> async coroutines, valid capabilities, secret fields marked `secret`).> Live-vendor sandbox smoke is a separate wave; this gates the contract.-**87 / 87 connectors conform** to the runtime contract.+**90 / 90 connectors conform** to the runtime contract.| connector | category | fields | vaulted | caps | test_connection | fetch_alerts | normalize ||-----------|----------|-------:|--------:|-----:|:---------------:|:------------:|:---------:|@@ -23,6 +23,7 @@| azure_defender | edr | 3 | 1 | 5 | ✅ | ✅ | ✅ || azure_entra | iam | 3 | 1 | 2 | ✅ | ✅ | ✅ || azure_event_hubs | cloud | 6 | 1 | 2 | ✅ | ✅ | ✅ |+| bamboohr | hr | 3 | 1 | 1 | ✅ | ✅ | — || box | saas | 1 | 1 | 3 | ✅ | ✅ | ✅ || carbon_black | edr | 4 | 1 | 6 | ✅ | ✅ | ✅ || chronicle | siem | 4 | 1 | 5 | ✅ | ✅ | ✅ |@@ -58,6 +59,7 @@| lacework | cloud | 4 | 1 | 5 | ✅ | ✅ | ✅ || llm_usage | saas | 4 | 1 | 2 | ✅ | ✅ | ✅ || m365_audit | saas | 3 | 1 | 1 | ✅ | ✅ | ✅ |+| microsoft_intune | mdm | 3 | 1 | 1 | ✅ | ✅ | — || microsoft_sentinel | siem | 6 | 1 | 2 | ✅ | ✅ | ✅ || mimecast | saas | 3 | 1 | 4 | ✅ | ✅ | ✅ || netskope | network | 3 | 1 | 3 | ✅ | ✅ | ✅ |@@ -73,6 +75,7 @@| qradar | siem | 3 | 1 | 2 | ✅ | ✅ | ✅ || qualys | cloud | 3 | 1 | 3 | ✅ | ✅ | ✅ || rapid7_insightidr | siem | 2 | 1 | 4 | ✅ | ✅ | ✅ |+| rippling | hr | 2 | 1 | 1 | ✅ | ✅ | — || salesforce | saas | 4 | 2 | 4 | ✅ | ✅ | ✅ || securonix | siem | 3 | 1 | 2 | ✅ | ✅ | ✅ || sentinelone | edr | 3 | 1 | 4 | ✅ | ✅ | ✅ |diff --git a/marketplace/curated.json b/marketplace/curated.jsonindex aafc38173..9cbce3733 100644--- a/marketplace/curated.json+++ b/marketplace/curated.json@@ -1,7 +1,7 @@{"$schema": "https://aisoc.example.com/schemas/curated/v1.json","version": "1.0.0",- "generated": "2026-11-01T11:45:50Z",+ "generated": "2026-11-01T19:20:24Z","stats": {"considered": 2510,"eligible": 2499,diff --git a/marketplace/index.json b/marketplace/index.jsonindex faeeeddb5..d119ef249 100644--- a/marketplace/index.json+++ b/marketplace/index.json@@ -1,7 +1,7 @@{"$schema": "https://example.com/schemas/marketplace/v1.json","version": "1.0.0",- "generated": "2026-11-01T11:45:43Z",+ "generated": "2026-11-01T19:20:18Z","categories": [{"id": "playbooks",@@ -20,29 +20,29 @@}],"stats": {- "total": 7187,+ "total": 7190,"playbooks": 88,"playbook_packs": 63,"detections": 7019,- "plugins": 80,- "verified": 1066,+ "plugins": 83,+ "verified": 1069,"community": 1,"by_tier": {"beta": 7,"community": 1,"imported": 6113,- "stable": 1066+ "stable": 1069},"detections_by_tier": {"community": 1,"imported": 6113,"stable": 905},- "executable": 2702,+ "executable": 2705,"quarantined": 4485,"executable_detections": 2534,"reference_only_detections": 4485,- "not_a_detection": 168+ "not_a_detection": 171},"mitre_coverage": {"unique_techniques": 391,@@ -238551,6 +238551,32 @@"path": "plugins/azure-event-hubs/plugin.yaml","sha256": "985bb360b3ecb9cb252c48a84b321d85dfb454e9ac4483ef62353a0373d8fd10"},+ {+ "id": "bamboohr",+ "type": "plugin",+ "name": "BambooHR Connector",+ "description": "Employment status, start and last-day dates, manager, department and worker type from BambooHR, as triage context. Read-only. The employee endpoint is read with an explicit field list, so compensation, date of birth and home address are never requested, let alone stored.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "hr",+ "workforce",+ "identity",+ "context",+ "bamboohr"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/bamboohr.py",+ "min_aisoc_version": "21.0.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/bamboohr/plugin.yaml",+ "sha256": "c058cbc9927c18df427ae672d3c80930ed5b8c9437d2f6c2c8ada75b06382d6f"+ },{"id": "box","type": "plugin",@@ -239343,6 +239369,33 @@"path": "plugins/m365-audit/plugin.yaml","sha256": "ea68a64d4da29f71904de2452bff2d1e9d775f79938b24370bcd2f9a0c9a3722"},+ {+ "id": "microsoft_intune",+ "type": "plugin",+ "name": "Microsoft Intune Connector",+ "description": "Managed device context from Microsoft Intune through Microsoft Graph: device owner, compliance state, OS version, encryption and threat-defence agent state. Read-only; the app registration needs only the Read.All permission.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "mdm",+ "device",+ "compliance",+ "endpoint",+ "intune",+ "microsoft"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/microsoft_intune.py",+ "min_aisoc_version": "21.0.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/microsoft_intune/plugin.yaml",+ "sha256": "08595b41af02b6e3e2e7bcf0ae6b982e7fee7f3889fe881788a737540b98849a"+ },{"id": "mimecast","type": "plugin",@@ -239750,6 +239803,32 @@"path": "plugins/rapid7-insightidr/plugin.yaml","sha256": "d3eebd528cc17c4984879f33b71ae14af8a85fd317e715383e0ccee1ee916461"},+ {+ "id": "rippling",+ "type": "plugin",+ "name": "Rippling Connector",+ "description": "Employment status, start and end dates, manager, department and worker type from Rippling. Read-only. Only the department and employment-type relationships are expanded, so compensation and personal data are never fetched.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "hr",+ "workforce",+ "identity",+ "context",+ "rippling"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/rippling.py",+ "min_aisoc_version": "21.0.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/rippling/plugin.yaml",+ "sha256": "8499ceabc071dac745b545856a5e784b77fabf105229123f5a57d3454af2baf2"+ },{"id": "salesforce","type": "plugin",diff --git a/packages/types/src/generated/connector-types.json b/packages/types/src/generated/connector-types.jsonindex 39a853df0..060f742f2 100644--- a/packages/types/src/generated/connector-types.json+++ b/packages/types/src/generated/connector-types.json@@ -10,8 +10,8 @@"aliases": 2,"canonical-fold": 5,"profile": 6,- "registry": 87,- "total": 98+ "registry": 90,+ "total": 101},"generatedFrom": ["services/connectors/app/connectors/__init__.py",@@ -34,6 +34,7 @@"azure_defender","azure_entra","azure_event_hubs",+ "bamboohr","box","carbon_black","chronicle",@@ -72,6 +73,7 @@"lacework","llm_usage","m365_audit",+ "microsoft_intune","microsoft_sentinel","mimecast","netskope",@@ -89,6 +91,7 @@"qradar","qualys","rapid7_insightidr",+ "rippling","salesforce","securonix","sentinelone",@@ -134,6 +137,7 @@"azure_defender": "registry","azure_entra": "registry","azure_event_hubs": "registry",+ "bamboohr": "registry","box": "registry","carbon_black": "registry","chronicle": "registry",@@ -172,6 +176,7 @@"lacework": "registry","llm_usage": "registry","m365_audit": "registry",+ "microsoft_intune": "registry","microsoft_sentinel": "registry","mimecast": "registry","netskope": "registry",@@ -189,6 +194,7 @@"qradar": "registry","qualys": "registry","rapid7_insightidr": "registry",+ "rippling": "registry","salesforce": "registry","securonix": "registry","sentinelone": "registry",diff --git a/packages/types/src/generated/connector-types.ts b/packages/types/src/generated/connector-types.tsindex 231711788..93a8aef4c 100644--- a/packages/types/src/generated/connector-types.ts+++ b/packages/types/src/generated/connector-types.ts@@ -4,10 +4,10 @@// Every `connector_type` the ingest normalizer resolves, derived from the// registry that decides what the platform can ingest://-// 87 connector ids declared in services/connectors (_CONNECTOR_CLASSES)+// 90 connector ids declared in services/connectors (_CONNECTOR_CLASSES)// 6 connectorProfiles keys no connector declares under that spelling// 5 alternate spellings connectorTypeCanonical folds onto a declared id-// 98 total+// 101 total//// The union used to be written by hand, which is how ten members came to name// nothing: `ibm_qradar` reached no profile and no connector, so strict mode@@ -32,6 +32,7 @@ export const CONNECTOR_TYPES = ["azure_defender", // registry"azure_entra", // registry"azure_event_hubs", // registry+ "bamboohr", // registry"box", // registry"carbon_black", // registry"chronicle", // registry@@ -70,6 +71,7 @@ export const CONNECTOR_TYPES = ["lacework", // registry"llm_usage", // registry"m365_audit", // registry+ "microsoft_intune", // registry"microsoft_sentinel", // registry"mimecast", // registry"netskope", // registry@@ -87,6 +89,7 @@ export const CONNECTOR_TYPES = ["qradar", // registry"qualys", // registry"rapid7_insightidr", // registry+ "rippling", // registry"salesforce", // registry"securonix", // registry"sentinelone", // registrydiff --git a/plans/aisoc_depth_wave2.plan.md b/plans/aisoc_depth_wave2.plan.mdindex e89d7a969..c209d5b63 100644--- a/plans/aisoc_depth_wave2.plan.md+++ b/plans/aisoc_depth_wave2.plan.md@@ -22,7 +22,7 @@ todos:status: completed- id: p1-3-hr-device-contextcontent: "Phase 1.3: HR connectors (Workday, BambooHR, Rippling) and MDM connectors (Intune, Kandji, Jamf promoted from plugin) feeding employment status, manager, tenure, device owner and compliance into the identity graph and triage"- status: pending+ status: in_progress- id: p1-4-sub-principal-baselinescontent: "Phase 1.4: baselines per sub-principal (OAuth app, token, service account, AI agent acting for a human); GitHub tokens joined to scopes and classified by cadence"status: completed@@ -127,7 +127,7 @@ todos:status: pending- id: p8-4-scale-evidencecontent: "Phase 8.4: first depth plan 4.4 cloud-hardware run and 4.5 managed-cluster run, published or recorded as blocked"- status: pending+ status: completed- id: p9-1-voice-that-actscontent: "Phase 9.1: build on-device voice input behind the existing voice.ts interface, then read-back and voice approval of a pending response with biometric step-up; no audio leaves the device"status: pendingdiff --git a/plugins/bamboohr/plugin.yaml b/plugins/bamboohr/plugin.yamlnew file mode 100644index 000000000..cd4ce9486--- /dev/null+++ b/plugins/bamboohr/plugin.yaml@@ -0,0 +1,29 @@+id: bamboohr+name: BambooHR Connector+version: "1.0.0"+plugin_type: connector+tier: stable+description: >+ Employment status, start and last-day dates, manager, department and worker+ type from BambooHR, as triage context. Read-only. The employee endpoint is+ read with an explicit field list, so compensation, date of birth and home+ address are never requested, let alone stored.+author: AiSOC Core Team+tags: [hr, workforce, identity, context, bamboohr]+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/bamboohr.py+license: MIT+min_aisoc_version: "21.0.0"+config_schema:+ type: object+ required: [subdomain, api_key]+ properties:+ subdomain:+ type: string+ description: The first label of your BambooHR URL. acme.bamboohr.com gives acme.+ api_key:+ type: string+ description: API key from your BambooHR profile. Needs directory and employee read access.+ secret: true+ max_employees:+ type: integer+ description: Ceiling on the per-employee reads one sync will make. Defaults to 5000.diff --git a/plugins/microsoft_intune/plugin.yaml b/plugins/microsoft_intune/plugin.yamlnew file mode 100644index 000000000..accb06803--- /dev/null+++ b/plugins/microsoft_intune/plugin.yaml@@ -0,0 +1,28 @@+id: microsoft_intune+name: Microsoft Intune Connector+version: "1.0.0"+plugin_type: connector+tier: stable+description: >+ Managed device context from Microsoft Intune through Microsoft Graph: device+ owner, compliance state, OS version, encryption and threat-defence agent+ state. Read-only; the app registration needs only the Read.All permission.+author: AiSOC Core Team+tags: [mdm, device, compliance, endpoint, intune, microsoft]+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/microsoft_intune.py+license: MIT+min_aisoc_version: "21.0.0"+config_schema:+ type: object+ required: [tenant_id, client_id, client_secret]+ properties:+ tenant_id:+ type: string+ description: Directory (tenant) ID of the Entra tenant.+ client_id:+ type: string+ description: Application (client) ID of the app registration.+ client_secret:+ type: string+ description: Client secret for the app registration. Needs DeviceManagementManagedDevices.Read.All with admin consent.+ secret: truediff --git a/plugins/rippling/plugin.yaml b/plugins/rippling/plugin.yamlnew file mode 100644index 000000000..bcec92a68--- /dev/null+++ b/plugins/rippling/plugin.yaml@@ -0,0 +1,26 @@+id: rippling+name: Rippling Connector+version: "1.0.0"+plugin_type: connector+tier: stable+description: >+ Employment status, start and end dates, manager, department and worker type+ from Rippling. Read-only. Only the department and employment-type+ relationships are expanded, so compensation and personal data are never+ fetched.+author: AiSOC Core Team+tags: [hr, workforce, identity, context, rippling]+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/rippling.py+license: MIT+min_aisoc_version: "21.0.0"+config_schema:+ type: object+ required: [api_token]+ properties:+ api_token:+ type: string+ description: Rippling API token or installed-app access token carrying the workers.read scope.+ secret: true+ base_url:+ type: string+ description: API base URL. Defaults to https://rest.ripplingapis.com.diff --git a/scripts/check_connector_profiles.py b/scripts/check_connector_profiles.pyindex ebde8241e..1a85c83d0 100644--- a/scripts/check_connector_profiles.py+++ b/scripts/check_connector_profiles.py@@ -252,6 +252,31 @@ def _class_connector_id(tree: ast.Module) -> str | None:return None+def _emits_no_events(tree: ast.Module) -> bool:+ """Whether `fetch_alerts` is a declared no-op returning an empty list.++ A context-only connector -- an HR system or an MDM, which report state+ rather than security events -- is pollable by the ordinary scheduler and+ writes through the context-import path, never through ingest. It has no+ events for a normalization profile to describe, so the hazard the+ strict-mode check exists for cannot reach it: there is nothing to reject+ and nothing to resolve to a bare title.++ Deliberately narrow. Only a body whose single statement is `return []`+ (after an optional docstring) counts, so a connector that fetches+ anything at all still needs a profile. A connector that later starts+ emitting stops matching this and the gate asks for its profile again.+ """+ functions = (ast.FunctionDef, ast.AsyncFunctionDef)+ for fn in (n for n in ast.walk(tree) if isinstance(n, functions) and n.name == "fetch_alerts"):+ body = [n for n in fn.body if not (isinstance(n, ast.Expr) and isinstance(n.value, ast.Constant))]+ if len(body) != 1:+ return False+ stmt = body[0]+ return isinstance(stmt, ast.Return) and isinstance(stmt.value, ast.List) and not stmt.value.elts+ return False++def _emits_canonical_envelope(tree: ast.Module) -> bool:"""Whether the connector's normalized event carries `raw_event` + `source`.@@ -278,7 +303,14 @@ def _emits_canonical_envelope(tree: ast.Module) -> bool:def parse_connectors(directory: Path) -> dict[str, bool]:- """connector_id -> emits a canonical envelope."""+ """connector_id -> reaches strict mode.++ True when the connector emits a canonical envelope, and also true when+ it emits no events at all: both mean strict mode has nothing to reject.+ The two are collapsed here because every caller asks the same question+ -- "can an event from this connector fail to resolve" -- and for a+ context-only connector the answer is that there is no event.+ """out: dict[str, bool] = {}for path in sorted(directory.glob("*.py")):if path.name in {"__init__.py", "base.py"}:@@ -286,7 +318,7 @@ def parse_connectors(directory: Path) -> dict[str, bool]:tree = ast.parse(path.read_text(encoding="utf-8"))connector_id = _class_connector_id(tree)if connector_id:- out[connector_id] = _emits_canonical_envelope(tree)+ out[connector_id] = _emits_canonical_envelope(tree) or _emits_no_events(tree)return outdiff --git a/scripts/check_ocsf_class_coverage.py b/scripts/check_ocsf_class_coverage.pyindex 7ebb09032..bb64a8543 100644--- a/scripts/check_ocsf_class_coverage.py+++ b/scripts/check_ocsf_class_coverage.py@@ -45,6 +45,13 @@ direction things actually change slips past while the gate prints OK.map is archived to the lake and never alerts, silently, which isexactly how the borrowed ``splunk_enterprise`` profile broke 26connectors.+ CONTEXT every entry claiming ``contextOnly`` is telling the truth. A+ context-only connector emits no ingest events at all, so it+ carries no generic-mapping debt and is counted apart from the+ ceiling below. That exemption is only worth having if it cannot+ be taken by writing the words: the claim is checked against the+ connector's own ``fetch_alerts``, and one that can emit anything+ fails **and stays counted**, so a false claim buys no headroom.It also reports the **count of connector types on the generic mapping**, whichis the figure the depth plan's Phase 2 is graded against, and holds it with@@ -94,6 +101,14 @@ CONNECTORS_REL = Path("services/connectors/app/connectors")#:#: The number that must stay at zero is `unclassified`, which is a hard#: failure rather than a ceiling: every one of the 42 below carries a reason.+#:+#: Connectors that emit no ingest events at all are **not** counted here and+#: do not consume the ceiling. The bucket measures one thing — events taking+#: the lenient default — and a connector whose `fetch_alerts` returns an empty+#: list has no event to take it. Counting those would make the figure grow for+#: a reason it does not describe, and the honest response to that is to count+#: them separately, not to raise the number. See `contextOnly`, which is+#: verified against the connector rather than believed.MAX_GENERIC = 42#: OCSF categories whose events fusion promotes unconditionally.@@ -145,7 +160,7 @@ def parse_classes(src: str, consts: dict[str, int]) -> dict[int, tuple[str, int]def parse_connector_classes(src: str, consts: dict[str, int]) -> dict[str, dict]:- """connector type -> {"class_uid": int|None, "reason": str|None}."""+ """connector type -> {"class_uid": int|None, "reason": str|None, "context_only": bool}."""block = _go_block(src, "var connectorOCSFClass = map[string]connectorClass{")out: dict[str, dict] = {}for name, body in re.findall(r'^\t"([a-z0-9_]+)":\s*\{([^}]*)\},?$', block, re.MULTILINE):@@ -157,7 +172,11 @@ def parse_connector_classes(src: str, consts: dict[str, int]) -> dict[str, dict]if key not in consts:raise GateError(f"connector {name!r} names class constant {key!r}, which is not declared")class_uid = consts[key]- out[name] = {"class_uid": class_uid, "reason": reason_match.group(1) if reason_match else None}+ out[name] = {+ "class_uid": class_uid,+ "reason": reason_match.group(1) if reason_match else None,+ "context_only": bool(re.search(r"contextOnly:\s*true\b", body)),+ }return out@@ -209,30 +228,72 @@ def parse_canonical_severity_promotes(src: str) -> bool:# --------------------------------------------------------------------------# Python side# ---------------------------------------------------------------------------def parse_declared_connectors(directory: Path) -> set[str]:- """Every `connector_id` the connectors service declares."""- out: set[str] = set()+def _connector_id(cls: ast.ClassDef) -> str | None:+ """The `connector_id` a class declares, or None."""+ for stmt in cls.body:+ # The value is bound in each branch rather than read off+ # `stmt` afterwards: past the if/elif the name is still an+ # `ast.stmt`, which has no `.value`, so the later read was+ # four unchecked attribute accesses that happened to be safe.+ if isinstance(stmt, ast.Assign):+ target = next((getattr(t, "id", None) for t in stmt.targets), None)+ value: ast.expr | None = stmt.value+ elif isinstance(stmt, ast.AnnAssign):+ target = getattr(stmt.target, "id", None)+ value = stmt.value+ else:+ continue+ if target == "connector_id" and isinstance(value, ast.Constant) and isinstance(value.value, str) and value.value:+ return value.value+ return None+++def _connector_classes(directory: Path):+ """Every (connector_id, ClassDef) the connectors service declares."""for path in sorted(directory.glob("*.py")):if path.name in {"__init__.py", "base.py"}:continuetree = ast.parse(path.read_text(encoding="utf-8"))for cls in (n for n in ast.walk(tree) if isinstance(n, ast.ClassDef)):- for stmt in cls.body:- # The value is bound in each branch rather than read off- # `stmt` afterwards: past the if/elif the name is still an- # `ast.stmt`, which has no `.value`, so the later read was- # four unchecked attribute accesses that happened to be safe.- if isinstance(stmt, ast.Assign):- target = next((getattr(t, "id", None) for t in stmt.targets), None)- value: ast.expr | None = stmt.value- elif isinstance(stmt, ast.AnnAssign):- target = getattr(stmt.target, "id", None)- value = stmt.value- else:- continue- if target == "connector_id" and isinstance(value, ast.Constant) and isinstance(value.value, str) and value.value:- out.add(value.value)- return out+ name = _connector_id(cls)+ if name is not None:+ yield name, cls+++def parse_declared_connectors(directory: Path) -> set[str]:+ """Every `connector_id` the connectors service declares."""+ return {name for name, _ in _connector_classes(directory)}+++def _emits_events(cls: ast.ClassDef) -> bool:+ """Whether this connector's `fetch_alerts` can hand ingest an event.++ Conservative in one direction on purpose. Anything the parser cannot+ *prove* returns nothing but an empty list counts as emitting: a connector+ is only ever credited with emitting nothing, never penalised for it, so+ the unproven case falls on the side that keeps it counted against the+ ceiling. An inherited or absent `fetch_alerts` therefore reads as+ emitting, which is also what the base class does.+ """+ fn = next(+ (s for s in cls.body if isinstance(s, ast.FunctionDef | ast.AsyncFunctionDef) and s.name == "fetch_alerts"),+ None,+ )+ if fn is None:+ return True+ # A generator hands values out without returning them, so `return` tells+ # us nothing about what it emits.+ if any(isinstance(n, ast.Yield | ast.YieldFrom) for n in ast.walk(fn)):+ return True+ returns = [n for n in ast.walk(fn) if isinstance(n, ast.Return)]+ if not returns:+ return True+ return not all(isinstance(n.value, ast.List) and not n.value.elts for n in returns)+++def parse_connector_emission(directory: Path) -> dict[str, bool]:+ """connector type -> whether its `fetch_alerts` can emit an event."""+ return {name: _emits_events(cls) for name, cls in _connector_classes(directory)}# --------------------------------------------------------------------------@@ -243,6 +304,7 @@ def evaluate(classes: dict[int, tuple[str, int]],connector_classes: dict[str, dict],profiles: dict[str, dict],+ emits_events: dict[str, bool],canonical_severity_promotes: bool,max_generic: int,check_count: bool,@@ -289,10 +351,33 @@ def evaluate("for a reviewer to disagree with it",))+ # CONTEXT. The exemption from the ceiling is only worth having if it+ # is checked. Both arms leave the connector counted as generic below,+ # so a claim the tree does not support costs the author a failure and+ # gains them nothing.+ if entry["context_only"]:+ if entry["class_uid"] is not None:+ failures.append(+ (+ "context-only-with-class",+ f"{name!r} is marked context-only and also names a class; a connector that emits no "+ "event has nothing to carry a class, so one of the two is not what happens",+ )+ )+ elif emits_events.get(name, True):+ failures.append(+ (+ "context-only-emits-events",+ f"{name!r} is marked context-only, but its fetch_alerts can return an event. Those "+ "events reach the normalizer and take the lenient 2001 default, which is the debt the "+ "ceiling counts: give it a class, or stop claiming it emits nothing",+ )+ )# PY -> GO. The direction the defect lived in: a declared connector with# no decision at all, reaching the default silently.generic: list[str] = []+ context_only: list[str] = []for name in sorted(declared):decision = connector_classes.get(name)if decision is None:@@ -306,7 +391,12 @@ def evaluate()generic.append(name)elif decision["class_uid"] is None:- generic.append(name)+ # Only a *verified* claim leaves the bucket. An unverified one+ # has already been reported above and is still counted here.+ if decision["context_only"] and not emits_events.get(name, True):+ context_only.append(name)+ else:+ generic.append(name)# PROMOTION. A class a connector is mapped to must be able to promote.for name, entry in sorted(connector_classes.items()):@@ -366,6 +456,7 @@ def evaluate("generic_connectors": generic,"generic_with_reason": sorted(set(generic) - set(unclassified)),"unclassified": unclassified,+ "context_only": context_only,"classes": len(classes),}@@ -397,10 +488,11 @@ def load(root: Path) -> dict:"classes": parse_classes(classes_src, consts),"connector_classes": parse_connector_classes(classes_src, consts),"profiles": parse_profile_classes(normalizer_src),+ "emits_events": parse_connector_emission(connectors_dir),"canonical_severity_promotes": parse_canonical_severity_promotes(normalizer_src),}# An empty parse means the format moved, not that the tree is clean.- for name in ("declared", "classes", "connector_classes", "profiles"):+ for name in ("declared", "classes", "connector_classes", "profiles", "emits_events"):if not data[name]:raise GateError(f"parsed zero {name} — refusing to report a clean tree from an empty read")if not data["canonical_severity_promotes"]:@@ -459,6 +551,9 @@ def main(argv: list[str] | None = None) -> int:)if stats["generic_connectors"]:print(f" {', '.join(stats['generic_connectors'])}")+ if stats["context_only"]:+ print(f" {len(stats['context_only'])} context-only, emitting no ingest event (not counted above)")+ print(f" {', '.join(stats['context_only'])}")print()if failures:print(f"FAIL — {len(failures)} finding(s):")@@ -504,31 +599,35 @@ def self_test(root: Path) -> int:("GO -> PY: a table entry naming a connector that does not exist","class-names-nothing",- mutate(connector_classes=lambda d: d.update({"acme_xdr_9000": {"class_uid": 4001, "reason": None}})),+ mutate(connector_classes=lambda d: d.update({"acme_xdr_9000": {"class_uid": 4001, "reason": None, "context_only": False}})),MAX_GENERIC,),("GO -> PY: an entry carrying both a class and a reason","class-entry-ambiguous",- mutate(connector_classes=lambda d: d.update({"okta": {"class_uid": 3002, "reason": "also stays generic somehow"}})),+ mutate(+ connector_classes=lambda d: d.update(+ {"okta": {"class_uid": 3002, "reason": "also stays generic somehow", "context_only": False}}+ )+ ),MAX_GENERIC,),("GO -> PY: an entry carrying neither","class-entry-empty",- mutate(connector_classes=lambda d: d.update({"okta": {"class_uid": None, "reason": None}})),+ mutate(connector_classes=lambda d: d.update({"okta": {"class_uid": None, "reason": None, "context_only": False}})),MAX_GENERIC + 1,),("GO -> PY: a class uid outside the service's closed set","class-uid-unknown",- mutate(connector_classes=lambda d: d.update({"okta": {"class_uid": 9999, "reason": None}})),+ mutate(connector_classes=lambda d: d.update({"okta": {"class_uid": 9999, "reason": None, "context_only": False}})),MAX_GENERIC,),("GO -> PY: a reason too thin to review","class-reason-thin",- mutate(connector_classes=lambda d: d.update({"splunk": {"class_uid": None, "reason": "noisy"}})),+ mutate(connector_classes=lambda d: d.update({"splunk": {"class_uid": None, "reason": "noisy", "context_only": False}})),MAX_GENERIC + 1,),(@@ -563,6 +662,34 @@ def self_test(root: Path) -> int:mutate(declared=lambda s: s.add("acme_telemetry")),MAX_GENERIC,),+ (+ "CONTEXT: a context-only claim contradicted by the connector's own fetch_alerts",+ "context-only-emits-events",+ mutate(emits_events=lambda d: d.update({"bamboohr": True})),+ MAX_GENERIC + 1,+ ),+ (+ "CONTEXT: an entry claiming context-only and a class at once",+ "context-only-with-class",+ mutate(connector_classes=lambda d: d.update({"okta": {"class_uid": 3002, "reason": None, "context_only": True}})),+ MAX_GENERIC,+ ),+ # The control that makes the exemption safe to have at all: claiming+ # it without the tree supporting the claim must not buy the author+ # room under the ceiling. If this ever stops firing, `contextOnly`+ # has become a way to opt out of the count by typing a word.+ (+ "COUNT: an unsupported context-only claim buys no ceiling headroom",+ "generic-count-grew",+ mutate(+ declared=lambda s: s.add("acme_telemetry"),+ connector_classes=lambda d: d.update(+ {"acme_telemetry": {"class_uid": None, "reason": "claims to emit nothing, but does", "context_only": True}}+ ),+ emits_events=lambda d: d.update({"acme_telemetry": True}),+ ),+ MAX_GENERIC,+ ),]print(f"self-test against {root}")diff --git a/services/actions/app/live_actions/capabilities.py b/services/actions/app/live_actions/capabilities.pyindex 651818a83..7841f5186 100644--- a/services/actions/app/live_actions/capabilities.py+++ b/services/actions/app/live_actions/capabilities.py@@ -36,6 +36,12 @@ KNOWN_CAPABILITIES: frozenset[str] = frozenset("pull_logs","pull_pcap","pull_vulnerabilities",+ # Context rather than events: an HR system and an MDM report+ # slowly-changing state, which the connector scheduler materialises+ # into workforce_members and workforce_devices instead of pushing+ # through ingest.+ "pull_workforce",+ "pull_device_inventory",# QUERY"query_logs","query_processes",diff --git a/services/agents/app/context/identity.py b/services/agents/app/context/identity.pyindex c2fd0a8b5..055d4e1b6 100644--- a/services/agents/app/context/identity.py+++ b/services/agents/app/context/identity.py@@ -51,7 +51,7 @@ import osimport timefrom collections.abc import Mapping, Sequencefrom dataclasses import dataclass-from datetime import datetime+from datetime import date, datetimefrom typing import Anyimport httpx@@ -208,6 +208,111 @@ def _shape(payload: Mapping[str, Any], *, limit: int) -> IdentityContext:)+#: A departure this many days out or fewer counts as "departing". 30 days+#: because it is the common notice period and because the exfiltration+#: literature puts the elevated window in the final weeks; it is a default+#: rather than a constant, and the number is stated in the prompt so a+#: reader is never guessing which window produced the phrase.+DEPARTING_WITHIN_DAYS = 30++#: Bounded per principal: the prompt budget is shared with the evidence,+#: and a fleet user with forty enrolled devices must not crowd it out.+_MAX_DEVICES_PER_PRINCIPAL = 3+++def _parse_date(value: Any) -> date | None:+ """An ISO-8601 calendar date, or None.++ Dates only. A last day is a calendar date in a jurisdiction and not an+ instant, so a value carrying a time is truncated rather than converted:+ treating it as UTC would move somebody's departure by a day for half+ the world.+ """+ if not isinstance(value, str) or not value.strip():+ return None+ try:+ return date.fromisoformat(value.strip()[:10])+ except ValueError:+ return None+++def derive_employment_facts(row: Mapping[str, Any], *, today: date | None = None) -> dict[str, Any]:+ """Tenure, departure proximity and contractor status, from one row.++ Each is derived rather than stored, and each is absent rather than+ false when the underlying date is missing. A principal whose start date+ nobody imported is not a new joiner, and one with no end date is not+ "definitely staying" -- they are unknown, and the prompt says nothing+ instead of saying something reassuring.+ """+ now = today or date.today() # noqa: DTZ011 - a calendar date, deliberately+ facts: dict[str, Any] = {}++ start = _parse_date(row.get("start_date"))+ if start is not None:+ facts["tenure_days"] = max(0, (now - start).days)++ end = _parse_date(row.get("end_date"))+ if end is not None:+ remaining = (end - now).days+ facts["days_until_departure"] = remaining+ # Both directions are facts, and the past one is the sharper of the+ # two: an account whose last day has passed and which is still+ # authenticating is the single highest-signal row this source holds.+ facts["departed"] = remaining < 0+ facts["departing_soon"] = 0 <= remaining <= DEPARTING_WITHIN_DAYS++ employment = str(row.get("employment_type") or "").strip().lower()+ if employment in {"contractor", "contingent", "temp", "temporary"}:+ facts["is_contractor"] = True+ elif employment in {"employee", "full-time", "part-time", "full time", "part time"}:+ facts["is_contractor"] = False+ # Anything else, including "unknown" and a value no mapping covers,+ # leaves the key absent. A contractor read as staff loses exactly the+ # signal this field exists for, and the reverse is a false accusation.++ return facts+++def _render_device_line(device: Mapping[str, Any]) -> str | None:+ """One device, as a bounded phrase, or None when it says nothing."""+ hostname = sanitize_text(str(device.get("hostname") or ""), max_len=_MAX_FIELD_CHARS)+ compliance = str(device.get("compliance_state") or "").strip().lower()+ bits: list[str] = []+ if compliance == "noncompliant":+ bits.append("NOT COMPLIANT with this tenant's device policy")+ elif compliance == "in_grace_period":+ bits.append("in the policy grace period")+ elif compliance == "compliant":+ bits.append("compliant")+ elif compliance in {"", "unknown", "not_enrolled"}:+ # Said explicitly. An unmanaged or unevaluated device is a real+ # state and is not the same as a compliant one; leaving it out+ # would let the reader assume the quieter of the two.+ bits.append("compliance not evaluated by the MDM")++ encrypted = device.get("encrypted")+ if encrypted is False:+ bits.append("disk NOT encrypted")+ elif encrypted is True:+ bits.append("disk encrypted")+ # None is silent: "not reported" is not a finding.++ agent = sanitize_text(str(device.get("edr_agent_health") or ""), max_len=40).lower()+ if agent and agent not in {"secured", "cleared", "unknown"}:+ bits.append(f"threat-defence agent state {agent}")++ os_version = sanitize_text(str(device.get("os_version") or ""), max_len=40)+ os_name = sanitize_text(str(device.get("os_name") or ""), max_len=40)+ if os_name or os_version:+ bits.append(" ".join(part for part in (os_name, os_version) if part))++ if not bits:+ return None+ label = hostname or "an enrolled device"+ return f"{label}: " + ", ".join(bits)++def render_for_prompt(state_value: Mapping[str, Any] | None) -> str:"""The prompt block, or ``""`` when the tenant has imported nothing.@@ -244,17 +349,53 @@ def render_for_prompt(state_value: Mapping[str, Any] | None) -> str:employment = sanitize_text(str(row.get("employment_type") or ""), max_len=40)if employment:bits.append(employment)++ # Depth plan wave 2, item 1.3. Derived from the dates the row+ # already carries and stated with the window that produced each+ # phrase, so "departing soon" is never a number the reader has to+ # guess at. Absent when the date is absent: a principal whose start+ # date nobody imported is not a new joiner, and one with no end date+ # is not "definitely staying".+ facts = derive_employment_facts(row)+ if facts.get("departed"):+ bits.append("LAST DAY HAS PASSED and the account is still authenticating")+ elif facts.get("departing_soon"):+ bits.append(f"departing in {facts['days_until_departure']} day(s)")+ if facts.get("is_contractor"):+ bits.append("contractor, not an employee")+ tenure = facts.get("tenure_days")+ if isinstance(tenure, int) and tenure <= 30:+ bits.append(f"joined {tenure} day(s) ago")+lines.append(f"- {account}: " + ", ".join(bits) if bits else f"- {account}: no directory record")+ # The device half, indented under its owner. Rendered only when the+ # MDM said something: a principal with no enrolled device gets no+ # line, because "no device found" on a tenant with no MDM connector+ # is a statement about our coverage and not about the principal.+ devices = row.get("devices")+ if isinstance(devices, list):+ for device in devices[:_MAX_DEVICES_PER_PRINCIPAL]:+ if not isinstance(device, Mapping):+ continue+ rendered = _render_device_line(device)+ if rendered:+ lines.append(f" - device {rendered}")+if not lines:return ""return (- "Directory context for the principals in this alert, from this tenant's own imported "- "HR or identity data:\n" + "\n".join(lines) + "\nThis describes the account holder, not the activity. It is a reason to weigh the "- "activity differently, never a verdict on its own: an inactive account authenticating is "- "worth escalating, and a senior title is not evidence that anything was authorised. The "- "record reflects the last directory import and may be out of date."+ "Directory, HR and device context for the principals in this alert, from this tenant's own "+ "connected HR system, directory import or MDM:\n"+ + "\n".join(lines)+ + "\nThis describes the account holder, not the activity, and a device line describes the "+ "device rather than what was done on it. It is a reason to "+ "weigh the activity differently, never a verdict on its own: an account whose last day has "+ "passed authenticating is worth escalating, and a senior title is not evidence that "+ f'anything was authorised. "Departing" means a recorded last day within {DEPARTING_WITHIN_DAYS} days. The record '+ "reflects the last import or sync and may be out of date; a device with no line said "+ "nothing, which is not the same as a device that reported no problem.")@@ -268,4 +409,31 @@ def basis(state_value: Mapping[str, Any] | None) -> list[str]:line = f"Directory context in prompt: {len(rows)} principal(s)"if inactive:line += f", {inactive} no longer active in the directory"- return [line]+ out = [line]++ # Each derived fact is cited separately rather than folded into the+ # count above, because the confidence basis is what a reviewer reads to+ # see which input moved a verdict, and "1 principal in prompt" does not+ # say that one of them left last week.+ derived = [derive_employment_facts(r) for r in rows]+ departed = sum(1 for f in derived if f.get("departed"))+ departing = sum(1 for f in derived if f.get("departing_soon"))+ contractors = sum(1 for f in derived if f.get("is_contractor"))+ if departed:+ out.append(f"HR context: {departed} principal(s) whose recorded last day has passed")+ if departing:+ out.append(f"HR context: {departing} principal(s) departing within {DEPARTING_WITHIN_DAYS} days")+ if contractors:+ out.append(f"HR context: {contractors} principal(s) recorded as contractors")++ devices = [d for r in rows for d in (r.get("devices") or []) if isinstance(d, Mapping)]+ if devices:+ noncompliant = sum(1 for d in devices if str(d.get("compliance_state") or "").lower() == "noncompliant")+ unencrypted = sum(1 for d in devices if d.get("encrypted") is False)+ detail = f"Device context in prompt: {len(devices)} enrolled device(s)"+ if noncompliant:+ detail += f", {noncompliant} not compliant"+ if unencrypted:+ detail += f", {unencrypted} with no disk encryption"+ out.append(detail)+ return outdiff --git a/services/agents/tests/test_identity_employment_facts.py b/services/agents/tests/test_identity_employment_facts.pynew file mode 100644index 000000000..2986063d2--- /dev/null+++ b/services/agents/tests/test_identity_employment_facts.py@@ -0,0 +1,167 @@+"""Tenure, departure and device compliance have to reach the verdict, cited.++Depth plan wave 2, item 1.3.++The plan's wording is "each CITED", and that is the half worth testing. A+fact that reaches the prompt and not the confidence basis is one a reviewer+cannot see moved a verdict; a fact in the basis and not the prompt is one+the model never had. Both halves are asserted here for each of the four.++The other property under test is the direction of every absence. A missing+start date does not make somebody a new joiner, a missing end date does not+mean they are staying, an employment type nobody mapped does not make them+staff, and a device the MDM never evaluated is not a compliant one. Each of+those four is a reassurance the data cannot support, and each is the kind of+confident default this repository has shipped before.+"""++from __future__ import annotations++import sys+from datetime import date+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from app.context import identity as ident # noqa: E402++TODAY = date(2026, 11, 1)+++def _row(**overrides: object) -> dict[str, object]:+ base: dict[str, object] = {"account": "[email protected]", "is_active": True}+ base.update(overrides)+ return base+++class TestDerivedEmploymentFacts:+ def test_tenure_is_days_since_the_start_date(self) -> None:+ facts = ident.derive_employment_facts(_row(start_date="2026-10-02"), today=TODAY)+ assert facts["tenure_days"] == 30++ def test_no_start_date_means_no_tenure_rather_than_zero(self) -> None:+ """Zero tenure reads as "joined today", which is a finding. Absent+ reads as "nobody imported a start date", which is not."""+ assert "tenure_days" not in ident.derive_employment_facts(_row(), today=TODAY)++ def test_a_past_last_day_is_reported_as_departed(self) -> None:+ facts = ident.derive_employment_facts(_row(end_date="2026-10-20"), today=TODAY)+ assert facts["departed"] is True+ assert facts["departing_soon"] is False+ assert facts["days_until_departure"] == -12++ def test_a_last_day_inside_the_window_is_departing_soon(self) -> None:+ facts = ident.derive_employment_facts(_row(end_date="2026-11-20"), today=TODAY)+ assert facts["departing_soon"] is True+ assert facts["departed"] is False++ def test_a_last_day_outside_the_window_is_neither(self) -> None:+ facts = ident.derive_employment_facts(_row(end_date="2027-06-01"), today=TODAY)+ assert facts["departing_soon"] is False+ assert facts["departed"] is False++ def test_no_end_date_asserts_nothing_about_departure(self) -> None:+ facts = ident.derive_employment_facts(_row(), today=TODAY)+ assert "departed" not in facts+ assert "departing_soon" not in facts++ def test_a_contractor_is_flagged_and_an_employee_is_not(self) -> None:+ assert ident.derive_employment_facts(_row(employment_type="Contractor"), today=TODAY)["is_contractor"] is True+ assert ident.derive_employment_facts(_row(employment_type="Full-Time"), today=TODAY)["is_contractor"] is False++ def test_an_unmapped_employment_type_asserts_nothing(self) -> None:+ """A value no mapping covers must not become "employee". Reading a+ contractor as staff loses exactly the signal the field is for, and+ the reverse is a false accusation."""+ for value in ("unknown", "", "Seconded Partner Staff"):+ assert "is_contractor" not in ident.derive_employment_facts(_row(employment_type=value), today=TODAY)++ def test_a_malformed_date_is_absent_and_does_not_raise(self) -> None:+ facts = ident.derive_employment_facts(_row(start_date="not-a-date", end_date="2026-13-45"), today=TODAY)+ assert facts == {}+++class TestThePromptSaysIt:+ def _render(self, row: dict[str, object]) -> str:+ return ident.render_for_prompt({"identities": [row]})++ def test_a_departed_account_is_named_in_the_prompt(self) -> None:+ rendered = self._render(_row(end_date="2000-01-01"))+ assert "LAST DAY HAS PASSED" in rendered++ def test_a_contractor_is_named_in_the_prompt(self) -> None:+ assert "contractor, not an employee" in self._render(_row(employment_type="contractor"))++ def test_the_window_is_stated_rather_than_left_to_be_guessed(self) -> None:+ rendered = self._render(_row(end_date="2000-01-01"))+ assert str(ident.DEPARTING_WITHIN_DAYS) in rendered++ def test_a_noncompliant_device_is_named(self) -> None:+ rendered = self._render(_row(devices=[{"hostname": "LAPTOP-1", "compliance_state": "noncompliant", "encrypted": False}]))+ assert "LAPTOP-1" in rendered+ assert "NOT COMPLIANT" in rendered+ assert "disk NOT encrypted" in rendered++ def test_an_unevaluated_device_says_so_rather_than_reading_as_compliant(self) -> None:+ rendered = self._render(_row(devices=[{"hostname": "LAPTOP-2", "compliance_state": "unknown"}]))+ assert "compliance not evaluated" in rendered+ assert "compliant," not in rendered++ def test_unreported_encryption_is_silent_rather_than_a_finding(self) -> None:+ """None means nobody said. Only False is a finding."""+ rendered = self._render(_row(devices=[{"hostname": "LAPTOP-3", "compliance_state": "compliant", "encrypted": None}]))+ assert "encrypt" not in rendered.lower()++ def test_a_principal_with_no_device_gets_no_device_line(self) -> None:+ """ "No device found" on a tenant with no MDM connector is a+ statement about our coverage, not about the principal."""+ # The per-device bullet, not the word: the block's own preamble and+ # its honesty sentence both mention devices, and asserting on the+ # bare word would pass or fail on prose rather than on behaviour.+ assert "- device " not in self._render(_row())++ def test_devices_are_bounded_so_a_fleet_user_cannot_crowd_the_prompt(self) -> None:+ many = [{"hostname": f"HOST-{i}", "compliance_state": "noncompliant"} for i in range(12)]+ rendered = self._render(_row(devices=many))+ assert rendered.count("- device ") == ident._MAX_DEVICES_PER_PRINCIPAL+++class TestTheBasisCitesIt:+ """The citation half. A fact in the prompt and not the basis is one a+ reviewer cannot see moved a verdict."""++ def test_a_departed_principal_is_cited(self) -> None:+ lines = ident.basis({"identities": [_row(end_date="2000-01-01")]})+ assert any("last day has passed" in line for line in lines)++ def test_a_departing_principal_is_cited_with_the_window(self) -> None:+ soon = date.today().isoformat() # noqa: DTZ011 - a calendar date, deliberately+ lines = ident.basis({"identities": [_row(end_date=soon)]})+ assert any(f"within {ident.DEPARTING_WITHIN_DAYS} days" in line for line in lines)++ def test_a_contractor_is_cited(self) -> None:+ lines = ident.basis({"identities": [_row(employment_type="contractor")]})+ assert any("contractor" in line for line in lines)++ def test_device_compliance_is_cited_with_its_counts(self) -> None:+ lines = ident.basis(+ {+ "identities": [+ _row(+ devices=[+ {"hostname": "A", "compliance_state": "noncompliant", "encrypted": False},+ {"hostname": "B", "compliance_state": "compliant", "encrypted": True},+ ]+ )+ ]+ }+ )+ joined = " ".join(lines)+ assert "2 enrolled device(s)" in joined+ assert "1 not compliant" in joined+ assert "1 with no disk encryption" in joined++ def test_nothing_is_cited_when_nothing_was_derived(self) -> None:+ lines = ident.basis({"identities": [_row()]})+ assert len(lines) == 1+ assert "principal(s)" in lines[0]diff --git a/services/api/app/api/v1/endpoints/graph.py b/services/api/app/api/v1/endpoints/graph.pyindex 2f4ddc458..e0f7764c0 100644--- a/services/api/app/api/v1/endpoints/graph.py+++ b/services/api/app/api/v1/endpoints/graph.py@@ -13,13 +13,16 @@ from typing import Annotated, Anyfrom fastapi import APIRouter, Depends, Header, HTTPException, Query, statusfrom pydantic import BaseModel, Fieldfrom sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSessionfrom app.api.v1.deps import CurrentUser, DBSession, get_current_user, require_permissionfrom app.api.v1.endpoints.alert_writeback import service_token_valid+from app.db.database import get_dbfrom app.services import graph_servicefrom app.services.context_import import import_contextfrom app.services.incident_context import get_identity_context_for_accounts, get_incident_contextfrom app.services.investigation_tools import BACKED_TOOLS, TOOLS, dispatch+from app.services.workforce_context import get_workforce_context_for_accountslogger = logging.getLogger(__name__)@@ -990,6 +993,7 @@ class IdentityContextResponse(BaseModel):async def identity_context_for_triage(tenant_id: uuid.UUID,accounts: Annotated[list[str], Query()],+ db: Annotated[AsyncSession, Depends(get_db)],as_of: datetime | None = None,limit: Annotated[int, Query(ge=1, le=25)] = 5,x_aisoc_service_token: Annotated[str | None, Header()] = None,@@ -1029,6 +1033,19 @@ async def identity_context_for_triage(rows = await get_identity_context_for_accounts(str(tenant_id), list(accounts), limit=limit)+ # The CORE half. The reader above is Neo4j, which is a `full`-profile+ # service, so on the deployment `make up` produces it answers nothing+ # and this whole context dimension is silently dead. Migration 131 puts+ # the same facts in Postgres, written by the connector scheduler.+ #+ # Graph rows first and entity-store rows appended: the graph import+ # carries relationships the table does not, and an account present in+ # both should be described by the richer source. Accounts the graph did+ # not answer for are the ones this adds, which on CORE is all of them.+ seen_accounts = {str(row.get("account") or "").lower() for row in rows}+ store_rows = await get_workforce_context_for_accounts(db, str(tenant_id), list(accounts), limit=limit)+ rows = list(rows) + [row for row in store_rows if str(row.get("account") or "").lower() not in seen_accounts]+kept: list[dict[str, Any]] = []excluded = 0for row in rows:diff --git a/services/api/app/data/connector_catalog_fallback.json b/services/api/app/data/connector_catalog_fallback.jsonindex a68ff046e..5ae4837f9 100644--- a/services/api/app/data/connector_catalog_fallback.json+++ b/services/api/app/data/connector_catalog_fallback.json@@ -570,6 +570,41 @@"token_url": "https://login.microsoftonline.com/common/oauth2/v2.0/token"}},+ {+ "capabilities": [+ "pull_workforce"+ ],+ "category": "hr",+ "connector_id": "bamboohr",+ "connector_name": "BambooHR",+ "description": "Employment status, start and last-day dates, manager, department and worker type from BambooHR, as triage context. Read-only; no personal or compensation data is stored.",+ "docs_url": "/docs/connectors/bamboohr",+ "fields": [+ {+ "help_text": "The first label of your BambooHR URL: acme.bamboohr.com -> acme.",+ "label": "Company subdomain",+ "name": "subdomain",+ "placeholder": "acme",+ "required": true,+ "type": "string"+ },+ {+ "help_text": "Generated from your BambooHR profile under API Keys. Needs directory and employee read access.",+ "label": "API key",+ "name": "api_key",+ "required": true,+ "type": "secret"+ },+ {+ "default": 5000,+ "help_text": "A ceiling on the per-employee reads one sync will make.",+ "label": "Maximum employees per sync",+ "name": "max_employees",+ "required": false,+ "type": "number"+ }+ ]+ },{"capabilities": ["pull_audit",@@ -2109,6 +2144,37 @@"token_url": "https://login.microsoftonline.com/common/oauth2/v2.0/token"}},+ {+ "capabilities": [+ "pull_device_inventory"+ ],+ "category": "mdm",+ "connector_id": "microsoft_intune",+ "connector_name": "Microsoft Intune",+ "description": "Device owner, compliance state, OS version, encryption and threat-defence agent state from Microsoft Intune, as triage context. Read-only.",+ "docs_url": "/docs/connectors/microsoft-intune",+ "fields": [+ {+ "label": "Directory (tenant) ID",+ "name": "tenant_id",+ "required": true,+ "type": "string"+ },+ {+ "label": "Application (client) ID",+ "name": "client_id",+ "required": true,+ "type": "string"+ },+ {+ "help_text": "The app registration needs the application permission DeviceManagementManagedDevices.Read.All, granted with admin consent.",+ "label": "Client secret",+ "name": "client_secret",+ "required": true,+ "type": "secret"+ }+ ]+ },{"capabilities": ["pull_alerts",@@ -2753,6 +2819,33 @@}]},+ {+ "capabilities": [+ "pull_workforce"+ ],+ "category": "hr",+ "connector_id": "rippling",+ "connector_name": "Rippling",+ "description": "Employment status, start and end dates, manager, department and worker type from Rippling, as triage context. Read-only; compensation and personal data are never requested.",+ "docs_url": "/docs/connectors/rippling",+ "fields": [+ {+ "help_text": "A Rippling API token or installed-app access token carrying the workers.read scope.",+ "label": "API token",+ "name": "api_token",+ "required": true,+ "type": "secret"+ },+ {+ "default": "https://rest.ripplingapis.com",+ "help_text": "Override only if Rippling has given you a different regional host.",+ "label": "API base URL",+ "name": "base_url",+ "required": false,+ "type": "string"+ }+ ]+ },{"capabilities": ["pull_audit",diff --git a/services/api/app/data/marketplace/index.json b/services/api/app/data/marketplace/index.jsonindex faeeeddb5..d119ef249 100644--- a/services/api/app/data/marketplace/index.json+++ b/services/api/app/data/marketplace/index.json@@ -1,7 +1,7 @@{"$schema": "https://example.com/schemas/marketplace/v1.json","version": "1.0.0",- "generated": "2026-11-01T11:45:43Z",+ "generated": "2026-11-01T19:20:18Z","categories": [{"id": "playbooks",@@ -20,29 +20,29 @@}],"stats": {- "total": 7187,+ "total": 7190,"playbooks": 88,"playbook_packs": 63,"detections": 7019,- "plugins": 80,- "verified": 1066,+ "plugins": 83,+ "verified": 1069,"community": 1,"by_tier": {"beta": 7,"community": 1,"imported": 6113,- "stable": 1066+ "stable": 1069},"detections_by_tier": {"community": 1,"imported": 6113,"stable": 905},- "executable": 2702,+ "executable": 2705,"quarantined": 4485,"executable_detections": 2534,"reference_only_detections": 4485,- "not_a_detection": 168+ "not_a_detection": 171},"mitre_coverage": {"unique_techniques": 391,@@ -238551,6 +238551,32 @@"path": "plugins/azure-event-hubs/plugin.yaml","sha256": "985bb360b3ecb9cb252c48a84b321d85dfb454e9ac4483ef62353a0373d8fd10"},+ {+ "id": "bamboohr",+ "type": "plugin",+ "name": "BambooHR Connector",+ "description": "Employment status, start and last-day dates, manager, department and worker type from BambooHR, as triage context. Read-only. The employee endpoint is read with an explicit field list, so compensation, date of birth and home address are never requested, let alone stored.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "hr",+ "workforce",+ "identity",+ "context",+ "bamboohr"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/bamboohr.py",+ "min_aisoc_version": "21.0.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/bamboohr/plugin.yaml",+ "sha256": "c058cbc9927c18df427ae672d3c80930ed5b8c9437d2f6c2c8ada75b06382d6f"+ },{"id": "box","type": "plugin",@@ -239343,6 +239369,33 @@"path": "plugins/m365-audit/plugin.yaml","sha256": "ea68a64d4da29f71904de2452bff2d1e9d775f79938b24370bcd2f9a0c9a3722"},+ {+ "id": "microsoft_intune",+ "type": "plugin",+ "name": "Microsoft Intune Connector",+ "description": "Managed device context from Microsoft Intune through Microsoft Graph: device owner, compliance state, OS version, encryption and threat-defence agent state. Read-only; the app registration needs only the Read.All permission.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "mdm",+ "device",+ "compliance",+ "endpoint",+ "intune",+ "microsoft"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/microsoft_intune.py",+ "min_aisoc_version": "21.0.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/microsoft_intune/plugin.yaml",+ "sha256": "08595b41af02b6e3e2e7bcf0ae6b982e7fee7f3889fe881788a737540b98849a"+ },{"id": "mimecast","type": "plugin",@@ -239750,6 +239803,32 @@"path": "plugins/rapid7-insightidr/plugin.yaml","sha256": "d3eebd528cc17c4984879f33b71ae14af8a85fd317e715383e0ccee1ee916461"},+ {+ "id": "rippling",+ "type": "plugin",+ "name": "Rippling Connector",+ "description": "Employment status, start and end dates, manager, department and worker type from Rippling. Read-only. Only the department and employment-type relationships are expanded, so compensation and personal data are never fetched.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "hr",+ "workforce",+ "identity",+ "context",+ "rippling"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/rippling.py",+ "min_aisoc_version": "21.0.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/rippling/plugin.yaml",+ "sha256": "8499ceabc071dac745b545856a5e784b77fabf105229123f5a57d3454af2baf2"+ },{"id": "salesforce","type": "plugin",diff --git a/services/api/app/services/workforce_context.py b/services/api/app/services/workforce_context.pynew file mode 100644index 000000000..2959c73d4--- /dev/null+++ b/services/api/app/services/workforce_context.py@@ -0,0 +1,186 @@+"""HR and device context from the CORE entity store.++Depth plan wave 2, item 1.3.++`incident_context.get_identity_context_for_accounts` answers the same+question from Neo4j. Neo4j is a `full`-profile service, so on a CORE+install -- the one `make up` gives you -- it answers nothing, and every+triage input reading HR context is silently dead there.++This is the CORE half: the same question against `workforce_members` and+`workforce_devices`, which migration 131 puts in Postgres. The route merges+the two, graph rows first, because the graph import carries relationships+this table does not (an employee linked to an application they own) and the+connector sync carries freshness the graph import does not.++Why the join is on the email address+-------------------------------------+An HR system knows a work email; an authentication event names an account.+They are the same string often enough to be useful and not always, which is+why this returns `match: "email"` on every row it produces. A caller that+cannot see how a link was made will treat a coincidence as an identity, and+Phase 3.1 is the item that will do this properly with confidence and+evidence. Until then the link is stated rather than implied.+"""++from __future__ import annotations++import logging+from typing import Any++from sqlalchemy import text++logger = logging.getLogger("aisoc.workforce_context")++#: Bounded for the same reason the graph query is: this reaches a prompt,+#: and the prompt budget is shared with the evidence.+MAX_ROWS = 25++_BY_ACCOUNT = text(+ """+ SELECT m.external_id,+ m.email,+ m.display_name,+ m.status,+ m.start_date,+ m.end_date,+ m.department,+ m.worker_type,+ m.title,+ m.manager_external_id,+ m.connector_type,+ m.last_synced_at,+ mgr.display_name AS manager_display_name,+ mgr.email AS manager_email+ FROM workforce_members m+ LEFT JOIN workforce_members mgr+ ON mgr.tenant_id = m.tenant_id+ AND mgr.connector_type = m.connector_type+ AND mgr.external_id = m.manager_external_id+ WHERE m.tenant_id = CAST(:tenant_id AS uuid)+ AND lower(m.email) = ANY(CAST(:accounts AS text[]))+ ORDER BY m.last_synced_at DESC+ LIMIT :limit+ """+)++_DEVICES_FOR_OWNERS = text(+ """+ SELECT owner_email,+ hostname,+ compliance_state,+ os_name,+ os_version,+ encrypted,+ edr_agent_health,+ connector_type,+ last_seen+ FROM workforce_devices+ WHERE tenant_id = CAST(:tenant_id AS uuid)+ AND lower(owner_email) = ANY(CAST(:accounts AS text[]))+ ORDER BY last_seen DESC NULLS LAST+ LIMIT :limit+ """+)+++async def get_workforce_context_for_accounts(+ session: Any,+ tenant_id: str,+ accounts: list[str],+ *,+ limit: int = MAX_ROWS,+) -> list[dict[str, Any]]:+ """Rows in the same shape the graph reader produces, plus device state.++ Fail-soft, like every other context read on the triage path: an+ investigation without HR context is degraded, and one that dies because+ a table was unreadable is worse than the gap it was closing.+ """+ normalised = sorted({a.strip().lower() for a in accounts if isinstance(a, str) and a.strip()})+ if not normalised:+ return []++ try:+ result = await session.execute(+ _BY_ACCOUNT,+ {"tenant_id": tenant_id, "accounts": normalised, "limit": max(1, limit)},+ )+ members = [dict(row) for row in result.mappings()]++ device_result = await session.execute(+ _DEVICES_FOR_OWNERS,+ {"tenant_id": tenant_id, "accounts": normalised, "limit": max(1, limit)},+ )+ devices = [dict(row) for row in device_result.mappings()]+ except Exception as exc: # noqa: BLE001 - workforce context is advisory+ logger.warning(+ "workforce_context.unavailable error=%s",+ str(exc).replace("\r", "").replace("\n", " ")[:300],+ )+ return []++ by_owner: dict[str, list[dict[str, Any]]] = {}+ for device in devices:+ owner = str(device.get("owner_email") or "").lower()+ if owner:+ by_owner.setdefault(owner, []).append(device)++ rows: list[dict[str, Any]] = []+ for member in members:+ email = str(member.get("email") or "").lower()+ rows.append(+ {+ "account": email,+ "provider": member.get("connector_type"),+ "employee": member.get("display_name"),+ "title": member.get("title"),+ # The graph reader's field is a boolean, so the same key is+ # produced here rather than a second vocabulary the prompt+ # renderer would have to learn.+ "is_active": member.get("status") == "active",+ "status": member.get("status"),+ "employment_type": member.get("worker_type"),+ "start_date": _as_date_string(member.get("start_date")),+ "end_date": _as_date_string(member.get("end_date")),+ "department": member.get("department"),+ "manager": member.get("manager_display_name"),+ "manager_email": member.get("manager_email"),+ # The freshness of the fact, not an effective date. A row+ # nobody has refreshed in a month is not the same fact as one+ # refreshed this morning, and the caller applies the cutoff.+ "imported_at": _as_iso(member.get("last_synced_at")),+ # Stated rather than implied: this link was made on an email+ # string match and nothing stronger. Phase 3.1 is where it+ # gains a confidence and its evidence.+ "match": "email",+ "source": "entity_store",+ "devices": [+ {+ "hostname": device.get("hostname"),+ "compliance_state": device.get("compliance_state"),+ "os_name": device.get("os_name"),+ "os_version": device.get("os_version"),+ "encrypted": device.get("encrypted"),+ "edr_agent_health": device.get("edr_agent_health"),+ "provider": device.get("connector_type"),+ "last_seen": _as_iso(device.get("last_seen")),+ }+ for device in by_owner.get(email, [])[:5]+ ],+ }+ )+ return rows+++def _as_date_string(value: Any) -> str | None:+ if value is None:+ return None+ return str(value)[:10] or None+++def _as_iso(value: Any) -> str | None:+ if value is None:+ return None+ isoformat = getattr(value, "isoformat", None)+ return isoformat() if callable(isoformat) else str(value)diff --git a/services/api/migrations/131_workforce_context.sql b/services/api/migrations/131_workforce_context.sqlnew file mode 100644index 000000000..901828a48--- /dev/null+++ b/services/api/migrations/131_workforce_context.sql@@ -0,0 +1,166 @@+-- Depth plan wave 2, item 1.3: HR and device context, available on CORE.+--+-- `services/api/app/services/context_import.py` already imports exactly this+-- context and writes it to Neo4j, which is a `full`-profile service. On a+-- CORE install -- the one `make up` gives you -- there is no graph, so the+-- HR dimension would not exist at all and every triage input reading it+-- would be silently dead. ADR 0010 put the entity store in CORE for this+-- reason; these two tables are the same decision applied to the same data.+--+-- Both paths stay. The graph import is richer, because it links employees to+-- identities and applications through relationships. These tables are the+-- ones that are always there, and the connectors scheduler writes them+-- because that service holds a Postgres engine and no Neo4j driver.+--+-- Personal data minimisation (the plan's rule, enforced in the schema rather+-- than only in the readers): these columns are the complete list of what+-- item 1.3 names. There is no column for compensation, date of birth, home+-- address, personal contact details or a national identifier, and the+-- connectors do not request those fields from the vendor either. A schema+-- that cannot hold a salary cannot leak one.++CREATE TABLE IF NOT EXISTS workforce_members (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ -- Which HR system said so. Part of the identity because two sources can+ -- legitimately both know a person, and silently merging them would make+ -- the last connector to poll the only one that counts.+ connector_type TEXT NOT NULL,+ external_id TEXT NOT NULL,++ email TEXT,+ display_name TEXT,+ -- active | leave | terminated | pending | unknown.+ -- `unknown` is a real member and is what an unrecognised vendor value+ -- becomes. Deciding somebody still works here on a value nobody+ -- recognises is the wrong direction to be wrong in.+ status TEXT NOT NULL DEFAULT 'unknown',+ -- DATE and not TIMESTAMPTZ: a last day is a calendar date in a+ -- jurisdiction, not an instant. Storing it as an instant moves somebody's+ -- departure by a day for half the world.+ start_date DATE,+ end_date DATE,+ manager_external_id TEXT,+ department TEXT,+ -- employee | contractor | unknown. A contractor read as staff loses+ -- exactly the signal the column exists for, so a source that does not+ -- say stays unknown rather than defaulting.+ worker_type TEXT NOT NULL DEFAULT 'unknown',+ title TEXT,++ -- When the sync last saw this row, so a reader can tell stale context+ -- from current context. A row nobody has refreshed in a month is not the+ -- same fact as one refreshed this morning.+ last_synced_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ CONSTRAINT workforce_members_identity UNIQUE (tenant_id, connector_type, external_id),+ CONSTRAINT workforce_members_status_known CHECK (+ status IN ('active', 'leave', 'terminated', 'pending', 'unknown')+ ),+ CONSTRAINT workforce_members_type_known CHECK (+ worker_type IN ('employee', 'contractor', 'unknown')+ )+);++-- The lookup triage actually makes: "who is this email address". Partial on+-- a non-null email because a record with no work email cannot be joined to+-- an authentication event and would only pad the index.+CREATE INDEX IF NOT EXISTS idx_workforce_members_email+ ON workforce_members (tenant_id, lower(email))+ WHERE email IS NOT NULL;++-- "Who is leaving in the next N days" and "who left and is still+-- authenticating" are the two queries this table exists for.+CREATE INDEX IF NOT EXISTS idx_workforce_members_end_date+ ON workforce_members (tenant_id, end_date)+ WHERE end_date IS NOT NULL;+++CREATE TABLE IF NOT EXISTS workforce_devices (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ connector_type TEXT NOT NULL,+ external_id TEXT NOT NULL,++ hostname TEXT,+ owner_email TEXT,+ owner_external_id TEXT,+ -- compliant | noncompliant | in_grace_period | not_enrolled | unknown.+ -- `unknown` covers both "the MDM has not evaluated this device" and "the+ -- vendor reported a state we do not recognise", and must never render as+ -- compliant: a device nobody evaluated is not one that passed.+ compliance_state TEXT NOT NULL DEFAULT 'unknown',+ os_name TEXT,+ os_version TEXT,+ -- Nullable on purpose, and the null is load-bearing. FALSE means the MDM+ -- evaluated the device and found no encryption, which is a finding. NULL+ -- means nobody said, which is not. A NOT NULL DEFAULT FALSE here would+ -- put every unevaluated device into the finding.+ encrypted BOOLEAN,+ -- The agent's own verdict, carried through under the vendor's+ -- vocabulary rather than flattened to a boolean: "no agent is talking to+ -- us" and "the agent says this device is fine" are different facts and a+ -- boolean merges them.+ edr_agent_health TEXT,+ serial_number TEXT,+ last_seen TIMESTAMPTZ,++ last_synced_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ CONSTRAINT workforce_devices_identity UNIQUE (tenant_id, connector_type, external_id),+ CONSTRAINT workforce_devices_compliance_known CHECK (+ compliance_state IN ('compliant', 'noncompliant', 'in_grace_period', 'not_enrolled', 'unknown')+ )+);++CREATE INDEX IF NOT EXISTS idx_workforce_devices_hostname+ ON workforce_devices (tenant_id, lower(hostname))+ WHERE hostname IS NOT NULL;++CREATE INDEX IF NOT EXISTS idx_workforce_devices_owner+ ON workforce_devices (tenant_id, lower(owner_email))+ WHERE owner_email IS NOT NULL;+++-- Row-level security. Both tables are tenant-scoped and hold personal data,+-- so the policy is not defence in depth here, it is the control.+ALTER TABLE workforce_members ENABLE ROW LEVEL SECURITY;+ALTER TABLE workforce_devices ENABLE ROW LEVEL SECURITY;++-- FORCE, not just ENABLE. Without it the table owner -- which is the role+-- that runs migrations -- walks straight past the policy, so a policy that+-- reads correctly protects nothing when the owner is also a reader.+ALTER TABLE workforce_members FORCE ROW LEVEL SECURITY;+ALTER TABLE workforce_devices FORCE ROW LEVEL SECURITY;++-- The `OR current_tenant_id() IS NULL` arm is the shape every table here+-- uses, and it is load-bearing rather than a loosening: the connectors+-- scheduler writes these rows on a connection that binds no tenant GUC,+-- and without the arm it would see and write zero rows while reporting+-- success. The real control for those writers is the explicit tenant+-- predicate in the statement itself -- every read and write in+-- `app/workforce.py` and `app/services/workforce_context.py` names+-- `tenant_id` -- which is the query-layer scoping this repository treats+-- as primary, with RLS as defence in depth for session-bound callers.+DROP POLICY IF EXISTS workforce_members_tenant_isolation ON workforce_members;+CREATE POLICY workforce_members_tenant_isolation ON workforce_members+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)+ WITH CHECK (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++DROP POLICY IF EXISTS workforce_devices_tenant_isolation ON workforce_devices;+CREATE POLICY workforce_devices_tenant_isolation ON workforce_devices+ USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL)+ WITH CHECK (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL);++-- The runtime role is DML-only; without these grants every read and write+-- from the services fails with a permission error that reads as a missing+-- table.+GRANT SELECT, INSERT, UPDATE, DELETE ON workforce_members TO aisoc_app;+GRANT SELECT, INSERT, UPDATE, DELETE ON workforce_devices TO aisoc_app;++COMMENT ON TABLE workforce_members IS+ 'HR context per person, tenant-scoped: employment status, start and last-day dates, manager, department and worker type. Departures are recorded, never deleted: a terminated employee whose accounts still authenticate is the highest-signal row here.';+COMMENT ON TABLE workforce_devices IS+ 'Managed device context, tenant-scoped: owner, compliance state, OS version, encryption and agent health. NULL encryption means nobody reported, which is not the same as not encrypted.';diff --git a/services/connectors/app/connectors/__init__.py b/services/connectors/app/connectors/__init__.pyindex 28ca72bc4..881767df5 100644--- a/services/connectors/app/connectors/__init__.py+++ b/services/connectors/app/connectors/__init__.py@@ -29,6 +29,7 @@ from app.connectors.azure_activity import AzureActivityConnectorfrom app.connectors.azure_defender import AzureDefenderConnectorfrom app.connectors.azure_entra import AzureEntraConnectorfrom app.connectors.azure_event_hubs import AzureEventHubsConnector+from app.connectors.bamboohr import BambooHRConnectorfrom app.connectors.base import BaseConnector, ConnectorSchema, Field, OAuthHintsfrom app.connectors.box import BoxConnectorfrom app.connectors.carbon_black import CarbonBlackConnector@@ -65,6 +66,7 @@ from app.connectors.kubernetes_audit import KubernetesAuditConnectorfrom app.connectors.lacework import LaceworkConnectorfrom app.connectors.llm_usage import LlmUsageConnectorfrom app.connectors.m365_audit import M365AuditConnector+from app.connectors.microsoft_intune import MicrosoftIntuneConnectorfrom app.connectors.microsoft_sentinel import MicrosoftSentinelConnectorfrom app.connectors.mimecast import MimecastConnectorfrom app.connectors.netskope import NetskopeConnector@@ -80,6 +82,7 @@ from app.connectors.proofpoint import ProofpointConnectorfrom app.connectors.qradar import QRadarConnectorfrom app.connectors.qualys import QualysConnectorfrom app.connectors.rapid7_insightidr import Rapid7InsightIDRConnector+from app.connectors.rippling import RipplingConnectorfrom app.connectors.salesforce import SalesforceConnectorfrom app.connectors.securonix import SecuronixConnectorfrom app.connectors.sentinelone import SentinelOneConnector@@ -112,6 +115,9 @@ if TYPE_CHECKING:# Source of truth for "which connectors does this build know about".# Keep alphabetised by connector_id for predictable diffs._CONNECTOR_CLASSES: tuple[type[BaseConnector], ...] = (+ RipplingConnector,+ MicrosoftIntuneConnector,+ BambooHRConnector,AWSCloudTrailConnector,AWSCloudTrailS3Connector,AWSGuardDutyConnector,diff --git a/services/connectors/app/connectors/bamboohr.py b/services/connectors/app/connectors/bamboohr.pynew file mode 100644index 000000000..aefce178a--- /dev/null+++ b/services/connectors/app/connectors/bamboohr.py@@ -0,0 +1,237 @@+"""BambooHR workforce context.++Depth plan wave 2, item 1.3.++Vendor reference, verified 2026-11-01 at documentation.bamboohr.com:++* `GET https://api.bamboohr.com/api/v1/{subdomain}/v1/employees/directory`+ lists the published directory.+* `GET https://api.bamboohr.com/api/v1/{subdomain}/v1/employees/{id}?fields=...`+ returns an explicit field list for one employee.+* Authentication is HTTP Basic with the API key as the username and any+ string as the password.+* `Accept: application/json` is required; without it the API answers XML.++Why both endpoints and not just the directory+----------------------------------------------+The directory is one request and would have been the obvious read. Its own+reference rules it out for this feature twice over: it "never includes+compensation, national identifiers such as SSN, birth date, home address,+home contact details, **or employment status and history, in any+configuration**", and "inactive and former employees are also excluded".++Those two sentences remove every field item 1.3 actually asks for -+employment status, start date, termination date - and remove the entire+population the feature exists to see, which is the person who left on+Friday and whose account authenticated on Saturday. So the directory is+used only to enumerate ids, and each employee's fields are read+individually with the field list named in the request.++That costs one request per employee. It is a scheduled background sync+reading a slowly-changing roster, not a hot path, and the alternative is a+feature that cannot see a departure.++What is deliberately not read+------------------------------+Everything else. The per-employee endpoint can return compensation, home+address, date of birth and national identifiers; this connector names+exactly the fields the plan lists and nothing more, so the data minimisation+is in the request rather than in a filter applied afterwards.+"""++from __future__ import annotations++from typing import Any++import httpx+import structlog++from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field+from app.workforce import WorkforceRecord, normalise_status++logger = structlog.get_logger()++#: Named in the request. A reader that does not ask for a column cannot+#: recover it with an adapter afterwards, which is how four of five vendor+#: readers in this tree came to return null hostnames.+_FIELDS = (+ "id",+ "displayName",+ "workEmail",+ "department",+ "jobTitle",+ "supervisorEid",+ "hireDate",+ "terminationDate",+ "status",+ "employmentHistoryStatus",+)++#: BambooHR's `status` field is `Active` or `Inactive`. It carries no+#: "on leave" member, so this map has none either rather than inventing one.+_STATUS_MAP = {"active": "active", "inactive": "terminated"}++#: `employmentHistoryStatus` is a free-text employment-type field whose+#: values a company configures. These are the shipped defaults; anything+#: else is `unknown`, because a bespoke value read as "employee" would lose+#: exactly the contractor signal the field is here for.+_TYPE_MAP = {+ "full-time": "employee",+ "part-time": "employee",+ "full time": "employee",+ "part time": "employee",+ "contractor": "contractor",+ "intern": "contractor",+ "temporary": "contractor",+ "temp": "contractor",+}+++class BambooHRConnector(BaseConnector):+ connector_id = "bamboohr"+ connector_name = "BambooHR"+ connector_category = "hr"++ @classmethod+ def schema(cls) -> ConnectorSchema:+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "Employment status, start and last-day dates, manager, department and worker type "+ "from BambooHR, as triage context. Read-only; no personal or compensation data is stored."+ ),+ docs_url="/docs/connectors/bamboohr",+ fields=[+ Field(+ "subdomain",+ "string",+ "Company subdomain",+ placeholder="acme",+ help_text="The first label of your BambooHR URL: acme.bamboohr.com -> acme.",+ ),+ Field(+ "api_key",+ "secret",+ "API key",+ help_text="Generated from your BambooHR profile under API Keys. Needs directory and employee read access.",+ ),+ Field(+ "max_employees",+ "number",+ "Maximum employees per sync",+ required=False,+ default=5000,+ help_text="A ceiling on the per-employee reads one sync will make.",+ ),+ ],+ capabilities=cls.capabilities(),+ )++ @classmethod+ def capabilities(cls) -> tuple[Capability, ...]:+ return (Capability.PULL_WORKFORCE,)++ def __init__(+ self,+ subdomain: str,+ api_key: str,+ max_employees: int = 5000,+ transport: Any | None = None,+ ) -> None:+ self._subdomain = subdomain.strip().strip("/")+ self._api_key = api_key+ self._max_employees = max(1, int(max_employees))+ self._transport = transport++ def _client(self) -> httpx.AsyncClient:+ return httpx.AsyncClient(+ base_url=f"https://api.bamboohr.com/api/gateway.php/{self._subdomain}/v1",+ # Basic with the key as username and any password, per the+ # vendor's authentication page.+ auth=(self._api_key, "x"),+ headers={"Accept": "application/json"},+ timeout=30.0,+ transport=self._transport,+ )++ async def test_connection(self) -> dict[str, Any]:+ try:+ async with self._client() as client:+ response = await client.get("/employees/directory")+ if response.status_code == 403:+ # Named rather than reported as a bad credential: the+ # vendor returns 403 with an empty body when directory+ # sharing is off company-wide, which is a setting the+ # operator can fix and a wrong key is not.+ return {+ "ok": False,+ "error": (+ "BambooHR answered 403. The key may be valid but the company's directory "+ "sharing is off (Settings > Company Directory), which every caller including "+ "administrators hits."+ ),+ }+ response.raise_for_status()+ count = len(response.json().get("employees") or [])+ return {"ok": True, "detail": f"directory readable, {count} employee(s) published"}+ except httpx.HTTPError as exc:+ return {"ok": False, "error": str(exc)}++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ """No alerts. An HR system reports state, not security events.++ Returning an empty list rather than raising keeps the connector+ pollable by the ordinary scheduler loop; the workforce sync is a+ separate branch in the same poll.+ """+ return []++ async def fetch_workforce(self) -> list[WorkforceRecord]:+ records: list[WorkforceRecord] = []+ async with self._client() as client:+ directory = await client.get("/employees/directory")+ directory.raise_for_status()+ employees = directory.json().get("employees") or []++ for entry in employees[: self._max_employees]:+ employee_id = str(entry.get("id") or "").strip()+ if not employee_id:+ continue+ detail = await client.get(+ f"/employees/{employee_id}",+ params={"fields": ",".join(_FIELDS)},+ )+ if detail.status_code != 200:+ # One unreadable employee is not an unreadable roster.+ logger.warning(+ "bamboohr.employee_unreadable",+ employee_id=employee_id,+ status=detail.status_code,+ )+ continue+ records.append(self._to_record(detail.json()))+ return records++ @staticmethod+ def _to_record(payload: dict[str, Any]) -> WorkforceRecord:+ end_date = (payload.get("terminationDate") or "").strip() or None+ status = normalise_status(payload.get("status"), _STATUS_MAP)+ # A termination date in the record and a status of Active is the+ # normal state of a notice period, and it is the case this feature+ # exists for. The date wins nothing here: status stays what the+ # vendor said, and "departing within N days" is derived downstream+ # from the date, so both facts survive.+ return WorkforceRecord(+ external_id=str(payload.get("id") or "").strip(),+ email=(payload.get("workEmail") or "").strip() or None,+ display_name=(payload.get("displayName") or "").strip() or None,+ status=status,+ start_date=(payload.get("hireDate") or "").strip() or None,+ end_date=end_date,+ manager_external_id=(str(payload.get("supervisorEid") or "").strip() or None),+ department=(payload.get("department") or "").strip() or None,+ worker_type=_TYPE_MAP.get(str(payload.get("employmentHistoryStatus") or "").strip().lower(), "unknown"),+ title=(payload.get("jobTitle") or "").strip() or None,+ )diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.pyindex c06c3ca64..3a23a431d 100644--- a/services/connectors/app/connectors/base.py+++ b/services/connectors/app/connectors/base.py@@ -81,6 +81,18 @@ class Capability(str, Enum):#: into ``asset_vulnerabilities`` (docs/cve-patch-policy.md): scanner#: findings are inventory rows with patch windows, not console alerts.PULL_VULNERABILITIES = "pull_vulnerabilities"+ #: Pull *workforce context* -- employment status, start and last-day+ #: dates, manager, department and worker type -- rather than events.+ #: Connectors declaring it must expose ``fetch_workforce()``, which the+ #: scheduler materialises into ``workforce_members`` (depth plan wave 2+ #: item 1.3). An HR system reports slowly-changing state, not security+ #: events, and pushing it through ingest would make "is this person+ #: leaving" a lake search rather than a lookup.+ PULL_WORKFORCE = "pull_workforce"+ #: Pull *managed device state* -- owner, compliance, OS version,+ #: encryption and agent health. Connectors declaring it must expose+ #: ``fetch_devices()``, materialised into ``workforce_devices``.+ PULL_DEVICE_INVENTORY = "pull_device_inventory"# QUERY — ad-hoc search across the source's index.QUERY_LOGS = "query_logs"diff --git a/services/connectors/app/connectors/microsoft_intune.py b/services/connectors/app/connectors/microsoft_intune.pynew file mode 100644index 000000000..eb2a11c7c--- /dev/null+++ b/services/connectors/app/connectors/microsoft_intune.py@@ -0,0 +1,240 @@+"""Microsoft Intune device context.++Depth plan wave 2, item 1.3.++Vendor reference, verified 2026-11-01 at+learn.microsoft.com/en-us/graph/api/intune-devices-manageddevice-list:++* `GET https://graph.microsoft.com/v1.0/deviceManagement/managedDevices`+* Application permission `DeviceManagementManagedDevices.Read.All`+ (the read-only half of the pair; the ReadWrite variant is never requested+ because nothing here changes vendor state).+* Token from `https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token`+ with scope `https://graph.microsoft.com/.default`.+* Paging follows `@odata.nextLink`.++The fields the plan's list maps onto, by their documented names:++| Plan field | Graph property |+|---|---|+| device owner | `userPrincipalName`, `userId` |+| compliance state | `complianceState` |+| OS version | `operatingSystem`, `osVersion` |+| encryption | `isEncrypted` |+| EDR agent health | `partnerReportedThreatState` |++`partnerReportedThreatState` is the mobile-threat-defence partner's own+verdict on the device, and it is the closest thing Graph's managedDevice+publishes to EDR agent health. It is carried through under its own name+rather than flattened into a boolean, because its vocabulary+(`unknown`, `activated`, `deactivated`, `secured`, `lowSeverity`,+`mediumSeverity`, `highSeverity`, `unresponsive`, `compromised`, `misconfigured`)+distinguishes "no agent is talking to us" from "the agent says this device+is fine", and a boolean would merge them.++What is deliberately not read+------------------------------+`managedDevice` returns phone numbers, IMEI, ICCID, subscriber carrier,+notes and a full device-health-attestation block. None of it is stored.+"""++from __future__ import annotations++import time+from typing import Any++import httpx+import structlog++from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field+from app.workforce import DeviceRecord++logger = structlog.get_logger()++_GRAPH = "https://graph.microsoft.com/v1.0"+_LOGIN = "https://login.microsoftonline.com"++#: `$select` rather than the full object. Graph returns roughly sixty+#: properties per device and the plan's list needs nine; asking for nine is+#: the data minimisation, and doing it in the request means a future reader+#: cannot quietly start using a field nobody decided to collect.+_SELECT = ",".join(+ (+ "id",+ "deviceName",+ "userId",+ "userPrincipalName",+ "complianceState",+ "operatingSystem",+ "osVersion",+ "isEncrypted",+ "partnerReportedThreatState",+ "managedDeviceOwnerType",+ "serialNumber",+ "lastSyncDateTime",+ )+)++#: Graph's documented `complianceState` vocabulary. `unknown`,+#: `conflict` and `error` all mean Intune could not reach a verdict, and+#: each maps to `unknown` rather than to compliant: a device nobody+#: evaluated must never read as one that passed.+_COMPLIANCE_MAP = {+ "compliant": "compliant",+ "noncompliant": "noncompliant",+ "ingraceperiod": "in_grace_period",+ "configmanager": "unknown",+ "conflict": "unknown",+ "error": "unknown",+ "unknown": "unknown",+}++_MAX_PAGES = 200+++class MicrosoftIntuneConnector(BaseConnector):+ connector_id = "microsoft_intune"+ connector_name = "Microsoft Intune"+ connector_category = "mdm"++ @classmethod+ def schema(cls) -> ConnectorSchema:+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "Device owner, compliance state, OS version, encryption and threat-defence agent state "+ "from Microsoft Intune, as triage context. Read-only."+ ),+ docs_url="/docs/connectors/microsoft-intune",+ fields=[+ Field("tenant_id", "string", "Directory (tenant) ID"),+ Field("client_id", "string", "Application (client) ID"),+ Field(+ "client_secret",+ "secret",+ "Client secret",+ help_text=(+ "The app registration needs the application permission "+ "DeviceManagementManagedDevices.Read.All, granted with admin consent."+ ),+ ),+ ],+ capabilities=cls.capabilities(),+ )++ @classmethod+ def capabilities(cls) -> tuple[Capability, ...]:+ return (Capability.PULL_DEVICE_INVENTORY,)++ def __init__(+ self,+ tenant_id: str,+ client_id: str,+ client_secret: str,+ transport: Any | None = None,+ ) -> None:+ self._tenant_id = tenant_id+ self._client_id = client_id+ self._client_secret = client_secret+ self._transport = transport+ self._token: str | None = None+ self._token_expires_at: float = 0.0++ async def _access_token(self) -> str:+ # A minute of headroom: a token that expires between the check and+ # the call produces a 401 an operator reads as a bad credential.+ if self._token and time.time() < self._token_expires_at - 60:+ return self._token+ async with httpx.AsyncClient(timeout=30.0, transport=self._transport) as client:+ response = await client.post(+ f"{_LOGIN}/{self._tenant_id}/oauth2/v2.0/token",+ data={+ "grant_type": "client_credentials",+ "client_id": self._client_id,+ "client_secret": self._client_secret,+ "scope": "https://graph.microsoft.com/.default",+ },+ )+ response.raise_for_status()+ body = response.json()+ self._token = str(body["access_token"])+ self._token_expires_at = time.time() + float(body.get("expires_in") or 3600)+ return self._token++ async def test_connection(self) -> dict[str, Any]:+ try:+ token = await self._access_token()+ async with httpx.AsyncClient(timeout=30.0, transport=self._transport) as client:+ response = await client.get(+ f"{_GRAPH}/deviceManagement/managedDevices",+ headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},+ params={"$top": 1, "$select": "id"},+ )+ if response.status_code == 403:+ return {+ "ok": False,+ "error": (+ "Graph answered 403. The app registration is missing "+ "DeviceManagementManagedDevices.Read.All, or admin consent has not been granted."+ ),+ }+ response.raise_for_status()+ return {"ok": True, "detail": "managedDevices readable"}+ except httpx.HTTPError as exc:+ return {"ok": False, "error": str(exc)}++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ """No alerts. An MDM reports device state, not security events."""+ return []++ async def fetch_devices(self) -> list[DeviceRecord]:+ token = await self._access_token()+ headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}+ records: list[DeviceRecord] = []++ async with httpx.AsyncClient(timeout=30.0, transport=self._transport) as client:+ url: str | None = f"{_GRAPH}/deviceManagement/managedDevices"+ params: dict[str, Any] | None = {"$select": _SELECT, "$top": 100}+ for _ in range(_MAX_PAGES):+ if url is None:+ break+ response = await client.get(url, headers=headers, params=params)+ response.raise_for_status()+ body = response.json()+ for device in body.get("value") or []:+ record = self._to_record(device)+ if record is not None:+ records.append(record)+ # `@odata.nextLink` already carries `$select` and the skip+ # token; re-sending the first page's params would reset it.+ url = body.get("@odata.nextLink") or None+ params = None+ return records++ @staticmethod+ def _to_record(device: dict[str, Any]) -> DeviceRecord | None:+ external_id = str(device.get("id") or "").strip()+ if not external_id:+ return None++ raw_compliance = str(device.get("complianceState") or "").strip().lower()+ encrypted = device.get("isEncrypted")++ return DeviceRecord(+ external_id=external_id,+ hostname=(device.get("deviceName") or "").strip() or None,+ owner_email=(device.get("userPrincipalName") or "").strip() or None,+ owner_external_id=(str(device.get("userId") or "").strip() or None),+ compliance_state=_COMPLIANCE_MAP.get(raw_compliance, "unknown"),+ os_name=(device.get("operatingSystem") or "").strip() or None,+ os_version=(device.get("osVersion") or "").strip() or None,+ # Tri-state preserved: a device Graph did not report on is None,+ # not False. "Not encrypted" is a finding; "not reported" is not,+ # and merging them would put every unevaluated device in it.+ encrypted=(bool(encrypted) if isinstance(encrypted, bool) else None),+ edr_agent_health=(device.get("partnerReportedThreatState") or "").strip() or None,+ serial_number=(device.get("serialNumber") or "").strip() or None,+ last_seen=(device.get("lastSyncDateTime") or "").strip() or None,+ )diff --git a/services/connectors/app/connectors/rippling.py b/services/connectors/app/connectors/rippling.pynew file mode 100644index 000000000..5756faa63--- /dev/null+++ b/services/connectors/app/connectors/rippling.py@@ -0,0 +1,193 @@+"""Rippling workforce context.++Depth plan wave 2, item 1.3.++Vendor reference, verified 2026-11-01 at developer.rippling.com:++* `GET https://rest.ripplingapis.com/workers/`+* OAuth scope `workers.read`, sent as a bearer token.+* Response is `{"results": [...], "next_link": "..."}`; paging follows+ `next_link` until it is absent.+* `expand` is a comma-separated list of relationship fields. Without it,+ `department` and `employment_type` arrive as bare `*_id` strings, which+ would make the department of every employee an opaque identifier.+* `status` is a closed vocabulary: `INIT`, `HIRED`, `ACCEPTED`, `ACTIVE`,+ `TERMINATED`.+* `employment_type.type` is `CONTRACTOR` or `EMPLOYEE`.++What is deliberately not read+------------------------------+The worker object also carries compensation, date of birth, gender, race,+ethnicity, citizenship, personal email and home address. None of it is+expanded, none of it is stored, and `expand` names only the two+relationships the plan's field list needs. The vendor's own+`__meta.redacted_fields` is logged rather than ignored, because a field the+tenant's own configuration redacts is a fact about their data and not an+error.+"""++from __future__ import annotations++from typing import Any++import httpx+import structlog++from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field+from app.workforce import WorkforceRecord, normalise_status++logger = structlog.get_logger()++_BASE_URL = "https://rest.ripplingapis.com"++#: Only the two relationships the plan's field list needs. Expanding+#: `compensation` here would pull a salary into a security product.+_EXPAND = "department,employment_type"++#: The vendor's documented vocabulary, mapped onto the closed set. `INIT`,+#: `HIRED` and `ACCEPTED` are all pre-start states, which is a real and+#: separate thing from employed: a worker who has accepted but not started+#: should not look like staff, and should not look terminated either.+_STATUS_MAP = {+ "active": "active",+ "terminated": "terminated",+ "init": "pending",+ "hired": "pending",+ "accepted": "pending",+}++_TYPE_MAP = {"employee": "employee", "contractor": "contractor"}++#: A ceiling on pages followed, so a paging bug upstream cannot turn one+#: scheduled sync into an unbounded walk. 100 results per page at the+#: documented maximum covers 20,000 workers.+_MAX_PAGES = 200+++class RipplingConnector(BaseConnector):+ connector_id = "rippling"+ connector_name = "Rippling"+ connector_category = "hr"++ @classmethod+ def schema(cls) -> ConnectorSchema:+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "Employment status, start and end dates, manager, department and worker type from "+ "Rippling, as triage context. Read-only; compensation and personal data are never requested."+ ),+ docs_url="/docs/connectors/rippling",+ fields=[+ Field(+ "api_token",+ "secret",+ "API token",+ help_text="A Rippling API token or installed-app access token carrying the workers.read scope.",+ ),+ Field(+ "base_url",+ "string",+ "API base URL",+ required=False,+ default=_BASE_URL,+ help_text="Override only if Rippling has given you a different regional host.",+ ),+ ],+ capabilities=cls.capabilities(),+ )++ @classmethod+ def capabilities(cls) -> tuple[Capability, ...]:+ return (Capability.PULL_WORKFORCE,)++ def __init__(self, api_token: str, base_url: str = _BASE_URL, transport: Any | None = None) -> None:+ self._token = api_token+ self._base_url = (base_url or _BASE_URL).rstrip("/")+ self._transport = transport++ def _client(self) -> httpx.AsyncClient:+ return httpx.AsyncClient(+ base_url=self._base_url,+ headers={"Authorization": f"Bearer {self._token}", "Accept": "application/json"},+ timeout=30.0,+ transport=self._transport,+ )++ async def test_connection(self) -> dict[str, Any]:+ try:+ async with self._client() as client:+ response = await client.get("/workers/", params={"limit": 1})+ if response.status_code == 403:+ return {+ "ok": False,+ "error": "Rippling answered 403. The token is valid but is missing the workers.read scope.",+ }+ response.raise_for_status()+ return {"ok": True, "detail": "workers endpoint readable"}+ except httpx.HTTPError as exc:+ return {"ok": False, "error": str(exc)}++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ """No alerts. See the BambooHR connector for the reasoning."""+ return []++ async def fetch_workforce(self) -> list[WorkforceRecord]:+ records: list[WorkforceRecord] = []+ async with self._client() as client:+ url: str | None = "/workers/"+ params: dict[str, Any] | None = {"limit": 100, "expand": _EXPAND}+ for _ in range(_MAX_PAGES):+ if url is None:+ break+ response = await client.get(url, params=params)+ response.raise_for_status()+ body = response.json()++ redacted = ((body.get("__meta") or {}).get("redacted_fields")) or []+ if redacted:+ # A fact about the tenant's configuration, not an error.+ # Logged so an operator can see why a column is empty+ # rather than concluding the connector is broken.+ logger.info(+ "rippling.fields_redacted_by_tenant_policy",+ fields=[str(entry.get("name")) for entry in redacted][:10],+ )++ for worker in body.get("results") or []:+ record = self._to_record(worker)+ if record is not None:+ records.append(record)++ url = body.get("next_link") or None+ # `next_link` is an absolute URL already carrying the+ # cursor; re-sending the first page's params would reset it.+ params = None+ return records++ @staticmethod+ def _to_record(worker: dict[str, Any]) -> WorkforceRecord | None:+ external_id = str(worker.get("id") or "").strip()+ if not external_id:+ return None++ department = worker.get("department")+ department_name = department.get("name") if isinstance(department, dict) else None++ employment_type = worker.get("employment_type")+ raw_type = employment_type.get("type") if isinstance(employment_type, dict) else None++ return WorkforceRecord(+ external_id=external_id,+ email=(worker.get("work_email") or "").strip() or None,+ display_name=None,+ status=normalise_status(worker.get("status"), _STATUS_MAP),+ start_date=(worker.get("start_date") or "").strip() or None,+ end_date=(worker.get("end_date") or "").strip() or None,+ manager_external_id=(str(worker.get("manager_id") or "").strip() or None),+ department=(department_name or "").strip() or None,+ worker_type=_TYPE_MAP.get(str(raw_type or "").strip().lower(), "unknown"),+ title=(worker.get("title") or "").strip() or None,+ )diff --git a/services/connectors/app/scheduler.py b/services/connectors/app/scheduler.pyindex b8336f463..ee70f041c 100644--- a/services/connectors/app/scheduler.py+++ b/services/connectors/app/scheduler.py@@ -650,6 +650,15 @@ class ConnectorScheduler:# fetch that fails must not be reported as a successful sync.await self._sync_vulnerability_findings(connector, target)+ # Workforce and device context, for the same reason and by the same+ # route. `import_context` in the API had exactly one production+ # caller before this -- a manual POST -- so a tenant's HR data was+ # only ever as current as the last file somebody uploaded, and a+ # termination that happened on Friday reached triage on Monday if+ # anyone remembered. Depth plan wave 2 item 1.3 says this runs on+ # the schedule, which means here.+ await self._sync_workforce_context(connector, target)+# Normalize defensively: connectors *should* normalize themselves# in fetch_alerts, but we double-tap so a connector that returns# raw events still produces consistent shapes downstream.@@ -1100,6 +1109,76 @@ class ConnectorScheduler:target.connector_type,)+ async def _sync_workforce_context(self, connector: Any, target: Any) -> None:+ """Materialise an HR or MDM connector's context, if it has any.++ Written here rather than posted to the API for the same reason+ `_sync_vulnerability_findings` above is: the service principal is+ deliberately read-only, and this service already holds a database+ engine and the tenant id it is polling for.++ Deliberately in its own `try`: a context sync that fails must not+ cost the poll its events, and a fetch that fails must not be+ reported as a successful sync.+ """+ fetch_workers = getattr(connector, "fetch_workforce", None)+ fetch_devices = getattr(connector, "fetch_devices", None)+ if fetch_workers is None and fetch_devices is None:+ return++ workers = []+ devices = []+ try:+ if fetch_workers is not None:+ workers = await fetch_workers()+ if fetch_devices is not None:+ devices = await fetch_devices()+ except Exception:+ logger.exception(+ "connector.scheduler.workforce_fetch_failed id=%s type=%s",+ getattr(target, "id", None),+ getattr(target, "connector_type", None),+ )+ return++ if not workers and not devices:+ return++ try:+ from app.workforce_store import sync_workforce++ report = await sync_workforce(+ self._engine,+ tenant_id=target.tenant_id,+ connector_type=target.connector_type,+ workers=workers,+ devices=devices,+ )+ logger.info(+ "connector.scheduler.workforce_synced id=%s workers=%d devices=%d rejected=%d",+ target.id,+ report.workers,+ report.devices,+ len(report.rejected),+ )+ for rejection in report.rejected[:20]:+ # Named rather than counted. "synced 900 of 1000" does not+ # say whether the missing hundred are one malformed+ # department or every contractor.+ logger.warning(+ "connector.scheduler.workforce_record_rejected id=%s kind=%s record=%s reason=%s",+ target.id,+ rejection["kind"],+ rejection["id"],+ rejection["reason"],+ )+ except Exception:+ logger.exception(+ "connector.scheduler.workforce_sync_failed id=%s type=%s",+ getattr(target, "id", None),+ getattr(target, "connector_type", None),+ )+async def _promote_overdue_findings(self) -> None:"""Patch-window promotion sweep (docs/cve-patch-policy.md rule 5).diff --git a/services/connectors/app/workforce.py b/services/connectors/app/workforce.pynew file mode 100644index 000000000..ff1ebd355--- /dev/null+++ b/services/connectors/app/workforce.py@@ -0,0 +1,123 @@+"""Workforce and device context: the record shapes.++Depth plan wave 2, item 1.3.++Why this is a store and not an event stream+-------------------------------------------+An employee's last day and a laptop's compliance state are not events. They+are current facts that change slowly and are read at triage time, which is+the opposite of the alert pipeline's shape. Pushing them through ingest+would make "is this person leaving" a question answered by searching the+lake for the most recent HR event, which is both slower and wrong whenever+the last poll failed.++Why a Postgres table and not only the graph+--------------------------------------------+`services/api/app/services/context_import.py` already imports exactly this+context, and writes it to Neo4j. Neo4j is in the `full` profile. A CORE+install -- the one `make up` gives you -- has no graph, so on CORE the HR+dimension would not exist at all and every detection and triage input that+reads it would be silently dead. ADR 0010 put the entity store in CORE for+this reason; this is the same decision applied to the same data.++Both paths stay. The graph import is richer (it links employees to+identities and applications through relationships), the table is the one+that is always there, and the scheduler writes the table because the+connectors service has a Postgres engine and no Neo4j driver.++No database dependency, on purpose+-----------------------------------+This module holds the shapes and nothing else; the store that writes them+is `app/workforce_store.py`. The split is not tidiness: the detection+replay worker imports the whole connector registry with a minimal+dependency set, so a `from sqlalchemy import text` reachable from a+connector's import graph takes the entire validation job down with+`ModuleNotFoundError: No module named 'sqlalchemy'`. A connector must not+pull a database driver in behind it.++Personal data minimisation+--------------------------+Only the fields item 1.3 lists are stored: employment status, start date,+termination or last-day date, manager, department and worker type for a+person; owner, compliance state, OS version, encryption and EDR agent+health for a device. No compensation, no personal contact details, no date+of birth, no national identifier -- several of which the vendor APIs return+and this module drops on the floor rather than persisting. Rows are+tenant-scoped under RLS and are covered by the tenant-erasure path.+"""++from __future__ import annotations++import logging+from dataclasses import dataclass+from typing import Any++logger = logging.getLogger(__name__)++#: Employment status, normalised. `unknown` is a real member and is what an+#: unrecognised vendor value becomes: deciding somebody still works here on+#: a value we do not recognise is the wrong direction to be wrong in.+WORKER_STATUSES = ("active", "leave", "terminated", "pending", "unknown")++#: Worker type. The distinction 1.3 asks for is employee versus contractor,+#: and a source that does not say stays `unknown` rather than defaulting to+#: employee -- a contractor misread as staff loses exactly the signal the+#: field exists for.+WORKER_TYPES = ("employee", "contractor", "unknown")++#: Device compliance, normalised across vendors. `unknown` covers both "the+#: MDM has not evaluated this device" and "the vendor reported a state we do+#: not recognise", and must never render as compliant.+COMPLIANCE_STATES = ("compliant", "noncompliant", "in_grace_period", "not_enrolled", "unknown")+++@dataclass(frozen=True)+class WorkforceRecord:+ """One person, as an HR system reports them.++ Dates are kept as the vendor's own ISO-8601 date strings rather than+ parsed: a termination date is a calendar date in a jurisdiction, not an+ instant, and parsing it into a UTC datetime here would move somebody's+ last day by a day for half the world.+ """++ external_id: str+ email: str | None = None+ display_name: str | None = None+ status: str = "unknown"+ start_date: str | None = None+ end_date: str | None = None+ manager_external_id: str | None = None+ department: str | None = None+ worker_type: str = "unknown"+ title: str | None = None+++@dataclass(frozen=True)+class DeviceRecord:+ """One managed device, as an MDM reports it.++ `encrypted` is a tri-state on purpose. `False` means the MDM evaluated+ the device and found no encryption, which is a finding; `None` means+ nobody said, which is not. Collapsing them would put every+ unenrolled-but-known device into the finding.+ """++ external_id: str+ hostname: str | None = None+ owner_email: str | None = None+ owner_external_id: str | None = None+ compliance_state: str = "unknown"+ os_name: str | None = None+ os_version: str | None = None+ encrypted: bool | None = None+ edr_agent_health: str | None = None+ serial_number: str | None = None+ last_seen: str | None = None+++def normalise_status(raw: Any, mapping: dict[str, str]) -> str:+ """Map a vendor status onto the closed set, or `unknown`."""+ if not isinstance(raw, str):+ return "unknown"+ return mapping.get(raw.strip().lower(), "unknown")diff --git a/services/connectors/app/workforce_store.py b/services/connectors/app/workforce_store.pynew file mode 100644index 000000000..9f19fd534--- /dev/null+++ b/services/connectors/app/workforce_store.py@@ -0,0 +1,196 @@+"""Where the scheduler puts workforce and device context.++Depth plan wave 2, item 1.3. The record shapes live in `app/workforce.py`,+which deliberately carries no database dependency so a connector importing+them does not pull SQLAlchemy into its import graph. This half does the+writing and may.++**Upsert, never replace.** An import runs on a schedule against a source of+record that may be partial or briefly unavailable. Replacing a tenant's+context with whatever one run produced would delete a department because an+HR export timed out.++**Departure is recorded, not deleted.** A terminated employee whose+accounts still authenticate is the highest-signal row this table can hold,+and removing it on offboarding destroys exactly that signal.+"""++from __future__ import annotations++import logging+from dataclasses import dataclass+from typing import Any++from sqlalchemy import text++from app.workforce import (+ COMPLIANCE_STATES,+ WORKER_STATUSES,+ WORKER_TYPES,+ DeviceRecord,+ WorkforceRecord,+)++logger = logging.getLogger(__name__)++_UPSERT_WORKER = text(+ """+ INSERT INTO workforce_members (+ tenant_id, connector_type, external_id, email, display_name,+ status, start_date, end_date, manager_external_id, department,+ worker_type, title, last_synced_at+ ) VALUES (+ CAST(:tenant_id AS uuid), :connector_type, :external_id, :email, :display_name,+ :status, CAST(:start_date AS date), CAST(:end_date AS date),+ :manager_external_id, :department, :worker_type, :title, NOW()+ )+ ON CONFLICT (tenant_id, connector_type, external_id) DO UPDATE SET+ email = EXCLUDED.email,+ display_name = EXCLUDED.display_name,+ status = EXCLUDED.status,+ start_date = EXCLUDED.start_date,+ end_date = EXCLUDED.end_date,+ manager_external_id = EXCLUDED.manager_external_id,+ department = EXCLUDED.department,+ worker_type = EXCLUDED.worker_type,+ title = EXCLUDED.title,+ last_synced_at = NOW()+ """+)++_UPSERT_DEVICE = text(+ """+ INSERT INTO workforce_devices (+ tenant_id, connector_type, external_id, hostname, owner_email,+ owner_external_id, compliance_state, os_name, os_version,+ encrypted, edr_agent_health, serial_number, last_seen, last_synced_at+ ) VALUES (+ CAST(:tenant_id AS uuid), :connector_type, :external_id, :hostname, :owner_email,+ :owner_external_id, :compliance_state, :os_name, :os_version,+ :encrypted, :edr_agent_health, :serial_number,+ CAST(:last_seen AS timestamptz), NOW()+ )+ ON CONFLICT (tenant_id, connector_type, external_id) DO UPDATE SET+ hostname = EXCLUDED.hostname,+ owner_email = EXCLUDED.owner_email,+ owner_external_id = EXCLUDED.owner_external_id,+ compliance_state = EXCLUDED.compliance_state,+ os_name = EXCLUDED.os_name,+ os_version = EXCLUDED.os_version,+ encrypted = EXCLUDED.encrypted,+ edr_agent_health = EXCLUDED.edr_agent_health,+ serial_number = EXCLUDED.serial_number,+ last_seen = EXCLUDED.last_seen,+ last_synced_at = NOW()+ """+)+++@dataclass+class SyncReport:+ """Per-record outcome, named.++ Modelled on `ImportReport` in `context_import.py` and for the same+ reason its docstring gives: "imported 900 of 1000" does not say whether+ the missing hundred are one malformed department or every contractor.+ """++ workers: int = 0+ devices: int = 0+ rejected: list[dict[str, str]] = None # type: ignore[assignment]++ def __post_init__(self) -> None:+ if self.rejected is None:+ self.rejected = []++ def reject(self, kind: str, identifier: str, reason: str) -> None:+ self.rejected.append({"kind": kind, "id": identifier[:80], "reason": reason})+++async def sync_workforce(+ engine: Any,+ *,+ tenant_id: Any,+ connector_type: str,+ workers: list[WorkforceRecord] | None = None,+ devices: list[DeviceRecord] | None = None,+) -> SyncReport:+ """Upsert workforce and device context for one tenant.++ Upsert and never replace, the same rule `context_import.py` states:+ an import runs on a schedule against a source that may be partial or+ briefly unavailable, and replacing a tenant's context with whatever one+ run produced would delete a department because an HR export timed out.++ A departure is recorded, not deleted. A terminated employee whose+ accounts still authenticate is the highest-signal row this table can+ hold, and removing it on offboarding destroys exactly that signal.+ """+ report = SyncReport()+ scoped_workers = workers or []+ scoped_devices = devices or []+ if not scoped_workers and not scoped_devices:+ return report++ async with engine.begin() as conn:+ for worker in scoped_workers:+ if not worker.external_id:+ report.reject("worker", "<missing>", "no external id")+ continue+ if worker.status not in WORKER_STATUSES:+ report.reject("worker", worker.external_id, f"status {worker.status!r} is not one of {WORKER_STATUSES}")+ continue+ if worker.worker_type not in WORKER_TYPES:+ report.reject("worker", worker.external_id, f"worker_type {worker.worker_type!r} is not one of {WORKER_TYPES}")+ continue+ await conn.execute(+ _UPSERT_WORKER,+ {+ "tenant_id": str(tenant_id),+ "connector_type": connector_type,+ "external_id": worker.external_id,+ "email": (worker.email or None),+ "display_name": worker.display_name,+ "status": worker.status,+ "start_date": worker.start_date,+ "end_date": worker.end_date,+ "manager_external_id": worker.manager_external_id,+ "department": worker.department,+ "worker_type": worker.worker_type,+ "title": worker.title,+ },+ )+ report.workers += 1++ for device in scoped_devices:+ if not device.external_id:+ report.reject("device", "<missing>", "no external id")+ continue+ if device.compliance_state not in COMPLIANCE_STATES:+ report.reject(+ "device",+ device.external_id,+ f"compliance_state {device.compliance_state!r} is not one of {COMPLIANCE_STATES}",+ )+ continue+ await conn.execute(+ _UPSERT_DEVICE,+ {+ "tenant_id": str(tenant_id),+ "connector_type": connector_type,+ "external_id": device.external_id,+ "hostname": device.hostname,+ "owner_email": (device.owner_email or None),+ "owner_external_id": device.owner_external_id,+ "compliance_state": device.compliance_state,+ "os_name": device.os_name,+ "os_version": device.os_version,+ "encrypted": device.encrypted,+ "edr_agent_health": device.edr_agent_health,+ "serial_number": device.serial_number,+ "last_seen": device.last_seen,+ },+ )+ report.devices += 1++ return reportdiff --git a/services/connectors/tests/connectors/test_workforce_context.py b/services/connectors/tests/connectors/test_workforce_context.pynew file mode 100644index 000000000..872fd10ed--- /dev/null+++ b/services/connectors/tests/connectors/test_workforce_context.py@@ -0,0 +1,329 @@+"""HR and device context has to reach triage, not just exist.++Depth plan wave 2, item 1.3.++Three things are asserted here and each one has failed in this repository+before, in this order of severity:++1. **The connector is registered.** A class in the tree that is not in+ `_CONNECTOR_CLASSES` is invisible to the catalogue, the wizard and the+ scheduler.+2. **The scheduler actually syncs it.** The defining defect of this tree is+ a mechanism with no caller. An HR connector whose `fetch_workforce` is+ called by nothing is indistinguishable from no connector at all, and the+ plan says so explicitly: the import must run on the schedule, not only on+ the manual route.+3. **The vendor shapes are real.** Every read is replayed against a+ recorded, vendor-shaped payload through a mock transport, following+ `test_live_vendor_smoke.py`. The field names come from each vendor's+ current public reference, cited in the connector module.++The mock payloads are synthetic and labelled as such. They carry the field+names and the response envelope the vendor documents, and nothing else.+"""++from __future__ import annotations++import sys+from pathlib import Path++import httpx+import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++from app.connectors import _CONNECTOR_CLASSES # noqa: E402+from app.connectors.bamboohr import BambooHRConnector # noqa: E402+from app.connectors.microsoft_intune import MicrosoftIntuneConnector # noqa: E402+from app.connectors.rippling import RipplingConnector # noqa: E402+from app.workforce import WorkforceRecord # noqa: E402++WORKFORCE_CONNECTOR_IDS = {"bamboohr", "rippling", "microsoft_intune"}+++def _registered() -> set[str]:+ return {cls.connector_id for cls in _CONNECTOR_CLASSES}+++class TestRegistration:+ def test_every_workforce_connector_is_in_the_registry(self) -> None:+ missing = WORKFORCE_CONNECTOR_IDS - _registered()+ assert not missing, f"not in _CONNECTOR_CLASSES, so invisible to the catalogue and the scheduler: {sorted(missing)}"++ def test_secrets_are_declared_secret(self) -> None:+ """A credential field typed `string` renders in the clear and is+ stored unencrypted, because the vault keys off the declared type."""+ expected_secret = {+ "bamboohr": {"api_key"},+ "rippling": {"api_token"},+ "microsoft_intune": {"client_secret"},+ }+ for cls in (BambooHRConnector, RipplingConnector, MicrosoftIntuneConnector):+ declared = {f.name for f in cls.schema().fields if f.type == "secret"}+ assert declared == expected_secret[cls.connector_id], cls.connector_id++ def test_each_declares_the_capability_the_scheduler_dispatches_on(self) -> None:+ """Two capabilities, not one. An HR system answers "who works here"+ and an MDM answers "what is this laptop"; a single verb would make+ the catalogue claim each connector can answer both."""+ from app.connectors.base import Capability++ for cls in (BambooHRConnector, RipplingConnector):+ assert Capability.PULL_WORKFORCE in cls.capabilities(), cls.connector_id+ assert Capability.PULL_DEVICE_INVENTORY in MicrosoftIntuneConnector.capabilities()+++class TestTheRegistryCarriesNoDatabaseDependency:+ """A connector must not pull a database driver into its import graph.++ `scripts/connector_normalize_worker.py` imports the whole registry with+ a minimal dependency set to replay detections through real connectors.+ A module-level `from sqlalchemy import text` reachable from any+ connector took that entire job down with+ `ModuleNotFoundError: No module named 'sqlalchemy'`, which is why the+ record shapes and the store that writes them are separate modules.+ """++ def test_importing_every_connector_needs_no_sqlalchemy(self) -> None:+ import subprocess++ # A subprocess with sqlalchemy blocked at import, because this+ # process has already imported it and a monkeypatched sys.modules+ # entry would not reproduce the worker's environment faithfully.+ probe = (+ "import sys\n"+ "class _Block:\n"+ " def find_module(self, name, path=None):\n"+ " return self if name == 'sqlalchemy' or name.startswith('sqlalchemy.') else None\n"+ " def load_module(self, name):\n"+ " raise ImportError('No module named ' + repr(name))\n"+ "sys.meta_path.insert(0, _Block())\n"+ "from app.connectors import _CONNECTOR_CLASSES\n"+ "print(len(_CONNECTOR_CLASSES))\n"+ )+ done = subprocess.run(+ [sys.executable, "-c", probe],+ cwd=str(Path(__file__).resolve().parents[2]),+ capture_output=True,+ text=True,+ check=False,+ )+ assert done.returncode == 0, (+ "importing the connector registry failed with sqlalchemy unavailable, so the "+ f"detection-replay worker cannot load it either:\n{done.stderr[-800:]}"+ )+ assert int(done.stdout.strip()) > 50+++class TestSchedulerRunsTheImport:+ """The wiring half. `import_context` had exactly one production caller+ before this work -- a manual POST route -- so a tenant's HR data was only+ ever as current as the last time somebody uploaded a file."""++ def test_the_scheduler_calls_a_workforce_sync_on_every_poll(self) -> None:+ import inspect++ from app.scheduler import ConnectorScheduler++ source = inspect.getsource(ConnectorScheduler._poll_one)+ assert "_sync_workforce_context" in source, (+ "the poll path does not sync workforce context, so an HR connector would be registered, configured, polled and silently ignored"+ )++ @pytest.mark.asyncio+ async def test_a_connector_without_the_method_is_skipped_quietly(self) -> None:+ """An EDR connector must not be asked for an employee roster."""+ from app.scheduler import ConnectorScheduler++ scheduler = ConnectorScheduler.__new__(ConnectorScheduler)+ scheduler._engine = None+ # No `fetch_workforce` attribute at all: the sync returns without+ # touching the engine, which is None here precisely so that a sync+ # that tried would raise rather than pass.+ await ConnectorScheduler._sync_workforce_context(scheduler, object(), object())+++def _transport(handler): # noqa: ANN001, ANN202+ return httpx.MockTransport(handler)+++class TestBambooHRVendorShape:+ """Recorded against `GET /api/v1/employees/{id}` with an explicit field+ list, documented at documentation.bamboohr.com.++ The directory endpoint is deliberately NOT used: its own reference says+ it "never includes ... employment status and history, in any+ configuration" and excludes former employees entirely -- which is+ precisely the population this feature exists to see.+ """++ @pytest.mark.asyncio+ async def test_it_reads_the_fields_1_3_names_and_nothing_else(self) -> None:+ seen: dict[str, str] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["url"] = str(request.url)+ if request.url.path.endswith("/employees/directory"):+ return httpx.Response(+ 200,+ json={+ "fields": [{"id": "displayName"}, {"id": "workEmail"}],+ "employees": [{"id": "431", "displayName": "Ada Byron", "workEmail": "[email protected]"}],+ },+ )+ return httpx.Response(+ 200,+ json={+ "id": "431",+ "displayName": "Ada Byron",+ "workEmail": "[email protected]",+ "department": "Platform Engineering",+ "jobTitle": "Staff Engineer",+ "supervisorEid": "12",+ "hireDate": "2021-03-01",+ "terminationDate": "2026-11-14",+ "status": "Active",+ "employmentHistoryStatus": "Full-Time",+ },+ )++ connector = BambooHRConnector(subdomain="acme", api_key="k", transport=_transport(handler))+ records = await connector.fetch_workforce()++ assert len(records) == 1+ record = records[0]+ assert isinstance(record, WorkforceRecord)+ assert record.external_id == "431"+ assert record.email == "[email protected]"+ assert record.department == "Platform Engineering"+ assert record.manager_external_id == "12"+ assert record.start_date == "2021-03-01"+ assert record.end_date == "2026-11-14"+ assert record.worker_type == "employee"+ # The request must ask for the fields, not hope for them: a reader+ # that does not name a column cannot recover it with an adapter.+ assert "terminationDate" in seen["url"]+ assert "hireDate" in seen["url"]++ @pytest.mark.asyncio+ async def test_a_contractor_is_reported_as_one(self) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/employees/directory"):+ return httpx.Response(200, json={"fields": [], "employees": [{"id": "7"}]})+ return httpx.Response(+ 200,+ json={"id": "7", "employmentHistoryStatus": "Contractor", "status": "Active"},+ )++ connector = BambooHRConnector(subdomain="acme", api_key="k", transport=_transport(handler))+ assert (await connector.fetch_workforce())[0].worker_type == "contractor"+++class TestRipplingVendorShape:+ """Recorded against `GET https://rest.ripplingapis.com/workers/`, OAuth+ scope `workers.read`, documented at developer.rippling.com."""++ @pytest.mark.asyncio+ async def test_it_maps_the_documented_status_vocabulary(self) -> None:+ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={+ "results": [+ {+ "id": "w_1",+ "work_email": "[email protected]",+ "status": "TERMINATED",+ "start_date": "2019-06-03",+ "end_date": "2026-10-30",+ "manager_id": "w_0",+ "department": {"id": "d_1", "name": "Security"},+ "employment_type": {"type": "CONTRACTOR"},+ "title": "Principal Analyst",+ }+ ],+ "next_link": None,+ },+ )++ connector = RipplingConnector(api_token="t", transport=_transport(handler))+ record = (await connector.fetch_workforce())[0]+ assert record.external_id == "w_1"+ assert record.status == "terminated"+ assert record.end_date == "2026-10-30"+ assert record.manager_external_id == "w_0"+ assert record.department == "Security"+ assert record.worker_type == "contractor"++ @pytest.mark.asyncio+ async def test_an_unknown_status_is_unknown_and_not_guessed(self) -> None:+ """A vocabulary the vendor adds later must not be read as `active`.+ Deciding somebody still works here on a value we do not recognise is+ the wrong direction to be wrong in."""++ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={"results": [{"id": "w_2", "status": "ON_LEAVE_EXTENDED"}], "next_link": None},+ )++ connector = RipplingConnector(api_token="t", transport=_transport(handler))+ assert (await connector.fetch_workforce())[0].status == "unknown"+++class TestIntuneVendorShape:+ """Recorded against `GET /deviceManagement/managedDevices` on Microsoft+ Graph v1.0, permission `DeviceManagementManagedDevices.Read.All`."""++ @pytest.mark.asyncio+ async def test_it_reads_the_device_fields_1_3_names(self) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/token"):+ return httpx.Response(200, json={"access_token": "a", "expires_in": 3600})+ return httpx.Response(+ 200,+ json={+ "value": [+ {+ "id": "705c034c-034c-705c-4c03-5c704c035c70",+ "deviceName": "LAPTOP-ADA",+ "userPrincipalName": "[email protected]",+ "complianceState": "noncompliant",+ "operatingSystem": "Windows",+ "osVersion": "10.0.26100.2033",+ "isEncrypted": False,+ "partnerReportedThreatState": "activated",+ "managedDeviceOwnerType": "company",+ "serialNumber": "S-1",+ "lastSyncDateTime": "2026-10-31T23:00:00Z",+ }+ ]+ },+ )++ connector = MicrosoftIntuneConnector(tenant_id="t", client_id="c", client_secret="s", transport=_transport(handler))+ device = (await connector.fetch_devices())[0]+ assert device.external_id == "705c034c-034c-705c-4c03-5c704c035c70"+ assert device.hostname == "LAPTOP-ADA"+ assert device.owner_email == "[email protected]"+ assert device.compliance_state == "noncompliant"+ assert device.os_version == "10.0.26100.2033"+ assert device.encrypted is False+ assert device.edr_agent_health == "activated"++ @pytest.mark.asyncio+ async def test_an_unreported_compliance_state_is_unknown(self) -> None:+ """Graph's own enumeration has `unknown`, and a device Intune has+ not evaluated must not read as compliant."""++ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/token"):+ return httpx.Response(200, json={"access_token": "a", "expires_in": 3600})+ return httpx.Response(200, json={"value": [{"id": "d1", "complianceState": "unknown"}]})++ connector = MicrosoftIntuneConnector(tenant_id="t", client_id="c", client_secret="s", transport=_transport(handler))+ device = (await connector.fetch_devices())[0]+ assert device.compliance_state == "unknown"+ # Encryption nobody reported is None, not False: "not encrypted" is+ # a finding and "not reported" is not.+ assert device.encrypted is Nonediff --git a/services/connectors/tests/test_schemas.py b/services/connectors/tests/test_schemas.pyindex d97d729ac..959ee5062 100644--- a/services/connectors/tests/test_schemas.py+++ b/services/connectors/tests/test_schemas.py@@ -16,7 +16,13 @@ from app.connectors.base import BaseConnector, ConnectorSchema, Field# Deliberately its own category rather than folded into `saas`. A `saas`# connector pulls a vendor's audit log; these pull runtime activity from# software the customer operates, and the console groups by category.-ALLOWED_CATEGORIES = {"siem", "edr", "cloud", "iam", "saas", "audit", "vcs", "ndr", "network", "ai"}+# `hr` and `mdm` are their own categories rather than folded into `saas`+# for the same reason `ai` is: a `saas` connector pulls a vendor's audit log+# and produces events, while these produce slowly-changing *context* about+# people and devices and emit no events at all. The console groups by+# category, and a reader looking for "where does my employee data come+# from" should not have to find it among twenty-two SaaS audit sources.+ALLOWED_CATEGORIES = {"siem", "edr", "cloud", "iam", "saas", "audit", "vcs", "ndr", "network", "ai", "hr", "mdm"}ALLOWED_FIELD_TYPES = {"string", "secret", "select", "textarea", "boolean", "number"}diff --git a/services/ingest/internal/normalizer/ocsf_classes.go b/services/ingest/internal/normalizer/ocsf_classes.goindex 1bee6fcf9..80820a7aa 100644--- a/services/ingest/internal/normalizer/ocsf_classes.go+++ b/services/ingest/internal/normalizer/ocsf_classes.go@@ -149,6 +149,13 @@ var classesWithNoProducerYet = map[int]string{type connectorClass struct {classUID intgenericReason string+ // contextOnly marks a connector that emits no ingest events at all: its+ // fetch_alerts returns an empty list and its data reaches the platform+ // through a different writer. Such a connector carries no generic-mapping+ // debt, because no event of its ever reaches the normalizer to be mapped,+ // so it is counted apart from the ceiling. The gate verifies the claim+ // against the connector's own fetch_alerts rather than believing it.+ contextOnly bool}// connectorOCSFClass carries a decision for every connector type@@ -299,6 +306,22 @@ var connectorOCSFClass = map[string]connectorClass{// correct outcome rather than an oversight. The reason is recorded so a// reader can tell these apart from a connector nobody classified.// ---------------------------------------------------------------+ // ---------------------------------------------------------------+ // Depth plan wave 2, item 1.3. HR and MDM connectors publish **no+ // events at all**: `fetch_alerts` returns an empty list on each by+ // design, and their output is slowly-changing context written to+ // `workforce_members` and `workforce_devices` by the connector+ // scheduler, never to ingest. So there is no class to assign, and a+ // profile would be an entry nothing can reach.+ //+ // Recorded here rather than left absent precisely because this table+ // exists to tell "decided to take the generic path" apart from "nobody+ // looked", and an HR connector with no entry reads as the second.+ // ---------------------------------------------------------------+ "bamboohr": {genericReason: "HR context, not events: fetch_alerts returns nothing and the scheduler writes workforce_members", contextOnly: true},+ "rippling": {genericReason: "HR context, not events: fetch_alerts returns nothing and the scheduler writes workforce_members", contextOnly: true},+ "microsoft_intune": {genericReason: "MDM device context, not events: fetch_alerts returns nothing and the scheduler writes workforce_devices", contextOnly: true},+"crowdstrike": {genericReason: "EDR detections: already judged by the vendor"},"sentinelone": {genericReason: "EDR threats: already judged by the vendor"},"carbon_black": {genericReason: "EDR alerts: already judged by the vendor"},