mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-24 08:35:46 +08:00
feat(connectors): the M365 audit DLP.All stream is a real per-instance switch (WS4.2) (#2004)
## What WS4.2 of the gap-closure program. The `m365_audit` module docstring promised *"DLP can be re-enabled per-instance later via `connector_config` once the analyst opt-in path lands"* while `_DEFAULT_CONTENT_TYPES` was hard-coded and the constructor accepted no such setting — the aspirational-comment family. A tenant who wanted Purview DLP events through the audit trail had no switch to flip. ## The change - `schema()` declares **`include_dlp`** (boolean, default **off**) with help text naming the volume cost and the stricter `ActivityFeed.ReadDlp` permission that sensitive-data details require. - The constructor accepts it; coercion follows the house `_truthy` rule (the `wiz` connector's): a boolean from the wizard and a string from a hand-written instance row mean the same thing, and **an unparseable value means off** — a collector that defaults to on when it cannot read its own switch is a poll the tenant did not ask for. - `content_types()` replaces direct `_DEFAULT_CONTENT_TYPES` iteration in both the subscription-start and content-listing loops; a transport seam lets tests drive the real fetch path. - Docs page corrected: it claimed *"the connector subscribes to all five content types"*, which was false before this change and would have been misleading after; it now states the four-by-default / opt-in-fifth truth and what `ActivityFeed.ReadDlp` does and does not gate. - Docstring rewritten to state what is true (the 'later' promise is gone, and a test pins that). ## Testing (failing test first) - `test_m365_audit_dlp_toggle.py` — **15 cases, all red on the pre-change tree** (schema field absent, constructor rejects the kwarg, fetch path unobservable): schema declares the field defaulting off; the docstring no longer says 'later'; default polls exactly the four `Audit.*` types; five truthy spellings enable `DLP.All`; six garbage/falsy values mean off; and the fetch path is observed **at the wire** — the mock Management API records the real HTTP requests and the content-type selection is read off them, not off a constant. - **Negative control**: forcing the coercion to always-`False` fails the four enable cases (`4 failed, 11 passed`); restored, `15 passed`. - Full connectors suite: **2040 passed, 3 skipped**. `ruff` clean, `check_mypy_baseline` OK, `check_claim_gate_matrix` 408 rows / 399 GATED, `readme_gates` OK. ## Artifacts regenerated (not hand-edited) `scripts/connector_conformance.py`, `scripts/generate_connector_catalog_fallback.py`, `scripts/generate_connector_docs.py`, `pnpm marketplace:sync` (the `coverage.md` timestamp diff is the normal regeneration artifact). `plugins/m365-audit/plugin.yaml` mirrors the schema field. ## Claim matrix One new GATED row (the switch reaches the wire), tallies recomputed by the script: 408 rows — 399 GATED / 9 PARTIAL / 0 NO GATE.
This commit is contained in:
@@ -53,6 +53,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
cases and a live-Postgres suite (expiry exclusion is the SQL's own
|
||||
WHERE; the two upserts own one column each; RLS under the NOBYPASSRLS
|
||||
role; the HR door end to end).
|
||||
- **The M365 audit connector's `DLP.All` stream is a real per-instance
|
||||
switch** (WS4.2 of the gap-closure program). The module docstring had
|
||||
promised "DLP can be re-enabled per-instance later via `connector_config`"
|
||||
while `_DEFAULT_CONTENT_TYPES` was hard-coded and the constructor accepted
|
||||
no such setting — the aspirational-comment family. The schema now declares
|
||||
`include_dlp` (boolean, default off, rendered by the wizard and persisted
|
||||
on the instance row); coercion follows the house rule that a boolean from
|
||||
the wizard and a string from a hand-written row mean the same thing and an
|
||||
unparseable value means *off*, because a collector that defaults to on
|
||||
when it cannot read its own switch is a poll the tenant did not ask for.
|
||||
Proven at the wire: `test_m365_audit_dlp_toggle.py` (15 cases) drives the
|
||||
real fetch path against a mock Management API and reads the content-type
|
||||
selection off the HTTP requests — default polls exactly the four `Audit.*`
|
||||
types, opt-in adds `DLP.All`. The connector docs page now states the
|
||||
default honestly (it had claimed "subscribes to all five content types")
|
||||
and names the stricter `ActivityFeed.ReadDlp` permission that
|
||||
sensitive-data details require.
|
||||
|
||||
- **Every open case has an accountable owner and a next-action clock**
|
||||
(WS7.4, completing WS7 of the gap-closure program). An owner is a person
|
||||
|
||||
+1
-1
@@ -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 **409 rows — 400 GATED / 9 PARTIAL / 0 NO GATE**. Nine rows are PARTIAL, each naming what closes it: responder-app voice until a screen and an allowlisted on-device recogniser land with a device test; console internationalisation until the analyst surfaces render through `translate()` with a test that fails if a hardcoded string returns; "where does package P at version V run" until a connector fetches a code platform's SBOM, since the SPDX path is proven against a document and has no live producer; "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; "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; "several individually unalarming signals become one finding" until a corpus replayed through fusion's own enrichment exists, because the balanced corpus carries vendor alert evidence while every weak signal is produced by that enrichment, so all 72 items score zero and `scripts/calibrate_weak_signals.py` refuses to publish a sweep rather than calibrate against nothing; 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 **410 rows — 401 GATED / 9 PARTIAL / 0 NO GATE**. Nine rows are PARTIAL, each naming what closes it: responder-app voice until a screen and an allowlisted on-device recogniser land with a device test; console internationalisation until the analyst surfaces render through `translate()` with a test that fails if a hardcoded string returns; "where does package P at version V run" until a connector fetches a code platform's SBOM, since the SPDX path is proven against a document and has no live producer; "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; "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; "several individually unalarming signals become one finding" until a corpus replayed through fusion's own enrichment exists, because the balanced corpus carries vendor alert evidence while every weak signal is produced by that enrichment, so all 72 items score zero and `scripts/calibrate_weak_signals.py` refuses to publish a sweep rather than calibrate against nothing; 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
|
||||
|
||||
@@ -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: 400 rows
|
||||
The last row is the one worth reading first. It is the honest index: 401 rows
|
||||
`GATED`, 9 `PARTIAL`, and a ratchet that refuses to let a row sit at
|
||||
`NO GATE`. Re-read the figure from the table rather than from here — a count
|
||||
copied into prose goes stale in silence, which is why
|
||||
|
||||
@@ -16,9 +16,9 @@ The M365 connector pulls **unified audit log events** from the Office 365 Manage
|
||||
| `Audit.SharePoint` | File access, sharing-link create, anonymous-link |
|
||||
| `Audit.AzureActiveDirectory` | User sign-in, MFA disable, app consent |
|
||||
| `Audit.General` | Teams meeting events, DLP matches, eDiscovery |
|
||||
| `DLP.All` | Data loss prevention rule matches |
|
||||
| `DLP.All` | Data loss prevention rule matches (opt-in) |
|
||||
|
||||
The connector subscribes to all five content types. Events are normalized with `source: m365` and `category` derived from the workload.
|
||||
The connector subscribes to the four `Audit.*` content types by default. `DLP.All` is a per-instance opt-in (the **Include DLP events** switch): the stream is high volume, and the Management API only includes sensitive-data details when the app registration also holds the stricter **`ActivityFeed.ReadDlp`** ("Read DLP policy events including sensitive details") permission — without it you still get the rule match and the affected file, just not the matched content excerpts. Events are normalized with `source: m365` and `category` derived from the workload.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
@@ -124,6 +124,7 @@ The Management API does not provide severity, so AiSOC infers from `Operation`:
|
||||
| `certificate_pem` | Certificate PEM (private key) | secret | no | — | **encrypted at rest** · Recommended over a client secret. Paste a PEM containing the PRIVATE KEY (and optionally the CERTIFICATE) for the certificate whose public .cer you uploaded under Entra portal > App registrations > your app > Certificates & secrets. |
|
||||
| `certificate_thumbprint` | Certificate Thumbprint | string | no | — | SHA-1 thumbprint shown next to the certificate under App registrations > Certificates & secrets. Optional when the PEM above also contains the certificate. |
|
||||
| `private_key_password` | Private Key Password | secret | no | — | **encrypted at rest** · Only if the private key in the PEM is encrypted. |
|
||||
| `include_dlp` | Include DLP events (DLP.All) | boolean | no | `False` | Also subscribe to the DLP.All content type — Purview DLP rule matches across Exchange, SharePoint/OneDrive and endpoints. Off by default: the stream is high volume, and reading sensitive-data details requires the separate 'Read DLP policy events including sensitive details' permission on the app registration. |
|
||||
|
||||
:::note Credential handling
|
||||
`client_secret`, `certificate_pem`, `private_key_password` are 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. See [credential vault](../operations/credentials.md).
|
||||
|
||||
@@ -10,7 +10,7 @@ sidebar_position: 2
|
||||
|
||||
# Detection Coverage
|
||||
|
||||
Generated: `2026-11-22T04:59:26Z`
|
||||
Generated: `2026-11-22T16:36:00Z`
|
||||
|
||||
This page is a **curated selection**, not the size of the corpus.
|
||||
It picks the highest-scoring rules per threat family from the set
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://aisoc.example.com/schemas/curated/v1.json",
|
||||
"version": "1.0.0",
|
||||
"generated": "2026-11-22T04:59:26Z",
|
||||
"generated": "2026-11-22T16:36:00Z",
|
||||
"stats": {
|
||||
"considered": 2942,
|
||||
"eligible": 2931,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://example.com/schemas/marketplace/v1.json",
|
||||
"version": "1.0.0",
|
||||
"generated": "2026-11-22T04:59:19Z",
|
||||
"generated": "2026-11-22T16:35:53Z",
|
||||
"categories": [
|
||||
{
|
||||
"id": "playbooks",
|
||||
@@ -255285,7 +255285,7 @@
|
||||
"source": "core",
|
||||
"tier": "stable",
|
||||
"path": "plugins/m365-audit/plugin.yaml",
|
||||
"sha256": "ea68a64d4da29f71904de2452bff2d1e9d775f79938b24370bcd2f9a0c9a3722"
|
||||
"sha256": "b8ec2a99a42973da4755938d7c92b80c796688d6d78099f3ca64451eaf086143"
|
||||
},
|
||||
{
|
||||
"id": "microsoft_intune",
|
||||
|
||||
@@ -10,6 +10,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
|
||||
|---|---|---|---|---|---|
|
||||
| A DLP alert normalizes into one finding whatever vendor raised it — policy, rule, data classes, file name/hash/size, channel, destination and its class, the enforcement the DLP product itself applied (`blocked` / `warned` / `allowed` / `audited`), user and device — with per-source profiles mapping only vendor-documented fields: an absent fact stays empty, a destination class is derived only from explicit vendor facts, an unstated enforcement stays null, and a source without a profile yields no finding rather than a best-effort parse | `services/api/app/services/dlp_finding.py`; `GET /alerts/{id}/dlp-finding` | `ci.yml :: Python — Tests` (api, `test_dlp_finding.py`, 15 cases over the vendors' own published shapes — Netskope's DLP alert export sample, the O365 Management Activity DLP schema with its 1–5 EnforcementMode ladder, Graph `alerts_v2` evidence objects — including absent-stays-empty, the managed_app-only destination-class rule, and the honest `finding: null` route answer) | core | GATED | Negative control recorded in the PR: corrupting one enforcement mapping fails two cases |
|
||||
| The insider watchlist is a control, not a checkbox: a watchlist row is never indefinite (reason + future expiry required, expired rows stop elevating), a watchlisted identity's alerts are tagged and floored `info`/`low` → `medium` **through the existing business-context path** (a machine-owned `managed_yaml` document beside the analyst's verbatim `yaml_text`, same engine, same triage-worker application point, never a downgrade of `high`/`critical`), the transition onto the list opens a departure-review case whose lake half reports *could not check* rather than zero when unreachable, and the HR door (`workforce_members` status/last-day, per-tenant opt-in, default off) lists departing members idempotently without ever shortening a manual row | `services/api/app/services/insider_watchlist.py`; migration 168; `services/api/app/workers/insider_watchlist_sweep.py` | `ci.yml :: Python — Tests` (api `test_insider_watchlist.py` 21 cases: the generated document parses with the console's own loader and evaluated by the real engine floors low and never touches high/critical, adversarial reasons stay data, validation names each unmet requirement, the lookback renders per-event-type counts and an unreachable lake as unknown-not-zero, the HR door never overwrites an existing row; agents `test_business_context_managed_rules.py` 8 cases: the **agents service's independent grammar implementation** parses the same golden fixture bytes and applies the same floor, and a parse error in either document never withdraws the other's rules) + `integration.yml :: The insider watchlist expires, elevates and reviews for real (live Postgres)` (expiry exclusion is the rebuild SELECT's own WHERE; the console save and the watchlist upsert own one column each and must not clobber the other; `watchlist_source` is a DB CHECK; policy RLS judged under the NOBYPASSRLS role including the unbound sweep arm; the HR door end to end — workforce row → watchlist row + managed rule + review case — idempotent on the second sweep; fails at setup on the pre-change tree) | core | GATED | Negative controls recorded in the PR: removing the expiry exclusion fails the live rebuild test; removing the severity guard makes the floor a downgrade and fails two never-downgrade cases |
|
||||
| The M365 audit connector's `DLP.All` stream is a real per-instance switch, not a promise: the `include_dlp` schema field (default off) reaches the wire — the subscription and content-listing calls name `DLP.All` only when the instance opted in — and an unparseable value means off, because a collector that defaults to on when it cannot read its own switch is a poll the tenant did not ask for | `services/connectors/app/connectors/m365_audit.py`; `apps/docs/docs/connectors/m365-audit.md` | `ci.yml :: Python — Tests` (connectors, `test_m365_audit_dlp_toggle.py`, 15 cases: the schema declares the field defaulting off, the module docstring no longer promises the switch "later", default polls exactly the four `Audit.*` types, five truthy spellings enable `DLP.All` and six garbage/falsy values mean off, and the fetch path is observed against a mock vendor — the content-type selection is read off the real HTTP requests, not off a constant) | core | GATED | Negative control recorded in the PR: forcing the coercion to always-off fails the four enable cases |
|
||||
| Every open case has an accountable owner — a person or an agent run — and a next-action clock: launching an investigation claims an unowned case for the run and never steals one a person holds, and `GET /cases/attention` surfaces open cases that are unowned or overdue with `owner_kind` named and `overdue_seconds` null until due (never a confident zero) | `services/api/app/api/v1/endpoints/cases.py` (`get_cases_attention`, `_claim_case_for_run`); migration 167 | `ci.yml :: Python — Tests` (api, `test_case_ownership_attention.py`: the feed names the owner kind per row and keeps not-yet-due as null; the claim SQL carries both no-person and no-agent predicates — the negative control removes them and the test fails; the query is tenant-scoped; the PATCH surface carries both fields) | core | GATED | - |
|
||||
| The investigator carries named strategies for the reference-service surfaces — AI-agent misuse, data handling against business context, BEC payment fraud, SaaS OAuth abuse, cloud exposure — each declaring the pivots the depth gate grades it on | `services/agents/app/investigator/strategies.py` | `ci.yml :: Python — Tests` (agents, `test_deep_investigation.py::TestStrategySelection` — each of the five has its own selection row, technique-match outranking keywords, and disabling any one fails its row) + `ci.yml :: python-lint` (`check_investigation_depth.py`: 15 strategies, every expected pivot resolves to a real tool in both directions) | core | GATED | Negative control recorded in the PR: renaming one strategy id fails exactly its selection row |
|
||||
| A case reaches `resolved` only through the tenant's resolution contract — containment verified-or-waived-with-reason, eradication and recovery recorded, root cause determined or undetermined (a hypothesis does not satisfy), affected entities derived from the case's own rows, customer notified channel-and-time — enforced by **one shared checker** at every writer: the PATCH gate (422 naming each gap), the war-room resolve decision (refusal note, no status write), and the inbound ITSM mirror (vendor resolve demoted to `contained` with the gaps in the system note, because a webhook cannot be 422'd); off by default per tenant | `services/api/app/services/case_resolution.py`; migration 166 | `ci.yml :: Python — Tests` (api, `test_case_resolution_contract.py`, 16 cases: the pure gap computation names every unmet requirement, a hypothesis is refused in so many words, toggled-off requirements do not gap, facts validation enforces verified-requires-reference / waived-requires-reason / notification-channel-and-time-together, and all three writers are driven through their real functions with the checker monkeypatched both ways) + `integration.yml :: Resolving a case is earned, and the contract's rows are tenant-scoped (live Postgres)` (the opt-in default is the real absent-row state, one-per-tenant policy and one-per-case facts are unique-constraint behaviour, the derived entity count is JSONB arithmetic over the real schema, RLS under the NOBYPASSRLS role; fails at setup on the pre-change tree) | core | GATED | Negative control recorded in the PR: forcing the checker to answer no-gaps fails two cases |
|
||||
@@ -420,8 +421,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
|
||||
|
||||
## Summary
|
||||
|
||||
- Total: 409
|
||||
- GATED: 400
|
||||
- Total: 410
|
||||
- GATED: 401
|
||||
- PARTIAL: 9
|
||||
- NO GATE: 0
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@
|
||||
| kubernetes_audit | cloud | 5 | 1 | 2 | ✅ | ✅ | ✅ |
|
||||
| lacework | cloud | 4 | 1 | 5 | ✅ | ✅ | ✅ |
|
||||
| llm_usage | saas | 4 | 1 | 2 | ✅ | ✅ | ✅ |
|
||||
| m365_audit | saas | 6 | 3 | 1 | ✅ | ✅ | ✅ |
|
||||
| m365_audit | saas | 7 | 3 | 1 | ✅ | ✅ | ✅ |
|
||||
| microsoft_intune | mdm | 3 | 1 | 1 | ✅ | ✅ | — |
|
||||
| microsoft_sentinel | siem | 6 | 1 | 2 | ✅ | ✅ | ✅ |
|
||||
| mimecast | saas | 3 | 1 | 4 | ✅ | ✅ | ✅ |
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://aisoc.example.com/schemas/curated/v1.json",
|
||||
"version": "1.0.0",
|
||||
"generated": "2026-11-22T04:59:26Z",
|
||||
"generated": "2026-11-22T16:36:00Z",
|
||||
"stats": {
|
||||
"considered": 2942,
|
||||
"eligible": 2931,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://example.com/schemas/marketplace/v1.json",
|
||||
"version": "1.0.0",
|
||||
"generated": "2026-11-22T04:59:19Z",
|
||||
"generated": "2026-11-22T16:35:53Z",
|
||||
"categories": [
|
||||
{
|
||||
"id": "playbooks",
|
||||
@@ -255285,7 +255285,7 @@
|
||||
"source": "core",
|
||||
"tier": "stable",
|
||||
"path": "plugins/m365-audit/plugin.yaml",
|
||||
"sha256": "ea68a64d4da29f71904de2452bff2d1e9d775f79938b24370bcd2f9a0c9a3722"
|
||||
"sha256": "b8ec2a99a42973da4755938d7c92b80c796688d6d78099f3ca64451eaf086143"
|
||||
},
|
||||
{
|
||||
"id": "microsoft_intune",
|
||||
|
||||
@@ -28,3 +28,11 @@ config_schema:
|
||||
type: string
|
||||
description: "Client secret for the Azure AD app registration"
|
||||
secret: true
|
||||
include_dlp:
|
||||
type: boolean
|
||||
description: >-
|
||||
Also subscribe to the DLP.All content type (Purview DLP rule matches
|
||||
across Exchange, SharePoint/OneDrive and endpoints). Off by default:
|
||||
high volume, and sensitive-data details need the separate 'Read DLP
|
||||
policy events including sensitive details' permission.
|
||||
default: false
|
||||
|
||||
@@ -2344,6 +2344,14 @@
|
||||
"name": "private_key_password",
|
||||
"required": false,
|
||||
"type": "secret"
|
||||
},
|
||||
{
|
||||
"default": false,
|
||||
"help_text": "Also subscribe to the DLP.All content type \u2014 Purview DLP rule matches across Exchange, SharePoint/OneDrive and endpoints. Off by default: the stream is high volume, and reading sensitive-data details requires the separate 'Read DLP policy events including sensitive details' permission on the app registration.",
|
||||
"label": "Include DLP events (DLP.All)",
|
||||
"name": "include_dlp",
|
||||
"required": false,
|
||||
"type": "boolean"
|
||||
}
|
||||
],
|
||||
"oauth": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://example.com/schemas/marketplace/v1.json",
|
||||
"version": "1.0.0",
|
||||
"generated": "2026-11-22T04:59:19Z",
|
||||
"generated": "2026-11-22T16:35:53Z",
|
||||
"categories": [
|
||||
{
|
||||
"id": "playbooks",
|
||||
@@ -255285,7 +255285,7 @@
|
||||
"source": "core",
|
||||
"tier": "stable",
|
||||
"path": "plugins/m365-audit/plugin.yaml",
|
||||
"sha256": "ea68a64d4da29f71904de2452bff2d1e9d775f79938b24370bcd2f9a0c9a3722"
|
||||
"sha256": "b8ec2a99a42973da4755938d7c92b80c796688d6d78099f3ca64451eaf086143"
|
||||
},
|
||||
{
|
||||
"id": "microsoft_intune",
|
||||
|
||||
@@ -17,9 +17,12 @@ fetch each blob URL to materialise the events. We cover (1) and (2) in
|
||||
``test_connection`` / ``fetch_alerts``, and inline the blob fetch so the
|
||||
connector contract still returns flat events.
|
||||
|
||||
Scope: we deliberately limit to Audit.* content types and skip DLP.All by
|
||||
default. DLP can be re-enabled per-instance later via ``connector_config``
|
||||
once the analyst opt-in path lands.
|
||||
Scope: the four Audit.* content types are polled by default; the noisy
|
||||
``DLP.All`` stream is a per-instance opt-in (the ``include_dlp`` schema
|
||||
field, default off) — a boolean from the wizard and a string from a
|
||||
hand-written instance row mean the same thing, and an unparseable value
|
||||
means off, because a collector that defaults to on when it cannot read its
|
||||
own switch is a poll the tenant did not ask for.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -35,11 +38,21 @@ from app.connectors.ms_cert_auth import build_credential, cert_schema_fields, to
|
||||
|
||||
logger = structlog.get_logger()
|
||||
|
||||
|
||||
def _truthy(value: Any) -> bool:
|
||||
"""Config toggles arrive as booleans from the wizard and as strings from
|
||||
a hand-written instance row. Both have to mean the same thing, and an
|
||||
unparseable value has to mean *off*."""
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return str(value or "").strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
_TOKEN_URL = "https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
|
||||
_BASE = "https://manage.office.com/api/v1.0/{tenant_id}/activity/feed"
|
||||
|
||||
# Content types we pull by default. Audit.General captures Power BI, Teams,
|
||||
# Dynamics, etc.; the noisy DLP.All stream is left off to keep volumes sane.
|
||||
# Content types pulled by default. Audit.General captures Power BI, Teams,
|
||||
# Dynamics, etc. DLP.All joins them only when the instance opts in.
|
||||
_DEFAULT_CONTENT_TYPES = (
|
||||
"Audit.AzureActiveDirectory",
|
||||
"Audit.Exchange",
|
||||
@@ -84,6 +97,21 @@ class M365AuditConnector(BaseConnector):
|
||||
help_text="Leave empty when using a certificate (recommended). Exactly one of secret or certificate is required.",
|
||||
),
|
||||
*cert_schema_fields(Field),
|
||||
Field(
|
||||
"include_dlp",
|
||||
"boolean",
|
||||
"Include DLP events (DLP.All)",
|
||||
required=False,
|
||||
default=False,
|
||||
help_text=(
|
||||
"Also subscribe to the DLP.All content type — Purview "
|
||||
"DLP rule matches across Exchange, SharePoint/OneDrive "
|
||||
"and endpoints. Off by default: the stream is high "
|
||||
"volume, and reading sensitive-data details requires "
|
||||
"the separate 'Read DLP policy events including "
|
||||
"sensitive details' permission on the app registration."
|
||||
),
|
||||
),
|
||||
],
|
||||
oauth=OAuthHints(
|
||||
supported_in_hosted=True,
|
||||
@@ -110,18 +138,30 @@ class M365AuditConnector(BaseConnector):
|
||||
certificate_pem: str = "",
|
||||
certificate_thumbprint: str = "",
|
||||
private_key_password: str = "",
|
||||
include_dlp: Any = False,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
):
|
||||
self._tenant_id = tenant_id
|
||||
self._client_id = client_id
|
||||
self._client_secret = client_secret
|
||||
self._cert = build_credential(client_secret, certificate_pem, certificate_thumbprint, private_key_password)
|
||||
self._access_token: str | None = None
|
||||
self._include_dlp = _truthy(include_dlp)
|
||||
#: Test seam: a mock transport exercises the real URL construction
|
||||
#: and content-type selection without a live tenant.
|
||||
self._transport = transport
|
||||
|
||||
def content_types(self) -> tuple[str, ...]:
|
||||
"""The content types this instance polls — the switch made real."""
|
||||
if self._include_dlp:
|
||||
return (*_DEFAULT_CONTENT_TYPES, "DLP.All")
|
||||
return _DEFAULT_CONTENT_TYPES
|
||||
|
||||
# --------------------------- auth ---------------------------
|
||||
|
||||
async def _authenticate(self) -> str:
|
||||
token_url = _TOKEN_URL.format(tenant_id=self._tenant_id)
|
||||
async with httpx.AsyncClient(timeout=15.0) as client:
|
||||
async with httpx.AsyncClient(timeout=15.0, transport=self._transport) as client:
|
||||
resp = await client.post(
|
||||
token_url,
|
||||
data={
|
||||
@@ -157,7 +197,7 @@ class M365AuditConnector(BaseConnector):
|
||||
# wired up correctly" probe — it returns 200 + JSON list even
|
||||
# when zero subscriptions exist, and 403 if ActivityFeed.Read
|
||||
# admin consent is missing.
|
||||
async with httpx.AsyncClient(timeout=15.0) as client:
|
||||
async with httpx.AsyncClient(timeout=15.0, transport=self._transport) as client:
|
||||
resp = await client.get(
|
||||
f"{self._base()}/subscriptions/list",
|
||||
headers=self._headers(),
|
||||
@@ -184,7 +224,7 @@ class M365AuditConnector(BaseConnector):
|
||||
returns 200 if the subscription was created, 400 if it was already
|
||||
active. We treat both as success.
|
||||
"""
|
||||
for content_type in _DEFAULT_CONTENT_TYPES:
|
||||
for content_type in self.content_types():
|
||||
try:
|
||||
resp = await client.post(
|
||||
f"{self._base()}/subscriptions/start",
|
||||
@@ -224,13 +264,13 @@ class M365AuditConnector(BaseConnector):
|
||||
}
|
||||
|
||||
events: list[dict[str, Any]] = []
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
async with httpx.AsyncClient(timeout=30.0, transport=self._transport) as client:
|
||||
await self._ensure_subscriptions(client)
|
||||
|
||||
# For each content type, list available content blobs in the
|
||||
# window then fetch each blob URI. The blob URIs are short-lived
|
||||
# (~24h) signed URLs hosted on the same management API.
|
||||
for content_type in _DEFAULT_CONTENT_TYPES:
|
||||
for content_type in self.content_types():
|
||||
resp = await client.get(
|
||||
f"{self._base()}/subscriptions/content",
|
||||
headers=self._headers(),
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""The M365 audit DLP.All switch is real, per instance (WS4.2).
|
||||
|
||||
What was wrong
|
||||
--------------
|
||||
The module docstring promised "DLP can be re-enabled per-instance later via
|
||||
``connector_config``" while ``_DEFAULT_CONTENT_TYPES`` was hard-coded and
|
||||
``__init__`` accepted no such setting — the aspirational-comment family the
|
||||
registry already carries in three other connectors. A tenant who wanted
|
||||
Purview DLP events through the audit trail had no switch to flip, and the
|
||||
docstring said there was one coming, indefinitely.
|
||||
|
||||
What this asserts
|
||||
-----------------
|
||||
* ``schema()`` declares the opt-in boolean (``default=False``) so the wizard
|
||||
renders it and the instance row persists it.
|
||||
* The constructor accepts it; coercion follows the house `_truthy` rule — a
|
||||
boolean from the wizard and a string from a hand-written row mean the same
|
||||
thing, and **an unparseable value means off** (a collector that defaults
|
||||
to on when it cannot read its own switch is a poll the tenant did not ask
|
||||
for).
|
||||
* With the switch off (the default), the content types polled are exactly
|
||||
the four ``Audit.*`` streams — the subscription and listing calls never
|
||||
name ``DLP.All``.
|
||||
* With the switch on, ``DLP.All`` joins them — observed through the real
|
||||
fetch path against a mock vendor, not inferred from a constant.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from app.connectors import m365_audit
|
||||
from app.connectors.m365_audit import M365AuditConnector
|
||||
|
||||
|
||||
class _FakeManagementApi:
|
||||
"""The Office 365 Management Activity API: token, subscriptions, content."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.requests: list[httpx.Request] = []
|
||||
|
||||
def content_types_listed(self) -> set[str]:
|
||||
types: set[str] = set()
|
||||
for request in self.requests:
|
||||
ct = request.url.params.get("contentType")
|
||||
if ct:
|
||||
types.add(ct)
|
||||
return types
|
||||
|
||||
def handle(self, request: httpx.Request) -> httpx.Response:
|
||||
self.requests.append(request)
|
||||
path = request.url.path
|
||||
if path.endswith("/oauth2/v2.0/token"):
|
||||
return httpx.Response(200, json={"access_token": "tok", "expires_in": 3599})
|
||||
if "/subscriptions/list" in path:
|
||||
return httpx.Response(200, json=[])
|
||||
if "/subscriptions/start" in path:
|
||||
return httpx.Response(200, json={"status": "enabled"})
|
||||
if "/subscriptions/content" in path:
|
||||
return httpx.Response(200, json=[])
|
||||
return httpx.Response(404, json={"error": f"no route {path}"})
|
||||
|
||||
|
||||
def _connector(api: _FakeManagementApi, **kwargs: Any) -> M365AuditConnector:
|
||||
return M365AuditConnector(
|
||||
tenant_id="t-1",
|
||||
client_id="c-1",
|
||||
client_secret="s-1",
|
||||
transport=httpx.MockTransport(api.handle),
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
class TestSchema:
|
||||
def test_the_switch_is_declared_and_defaults_off(self) -> None:
|
||||
fields = {f.name: f for f in M365AuditConnector.schema().fields}
|
||||
assert "include_dlp" in fields, "the per-instance switch must be a declared field"
|
||||
assert fields["include_dlp"].default in (False, "false", None)
|
||||
|
||||
def test_the_docstring_no_longer_promises_later(self) -> None:
|
||||
assert "later" not in (m365_audit.__doc__ or ""), (
|
||||
"the docstring promised the switch 'later'; now that it exists, say what is true instead"
|
||||
)
|
||||
|
||||
|
||||
class TestContentTypeSelection:
|
||||
def test_default_excludes_dlp(self) -> None:
|
||||
api = _FakeManagementApi()
|
||||
connector = _connector(api)
|
||||
assert "DLP.All" not in connector.content_types()
|
||||
assert set(connector.content_types()) == {
|
||||
"Audit.AzureActiveDirectory",
|
||||
"Audit.Exchange",
|
||||
"Audit.SharePoint",
|
||||
"Audit.General",
|
||||
}
|
||||
|
||||
@pytest.mark.parametrize("value", [True, "true", "1", "yes", "on"])
|
||||
def test_truthy_values_enable_dlp(self, value: Any) -> None:
|
||||
api = _FakeManagementApi()
|
||||
connector = _connector(api, include_dlp=value)
|
||||
assert "DLP.All" in connector.content_types()
|
||||
|
||||
@pytest.mark.parametrize("value", [False, "false", "0", "", None, "banana"])
|
||||
def test_everything_else_means_off(self, value: Any) -> None:
|
||||
api = _FakeManagementApi()
|
||||
connector = _connector(api, include_dlp=value)
|
||||
assert "DLP.All" not in connector.content_types()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestFetchPath:
|
||||
async def test_the_switch_reaches_the_wire(self) -> None:
|
||||
api_off = _FakeManagementApi()
|
||||
await _connector(api_off).fetch_alerts(since_seconds=300)
|
||||
assert "DLP.All" not in api_off.content_types_listed()
|
||||
assert "Audit.Exchange" in api_off.content_types_listed()
|
||||
|
||||
api_on = _FakeManagementApi()
|
||||
await _connector(api_on, include_dlp=True).fetch_alerts(since_seconds=300)
|
||||
assert "DLP.All" in api_on.content_types_listed()
|
||||
Reference in New Issue
Block a user