diff --git a/AGENTS.md b/AGENTS.md
index 55223cc6..3a3bd079 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -41,10 +41,11 @@ control plane, or runtime AI filter.
- `src/Bower.Source.Syslog`: RFC 5424/3164 syslog over TCP, TLS and UDP, routed to signed pack parsers (collector `BOWER_SYSLOG_CONFIG`).
- `src/Bower.Source.File`: security-selected local file tail (operator-named files under allowed roots, no wildcards), routed to signed pack parsers with durable cursors (collector `BOWER_FILE_CONFIG`).
- `src/Bower.Source.WindowsEventLog`: channel and event ID allow-listed Windows Event Log subscriptions with durable bookmarks, mapped by signed pack parsers (C# collector on Windows, `BOWER_WINDOWS_EVENTLOG_CONFIG`).
+- `src/Bower.Source.MicrosoftCloud`: least-privilege pull of Microsoft cloud admin and audit APIs (Intune audit and device compliance) with bounded HTTPS, a token host allow-list and durable per-page cursors, mapped by signed pack parsers (collector `BOWER_MICROSOFT_CONFIG`). Not the Unified Audit Log or an audit archive.
- `src/Bower.Agent.Docker`: Docker sidecar that forwards opted-in container security events.
- `src/Bower.ServiceDefaults`: opt-in OpenTelemetry host defaults; inert unless `OTEL_EXPORTER_OTLP_ENDPOINT` is set.
- `src/Bower.AppHost`, `tools/Bower.DevSinks`, `tests/Bower.AppHost.Tests`: Aspire local development and integration-test harness with local stand-in destinations (development only, never deployed). See `docs/getting-started/aspire.md`.
-- `packs`: signed content packs (`linux-ssh-gateway`, `linux-journald-ssh`, `linux-authlog-ssh`, `windows-security-logon`, `aws-security`, `gcp-security`, `owasp-asvs-app-logging`).
+- `packs`: signed content packs (`linux-ssh-gateway`, `linux-journald-ssh`, `linux-authlog-ssh`, `windows-security-logon`, `aws-security`, `gcp-security`, `owasp-asvs-app-logging`, `microsoft-intune`).
- `deploy/aws`, `deploy/gcp`: CloudFormation and Terraform for cloud signal and the S3 output policy (plan-only by default).
- `deploy/azure-function`: Bicep for the Azure Functions collector (Flex Consumption, managed identity; plan-only by default).
- `deploy/azure-webapp`, `deploy/docker/hosted`: private App Service pilot (Bicep, ephemeral queue) and hardened Compose for a hosted HTTPS collector. See `docs/deployment/hosted-collectors.md`.
diff --git a/Bower.sln b/Bower.sln
index 9d07a6c9..a1559e6d 100644
--- a/Bower.sln
+++ b/Bower.sln
@@ -105,6 +105,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bower.Source.Journald", "sr
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bower.Source.Kubernetes", "src\Bower.Source.Kubernetes\Bower.Source.Kubernetes.csproj", "{DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bower.Source.MicrosoftCloud", "src\Bower.Source.MicrosoftCloud\Bower.Source.MicrosoftCloud.csproj", "{34AF2780-854B-4886-9660-E97BCCDFCEC0}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -691,6 +693,18 @@ Global
{DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Release|x64.Build.0 = Release|Any CPU
{DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Release|x86.ActiveCfg = Release|Any CPU
{DBB32FBD-107E-4DDC-A110-F00C1A3EC9D9}.Release|x86.Build.0 = Release|Any CPU
+ {34AF2780-854B-4886-9660-E97BCCDFCEC0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {34AF2780-854B-4886-9660-E97BCCDFCEC0}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {34AF2780-854B-4886-9660-E97BCCDFCEC0}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {34AF2780-854B-4886-9660-E97BCCDFCEC0}.Debug|x64.Build.0 = Debug|Any CPU
+ {34AF2780-854B-4886-9660-E97BCCDFCEC0}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {34AF2780-854B-4886-9660-E97BCCDFCEC0}.Debug|x86.Build.0 = Debug|Any CPU
+ {34AF2780-854B-4886-9660-E97BCCDFCEC0}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {34AF2780-854B-4886-9660-E97BCCDFCEC0}.Release|Any CPU.Build.0 = Release|Any CPU
+ {34AF2780-854B-4886-9660-E97BCCDFCEC0}.Release|x64.ActiveCfg = Release|Any CPU
+ {34AF2780-854B-4886-9660-E97BCCDFCEC0}.Release|x64.Build.0 = Release|Any CPU
+ {34AF2780-854B-4886-9660-E97BCCDFCEC0}.Release|x86.ActiveCfg = Release|Any CPU
+ {34AF2780-854B-4886-9660-E97BCCDFCEC0}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -729,5 +743,6 @@ Global
{BBF9180B-5DEE-43BB-8D0B-B11F7D368A2E} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84}
{827CAE03-02C1-4625-AB39-B32FAF688A1D} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
{D784F971-24BA-435F-831E-4442A33FBC02} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
+ {34AF2780-854B-4886-9660-E97BCCDFCEC0} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
EndGlobalSection
EndGlobal
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d73cbc0e..b2e5aaa1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- Microsoft cloud pull source (`Bower.Source.MicrosoftCloud`, collector `BOWER_MICROSOFT_CONFIG`): Intune audit events and a daily device compliance snapshot from Microsoft Graph with least-privilege read-only permissions, a token host allow-list, capped retry honouring `Retry-After`, and durable per-page cursors in the queue database. Signed `microsoft-intune` pack 1.1.0 (two parsers, two policies, four detections) and the `deploy/privacy/microsoft-cloud.yaml` pseudonymisation profile (email addresses hashed whole, so pseudonyms stay distinct per person).
+
## [1.0.0] - 2026-11-21
Initial v1.0.0 release of Bower, a self-hosted security telemetry privacy gateway for Microsoft Sentinel following the Collect, Select, Arrange, Deliver and Prove model.
diff --git a/README.md b/README.md
index c242c2eb..9ab65c9b 100644
--- a/README.md
+++ b/README.md
@@ -190,6 +190,7 @@ Full design: [architecture](docs/architecture/overview.md).
| Management UI and API | Fleet inventory, approval, health, audit, custom-log parser generation, privacy profile versioning with two-person review and signed assignment, and Entra app-role RBAC implemented |
| AI-assisted custom log parser generator | Deterministic local JSON, CSV, key/value and common-regex inference with OCSF/ASIM mappings and redacted preview |
| Windows Service | MSI installs the collector as the `Bower` service (`NT SERVICE\Bower`) |
+| Microsoft cloud sources | Intune audit events and a daily device compliance snapshot pulled from Microsoft Graph with least-privilege read permissions, durable per-page checkpoints, retry and throttling handling; signed `microsoft-intune` pack. [Details](docs/deployment/microsoft-cloud-sources.md) |
| SQL Server source | EF Core adapter library with durable keyset/overlap cursors; collector polling orchestration not yet wired |
| AWS security signal | GuardDuty, Security Hub and high-value CloudTrail via EventBridge → SQS, plus Bower events from CloudWatch Logs via Firehose → S3; CloudFormation, signed `aws-security` pack, `bower-cloud` agent with IAM-role credentials |
| Google Cloud security signal | Security Command Center findings and Admin Activity audit logs via Pub/Sub with Australian storage policy; Terraform, signed `gcp-security` pack, ADC / Workload Identity Federation (key files refused) |
@@ -533,6 +534,7 @@ PowerShell). It has not been exercised against a live tenant yet.
| `BOWER_SOURCE_EXPECTATIONS` | — | JSON file of applications that must keep sending events; quiet ones degrade `/health`. [Details](docs/operations/suppression-archive-and-source-silence.md#source-silence) |
| `BOWER_ARCHIVE_PATH` | — | Directory for the ledger-verified long-term archive; retention then purges only events a verified archive of this queue covers. [Details](docs/operations/suppression-archive-and-source-silence.md#archive-and-replay) |
| `BOWER_FILE_CONFIG` | — | JSON file of security-selected local files (no wildcards), their allowed roots and routes to signed pack parsers; lines no parser selects are counted and dropped. [Details](docs/deployment/file-tail-source.md) |
+| `BOWER_MICROSOFT_CONFIG` | (unset) | JSON file of Microsoft cloud API inputs (Intune audit and device compliance), each one tenant and one route to a signed pack parser; least-privilege read-only Graph permissions. [Details](docs/deployment/microsoft-cloud-sources.md) |
| `BOWER_SYSLOG_CONFIG` | — | JSON file of syslog listeners (RFC 5424/3164 over TCP, TLS or UDP), sender allow-lists and routes to signed pack parsers. Loopback unless TLS. [Details](docs/deployment/syslog-source.md) |
| `BOWER_ORIGIN_PRODUCERS` | — | Tokens-file producer IDs trusted to report where an event came from (the cloud forwarder's `X-Bower-Origin`: CloudWatch Logs group and stream). Others' headers are ignored; `anonymous` is refused. Fills the `Origin` column. [Details](docs/reference/sentinel-table.md#origin) |
| `BOWER_TAP_ENABLED` / `BOWER_TAP_PRODUCERS` | `true` / — | Serve the post-redaction `bower tap` stream; tokens-file producers allowed to tap besides the shared token. [Details](docs/operations/tap-and-top.md) |
diff --git a/deploy/privacy/microsoft-cloud.yaml b/deploy/privacy/microsoft-cloud.yaml
new file mode 100644
index 00000000..659da7a5
--- /dev/null
+++ b/deploy/privacy/microsoft-cloud.yaml
@@ -0,0 +1,26 @@
+apiVersion: bower.security/v1
+kind: PrivacyProfile
+metadata:
+ id: microsoft-cloud-pseudonymised
+ version: 1.0.0
+ description: >-
+ For the microsoft-intune pack and the other Microsoft cloud source packs. Replaces user
+ principal names, object ids of people and resource display names with keyed HMAC
+ pseudonyms, so analysts can follow one person or resource across events without the
+ profile exposing who or what it is. Everything else keeps the default Australian
+ redaction. Set with BOWER_PRIVACY_PROFILE plus BOWER_PRIVACY_HMAC_KEY_FILE and
+ BOWER_PRIVACY_HMAC_KEY_ID.
+detectors:
+ # Value detectors run before field rules. The default email action (mask) would turn
+ # megan.bowen@ and mark.smith@ into the same m***@ before the field rule hashed it, so
+ # every user sharing an initial and domain would share one pseudonym. Hash the address
+ # itself instead, wherever it appears.
+ id.email: hmac
+fields:
+ - path: actor.username
+ action: hmac
+ - path: actor.userId
+ action: hmac
+ - path: target.name
+ action: hmac
+maximumFieldLength: 16384
diff --git a/docs/architecture/microsoft-cloud-envelope-contract.md b/docs/architecture/microsoft-cloud-envelope-contract.md
new file mode 100644
index 00000000..76d6df73
--- /dev/null
+++ b/docs/architecture/microsoft-cloud-envelope-contract.md
@@ -0,0 +1,41 @@
+# Microsoft cloud sources: envelope hand-off contract
+
+Bower's Microsoft cloud sources collect and normalise admin and audit data from Microsoft
+APIs that do not integrate cleanly with Sentinel. They do not keep it long term. A
+separate archive (owned outside Bower) holds long-term copies of the well-known streams
+(Unified Audit Log, Entra sign-in and audit, selected Defender events) for search, legal
+hold and evidence packs. This page is the contract that lets a copy forwarded or archived
+elsewhere line up with what Bower delivered.
+
+## What Bower guarantees
+
+| Field | Value | Stable across |
+|---|---|---|
+| `eventId` | `mscloud-` and 32 lowercase hex characters | Every re-read of an unchanged source record by the same input (overlap, crash recovery, restart) |
+| `eventOriginalId` | Same as `eventId` | As above |
+| `collector.sourceAdapter` | `mscloud:::` | The input's configuration |
+| `application.name` | Pack defined, for example `microsoft-intune` | Pack major version |
+| `eventType` | Pack defined, for example `intune_audit`, `intune_device_compliance` | Pack major version |
+| `request.correlationId` | The source's own correlation id when it has one (Intune `correlationId`), else the source record id | Source |
+| `labels.intuneAuditEventId` | `intune_audit`: the Intune audit event id (the source record id) | Source |
+| `labels.intuneDeviceId`, `labels.snapshotDate` | `intune_device_compliance`: the Intune managed device id and the UTC day of the snapshot (together, the source record id) | Source |
+| `target.id` | The source object's GUID (Intune resource id, Entra device id) | Source |
+| `timeGenerated` | The source's own activity time; for snapshots, when the snapshot started | Source |
+
+The event id is SHA-256 over `bower-mscloud-v1`, the input id, the source kind, the tenant
+id, the source record id (the Intune audit event id; for compliance, the device id and the
+snapshot date) and the bounded record content. A receiver that needs to join a Bower row
+to the original Microsoft record should use the source record id carried in the labels
+above, not recompute the hash.
+
+## What a receiver must not assume
+
+- Values are post-redaction. With `deploy/privacy/microsoft-cloud.yaml`, user principal
+ names, user object ids, resource names and email addresses are keyed HMAC pseudonyms;
+ the key never leaves the collector.
+- Bower delivers at least once. Deduplicate on (`collector.id`, `eventId`), as the
+ `BowerSecurityEvents` parser does.
+- Bower keeps queue rows only for its delivered retention period. It is not the system of
+ record and offers no legal hold.
+- Fields can be added in a later pack version; none are renamed or removed within a major
+ version.
diff --git a/docs/deployment/microsoft-cloud-sources.md b/docs/deployment/microsoft-cloud-sources.md
new file mode 100644
index 00000000..aad27bec
--- /dev/null
+++ b/docs/deployment/microsoft-cloud-sources.md
@@ -0,0 +1,165 @@
+# Microsoft cloud sources (Intune)
+
+Some Microsoft products hold security-relevant admin and audit data that is hard to get
+into Microsoft Sentinel in a stable shape. The Bower collector can pull it directly from the
+Microsoft API, keep only what a signed pack selects, redact it and deliver it through the
+same durable queue, Data Collection Rule and Logs Ingestion API as every other source. Rows
+land in `BowerSecurity_CL` (see [the table reference](../reference/sentinel-table.md)); there
+is no new table to create.
+
+The first sources are Microsoft Intune audit events and a daily device compliance snapshot,
+mapped by the signed [`microsoft-intune`](../../packs/microsoft-intune) pack.
+
+| Source kind | API | What becomes an event |
+|---|---|---|
+| `intune-audit` | Graph `GET /v1.0/deviceManagement/auditEvents` | Every Intune admin action: who did what to which resource, the result, the actor's IP address and the **names** of changed properties |
+| `intune-device-compliance` | Graph `GET /v1.0/deviceManagement/managedDevices` (once per UTC day) | One event per device that needs attention: noncompliant, in grace period, conflict or error (configurable) |
+
+Not collected, and why:
+
+- **Intune operational logs** (enrolment and policy processing). Microsoft offers no API
+ for them; they are only exported by Intune diagnostic settings to Log Analytics
+ (`IntuneOperationalLogs`), Event Hub or Storage. Where you can use diagnostic settings,
+ use them. Bower does not ship a stub that would only look like coverage.
+- **Unified Audit Log, Entra sign-in and Entra audit logs.** Out of scope: Bower is not a
+ long-term audit archive.
+
+## Before you start
+
+1. An active Intune licence on the tenant.
+2. An app registration (or the collector's managed identity) with these Microsoft Graph
+ **application** permissions, and admin consent:
+
+ | Source kind | Permission | Why this one |
+ |---|---|---|
+ | `intune-audit` | `DeviceManagementApps.Read.All` | Microsoft documents it as the least privileged permission for `auditEvents` |
+ | `intune-device-compliance` | `DeviceManagementManagedDevices.Read.All` | Least privileged read of managed devices |
+
+ No `ReadWrite` permission is needed or used.
+3. A collector that loads the signed `microsoft-intune` pack (`BOWER_PACKS`, signed by a key
+ in `BOWER_PACK_TRUSTED_KEYS`).
+
+## Turn it on
+
+Create `/etc/bower/microsoft.json` (owned by the collector account, mode 0600):
+
+```json
+{
+ "apiVersion": "bower.security/v1",
+ "kind": "MicrosoftCloudSource",
+ "pollIntervalSeconds": 300,
+ "inputs": [
+ {
+ "id": "intune-audit",
+ "sourceKind": "intune-audit",
+ "tenantId": "00000000-0000-0000-0000-000000000000",
+ "route": { "pack": "microsoft-intune", "parser": 0 }
+ },
+ {
+ "id": "intune-compliance",
+ "sourceKind": "intune-device-compliance",
+ "tenantId": "00000000-0000-0000-0000-000000000000",
+ "route": { "pack": "microsoft-intune", "parser": 1 }
+ }
+ ]
+}
+```
+
+Then set, and restart the collector:
+
+```bash
+BOWER_MICROSOFT_CONFIG=/etc/bower/microsoft.json
+BOWER_PRIVACY_PROFILE=/etc/bower/privacy/microsoft-cloud.yaml # deploy/privacy/microsoft-cloud.yaml
+BOWER_PRIVACY_HMAC_KEY_FILE=/etc/bower/privacy-hmac.key
+```
+
+The privacy profile replaces user principal names, user object ids, resource names and any
+email address with keyed HMAC pseudonyms (distinct for every address, so two people with
+the same initial never share one). Without it, the default Australian redaction still masks email
+addresses, but you lose the ability to follow one person across events.
+
+Check it with `bower status` or `GET /v1/status`: the `microsoftCloud` block lists each
+input's state, committed time, page, record and drop counters, retries and failure code.
+It never shows record content, URLs or tokens.
+
+### Credentials
+
+By default an input uses the collector's one configured Azure credential
+(`BOWER_AZURE_CREDENTIAL`: managed identity, workload identity, environment or Azure CLI).
+Grant the Graph permissions above to that identity.
+
+An MSP reading a customer tenant can give the input its own certificate-based app
+registration in that tenant instead:
+
+```json
+"credential": {
+ "clientId": "00000000-0000-0000-0000-000000000000",
+ "certificatePath": "/etc/bower/certs/customer-a.pem"
+}
+```
+
+The PEM holds the certificate and its private key, readable only by the collector account.
+Client secrets are not accepted.
+
+### Input settings
+
+| Setting | Default | Range | Meaning |
+|---|---|---|---|
+| `id` | | 1 to 63 lowercase letters, digits, hyphens | Names the cursor (`mscloud:`) and the source adapter |
+| `sourceKind` | | see the table above | The API and record shape |
+| `tenantId` | | lowercase GUID | The tenant read |
+| `route` | | an active parser of a loaded signed pack | Start-up fails without one |
+| `startLookbackHours` | 24 | 1 to 168 | How far back the first poll reads |
+| `settleDelaySeconds` | 300 | 0 to 86400 | Windows end this long before now, so late-written records fall in the next one |
+| `overlapSeconds` | 600 | 0 to 43200 | Each window starts this long before the last committed time; re-read records deduplicate |
+| `maxRecordsPerPoll` | 1000 | 1 to 10000 | Records handed to the parser per poll before it yields |
+| `complianceStates` | `noncompliant`, `inGracePeriod`, `conflict`, `error` | also `unknown`, `configManager`; never `compliant` | `intune-device-compliance` only |
+
+## How collection stays correct
+
+- **Checkpoints survive restart.** The cursor lives in the queue database. It records the
+ last completed window, the open window and the next page. A page is committed only after
+ every record in it was durably queued or definitively dropped.
+- **No unbounded re-reads.** Windows are at most 24 hours, and never start more than seven
+ days back. A collector stopped longer than that resumes at the seven day floor and counts
+ a gap in `gaps`.
+- **Duplicates collapse.** Event ids are derived from the input and the record, so the
+ overlap and any page re-read after a crash become queue duplicates, not new rows.
+- **Throttling and outages.** 429 and 5xx responses are retried with capped exponential
+ backoff and jitter, honouring `Retry-After`. After the retries the poll fails with
+ `mscloud-throttled` or `mscloud-unavailable` and backs off (30 seconds doubling to 30
+ minutes) without moving the cursor.
+- **Backpressure.** A full queue stops the poll and keeps the page. Nothing is dropped.
+- **Permission problems** show as `mscloud-permission-denied` (403) or
+ `mscloud-unauthorised` (401 after one token refresh). Fix the consent; the input retries
+ on its own.
+- **Bounded polls.** One poll reads at most 100 pages and `maxRecordsPerPoll` records, then
+ yields. An expired page link restarts its window once per poll; a second refusal, or a
+ next link that repeats, fails the poll so it backs off instead of spinning. A next link
+ is checked against the allowed host before the page that returned it is committed.
+
+## What reaches Sentinel
+
+| `EventType` | `EventCategory` | `EventAction` | Main columns |
+|---|---|---|---|
+| `intune_audit` | `administrative-activity` | Intune activity, for example `Wipe ManagedDevice` | `ActorUsername` (pseudonymised), `ActorUserId`, `SourceIpAddress`, `Target` (type, id, pseudonymised name), `CorrelationId`, `Labels.intuneAuditEventId`, `Labels.intuneCategory`, `Labels.intuneComponent`, `Labels.intuneOperationType`, `Labels.intuneModifiedProperties` |
+| `intune_device_compliance` | `application-security` | `device.compliance.` | `ActorUsername` (primary user, pseudonymised), `Target.id` (Entra device id), `Labels.intuneDeviceId`, `snapshotDate`, `operatingSystem`, `osVersion`, `ownerType`, `isEncrypted`, `jailBroken` |
+
+Each pack parser declares the ASIM and OCSF field each source field corresponds to (for
+example `actorIpAddress` to ASIM `SrcIpAddr` and OCSF `src_endpoint.ip`), so ASIM-style
+parsers over `BowerSecurity_CL` can be written without guessing. The rows use the Bower
+envelope: no third event standard.
+
+Pack detections: device wipe, retire or delete; Intune role or role assignment change;
+compliance or configuration policy deletion; jailbroken or rooted device.
+
+## Turn it off
+
+Remove the input from `BOWER_MICROSOFT_CONFIG` (or unset the variable) and restart the
+collector. To stop all access immediately, remove the Graph permissions or the app
+registration in Entra; the input then reports `mscloud-permission-denied` and reads
+nothing. The cursor row (`mscloud:`) stays in the queue database so re-enabling resumes
+where it stopped (within the seven day floor).
+
+See [Microsoft cloud sources security](../security/microsoft-cloud-sources.md) for scopes,
+tokens, checkpoints and the personal information in each event type.
diff --git a/docs/deployment/packs.md b/docs/deployment/packs.md
index 6e20707d..1a6e851c 100644
--- a/docs/deployment/packs.md
+++ b/docs/deployment/packs.md
@@ -16,6 +16,8 @@ Examples: [`packs/linux-ssh-gateway`](../../packs/linux-ssh-gateway),
[`packs/linux-journald-ssh`](../../packs/linux-journald-ssh) (uses transforms),
[`packs/linux-authlog-ssh`](../../packs/linux-authlog-ssh) (plain-text auth.log lines from
the [file tail source](file-tail-source.md), uses transforms) and
+[`packs/microsoft-intune`](../../packs/microsoft-intune) (Intune audit events and device
+compliance from the [Microsoft cloud source](microsoft-cloud-sources.md), uses transforms),
[`packs/windows-security-logon`](../../packs/windows-security-logon) (Security event 4625
from the [Windows Event Log source](windows-event-log-source.md), uses transforms). [`packs/owasp-asvs-app-logging`](../../packs/owasp-asvs-app-logging) selects
semantic application events with no parser (see the
diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md
index 250c2373..e95b8ad1 100644
--- a/docs/reference/configuration.md
+++ b/docs/reference/configuration.md
@@ -7,7 +7,7 @@ CI runs `generate_config_and_api_reference.py --check` so the reference cannot d
## Collector environment variables
-Recognised collector settings (`82` variables in `CollectorSettings.cs`):
+Recognised collector settings (`83` variables in `CollectorSettings.cs`):
| Environment variable |
|---|
@@ -49,6 +49,7 @@ Recognised collector settings (`82` variables in `CollectorSettings.cs`):
| `BOWER_MANAGEMENT_SCOPE` |
| `BOWER_MANAGEMENT_VIA_RELAY` |
| `BOWER_MAX_DELIVERY_ATTEMPTS` |
+| `BOWER_MICROSOFT_CONFIG` |
| `BOWER_ORIGIN_PRODUCERS` |
| `BOWER_OUTPUT` |
| `BOWER_PACKS` |
diff --git a/docs/security/microsoft-cloud-sources.md b/docs/security/microsoft-cloud-sources.md
new file mode 100644
index 00000000..9b586f3c
--- /dev/null
+++ b/docs/security/microsoft-cloud-sources.md
@@ -0,0 +1,103 @@
+# Microsoft cloud sources: security
+
+This page covers the Microsoft cloud pull source (`Bower.Source.MicrosoftCloud`,
+`BOWER_MICROSOFT_CONFIG`): what it may access, how tokens and checkpoints are handled, what
+personal information each event type carries, and how to switch a source off. Setup is in
+[Microsoft cloud sources](../deployment/microsoft-cloud-sources.md).
+
+## Trust boundary
+
+The collector makes outbound HTTPS requests to Microsoft APIs with a bearer token for one
+tenant. This is a new outbound trust boundary: API responses are untrusted input, and the
+token must never reach anything other than the API it was issued for.
+
+| Control | How |
+|---|---|
+| Token destination | Each source kind allow-lists exactly one host (`graph.microsoft.com` for Intune). Requests, `@odata.nextLink` and stored page links must be HTTPS on that host at the default port with no user info, or the poll fails with `mscloud-host-refused` before any request is sent. A refused next link is never stored in the cursor. |
+| Redirects | Never followed. A 3xx fails the poll (`mscloud-redirect-refused`). |
+| Response size | 16 MiB per response and JSON depth 32; larger fails with `mscloud-response-too-large`. |
+| Record size | Values clipped to the envelope limit of the field they map to (128 for actions and target types, 256 for labels and identities), with a per-record budget that keeps the escaped record below the pack parser's 32 KiB limit. IP addresses are canonicalised (a `:port` is stripped) or left out, so an odd address never drops the event. |
+| Failure reporting | Status, logs and exceptions carry a stable code and the HTTP status only. Response bodies, URLs with queries and tokens are never logged or shown. |
+| Default deny | A record becomes an event only through a signed pack parser's match filter, then the Privacy & Secret Protection Engine and default-deny policy. |
+
+## Permissions
+
+Application permissions, read-only, admin consent required. Use a dedicated app
+registration (or the collector's managed identity) for Bower, not one shared with other
+tools.
+
+| Source kind | Microsoft Graph application permission | Licence |
+|---|---|---|
+| `intune-audit` | `DeviceManagementApps.Read.All` | Intune |
+| `intune-device-compliance` | `DeviceManagementManagedDevices.Read.All` | Intune |
+
+`DeviceManagementApps.Read.All` is the permission Microsoft documents as least privileged
+for `deviceManagement/auditEvents`. It also allows reading Intune app configuration; Bower
+reads only `auditEvents`. `DeviceManagementManagedDevices.Read.All` allows reading full
+device inventory; Bower requests only the compliance fields with `$select` and never asks
+for the device name, IMEI, serial number, phone number, MAC addresses, email address or
+hardware details.
+
+## Tokens and credentials
+
+- Tokens come from exactly one credential per input: the collector's
+ `BOWER_AZURE_CREDENTIAL` (managed identity preferred), or an input's certificate app
+ registration. Azure.Identity caches tokens in memory only. Nothing is written to disk,
+ the cursor or status.
+- Client secrets are refused in configuration. A certificate file stays on disk with the
+ collector account's permissions (mode 0600); rotate it in Entra and replace the file,
+ then restart.
+- A 401 drops the cached credential and acquires one new token, once per request; the
+ retries after it reuse that token. A second 401 fails the poll with
+ `mscloud-unauthorised`.
+
+## Checkpoints
+
+- One cursor row per input (`mscloud:`) in the queue database's `source_cursors`
+ table, with the same file permissions as the queue. It holds times, the source kind and,
+ while a window is open, the next page link (an API URL with a skip token, no credential).
+- The cursor moves past a page only after every record in it is durably queued or
+ definitively dropped. A crash re-reads at most one page; event ids make the copies queue
+ duplicates.
+- A damaged cursor or one written for another source kind fails closed
+ (`mscloud-cursor-invalid`): the input stops instead of re-reading an unbounded window.
+ To reset an input deliberately, stop the collector and delete its `mscloud:` row.
+- The API keeps seven days. A collector stopped longer resumes at the seven day floor and
+ counts a gap; that data is not recoverable from the API.
+
+## Personal information by event type
+
+Values after the `deploy/privacy/microsoft-cloud.yaml` profile. The profile sets the email
+detector to `hmac`: value detectors run before field rules, and the default mask
+(`m***@domain`) would otherwise make every user with the same initial and domain share one
+pseudonym. Without the profile, the default Australian redaction still masks email
+addresses.
+
+| Event type | Personal or sensitive fields kept | Treatment | Never collected |
+|---|---|---|---|
+| `intune_audit` | Actor user principal name or service principal name, actor object id, actor IP address, resource display name | UPN, object id and resource name are HMAC pseudonyms; IP address kept for detections | Modified property old and new values, actor permissions list |
+| `intune_device_compliance` | Primary user principal name and object id, operating system and version, ownership, encryption and jailbreak state | UPN and object id are HMAC pseudonyms; the Entra and Intune device ids identify the device | Device name, IMEI, MEID, serial number, phone number, Wi-Fi and Ethernet MAC addresses, email address, hardware inventory, compliant devices (refused in `complianceStates`) |
+
+IP addresses are personal information under the Privacy Act 1988 when they can identify a
+person. They are kept because sign-in and admin anomaly detection depend on them. If your
+policy does not allow that, add `- path: source.ipAddress` with `action: hmac` (or
+`remove`) to your privacy profile.
+
+## Switch a source off
+
+1. Remove the input from `BOWER_MICROSOFT_CONFIG` (or unset the variable) and restart the
+ collector. The cursor row is kept, so turning it back on resumes within the seven day
+ floor.
+2. To revoke access at once, remove the Graph permission, the admin consent or the app
+ registration in Entra. The input reports `mscloud-permission-denied` and reads nothing.
+3. To remove the data already delivered, purge it in Log Analytics; Bower keeps queue rows
+ only for the delivered retention period (`BOWER_QUEUE_RETENTION_HOURS`).
+
+## Residual risks
+
+- A compromised collector host can use the collector's credential to read what the
+ permissions above allow. Keep the identity dedicated and the permissions to this list.
+- `DeviceManagementApps.Read.All` is broader than audit read. Microsoft offers no narrower
+ permission for Intune audit events.
+- Audit records Microsoft writes more than the overlap (10 minutes by default) after their
+ activity time are missed. Increase `overlapSeconds` if you see late arrivals.
diff --git a/docs/security/pack-runtime-catalogue.md b/docs/security/pack-runtime-catalogue.md
index 8de7d0e9..16c246b0 100644
--- a/docs/security/pack-runtime-catalogue.md
+++ b/docs/security/pack-runtime-catalogue.md
@@ -92,3 +92,28 @@ cloud raw parser is activated here. DCR templates remain packaged-only.
See [activation, limits, failure codes and Sigma subset](../deployment/packs.md#local-parser-and-detection-activation).
All host demonstrations are local and synthetic. Destination delivery requires a
separate authorised query; no Sentinel delivery or all-software coverage is claimed.
+
+`microsoft-intune` 1.1.0 exposes two signed JSON parsers for records from the
+[Microsoft cloud source](../deployment/microsoft-cloud-sources.md). Parser 0 maps
+`intune-audit` records (Graph `deviceManagement/auditEvents`): it requires source kind
+`intune-audit` and an activity time, maps the activity to the action, the Intune result
+through a static table to `success` or `failure` (else `unknown`), the actor to the user
+principal name, service principal name or application name in that order, the actor IP
+address (canonicalised by the source, or absent) to the source address, and the first
+resource to the target. It produces `intune_audit`, category `administrative-activity`,
+application `microsoft-intune`, with labels for the audit event id, category, component,
+operation type and the names of modified properties. Parser 1 maps
+`intune-device-compliance` records (daily `deviceManagement/managedDevices` snapshot): it
+requires that source kind and a state other than `compliant`, and produces
+`intune_device_compliance`, category `application-security`, action
+`device.compliance.`, target the Entra device id, with Intune device id, snapshot
+day, operating system, version, ownership, encryption and jailbreak labels. Device names,
+modified property values and hardware identifiers are never read by the source. Policies
+`BWR-PACK-INTUNE-AUDIT` 1.0.0 and `BWR-PACK-INTUNE-COMPLIANCE` 1.0.0 select. The pack ships
+no privacy profile; use `deploy/privacy/microsoft-cloud.yaml` to pseudonymise people,
+email addresses and resource names. Local rules: `bower-pack-intune-device-wipe-001`,
+`bower-pack-intune-rbac-change-001` 1.1.0 (role changes only, never reads),
+`bower-pack-intune-policy-deleted-001` and `bower-pack-intune-jailbroken-001`. Version
+1.1.0 adds the audit event id, Intune device id and snapshot day labels, drops the outcome
+reason (it repeated the result) and the last sync and grace period labels (parser mapping
+limit), and limits the RBAC rule to changes.
diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md
index dbd92ff8..59dc0777 100644
--- a/docs/security/threat-model.md
+++ b/docs/security/threat-model.md
@@ -163,6 +163,17 @@ evidence.
bounded tailer; CRI partial joins are capped; only allow-listed metadata labels are
attached (and pass through the privacy engine); non-envelope stdout noise is dropped.
See [Kubernetes source](../deployment/kubernetes-source.md).
+- Microsoft cloud pull source (`Bower.Source.MicrosoftCloud`, new outbound trust
+ boundary: bearer-token HTTPS requests to Microsoft Graph for one tenant per input):
+ read-only application permissions listed per source kind; tokens in memory only (the
+ collector's one Azure credential or a per-input certificate, never a client secret) and
+ sent only to the one host the kind allow-lists, HTTPS on the default port, with
+ redirects refused and next links on any other host refused before sending. Responses are
+ untrusted input: 16 MiB and depth 32 caps, bounded values, readers request only mapped
+ fields with `$select` and never read modified property values or hardware identifiers.
+ Records pass a signed pack parser, redaction and policy; cursors (`mscloud:`) commit
+ per page only after durable enqueue and fail closed when damaged. Errors carry codes and
+ HTTP status only. See [Microsoft cloud sources security](microsoft-cloud-sources.md).
- Event injection: the collector requires a shared bearer token
(`BOWER_INGEST_TOKEN`, compared in constant time) whenever it listens beyond
loopback and refuses to start without one. Kubernetes manifests add a
diff --git a/packs/microsoft-intune/detections/intune-device-wipe-or-retire.yml b/packs/microsoft-intune/detections/intune-device-wipe-or-retire.yml
new file mode 100644
index 00000000..d2877cf7
--- /dev/null
+++ b/packs/microsoft-intune/detections/intune-device-wipe-or-retire.yml
@@ -0,0 +1,25 @@
+title: Intune device wipe, retire or delete
+id: bower-pack-intune-device-wipe-001
+status: stable
+description: >-
+ An administrator or application wiped, retired or deleted an Intune managed device. A
+ compromised admin account or app can destroy a fleet this way; review every occurrence.
+version: 1.0.0
+level: high
+logsource:
+ product: bower
+ service: intune_audit
+detection:
+ selection:
+ EventType: intune_audit
+ EventAction|startswith:
+ - Wipe
+ - Retire
+ - Delete ManagedDevice
+ - Clean Windows Device
+ condition: selection
+tags:
+ - attack.t1485
+ - attack.impact
+falsepositives:
+ - Planned device decommissioning or lost-device response
diff --git a/packs/microsoft-intune/detections/intune-jailbroken-device.yml b/packs/microsoft-intune/detections/intune-jailbroken-device.yml
new file mode 100644
index 00000000..14e66d02
--- /dev/null
+++ b/packs/microsoft-intune/detections/intune-jailbroken-device.yml
@@ -0,0 +1,18 @@
+title: Jailbroken or rooted device enrolled in Intune
+id: bower-pack-intune-jailbroken-001
+status: stable
+description: The daily compliance snapshot reported a managed device as jailbroken or rooted.
+version: 1.0.0
+level: medium
+logsource:
+ product: bower
+ service: intune_device_compliance
+detection:
+ selection:
+ EventType: intune_device_compliance
+ jailBroken: 'True'
+ condition: selection
+tags:
+ - attack.t1398
+falsepositives:
+ - Developer test devices
diff --git a/packs/microsoft-intune/detections/intune-policy-deleted.yml b/packs/microsoft-intune/detections/intune-policy-deleted.yml
new file mode 100644
index 00000000..c7225a24
--- /dev/null
+++ b/packs/microsoft-intune/detections/intune-policy-deleted.yml
@@ -0,0 +1,27 @@
+title: Intune compliance or configuration policy deleted
+id: bower-pack-intune-policy-deleted-001
+status: stable
+description: >-
+ A compliance policy, configuration profile or security baseline was deleted, which can
+ remove device protections silently.
+version: 1.0.0
+level: medium
+logsource:
+ product: bower
+ service: intune_audit
+detection:
+ selection:
+ EventType: intune_audit
+ intuneOperationType: Delete
+ intuneCategory:
+ - Compliance
+ - DeviceConfiguration
+ - DeviceIntent
+ - SecurityBaseline
+ - EndpointSecurity
+ condition: selection
+tags:
+ - attack.t1562.001
+ - attack.defense_evasion
+falsepositives:
+ - Policy consolidation
diff --git a/packs/microsoft-intune/detections/intune-rbac-change.yml b/packs/microsoft-intune/detections/intune-rbac-change.yml
new file mode 100644
index 00000000..f1eb57e8
--- /dev/null
+++ b/packs/microsoft-intune/detections/intune-rbac-change.yml
@@ -0,0 +1,30 @@
+title: Intune role or role assignment changed
+id: bower-pack-intune-rbac-change-001
+status: stable
+description: >-
+ An Intune role definition or role assignment was created, changed or deleted. New Intune
+ administrators can push scripts and apps to every managed device. Reads are not matched.
+version: 1.1.0
+level: high
+logsource:
+ product: bower
+ service: intune_audit
+detection:
+ selection:
+ EventType: intune_audit
+ intuneCategory: Role
+ intuneOperationType:
+ - Create
+ - Patch
+ - Update
+ - Delete
+ - Assign
+ - Remove
+ - Action
+ condition: selection
+tags:
+ - attack.t1098
+ - attack.persistence
+ - attack.privilege_escalation
+falsepositives:
+ - Planned changes to Intune administration
diff --git a/packs/microsoft-intune/pack.yaml b/packs/microsoft-intune/pack.yaml
new file mode 100644
index 00000000..56c1f9b0
--- /dev/null
+++ b/packs/microsoft-intune/pack.yaml
@@ -0,0 +1,29 @@
+apiVersion: bower.security/v1
+kind: Pack
+metadata:
+ id: microsoft-intune
+ version: 1.1.0
+ name: Microsoft Intune audit and device compliance
+ description: >-
+ Intune audit events (who changed, wiped, retired or reassigned what) and a daily
+ snapshot of devices that need attention (noncompliant, in grace period, conflict or
+ error), from the Bower Microsoft cloud source (BOWER_MICROSOFT_CONFIG). Signed
+ transforms map each record to the Bower envelope inside the collector. Modified
+ property values, hardware identifiers and contact details are never read from the API.
+ Composes with other packs: it ships no privacy profile; use
+ deploy/privacy/microsoft-cloud.yaml to pseudonymise people and device names.
+ owner: Security Operations
+policies:
+ - policies/intune-audit.yaml
+ - policies/intune-device-compliance.yaml
+parsers:
+ - parsers/intune-audit.json
+ - parsers/intune-device-compliance.json
+detections:
+ - detections/intune-device-wipe-or-retire.yml
+ - detections/intune-rbac-change.yml
+ - detections/intune-policy-deleted.yml
+ - detections/intune-jailbroken-device.yml
+samples:
+ - samples/intune.jsonl
+dcr: true
diff --git a/packs/microsoft-intune/parsers/intune-audit.json b/packs/microsoft-intune/parsers/intune-audit.json
new file mode 100644
index 00000000..81813a1e
--- /dev/null
+++ b/packs/microsoft-intune/parsers/intune-audit.json
@@ -0,0 +1,285 @@
+{
+ "version": "1.0",
+ "format": "Json",
+ "fields": [
+ {
+ "sourceName": "id",
+ "type": "Text",
+ "ocsfPath": "metadata.uid",
+ "asimField": "EventOriginalUid",
+ "sensitive": false
+ },
+ {
+ "sourceName": "input",
+ "type": "Text",
+ "ocsfPath": null,
+ "asimField": null,
+ "sensitive": false
+ },
+ {
+ "sourceName": "sourceKind",
+ "type": "Text",
+ "ocsfPath": "metadata.log_name",
+ "asimField": "EventOriginalSubType",
+ "sensitive": false
+ },
+ {
+ "sourceName": "tenantId",
+ "type": "Text",
+ "ocsfPath": "cloud.account.uid",
+ "asimField": "DvcScopeId",
+ "sensitive": false
+ },
+ {
+ "sourceName": "auditEventId",
+ "type": "Text",
+ "ocsfPath": "metadata.original_uid",
+ "asimField": "EventOriginalUid",
+ "sensitive": false
+ },
+ {
+ "sourceName": "activityDateTime",
+ "type": "DateTime",
+ "ocsfPath": "time",
+ "asimField": "TimeGenerated",
+ "sensitive": false
+ },
+ {
+ "sourceName": "activity",
+ "type": "Text",
+ "ocsfPath": "api.operation",
+ "asimField": "Operation",
+ "sensitive": false
+ },
+ {
+ "sourceName": "activityType",
+ "type": "Text",
+ "ocsfPath": "activity_name",
+ "asimField": "EventOriginalType",
+ "sensitive": false
+ },
+ {
+ "sourceName": "activityOperationType",
+ "type": "Text",
+ "ocsfPath": "type_name",
+ "asimField": "EventType",
+ "sensitive": false
+ },
+ {
+ "sourceName": "activityResult",
+ "type": "Text",
+ "ocsfPath": "status",
+ "asimField": "EventOriginalResultDetails",
+ "sensitive": false
+ },
+ {
+ "sourceName": "category",
+ "type": "Text",
+ "ocsfPath": "category_name",
+ "asimField": "EventSubType",
+ "sensitive": false
+ },
+ {
+ "sourceName": "componentName",
+ "type": "Text",
+ "ocsfPath": "metadata.product.feature.name",
+ "asimField": "EventProduct",
+ "sensitive": false
+ },
+ {
+ "sourceName": "correlationId",
+ "type": "Text",
+ "ocsfPath": "metadata.correlation_uid",
+ "asimField": "EventOriginalUid",
+ "sensitive": false
+ },
+ {
+ "sourceName": "actorType",
+ "type": "Text",
+ "ocsfPath": "actor.user.type",
+ "asimField": "ActorUserType",
+ "sensitive": false
+ },
+ {
+ "sourceName": "actorUserPrincipalName",
+ "type": "Text",
+ "ocsfPath": "actor.user.email_addr",
+ "asimField": "ActorUsername",
+ "sensitive": true
+ },
+ {
+ "sourceName": "actorUserId",
+ "type": "Text",
+ "ocsfPath": "actor.user.uid",
+ "asimField": "ActorUserId",
+ "sensitive": true
+ },
+ {
+ "sourceName": "actorApplicationId",
+ "type": "Text",
+ "ocsfPath": "actor.app_uid",
+ "asimField": "ActingAppId",
+ "sensitive": false
+ },
+ {
+ "sourceName": "actorApplicationName",
+ "type": "Text",
+ "ocsfPath": "actor.app_name",
+ "asimField": "ActingAppName",
+ "sensitive": false
+ },
+ {
+ "sourceName": "actorServicePrincipalName",
+ "type": "Text",
+ "ocsfPath": "actor.user.name",
+ "asimField": "ActorUsername",
+ "sensitive": true
+ },
+ {
+ "sourceName": "actorIpAddress",
+ "type": "IpAddress",
+ "ocsfPath": "src_endpoint.ip",
+ "asimField": "SrcIpAddr",
+ "sensitive": true
+ },
+ {
+ "sourceName": "resourceType",
+ "type": "Text",
+ "ocsfPath": "resources.type",
+ "asimField": "TargetAppType",
+ "sensitive": false
+ },
+ {
+ "sourceName": "resourceId",
+ "type": "Text",
+ "ocsfPath": "resources.uid",
+ "asimField": "TargetAppId",
+ "sensitive": false
+ },
+ {
+ "sourceName": "resourceName",
+ "type": "Text",
+ "ocsfPath": "resources.name",
+ "asimField": "TargetAppName",
+ "sensitive": true
+ },
+ {
+ "sourceName": "resourceCount",
+ "type": "WholeNumber",
+ "ocsfPath": null,
+ "asimField": null,
+ "sensitive": false
+ },
+ {
+ "sourceName": "modifiedProperties",
+ "type": "Text",
+ "ocsfPath": "unmapped.modified_properties",
+ "asimField": null,
+ "sensitive": false
+ },
+ {
+ "sourceName": "selected",
+ "type": "Text",
+ "ocsfPath": null,
+ "asimField": null,
+ "sensitive": false
+ },
+ {
+ "sourceName": "action",
+ "type": "Text",
+ "ocsfPath": "api.operation",
+ "asimField": "Operation",
+ "sensitive": false
+ },
+ {
+ "sourceName": "result",
+ "type": "Text",
+ "ocsfPath": "status",
+ "asimField": "EventResult",
+ "sensitive": false
+ },
+ {
+ "sourceName": "actor",
+ "type": "Text",
+ "ocsfPath": "actor.user.name",
+ "asimField": "ActorUsername",
+ "sensitive": true
+ },
+ {
+ "sourceName": "actor_id",
+ "type": "Text",
+ "ocsfPath": "actor.user.uid",
+ "asimField": "ActorUserId",
+ "sensitive": true
+ },
+ {
+ "sourceName": "target_type",
+ "type": "Text",
+ "ocsfPath": "resources.type",
+ "asimField": "TargetAppType",
+ "sensitive": false
+ },
+ {
+ "sourceName": "correlation",
+ "type": "Text",
+ "ocsfPath": "metadata.correlation_uid",
+ "asimField": null,
+ "sensitive": false
+ },
+ {
+ "sourceName": "source_ip",
+ "type": "IpAddress",
+ "ocsfPath": "src_endpoint.ip",
+ "asimField": "SrcIpAddr",
+ "sensitive": true
+ }
+ ],
+ "runtime": {
+ "applicationName": "microsoft-intune",
+ "environment": "production",
+ "eventCategory": "administrative-activity",
+ "eventType": "intune_audit",
+ "eventAction": "intune.audit",
+ "eventResult": "unknown",
+ "transforms": [
+ "if .sourceKind == \"intune-audit\" && .activityDateTime != null { .selected = \"true\" } else { .selected = \"false\" }",
+ ".action = coalesce(.activity, .activityType, \"unknown\")",
+ ".result = coalesce(lookup(\"results\", lower(.activityResult)), \"unknown\")",
+ ".actor = coalesce(.actorUserPrincipalName, .actorServicePrincipalName, .actorApplicationName, .actorType, \"unknown\")",
+ ".actor_id = coalesce(.actorUserId, .actorApplicationId, \"unknown\")",
+ ".target_type = coalesce(.resourceType, \"IntuneResource\")",
+ ".correlation = coalesce(.correlationId, .auditEventId)",
+ ".source_ip = .actorIpAddress"
+ ],
+ "tables": {
+ "results": {
+ "success": "success",
+ "succeeded": "success",
+ "failure": "failure",
+ "failed": "failure",
+ "fail": "failure"
+ }
+ },
+ "match": {
+ "selected": "true"
+ },
+ "fields": {
+ "eventId": "id",
+ "timeGenerated": "activityDateTime",
+ "eventAction": "action",
+ "eventResult": "result",
+ "actor.username": "actor",
+ "actor.userId": "actor_id",
+ "target.type": "target_type",
+ "target.id": "resourceId",
+ "target.name": "resourceName",
+ "source.ipAddress": "source_ip",
+ "request.correlationId": "correlation",
+ "labels.intuneCategory": "category",
+ "labels.intuneComponent": "componentName",
+ "labels.intuneOperationType": "activityOperationType",
+ "labels.intuneModifiedProperties": "modifiedProperties",
+ "labels.intuneAuditEventId": "auditEventId"
+ }
+ }
+}
diff --git a/packs/microsoft-intune/parsers/intune-device-compliance.json b/packs/microsoft-intune/parsers/intune-device-compliance.json
new file mode 100644
index 00000000..92a30eca
--- /dev/null
+++ b/packs/microsoft-intune/parsers/intune-device-compliance.json
@@ -0,0 +1,228 @@
+{
+ "version": "1.0",
+ "format": "Json",
+ "fields": [
+ {
+ "sourceName": "id",
+ "type": "Text",
+ "ocsfPath": "metadata.uid",
+ "asimField": "EventOriginalUid",
+ "sensitive": false
+ },
+ {
+ "sourceName": "input",
+ "type": "Text",
+ "ocsfPath": null,
+ "asimField": null,
+ "sensitive": false
+ },
+ {
+ "sourceName": "sourceKind",
+ "type": "Text",
+ "ocsfPath": "metadata.log_name",
+ "asimField": "EventOriginalSubType",
+ "sensitive": false
+ },
+ {
+ "sourceName": "tenantId",
+ "type": "Text",
+ "ocsfPath": "cloud.account.uid",
+ "asimField": "DvcScopeId",
+ "sensitive": false
+ },
+ {
+ "sourceName": "snapshotDate",
+ "type": "Text",
+ "ocsfPath": null,
+ "asimField": null,
+ "sensitive": false
+ },
+ {
+ "sourceName": "snapshotAt",
+ "type": "DateTime",
+ "ocsfPath": "time",
+ "asimField": "TimeGenerated",
+ "sensitive": false
+ },
+ {
+ "sourceName": "deviceId",
+ "type": "Text",
+ "ocsfPath": "device.uid",
+ "asimField": "DvcId",
+ "sensitive": false
+ },
+ {
+ "sourceName": "complianceState",
+ "type": "Text",
+ "ocsfPath": "compliance.status",
+ "asimField": "EventResultDetails",
+ "sensitive": false
+ },
+ {
+ "sourceName": "operatingSystem",
+ "type": "Text",
+ "ocsfPath": "device.os.name",
+ "asimField": "DvcOs",
+ "sensitive": false
+ },
+ {
+ "sourceName": "osVersion",
+ "type": "Text",
+ "ocsfPath": "device.os.version",
+ "asimField": "DvcOsVersion",
+ "sensitive": false
+ },
+ {
+ "sourceName": "lastSyncDateTime",
+ "type": "DateTime",
+ "ocsfPath": "device.last_seen_time",
+ "asimField": null,
+ "sensitive": false
+ },
+ {
+ "sourceName": "userPrincipalName",
+ "type": "Text",
+ "ocsfPath": "device.owner.email_addr",
+ "asimField": "ActorUsername",
+ "sensitive": true
+ },
+ {
+ "sourceName": "userId",
+ "type": "Text",
+ "ocsfPath": "device.owner.uid",
+ "asimField": "ActorUserId",
+ "sensitive": true
+ },
+ {
+ "sourceName": "azureADDeviceId",
+ "type": "Text",
+ "ocsfPath": "device.uid_alt",
+ "asimField": "DvcAzureResourceId",
+ "sensitive": false
+ },
+ {
+ "sourceName": "ownerType",
+ "type": "Text",
+ "ocsfPath": "device.owner.type",
+ "asimField": null,
+ "sensitive": false
+ },
+ {
+ "sourceName": "isEncrypted",
+ "type": "Text",
+ "ocsfPath": "device.is_encrypted",
+ "asimField": null,
+ "sensitive": false
+ },
+ {
+ "sourceName": "jailBroken",
+ "type": "Text",
+ "ocsfPath": "device.is_jailbroken",
+ "asimField": null,
+ "sensitive": false
+ },
+ {
+ "sourceName": "gracePeriodExpires",
+ "type": "DateTime",
+ "ocsfPath": null,
+ "asimField": null,
+ "sensitive": false
+ },
+ {
+ "sourceName": "selected",
+ "type": "Text",
+ "ocsfPath": null,
+ "asimField": null,
+ "sensitive": false
+ },
+ {
+ "sourceName": "action",
+ "type": "Text",
+ "ocsfPath": "activity_name",
+ "asimField": "EventType",
+ "sensitive": false
+ },
+ {
+ "sourceName": "result",
+ "type": "Text",
+ "ocsfPath": "status",
+ "asimField": "EventResult",
+ "sensitive": false
+ },
+ {
+ "sourceName": "user",
+ "type": "Text",
+ "ocsfPath": "device.owner.email_addr",
+ "asimField": "ActorUsername",
+ "sensitive": true
+ },
+ {
+ "sourceName": "user_id",
+ "type": "Text",
+ "ocsfPath": "device.owner.uid",
+ "asimField": "ActorUserId",
+ "sensitive": true
+ },
+ {
+ "sourceName": "device",
+ "type": "Text",
+ "ocsfPath": "device.uid",
+ "asimField": "DvcId",
+ "sensitive": false
+ },
+ {
+ "sourceName": "target_type",
+ "type": "Text",
+ "ocsfPath": "device.type",
+ "asimField": "DvcIdType",
+ "sensitive": false
+ }
+ ],
+ "runtime": {
+ "applicationName": "microsoft-intune",
+ "environment": "production",
+ "eventCategory": "application-security",
+ "eventType": "intune_device_compliance",
+ "eventAction": "intune.compliance",
+ "eventResult": "unknown",
+ "transforms": [
+ "if .sourceKind == \"intune-device-compliance\" && .complianceState != null && .complianceState != \"compliant\" { .selected = \"true\" } else { .selected = \"false\" }",
+ ".action = concat(\"device.compliance.\", coalesce(.complianceState, \"unknown\"))",
+ ".result = coalesce(lookup(\"results\", .complianceState), \"unknown\")",
+ ".user = coalesce(.userPrincipalName, \"none\")",
+ ".user_id = coalesce(.userId, \"none\")",
+ ".device = coalesce(.azureADDeviceId, .deviceId)",
+ ".target_type = \"IntuneManagedDevice\""
+ ],
+ "tables": {
+ "results": {
+ "noncompliant": "failure",
+ "inGracePeriod": "failure",
+ "conflict": "failure",
+ "error": "failure",
+ "unknown": "unknown",
+ "configManager": "unknown"
+ }
+ },
+ "match": {
+ "selected": "true"
+ },
+ "fields": {
+ "eventId": "id",
+ "timeGenerated": "snapshotAt",
+ "eventAction": "action",
+ "eventResult": "result",
+ "actor.username": "user",
+ "actor.userId": "user_id",
+ "target.type": "target_type",
+ "target.id": "device",
+ "labels.operatingSystem": "operatingSystem",
+ "labels.osVersion": "osVersion",
+ "labels.ownerType": "ownerType",
+ "labels.isEncrypted": "isEncrypted",
+ "labels.jailBroken": "jailBroken",
+ "labels.intuneDeviceId": "deviceId",
+ "labels.snapshotDate": "snapshotDate"
+ }
+ }
+}
diff --git a/packs/microsoft-intune/policies/intune-audit.yaml b/packs/microsoft-intune/policies/intune-audit.yaml
new file mode 100644
index 00000000..636863e3
--- /dev/null
+++ b/packs/microsoft-intune/policies/intune-audit.yaml
@@ -0,0 +1,40 @@
+apiVersion: bower.security/v1
+kind: TelemetryPolicy
+
+metadata:
+ id: BWR-PACK-INTUNE-AUDIT
+ name: Microsoft Intune audit events
+ version: 1.0.0
+ owner: Security Operations
+ reviewDate: 2027-06-30
+
+match:
+ eventCategories:
+ - administrative-activity
+ eventTypes:
+ - intune_audit
+
+requirements:
+ requiredFields:
+ - timeGenerated
+ - eventType
+ - eventAction
+ - eventResult
+ - application.name
+ - target.type
+ atLeastOne:
+ - actor.username
+ - actor.userId
+ recommendedFields:
+ - source.ipAddress
+ - request.correlationId
+ - target.id
+
+decision:
+ action: accept
+ minimumValueScore: 75
+ neverSample: true
+
+routing:
+ profile: cloud-control-plane
+ destination: security-events
diff --git a/packs/microsoft-intune/policies/intune-device-compliance.yaml b/packs/microsoft-intune/policies/intune-device-compliance.yaml
new file mode 100644
index 00000000..339fc960
--- /dev/null
+++ b/packs/microsoft-intune/policies/intune-device-compliance.yaml
@@ -0,0 +1,35 @@
+apiVersion: bower.security/v1
+kind: TelemetryPolicy
+
+metadata:
+ id: BWR-PACK-INTUNE-COMPLIANCE
+ name: Microsoft Intune devices that need attention
+ version: 1.0.0
+ owner: Security Operations
+ reviewDate: 2027-06-30
+
+match:
+ eventCategories:
+ - application-security
+ eventTypes:
+ - intune_device_compliance
+
+requirements:
+ requiredFields:
+ - timeGenerated
+ - eventType
+ - eventAction
+ - application.name
+ - target.id
+ atLeastOne:
+ - actor.username
+ - actor.userId
+
+decision:
+ action: accept
+ minimumValueScore: 70
+ neverSample: true
+
+routing:
+ profile: device-posture
+ destination: security-events
diff --git a/packs/microsoft-intune/samples/intune.jsonl b/packs/microsoft-intune/samples/intune.jsonl
new file mode 100644
index 00000000..7f9d6fb8
--- /dev/null
+++ b/packs/microsoft-intune/samples/intune.jsonl
@@ -0,0 +1,9 @@
+{"name":"device wipe is mapped, selected and fires the wipe detection","parser":0,"raw":{"id":"mscloud-0f1e2d3c4b5a69788796a5b4c3d2e1f0","input":"intune-audit","sourceKind":"intune-audit","tenantId":"a1b2c3d4-0000-4000-8000-00000000aaaa","auditEventId":"5e1f0c2a-0000-4000-8000-000000000040","activityDateTime":"{{now}}","activity":"Wipe ManagedDevice","activityType":"Wipe ManagedDevice","activityOperationType":"Action","activityResult":"Success","category":"Device","componentName":"DeviceManagement","correlationId":"c0ffee00-0000-4000-8000-000000000001","actorType":"ItPro","actorUserPrincipalName":"megan.bowen@contoso.example","actorUserId":"0b7c1d3e-0000-4000-8000-000000000101","actorIpAddress":"203.0.113.40","resourceType":"ManagedDevice","resourceId":"8d1c0b3a-0000-4000-8000-000000000201","resourceName":"Device-7Q2","resourceCount":"1"},"expect":"accept","mustNotContain":["megan.bowen@contoso.example"],"expectedDetections":["bower-pack-intune-device-wipe-001"],"expectFields":{"eventType":"intune_audit","eventCategory":"administrative-activity","eventAction":"Wipe ManagedDevice","eventResult":"success","application.name":"microsoft-intune","target.type":"ManagedDevice","target.id":"8d1c0b3a-0000-4000-8000-000000000201","source.ipAddress":"203.0.113.40","request.correlationId":"c0ffee00-0000-4000-8000-000000000001","actor.username":"present","labels.intuneCategory":"Device","labels.intuneAuditEventId":"5e1f0c2a-0000-4000-8000-000000000040"}}
+{"name":"role assignment change fires the RBAC detection and keeps only property names","parser":0,"raw":{"id":"mscloud-1a2b3c4d5e6f708192a3b4c5d6e7f801","input":"intune-audit","sourceKind":"intune-audit","tenantId":"a1b2c3d4-0000-4000-8000-00000000aaaa","auditEventId":"5e1f0c2a-0000-4000-8000-000000000040","activityDateTime":"{{now}}","activity":"Patch RoleAssignment","activityType":"Patch RoleAssignment","activityOperationType":"Patch","activityResult":"Success","category":"Role","componentName":"DeviceManagement","correlationId":"c0ffee00-0000-4000-8000-000000000001","actorType":"ItPro","actorUserPrincipalName":"adele.vance@contoso.example","actorUserId":"0b7c1d3e-0000-4000-8000-000000000101","actorIpAddress":"2001:db8::40","resourceType":"RoleAssignment","resourceId":"5a5a5a5a-0000-4000-8000-000000000301","resourceName":"Helpdesk operators","resourceCount":"1","modifiedProperties":"Members,ScopeTags"},"expect":"accept","mustNotContain":["adele.vance@contoso.example"],"expectedDetections":["bower-pack-intune-rbac-change-001"],"expectFields":{"eventAction":"Patch RoleAssignment","labels.intuneModifiedProperties":"Members,ScopeTags","labels.intuneOperationType":"Patch","source.ipAddress":"2001:db8::40"}}
+{"name":"reading role definitions does not fire the RBAC detection","parser":0,"raw":{"id":"mscloud-8192a3b4c5d6e7f80112233445566778","input":"intune-audit","sourceKind":"intune-audit","tenantId":"a1b2c3d4-0000-4000-8000-00000000aaaa","auditEventId":"5e1f0c2a-0000-4000-8000-000000000040","activityDateTime":"{{now}}","activity":"Get RoleDefinitions","activityType":"Get RoleDefinitions","activityOperationType":"Get","activityResult":"Success","category":"Role","componentName":"DeviceManagement","correlationId":"c0ffee00-0000-4000-8000-000000000001","actorType":"ItPro","actorUserPrincipalName":"adele.vance@contoso.example","actorUserId":"0b7c1d3e-0000-4000-8000-000000000101","actorIpAddress":"198.51.100.20","resourceType":"RoleAssignment","resourceId":"5a5a5a5a-0000-4000-8000-000000000301","resourceName":"Helpdesk operators","resourceCount":"1"},"expect":"accept","expectedDetections":[],"expectFields":{"labels.intuneOperationType":"Get"}}
+{"name":"compliance policy deletion by an application is attributed to the app","parser":0,"raw":{"id":"mscloud-2b3c4d5e6f708192a3b4c5d6e7f80112","input":"intune-audit","sourceKind":"intune-audit","tenantId":"a1b2c3d4-0000-4000-8000-00000000aaaa","auditEventId":"5e1f0c2a-0000-4000-8000-000000000040","activityDateTime":"{{now}}","activity":"Delete DeviceCompliancePolicy","activityType":"Delete DeviceCompliancePolicy","activityOperationType":"Delete","activityResult":"Success","category":"Compliance","componentName":"DeviceManagement","correlationId":"c0ffee00-0000-4000-8000-000000000001","actorType":"Application","actorApplicationId":"9e9e9e9e-0000-4000-8000-000000000401","actorApplicationName":"Fleet automation","resourceType":"DeviceCompliancePolicy","resourceId":"7b7b7b7b-0000-4000-8000-000000000501","resourceName":"Windows baseline","resourceCount":"1"},"expect":"accept","expectedDetections":["bower-pack-intune-policy-deleted-001"],"expectFields":{"actor.username":"Fleet automation","actor.userId":"9e9e9e9e-0000-4000-8000-000000000401","eventResult":"success","source.ipAddress":"absent"}}
+{"name":"failed audit event keeps its result","parser":0,"raw":{"id":"mscloud-3c4d5e6f708192a3b4c5d6e7f8011223","input":"intune-audit","sourceKind":"intune-audit","tenantId":"a1b2c3d4-0000-4000-8000-00000000aaaa","auditEventId":"5e1f0c2a-0000-4000-8000-000000000040","activityDateTime":"{{now}}","activity":"Create DeviceConfiguration","activityType":"Create DeviceConfiguration","activityOperationType":"Create","activityResult":"Failure","category":"DeviceConfiguration","componentName":"DeviceManagement","correlationId":"c0ffee00-0000-4000-8000-000000000001","actorType":"ItPro","actorUserPrincipalName":"megan.bowen@contoso.example","actorUserId":"0b7c1d3e-0000-4000-8000-000000000101","actorIpAddress":"198.51.100.9","resourceType":"DeviceConfiguration","resourceId":"6c6c6c6c-0000-4000-8000-000000000601","resourceCount":"1"},"expect":"accept","mustNotContain":["megan.bowen@contoso.example"],"expectedDetections":[],"expectFields":{"eventResult":"failure"}}
+{"name":"a compliance record routed to the audit parser is not selected","parser":0,"raw":{"id":"mscloud-4d5e6f708192a3b4c5d6e7f801122334","input":"intune-compliance","sourceKind":"intune-device-compliance","tenantId":"a1b2c3d4-0000-4000-8000-00000000aaaa","deviceId":"x","complianceState":"noncompliant","snapshotAt":"{{now}}"},"expect":"reject"}
+{"name":"noncompliant device is selected without its owner address","parser":1,"raw":{"id":"mscloud-5e6f708192a3b4c5d6e7f80112233445","input":"intune-compliance","sourceKind":"intune-device-compliance","tenantId":"a1b2c3d4-0000-4000-8000-00000000aaaa","snapshotDate":"2026-11-22","snapshotAt":"{{now}}","deviceId":"11111111-0000-4000-8000-000000000701","complianceState":"noncompliant","operatingSystem":"Windows","osVersion":"10.0.26100.2314","lastSyncDateTime":"{{now}}","userPrincipalName":"megan.bowen@contoso.example","userId":"0b7c1d3e-0000-4000-8000-000000000101","azureADDeviceId":"22222222-0000-4000-8000-000000000801","ownerType":"company","isEncrypted":"false","jailBroken":"False"},"expect":"accept","mustNotContain":["megan.bowen@contoso.example"],"expectedDetections":[],"expectFields":{"eventType":"intune_device_compliance","eventCategory":"application-security","eventAction":"device.compliance.noncompliant","eventResult":"failure","target.type":"IntuneManagedDevice","target.id":"22222222-0000-4000-8000-000000000801","labels.isEncrypted":"false","labels.operatingSystem":"Windows","actor.username":"present","labels.intuneDeviceId":"11111111-0000-4000-8000-000000000701","labels.snapshotDate":"2026-11-22","labels.lastSyncDateTime":"absent"}}
+{"name":"jailbroken device in grace period fires the jailbreak detection","parser":1,"raw":{"id":"mscloud-6f708192a3b4c5d6e7f8011223344556","input":"intune-compliance","sourceKind":"intune-device-compliance","tenantId":"a1b2c3d4-0000-4000-8000-00000000aaaa","snapshotDate":"2026-11-22","snapshotAt":"{{now}}","deviceId":"11111111-0000-4000-8000-000000000701","complianceState":"inGracePeriod","operatingSystem":"iOS","osVersion":"17.4","lastSyncDateTime":"{{now}}","userPrincipalName":"megan.bowen@contoso.example","userId":"0b7c1d3e-0000-4000-8000-000000000101","azureADDeviceId":"22222222-0000-4000-8000-000000000801","ownerType":"personal","isEncrypted":"false","jailBroken":"True","gracePeriodExpires":"{{now}}"},"expect":"accept","expectedDetections":["bower-pack-intune-jailbroken-001"],"expectFields":{"eventAction":"device.compliance.inGracePeriod","labels.jailBroken":"True","labels.ownerType":"personal"}}
+{"name":"compliant device is never selected","parser":1,"raw":{"id":"mscloud-708192a3b4c5d6e7f801122334455667","input":"intune-compliance","sourceKind":"intune-device-compliance","tenantId":"a1b2c3d4-0000-4000-8000-00000000aaaa","snapshotDate":"2026-11-22","snapshotAt":"{{now}}","deviceId":"11111111-0000-4000-8000-000000000701","complianceState":"compliant","operatingSystem":"Windows","osVersion":"10.0.26100.2314","lastSyncDateTime":"{{now}}","userPrincipalName":"megan.bowen@contoso.example","userId":"0b7c1d3e-0000-4000-8000-000000000101","azureADDeviceId":"22222222-0000-4000-8000-000000000801","ownerType":"company","isEncrypted":"false","jailBroken":"False"},"expect":"reject"}
diff --git a/src/Bower.Collector/Bower.Collector.csproj b/src/Bower.Collector/Bower.Collector.csproj
index 4a7ca3d0..b104b6f2 100644
--- a/src/Bower.Collector/Bower.Collector.csproj
+++ b/src/Bower.Collector/Bower.Collector.csproj
@@ -23,6 +23,7 @@
+
diff --git a/src/Bower.Collector/CollectorApplication.cs b/src/Bower.Collector/CollectorApplication.cs
index 447a21fd..acb50eac 100644
--- a/src/Bower.Collector/CollectorApplication.cs
+++ b/src/Bower.Collector/CollectorApplication.cs
@@ -21,6 +21,7 @@
using Bower.Redaction;
using Bower.ServiceDefaults;
using Bower.Source.File;
+using Bower.Source.MicrosoftCloud;
using Bower.Source.Syslog;
using Bower.Source.WindowsEventLog;
using Microsoft.AspNetCore.RateLimiting;
@@ -273,6 +274,42 @@ public static WebApplication Build(
});
builder.Services.AddHostedService();
}
+ if (sources.MicrosoftCloud is { } microsoftCloud)
+ {
+ // Cursors live with the queue, so a restart resumes where the queue left off.
+ builder.Services.AddSingleton(new MicrosoftCloudCursors(settings.QueuePath));
+ builder.Services.AddSingleton(services =>
+ {
+ PolicyBundleHolder bundleHolder = services.GetRequiredService();
+ TimeProvider clock = services.GetRequiredService();
+ // Tests supply a fake API (IMicrosoftCloudTokenProvider and HttpClient); otherwise
+ // the collector's one configured Azure credential, or the input's certificate.
+ IMicrosoftCloudTokenProvider tokens = services.GetService()
+ ?? new MicrosoftCloudTokenProvider(() => credential ?? AzureCredentialFactory.Create(settings));
+ HttpClient? injected = services.GetService()?.Client;
+ HttpClient client = injected ?? MicrosoftCloudRoutes.CreateHttpClient();
+ return new MicrosoftCloudSource(
+ microsoftCloud,
+ new CollectorMicrosoftCloudSink(new PackRecordIntake(
+ () => bundleHolder.CurrentBundle,
+ services.GetRequiredService(),
+ services.GetRequiredService(),
+ services.GetRequiredService(),
+ services.GetRequiredService(),
+ clock,
+ services.GetRequiredService())),
+ services.GetRequiredService().Store,
+ new MicrosoftCloudHttp(client, tokens, clock),
+ clock)
+ {
+ // A busy queue database (for example during a retention batch) is backpressure.
+ IsTransientStorageFailure = QueueStorageErrors.IsBusy,
+ // The source owns the client it was given only when it created it.
+ OwnedClient = injected is null ? client : null
+ };
+ });
+ builder.Services.AddHostedService();
+ }
builder.Services.AddSingleton();
builder.Services.AddSingleton(
new CollectorIdentity(settings.CollectorId, settings.Version, "local-http", settings.ConfigurationHash()));
@@ -703,6 +740,7 @@ [.. pack.Parsers.Select(parser => parser.Runtime is null ? "inactive-preview-onl
WindowsEventLog = windowsEventLog?.Snapshot(),
WecRuntime = wecRuntime is { Count: > 0 } ? wecRuntime : null,
FileTail = context.RequestServices.GetService()?.Snapshot(),
+ MicrosoftCloud = context.RequestServices.GetService()?.Snapshot(),
QueuePages = pages is null ? null : StatusQueuePagesResponse.From(pages),
Output = context.RequestServices.GetService()?.Id,
DeliveryActivity = new StatusDeliveryActivityResponse(
diff --git a/src/Bower.Collector/CollectorJson.cs b/src/Bower.Collector/CollectorJson.cs
index 1498c4c7..7895d345 100644
--- a/src/Bower.Collector/CollectorJson.cs
+++ b/src/Bower.Collector/CollectorJson.cs
@@ -79,6 +79,10 @@ internal sealed record StatusResponse(
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public IReadOnlyList? FileTail { get; init; }
+ /// Microsoft cloud input counters; omitted when BOWER_MICROSOFT_CONFIG is not set. Metadata only.
+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+ public IReadOnlyList? MicrosoftCloud { get; init; }
+
///
/// Queue database pages against the limit at which new events are refused: in-use bytes,
/// free-list bytes, the limit and the settlement ceiling, so host checks never recompute
diff --git a/src/Bower.Collector/CollectorSettings.cs b/src/Bower.Collector/CollectorSettings.cs
index 854ccf6f..a8da87ea 100644
--- a/src/Bower.Collector/CollectorSettings.cs
+++ b/src/Bower.Collector/CollectorSettings.cs
@@ -180,6 +180,9 @@ public sealed record CollectorSettings
/// JSON file of security-selected local files and their pack routes (BOWER_FILE_CONFIG).
public string? FileTailConfigPath { get; init; }
+ /// JSON file of Microsoft cloud API inputs (Intune) and their pack routes (BOWER_MICROSOFT_CONFIG).
+ public string? MicrosoftCloudConfigPath { get; init; }
+
///
/// BOWER_POLICY_WATCH (default false): watch the policy directory, local privacy profile
/// and configured signed pack files and hot-reload atomically on change.
@@ -455,6 +458,7 @@ public static CollectorSettings FromEnvironment(Func? read = nu
OriginProducers = SplitList(read("BOWER_ORIGIN_PRODUCERS")),
WindowsEventLogConfigPath = Blank(read("BOWER_WINDOWS_EVENTLOG_CONFIG")),
FileTailConfigPath = Blank(read("BOWER_FILE_CONFIG")),
+ MicrosoftCloudConfigPath = Blank(read("BOWER_MICROSOFT_CONFIG")),
PolicyWatchEnabled = ReadBoolean(read, "BOWER_POLICY_WATCH"),
PolicyWatchDebounce = TimeSpan.FromMilliseconds(ReadInt32(read, "BOWER_POLICY_WATCH_DEBOUNCE_MS", 500))
};
@@ -940,6 +944,11 @@ public string ConfigurationHash()
material += '\u001f' + "file-tail:" + FileTailConfigPath;
}
+ if (MicrosoftCloudConfigPath is not null)
+ {
+ material += '\u001f' + "microsoft-cloud:" + MicrosoftCloudConfigPath;
+ }
+
if (PressureRetentionFloor != TimeSpan.FromHours(1))
{
material += '\u001f' + "pressure-retention-minutes:"
diff --git a/src/Bower.Collector/CollectorStartupSources.cs b/src/Bower.Collector/CollectorStartupSources.cs
index a5430ec4..4debae91 100644
--- a/src/Bower.Collector/CollectorStartupSources.cs
+++ b/src/Bower.Collector/CollectorStartupSources.cs
@@ -2,6 +2,7 @@
using Bower.Core;
using Bower.Packs;
using Bower.Source.File;
+using Bower.Source.MicrosoftCloud;
using Bower.Source.Syslog;
using Bower.Source.WindowsEventLog;
@@ -11,7 +12,7 @@ namespace Bower.Collector;
/// Every file a collector start reads besides the policy bundle, loaded and checked the
/// same way for start-up () and for the signed
/// reload pre-check: source expectations, producer scopes and ingest tokens, the
-/// syslog, Windows Event Log and file tail configurations and their routes to the loaded packs, the
+/// syslog, Windows Event Log, file tail and Microsoft cloud configurations and their routes to the loaded packs, the
/// syslog TLS material, and the relay's pins and certificates. A reload is therefore
/// refused for exactly the files that would stop a restart.
///
@@ -30,7 +31,8 @@ public sealed record CollectorStartupSources(
ProducerAuthorization Producers,
IngestAuthentication Ingest,
RelayDownstreams? RelayDownstreams,
- FileTailSourceConfiguration? FileTail = null)
+ FileTailSourceConfiguration? FileTail = null,
+ MicrosoftCloudSourceConfiguration? MicrosoftCloud = null)
{
public static CollectorStartupSources Load(CollectorSettings settings, PolicyBundle bundle)
{
@@ -61,6 +63,13 @@ public static CollectorStartupSources Load(CollectorSettings settings, PolicyBun
FileTailRoutes.Validate(fileTail, bundle);
}
+ MicrosoftCloudSourceConfiguration? microsoftCloud = null;
+ if (settings.MicrosoftCloudConfigPath is not null)
+ {
+ microsoftCloud = MicrosoftCloudSourceConfigurationLoader.LoadFile(settings.MicrosoftCloudConfigPath);
+ MicrosoftCloudRoutes.Validate(microsoftCloud, bundle);
+ }
+
RelayDownstreams? downstreams = null;
if (settings.IsRelay)
{
@@ -90,6 +99,7 @@ settings.ProducerScopesJson is null
: ProducerAuthorization.FromJson(settings.ProducerScopesJson),
new IngestAuthentication(settings.IngestToken, settings.IngestTokensFile),
downstreams,
- fileTail);
+ fileTail,
+ microsoftCloud);
}
}
diff --git a/src/Bower.Collector/MicrosoftCloudIntake.cs b/src/Bower.Collector/MicrosoftCloudIntake.cs
new file mode 100644
index 00000000..6b0f042f
--- /dev/null
+++ b/src/Bower.Collector/MicrosoftCloudIntake.cs
@@ -0,0 +1,150 @@
+using System.Collections.Concurrent;
+using System.Net;
+using Azure.Core;
+using Azure.Identity;
+using Bower.Packs;
+using Bower.Persistence;
+using Bower.Source.MicrosoftCloud;
+
+namespace Bower.Collector;
+
+///
+/// Collector side of the Microsoft cloud source (see ).
+/// means durably enqueued; only then can the
+/// cursor move past the page.
+///
+internal sealed class CollectorMicrosoftCloudSink(PackRecordIntake intake) : IMicrosoftCloudSink
+{
+ public async ValueTask SubmitAsync(
+ MicrosoftCloudInputOptions input,
+ string record,
+ CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(input);
+ PackRecordOutcome outcome = await intake.SubmitAsync(
+ input.Route.Pack,
+ input.Route.Parser,
+ $"mscloud:{input.Id}:{input.Route.Pack}:{input.Route.Parser}",
+ record,
+ cancellationToken);
+ return outcome switch
+ {
+ PackRecordOutcome.Queued => MicrosoftCloudSubmitOutcome.Queued,
+ PackRecordOutcome.Duplicate => MicrosoftCloudSubmitOutcome.Duplicate,
+ PackRecordOutcome.Suppressed => MicrosoftCloudSubmitOutcome.Suppressed,
+ PackRecordOutcome.NotSelected => MicrosoftCloudSubmitOutcome.NotSelected,
+ PackRecordOutcome.Invalid => MicrosoftCloudSubmitOutcome.Invalid,
+ PackRecordOutcome.TooLarge => MicrosoftCloudSubmitOutcome.TooLarge,
+ PackRecordOutcome.Unavailable => MicrosoftCloudSubmitOutcome.Unavailable,
+ _ => MicrosoftCloudSubmitOutcome.Rejected
+ };
+ }
+}
+
+internal static class MicrosoftCloudRoutes
+{
+ /// Every input must route to an active parser of a loaded signed pack; checked at start-up and before a signed reload.
+ public static void Validate(MicrosoftCloudSourceConfiguration configuration, PolicyBundle bundle)
+ {
+ foreach (MicrosoftCloudInputOptions input in configuration.Inputs)
+ {
+ if (PackRecordIntake.Parser(bundle, input.Route.Pack, input.Route.Parser) is null)
+ {
+ throw new InvalidOperationException(
+ $"Microsoft cloud input {input.Id}: route pack {input.Route.Pack} parser {input.Route.Parser} is not an active parser of a loaded pack.");
+ }
+
+ if (input.Credential is { } credential && !File.Exists(credential.CertificatePath))
+ {
+ throw new InvalidOperationException(
+ $"Microsoft cloud input {input.Id}: credential.certificatePath does not exist.");
+ }
+ }
+ }
+
+ ///
+ /// HTTPS only, no automatic redirects (a redirect could carry the bearer token to another
+ /// host), the system proxy and trust store, bounded connection lifetime.
+ ///
+ public static HttpClient CreateHttpClient() =>
+ new(new SocketsHttpHandler
+ {
+ AllowAutoRedirect = false,
+ AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
+ PooledConnectionLifetime = TimeSpan.FromMinutes(10),
+ ConnectTimeout = TimeSpan.FromSeconds(30)
+ })
+ {
+ Timeout = TimeSpan.FromSeconds(100)
+ };
+}
+
+///
+/// Tokens from exactly one credential per input: the collector's configured Azure credential
+/// (BOWER_AZURE_CREDENTIAL), or the input's certificate app registration for another tenant.
+/// Azure.Identity caches tokens in memory only; nothing is written to disk or logged.
+///
+internal sealed class MicrosoftCloudTokenProvider(Func collectorCredential) : IMicrosoftCloudTokenProvider
+{
+ private readonly ConcurrentDictionary credentials = new(StringComparer.Ordinal);
+
+ public async ValueTask GetTokenAsync(
+ MicrosoftCloudInputOptions input,
+ string scope,
+ bool forceRefresh,
+ CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(input);
+ if (forceRefresh)
+ {
+ // Drop the cached credential so a refused token is never reused.
+ credentials.TryRemove(input.Id, out _);
+ }
+
+ TokenCredential credential = credentials.GetOrAdd(input.Id, _ => Create(input));
+ AccessToken token = await credential.GetTokenAsync(
+ new TokenRequestContext([scope], tenantId: input.TenantId),
+ cancellationToken);
+ return token.Token;
+ }
+
+ private TokenCredential Create(MicrosoftCloudInputOptions input) =>
+ input.Credential is { } certificate
+ ? new ClientCertificateCredential(input.TenantId, certificate.ClientId, certificate.CertificatePath)
+ : collectorCredential();
+}
+
+/// Cursor table in the queue database, then the input loops; stopped first on shutdown.
+internal sealed partial class MicrosoftCloudIntakeService(
+ MicrosoftCloudSource source,
+ MicrosoftCloudCursors cursors,
+ ILogger logger) : IHostedService
+{
+ public async Task StartAsync(CancellationToken cancellationToken)
+ {
+ await cursors.Store.InitializeAsync(cancellationToken);
+ await source.StartAsync(cancellationToken);
+ foreach (MicrosoftCloudInputStatus input in source.Snapshot())
+ {
+ LogPolling(logger, input.Id, input.SourceKind);
+ }
+ }
+
+ public async Task StopAsync(CancellationToken cancellationToken) =>
+ await source.DisposeAsync().AsTask().WaitAsync(cancellationToken);
+
+ [LoggerMessage(EventId = 1130, Level = LogLevel.Information, Message = "Microsoft cloud input {Input} polling {Kind}.")]
+ private static partial void LogPolling(ILogger logger, string input, string kind);
+}
+
+/// Test seam: an over a fake Microsoft API. Never registered in production.
+internal sealed class MicrosoftCloudHttpClient(HttpClient client)
+{
+ public HttpClient Client { get; } = client;
+}
+
+/// The source cursor table inside the queue database (BOWER_QUEUE_PATH).
+internal sealed class MicrosoftCloudCursors(string queuePath)
+{
+ public EfSourceCursorStore Store { get; } = new(queuePath);
+}
diff --git a/src/Bower.Collector/packages.lock.json b/src/Bower.Collector/packages.lock.json
index 794b37d1..18028f6b 100644
--- a/src/Bower.Collector/packages.lock.json
+++ b/src/Bower.Collector/packages.lock.json
@@ -383,6 +383,12 @@
"Bower.Abstractions": "[1.0.0, )"
}
},
+ "bower.source.microsoftcloud": {
+ "type": "Project",
+ "dependencies": {
+ "Bower.Abstractions": "[1.0.0, )"
+ }
+ },
"bower.source.syslog": {
"type": "Project"
},
diff --git a/src/Bower.Source.MicrosoftCloud/AGENTS.md b/src/Bower.Source.MicrosoftCloud/AGENTS.md
new file mode 100644
index 00000000..49d20bdf
--- /dev/null
+++ b/src/Bower.Source.MicrosoftCloud/AGENTS.md
@@ -0,0 +1,50 @@
+# Bower.Source.MicrosoftCloud instructions
+
+Pull source for Microsoft cloud admin and audit APIs that do not integrate cleanly with
+Sentinel (collector `BOWER_MICROSOFT_CONFIG`). Each input reads one API (`sourceKind`) for
+one tenant and routes to one signed pack parser. Not log shipping and not an audit archive:
+there is no collect-everything kind, no default route, and the Unified Audit Log, Entra
+sign-in and Entra audit logs are out of scope (a separate archive owns them). Record shape,
+event ids, cursor format, limits and failure codes are a contract: change them only with a
+migration note.
+
+- Default deny: a record reaches the queue only through its input's route to an active
+ signed pack parser whose match filter selects it, then redaction and policy. Readers drop
+ out-of-scope items (for example compliant devices) in memory, before any parser, and only
+ count them.
+- Request only what a record maps. Use `$select` where the API supports it. Never read
+ modified property values, change data, hardware identifiers (IMEI, serial, MAC, phone)
+ or contact details into a record; keep property names only.
+- Tokens: `IMicrosoftCloudTokenProvider`, in memory only. Send a bearer token only to the
+ one host the reader allow-lists for the kind, over HTTPS on the default port, with no user
+ info. Refuse next links and content URIs on any other host (`mscloud-host-refused`) and
+ every redirect (the handler must not follow them). Application permissions only, least
+ privilege, read-only; list every scope in `docs/security/microsoft-cloud-sources.md`.
+- Retry 429, 408 and 5xx and transport failures with capped exponential backoff and full
+ jitter, honouring `Retry-After` up to its cap. Refresh the token once on 401. Never retry a
+ 403 (`mscloud-permission-denied`); the poll loop backs off.
+- Bound everything: response bytes (16 MiB default), JSON depth 32, values to the
+ envelope limit of the field they map to (128 or 256), a per-record escaped byte budget
+ under the 32 KiB pack limit, joined lists 256, URIs 4,096, records and 100 pages per poll,
+ windows 24 hours, overlap 12 hours, look-back 7 days. Canonicalise IP addresses or leave
+ them out; never let one odd value drop the whole event.
+- Check a next link against the host allow-list before the page that returned it is
+ committed. Restart an expired page link at most once per poll and fail on a repeated
+ next link, so a poll can never spin.
+- Cursors live in the queue database's `source_cursors` table (`mscloud:`), schema 1.
+ Store a newly opened window before reading it. Move past a page only once every record
+ in it is durably enqueued or definitively dropped; commit after every page. Backpressure
+ keeps the page; never drop for backpressure. A damaged or other-kind cursor fails closed
+ (`mscloud-cursor-invalid`). A refused stored page link restarts the window from its first
+ page (`PageRestarts`). A cursor older than the API's look-back starts at the floor and
+ counts a gap; never claim otherwise.
+- Event ids: `mscloud-` and 32 hex characters of SHA-256 over input, kind, tenant, source
+ record id and record content, written as the record's first field. Overlap and crash
+ re-reads must give the same id; change the derivation only with a migration note.
+- Never log or expose record content, URLs with queries, response bodies or tokens.
+ Failure codes, counters and HTTP status only.
+- Unit tests use a fake `HttpMessageHandler`, an in-memory cursor store and a fake clock.
+ No live tenant calls. Fixtures in `tests/fixtures/microsoft-cloud` are synthetic; never
+ commit captured tenant data. Changes need malformed-response, oversized, host allow-list,
+ throttling, cursor crash/recovery, backpressure and cancellation tests.
+- Code here must stay trim and AOT safe: source-generated JSON only.
diff --git a/src/Bower.Source.MicrosoftCloud/Bower.Source.MicrosoftCloud.csproj b/src/Bower.Source.MicrosoftCloud/Bower.Source.MicrosoftCloud.csproj
new file mode 100644
index 00000000..a555cdb8
--- /dev/null
+++ b/src/Bower.Source.MicrosoftCloud/Bower.Source.MicrosoftCloud.csproj
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
diff --git a/src/Bower.Source.MicrosoftCloud/MicrosoftCloudCursor.cs b/src/Bower.Source.MicrosoftCloud/MicrosoftCloudCursor.cs
new file mode 100644
index 00000000..d791359b
--- /dev/null
+++ b/src/Bower.Source.MicrosoftCloud/MicrosoftCloudCursor.cs
@@ -0,0 +1,85 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Bower.Source.MicrosoftCloud;
+
+///
+/// Durable position of one input, stored in the queue database's source_cursors table.
+/// Window kinds keep (every record before it is durably handled) and an
+/// open window with the next page to read. Snapshot kinds keep the last completed UTC day and
+/// an open snapshot. A page link is only ever stored after every record of the page before it
+/// was durably enqueued or definitively dropped, so a crash re-reads at most one page.
+///
+/// Always 1. Any other value fails closed ().
+/// Must equal the input's kind; a changed kind fails closed.
+/// Window kinds: the exclusive upper bound of the last completed window.
+/// Window kinds: inclusive lower bound of the open window (null when none is open).
+/// Window kinds: exclusive upper bound of the open window.
+/// The next page of the open window or snapshot; null means its first page.
+/// Snapshot kinds: the last UTC day whose snapshot finished (yyyy-MM-dd).
+/// Snapshot kinds: the UTC day of the open snapshot.
+/// Snapshot kinds: when the open snapshot started; the event time of its records.
+public sealed record MicrosoftCloudCursor(
+ int SchemaVersion,
+ string SourceKind,
+ DateTimeOffset? Committed = null,
+ DateTimeOffset? WindowStart = null,
+ DateTimeOffset? WindowEnd = null,
+ string? Page = null,
+ string? CompletedDate = null,
+ string? SnapshotDate = null,
+ DateTimeOffset? SnapshotAt = null)
+{
+ public const int CurrentSchemaVersion = 1;
+
+ public string Serialize() => JsonSerializer.Serialize(this, MicrosoftCloudCursorJsonContext.Default.MicrosoftCloudCursor);
+
+ /// Null for anything that is not a valid schema 1 cursor of .
+ public static MicrosoftCloudCursor? Deserialize(string value, string kind)
+ {
+ MicrosoftCloudCursor? cursor;
+ try
+ {
+ cursor = JsonSerializer.Deserialize(value, MicrosoftCloudCursorJsonContext.Default.MicrosoftCloudCursor);
+ }
+ catch (JsonException)
+ {
+ return null;
+ }
+
+ if (cursor is null || cursor.SchemaVersion != CurrentSchemaVersion
+ || !string.Equals(cursor.SourceKind, kind, StringComparison.Ordinal)
+ || (cursor.WindowStart is null) != (cursor.WindowEnd is null)
+ || cursor.WindowStart > cursor.WindowEnd
+ || (cursor.Page is not null && cursor.WindowStart is null && cursor.SnapshotDate is null)
+ || (cursor.SnapshotDate is null) != (cursor.SnapshotAt is null)
+ || cursor.Page?.Length > MicrosoftCloudHttp.MaximumUriLength
+ || (cursor.Page is not null && !Uri.TryCreate(cursor.Page, UriKind.Absolute, out _))
+ || !IsDate(cursor.CompletedDate)
+ || !IsDate(cursor.SnapshotDate))
+ {
+ return null;
+ }
+
+ // Window kinds carry window fields only, snapshot kinds snapshot fields only.
+ bool snapshotKind = string.Equals(kind, MicrosoftCloudKinds.IntuneDeviceCompliance, StringComparison.Ordinal);
+ bool windowFields = cursor.Committed is not null || cursor.WindowStart is not null;
+ bool snapshotFields = cursor.CompletedDate is not null || cursor.SnapshotDate is not null;
+ if (snapshotKind ? windowFields : snapshotFields)
+ {
+ return null;
+ }
+
+ return cursor;
+ }
+
+ private static bool IsDate(string? value) =>
+ value is null || DateOnly.TryParseExact(value, "yyyy'-'MM'-'dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out _);
+}
+
+[JsonSourceGenerationOptions(
+ PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
+ UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow)]
+[JsonSerializable(typeof(MicrosoftCloudCursor))]
+internal sealed partial class MicrosoftCloudCursorJsonContext : JsonSerializerContext;
diff --git a/src/Bower.Source.MicrosoftCloud/MicrosoftCloudHttp.cs b/src/Bower.Source.MicrosoftCloud/MicrosoftCloudHttp.cs
new file mode 100644
index 00000000..544bf916
--- /dev/null
+++ b/src/Bower.Source.MicrosoftCloud/MicrosoftCloudHttp.cs
@@ -0,0 +1,334 @@
+using System.Globalization;
+using System.Net;
+using System.Net.Http.Headers;
+using System.Text.Json;
+
+namespace Bower.Source.MicrosoftCloud;
+
+///
+/// Access tokens for one input. Implementations keep tokens in memory only and never log
+/// them. is set once after a 401.
+///
+public interface IMicrosoftCloudTokenProvider
+{
+ ValueTask GetTokenAsync(
+ MicrosoftCloudInputOptions input,
+ string scope,
+ bool forceRefresh,
+ CancellationToken cancellationToken);
+}
+
+/// Stable, metadata-only failure codes. Never carry a body, URL query or token.
+public static class MicrosoftCloudFailures
+{
+ /// 403: the app registration lacks the permission or admin consent.
+ public const string PermissionDenied = "mscloud-permission-denied";
+
+ /// 401 after one token refresh, or the token could not be acquired.
+ public const string Unauthorised = "mscloud-unauthorised";
+
+ /// 429 or 5xx after every retry.
+ public const string Throttled = "mscloud-throttled";
+ public const string Unavailable = "mscloud-unavailable";
+
+ /// Another 4xx (bad filter, expired page link, missing subscription).
+ public const string RequestRefused = "mscloud-request-refused";
+
+ /// A next link or content URI is not HTTPS on the host allow-listed for the input's kind.
+ public const string HostRefused = "mscloud-host-refused";
+ public const string RedirectRefused = "mscloud-redirect-refused";
+ public const string ResponseTooLarge = "mscloud-response-too-large";
+ public const string ResponseInvalid = "mscloud-response-invalid";
+ public const string CursorInvalid = "mscloud-cursor-invalid";
+ public const string CursorConflict = "mscloud-cursor-conflict";
+ public const string SourceFailed = "mscloud-source-failed";
+}
+
+public sealed class MicrosoftCloudException(string code, HttpStatusCode? status = null, Exception? innerException = null)
+ : Exception(status is null ? code : $"{code} (HTTP {(int)status})", innerException)
+{
+ public string Code { get; } = code;
+
+ public HttpStatusCode? Status { get; } = status;
+}
+
+/// One response: the parsed JSON body and the headers callers may page with.
+public sealed class MicrosoftCloudResponse(JsonDocument document, string? nextPageUri) : IDisposable
+{
+ public JsonDocument Document { get; } = document;
+
+ /// The Office 365 Management Activity API's NextPageUri header, if any.
+ public string? NextPageUri { get; } = nextPageUri;
+
+ public void Dispose() => Document.Dispose();
+}
+
+/// Retry counters for status. Metadata only.
+internal sealed class MicrosoftCloudRetryCounters
+{
+ public long Retries;
+ public long Throttled;
+}
+
+///
+/// Bounded HTTPS client for Microsoft cloud APIs. A bearer token is only ever sent to the
+/// one host the caller allow-lists, over HTTPS on the default port; redirects are refused
+/// (the handler must not follow them). Responses are capped in size and JSON depth.
+/// 429, 5xx and transport failures are retried with exponential backoff and full jitter,
+/// honouring Retry-After. A 401 refreshes the token once. A 403 is never retried.
+///
+public sealed class MicrosoftCloudHttp(
+ HttpClient client,
+ IMicrosoftCloudTokenProvider tokens,
+ TimeProvider clock,
+ Func? jitter = null)
+{
+ public const int DefaultMaximumResponseBytes = 16 * 1024 * 1024;
+ public const int MaximumUriLength = 4_096;
+
+ private readonly Func jitter = jitter ?? Random.Shared.NextDouble;
+
+ public int MaximumAttempts { get; init; } = 6;
+
+ public TimeSpan BaseDelay { get; init; } = TimeSpan.FromSeconds(1);
+
+ public TimeSpan MaximumDelay { get; init; } = TimeSpan.FromSeconds(60);
+
+ /// Longest Retry-After honoured; a longer one fails the poll, which backs off itself.
+ public TimeSpan MaximumRetryAfter { get; init; } = TimeSpan.FromMinutes(5);
+
+ public int MaximumResponseBytes { get; init; } = DefaultMaximumResponseBytes;
+
+ private readonly System.Collections.Concurrent.ConcurrentDictionary counters =
+ new(StringComparer.Ordinal);
+
+ /// Retry and throttle counts for one input (inputs share this client).
+ internal MicrosoftCloudRetryCounters Counters(string inputId) => counters.GetOrAdd(inputId, static _ => new());
+
+ /// True when is HTTPS on at the default port.
+ public static bool IsAllowed(Uri uri, string host) =>
+ uri.IsAbsoluteUri
+ && string.Equals(uri.Scheme, Uri.UriSchemeHttps, StringComparison.Ordinal)
+ && uri.IsDefaultPort
+ && string.IsNullOrEmpty(uri.UserInfo)
+ && string.Equals(uri.IdnHost, host, StringComparison.OrdinalIgnoreCase)
+ && uri.OriginalString.Length <= MaximumUriLength;
+
+ public async Task SendAsync(
+ HttpMethod method,
+ Uri uri,
+ MicrosoftCloudInputOptions input,
+ string scope,
+ string allowedHost,
+ CancellationToken cancellationToken)
+ {
+ if (!IsAllowed(uri, allowedHost))
+ {
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.HostRefused);
+ }
+
+ MicrosoftCloudRetryCounters inputCounters = Counters(input.Id);
+ bool refreshed = false;
+ bool forceRefresh = false;
+ for (int attempt = 1; ; attempt++)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ string token;
+ try
+ {
+ token = await tokens.GetTokenAsync(input, scope, forceRefresh, cancellationToken);
+ // Refresh exactly once after a 401, never on the retries that follow it.
+ forceRefresh = false;
+ }
+ catch (Exception exception) when (exception is not OperationCanceledException)
+ {
+ // The credential's own message can name files or claims; report the code only.
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.Unauthorised, innerException: null);
+ }
+
+ using HttpRequestMessage request = new(method, uri);
+ request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
+ request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+ if (method == HttpMethod.Post)
+ {
+ request.Content = new ByteArrayContent([]);
+ }
+
+ HttpResponseMessage response;
+ try
+ {
+ response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
+ }
+ catch (Exception exception) when (IsTransport(exception, cancellationToken))
+ {
+ await RetryTransportAsync(attempt, inputCounters, cancellationToken);
+ continue;
+ }
+
+ using (response)
+ {
+ HttpStatusCode status = response.StatusCode;
+ if (status == HttpStatusCode.Unauthorized && !refreshed)
+ {
+ refreshed = true;
+ forceRefresh = true;
+ continue;
+ }
+
+ if (status == HttpStatusCode.Unauthorized)
+ {
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.Unauthorised, status);
+ }
+
+ if (status == HttpStatusCode.Forbidden)
+ {
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.PermissionDenied, status);
+ }
+
+ if ((int)status is >= 300 and < 400)
+ {
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.RedirectRefused, status);
+ }
+
+ bool throttled = status == HttpStatusCode.TooManyRequests;
+ if (throttled || IsTransient(status))
+ {
+ if (throttled)
+ {
+ Interlocked.Increment(ref inputCounters.Throttled);
+ }
+
+ TimeSpan? retryAfter = RetryAfter(response.Headers.RetryAfter);
+ if (attempt >= MaximumAttempts || retryAfter > MaximumRetryAfter)
+ {
+ throw new MicrosoftCloudException(
+ throttled ? MicrosoftCloudFailures.Throttled : MicrosoftCloudFailures.Unavailable, status);
+ }
+
+ Interlocked.Increment(ref inputCounters.Retries);
+ // A zero or past Retry-After falls back to jittered backoff, never a burst.
+ await WaitAsync(retryAfter is { } after && after > TimeSpan.Zero ? after : Backoff(attempt), cancellationToken);
+ continue;
+ }
+
+ if (!response.IsSuccessStatusCode)
+ {
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.RequestRefused, status);
+ }
+
+ string? nextPage = response.Headers.TryGetValues("NextPageUri", out IEnumerable? values)
+ ? values.FirstOrDefault()
+ : null;
+ JsonDocument document;
+ try
+ {
+ // Headers arrived; the body can still fail in transit. Retry that the same way.
+ document = await ReadJsonAsync(response, cancellationToken);
+ }
+ catch (Exception exception) when (IsTransport(exception, cancellationToken))
+ {
+ await RetryTransportAsync(attempt, inputCounters, cancellationToken);
+ continue;
+ }
+
+ return new MicrosoftCloudResponse(document, nextPage);
+ }
+ }
+ }
+
+ private static bool IsTransport(Exception exception, CancellationToken cancellationToken) =>
+ exception is HttpRequestException or IOException
+ || (exception is TaskCanceledException && !cancellationToken.IsCancellationRequested);
+
+ private async Task RetryTransportAsync(int attempt, MicrosoftCloudRetryCounters inputCounters, CancellationToken cancellationToken)
+ {
+ if (attempt >= MaximumAttempts)
+ {
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.Unavailable);
+ }
+
+ Interlocked.Increment(ref inputCounters.Retries);
+ await WaitAsync(Backoff(attempt), cancellationToken);
+ }
+
+ private static bool IsTransient(HttpStatusCode status) =>
+ status is HttpStatusCode.InternalServerError or HttpStatusCode.BadGateway
+ or HttpStatusCode.ServiceUnavailable or HttpStatusCode.GatewayTimeout or HttpStatusCode.RequestTimeout;
+
+ private TimeSpan? RetryAfter(RetryConditionHeaderValue? header)
+ {
+ if (header?.Delta is { } delta)
+ {
+ return delta < TimeSpan.Zero ? TimeSpan.Zero : delta;
+ }
+
+ if (header?.Date is { } date)
+ {
+ TimeSpan wait = date - clock.GetUtcNow();
+ return wait < TimeSpan.Zero ? TimeSpan.Zero : wait;
+ }
+
+ return null;
+ }
+
+ /// Full jitter: a uniform wait between zero and the capped exponential delay.
+ internal TimeSpan Backoff(int attempt)
+ {
+ double ceiling = Math.Min(MaximumDelay.Ticks, BaseDelay.Ticks * Math.Pow(2, Math.Min(attempt - 1, 16)));
+ return TimeSpan.FromTicks((long)(ceiling * Math.Clamp(jitter(), 0, 1)));
+ }
+
+ private Task WaitAsync(TimeSpan wait, CancellationToken cancellationToken) =>
+ wait <= TimeSpan.Zero ? Task.CompletedTask : Task.Delay(wait, clock, cancellationToken);
+
+ private async Task ReadJsonAsync(HttpResponseMessage response, CancellationToken cancellationToken)
+ {
+ if (response.Content.Headers.ContentLength > MaximumResponseBytes)
+ {
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.ResponseTooLarge, response.StatusCode);
+ }
+
+ await using Stream stream = await response.Content.ReadAsStreamAsync(cancellationToken);
+ using MemoryStream buffer = new();
+ byte[] chunk = new byte[81_920];
+ int read;
+ while (true)
+ {
+ try
+ {
+ read = await stream.ReadAsync(chunk, cancellationToken);
+ }
+ catch (InvalidDataException)
+ {
+ // Corrupt gzip or deflate content.
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.ResponseInvalid, response.StatusCode);
+ }
+
+ if (read == 0)
+ {
+ break;
+ }
+
+ if (buffer.Length + read > MaximumResponseBytes)
+ {
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.ResponseTooLarge, response.StatusCode);
+ }
+
+ buffer.Write(chunk, 0, read);
+ }
+
+ try
+ {
+ return JsonDocument.Parse(buffer.GetBuffer().AsMemory(0, (int)buffer.Length), new JsonDocumentOptions { MaxDepth = 32 });
+ }
+ catch (JsonException)
+ {
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.ResponseInvalid, response.StatusCode);
+ }
+ }
+
+ internal static string Escape(string value) => Uri.EscapeDataString(value);
+
+ internal static string Time(DateTimeOffset value) =>
+ value.UtcDateTime.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture);
+}
diff --git a/src/Bower.Source.MicrosoftCloud/MicrosoftCloudReaders.cs b/src/Bower.Source.MicrosoftCloud/MicrosoftCloudReaders.cs
new file mode 100644
index 00000000..7c8ca3a4
--- /dev/null
+++ b/src/Bower.Source.MicrosoftCloud/MicrosoftCloudReaders.cs
@@ -0,0 +1,231 @@
+using System.Text.Json;
+
+namespace Bower.Source.MicrosoftCloud;
+
+/// The span one read covers: a time window, or one UTC day's snapshot.
+/// Window kinds: inclusive lower bound.
+/// Window kinds: exclusive upper bound. Snapshot kinds: when the snapshot started.
+/// Snapshot kinds: the UTC day (yyyy-MM-dd).
+internal sealed record MicrosoftCloudSpan(DateTimeOffset Start, DateTimeOffset End, string? SnapshotDate = null);
+
+/// One page: finished records (each with its event id), the next page and how many items were out of scope.
+/// Items the source kind never turns into records (for example compliant devices): dropped in memory, before any parser.
+internal sealed record MicrosoftCloudPage(IReadOnlyList Records, string? Next, int Items, int OutOfScope);
+
+///
+/// One source kind: the API it reads, the one host its token may be sent to, and how an API
+/// item becomes a bounded record. Readers only ever request the fields they map.
+///
+internal abstract class MicrosoftCloudReader
+{
+ /// Microsoft documents a seven day window for most audit APIs; never read further back.
+ public virtual TimeSpan MaximumLookback => TimeSpan.FromDays(7);
+
+ /// Longest window read before the cursor commits its upper bound.
+ public virtual TimeSpan MaximumWindow => TimeSpan.FromHours(24);
+
+ /// Snapshot kinds read the full set once per UTC day instead of a time window.
+ public virtual bool IsSnapshot => false;
+
+ public abstract string Scope(MicrosoftCloudInputOptions input);
+
+ public abstract string Host(MicrosoftCloudInputOptions input);
+
+ public abstract Uri FirstPage(MicrosoftCloudInputOptions input, MicrosoftCloudSpan span);
+
+ public abstract MicrosoftCloudPage Read(MicrosoftCloudInputOptions input, MicrosoftCloudSpan span, MicrosoftCloudResponse response);
+
+ ///
+ /// A next link is stored in the cursor and followed with a bearer token, so it must pass
+ /// the same host check as a request before the page that returned it is committed.
+ ///
+ internal MicrosoftCloudPage Checked(MicrosoftCloudInputOptions input, MicrosoftCloudPage page)
+ {
+ if (page.Next is { } next
+ && (!Uri.TryCreate(next, UriKind.Absolute, out Uri? uri) || !MicrosoftCloudHttp.IsAllowed(uri, Host(input))))
+ {
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.HostRefused);
+ }
+
+ return page;
+ }
+
+ public virtual async Task ReadPageAsync(
+ MicrosoftCloudHttp http,
+ MicrosoftCloudInputOptions input,
+ MicrosoftCloudSpan span,
+ string? page,
+ CancellationToken cancellationToken)
+ {
+ Uri uri = page is null ? FirstPage(input, span) : new Uri(page, UriKind.Absolute);
+ using MicrosoftCloudResponse response = await http.SendAsync(
+ HttpMethod.Get, uri, input, Scope(input), Host(input), cancellationToken);
+ return Checked(input, Read(input, span, response));
+ }
+
+ public static MicrosoftCloudReader For(string kind) => kind switch
+ {
+ MicrosoftCloudKinds.IntuneAudit => new IntuneAuditReader(),
+ MicrosoftCloudKinds.IntuneDeviceCompliance => new IntuneComplianceReader(),
+ _ => throw new InvalidDataException("Unsupported Microsoft cloud source kind.")
+ };
+
+ /// The value array of an OData collection and its @odata.nextLink.
+ protected static (IReadOnlyList Items, string? Next) ODataPage(MicrosoftCloudResponse response)
+ {
+ JsonElement root = response.Document.RootElement;
+ if (root.ValueKind != JsonValueKind.Object
+ || !root.TryGetProperty("value", out JsonElement value)
+ || value.ValueKind != JsonValueKind.Array)
+ {
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.ResponseInvalid);
+ }
+
+ string? next = null;
+ if (root.TryGetProperty("@odata.nextLink", out JsonElement link))
+ {
+ next = link.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(link.GetString())
+ ? link.GetString()
+ : throw new MicrosoftCloudException(MicrosoftCloudFailures.ResponseInvalid);
+ if (!Uri.TryCreate(next, UriKind.Absolute, out _))
+ {
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.ResponseInvalid);
+ }
+ }
+
+ return ([.. value.EnumerateArray()], next);
+ }
+}
+
+internal abstract class GraphReader : MicrosoftCloudReader
+{
+ public const string GraphHost = "graph.microsoft.com";
+
+ public override string Scope(MicrosoftCloudInputOptions input) => "https://graph.microsoft.com/.default";
+
+ public override string Host(MicrosoftCloudInputOptions input) => GraphHost;
+}
+
+///
+/// GET /v1.0/deviceManagement/auditEvents, filtered to the window on
+/// activityDateTime. Least privileged application permission:
+/// DeviceManagementApps.Read.All. Modified property values are never read: they can
+/// carry configuration secrets and personal data. Only their names are kept.
+///
+internal sealed class IntuneAuditReader : GraphReader
+{
+ /// Envelope limits: actions and target types hold 128 characters, labels and identities 256.
+ internal const int Action = 128;
+ internal const int Label = 256;
+
+ public override Uri FirstPage(MicrosoftCloudInputOptions input, MicrosoftCloudSpan span)
+ {
+ string filter = $"activityDateTime ge {MicrosoftCloudHttp.Time(span.Start)} and activityDateTime lt {MicrosoftCloudHttp.Time(span.End)}";
+ return new Uri($"https://{GraphHost}/v1.0/deviceManagement/auditEvents?$filter={MicrosoftCloudHttp.Escape(filter)}");
+ }
+
+ public override MicrosoftCloudPage Read(MicrosoftCloudInputOptions input, MicrosoftCloudSpan span, MicrosoftCloudResponse response)
+ {
+ (IReadOnlyList items, string? next) = ODataPage(response);
+ List records = new(items.Count);
+ int outOfScope = 0;
+ foreach (JsonElement item in items)
+ {
+ string? id = MicrosoftCloudRecord.String(item, "id");
+ string? time = MicrosoftCloudRecord.Time(MicrosoftCloudRecord.String(item, "activityDateTime"));
+ if (id is null || time is null)
+ {
+ outOfScope++;
+ continue;
+ }
+
+ JsonElement actor = MicrosoftCloudRecord.Object(item, "actor");
+ JsonElement[] resources = [.. MicrosoftCloudRecord.Array(item, "resources").Where(resource => resource.ValueKind == JsonValueKind.Object)];
+ JsonElement resource = resources.Length > 0 ? resources[0] : default;
+ records.Add(new MicrosoftCloudRecord(input)
+ .Add("auditEventId", id, Label)
+ .Add("activityDateTime", time)
+ .Add("activity", MicrosoftCloudRecord.String(item, "activity"), Action)
+ .Add("activityType", MicrosoftCloudRecord.String(item, "activityType"), Action)
+ .Add("activityOperationType", MicrosoftCloudRecord.String(item, "activityOperationType"), Label)
+ .Add("activityResult", MicrosoftCloudRecord.String(item, "activityResult"), Label)
+ .Add("category", MicrosoftCloudRecord.String(item, "category"), Label)
+ .Add("componentName", MicrosoftCloudRecord.String(item, "componentName"), Label)
+ .Add("correlationId", MicrosoftCloudRecord.String(item, "correlationId"), Label)
+ .Add("actorType", MicrosoftCloudRecord.String(actor, "auditActorType") ?? MicrosoftCloudRecord.String(actor, "type"), Label)
+ .Add("actorUserPrincipalName", MicrosoftCloudRecord.String(actor, "userPrincipalName"), Label)
+ .Add("actorUserId", MicrosoftCloudRecord.String(actor, "userId"), Label)
+ .Add("actorApplicationId", MicrosoftCloudRecord.String(actor, "applicationId"), Label)
+ .Add("actorApplicationName", MicrosoftCloudRecord.String(actor, "applicationDisplayName"), Label)
+ .Add("actorServicePrincipalName", MicrosoftCloudRecord.String(actor, "servicePrincipalName"), Label)
+ .Add("actorIpAddress", MicrosoftCloudRecord.Address(MicrosoftCloudRecord.String(actor, "ipAddress")))
+ .Add("resourceType", MicrosoftCloudRecord.String(resource, "auditResourceType") ?? MicrosoftCloudRecord.String(resource, "type"), Action)
+ .Add("resourceId", MicrosoftCloudRecord.String(resource, "resourceId"), Label)
+ .Add("resourceName", MicrosoftCloudRecord.String(resource, "displayName"), Label)
+ .Add("resourceCount", resources.Length == 0 ? null : resources.Length.ToString(System.Globalization.CultureInfo.InvariantCulture))
+ .Add("modifiedProperties", MicrosoftCloudRecord.Join(resources
+ .SelectMany(item => MicrosoftCloudRecord.Array(item, "modifiedProperties"))
+ .Select(property => MicrosoftCloudRecord.String(property, "displayName"))))
+ .Build(id));
+ }
+
+ return new MicrosoftCloudPage(records, next, items.Count, outOfScope);
+ }
+}
+
+///
+/// Once per UTC day, GET /v1.0/deviceManagement/managedDevices with $select
+/// limited to compliance fields. Least privileged application permission:
+/// DeviceManagementManagedDevices.Read.All. Device name, IMEI, serial number, phone
+/// number, MAC addresses, email address and hardware inventory are never requested. Devices whose state
+/// is not in the input's complianceStates are dropped in memory.
+///
+internal sealed class IntuneComplianceReader : GraphReader
+{
+ internal const string Select =
+ "id,complianceState,operatingSystem,osVersion,lastSyncDateTime,userPrincipalName,userId,"
+ + "azureADDeviceId,managedDeviceOwnerType,isEncrypted,jailBroken,complianceGracePeriodExpirationDateTime";
+
+ public override bool IsSnapshot => true;
+
+ public override Uri FirstPage(MicrosoftCloudInputOptions input, MicrosoftCloudSpan span) =>
+ new($"https://{GraphHost}/v1.0/deviceManagement/managedDevices?$select={Select}");
+
+ public override MicrosoftCloudPage Read(MicrosoftCloudInputOptions input, MicrosoftCloudSpan span, MicrosoftCloudResponse response)
+ {
+ (IReadOnlyList items, string? next) = ODataPage(response);
+ HashSet states = new(MicrosoftCloudSourceConfigurationLoader.ComplianceStates(input), StringComparer.Ordinal);
+ string snapshotAt = MicrosoftCloudSourceConfigurationLoader.Format(span.End);
+ List records = [];
+ int outOfScope = 0;
+ foreach (JsonElement item in items)
+ {
+ string? id = MicrosoftCloudRecord.String(item, "id");
+ string? state = MicrosoftCloudRecord.String(item, "complianceState");
+ if (id is null || state is null || !states.Contains(state))
+ {
+ outOfScope++;
+ continue;
+ }
+
+ records.Add(new MicrosoftCloudRecord(input)
+ .Add("snapshotDate", span.SnapshotDate)
+ .Add("snapshotAt", snapshotAt)
+ .Add("deviceId", id, IntuneAuditReader.Label)
+ .Add("complianceState", state, IntuneAuditReader.Label)
+ .Add("operatingSystem", MicrosoftCloudRecord.String(item, "operatingSystem"), IntuneAuditReader.Label)
+ .Add("osVersion", MicrosoftCloudRecord.String(item, "osVersion"), IntuneAuditReader.Label)
+ .Add("lastSyncDateTime", MicrosoftCloudRecord.Time(MicrosoftCloudRecord.String(item, "lastSyncDateTime")))
+ .Add("userPrincipalName", MicrosoftCloudRecord.String(item, "userPrincipalName"), IntuneAuditReader.Label)
+ .Add("userId", MicrosoftCloudRecord.String(item, "userId"), IntuneAuditReader.Label)
+ .Add("azureADDeviceId", MicrosoftCloudRecord.String(item, "azureADDeviceId"), IntuneAuditReader.Label)
+ .Add("ownerType", MicrosoftCloudRecord.String(item, "managedDeviceOwnerType"), IntuneAuditReader.Label)
+ .Add("isEncrypted", MicrosoftCloudRecord.String(item, "isEncrypted"), IntuneAuditReader.Label)
+ .Add("jailBroken", MicrosoftCloudRecord.String(item, "jailBroken"), IntuneAuditReader.Label)
+ .Add("gracePeriodExpires", MicrosoftCloudRecord.Time(MicrosoftCloudRecord.String(item, "complianceGracePeriodExpirationDateTime")))
+ .Build(id + "\u001f" + span.SnapshotDate));
+ }
+
+ return new MicrosoftCloudPage(records, next, items.Count, outOfScope);
+ }
+}
diff --git a/src/Bower.Source.MicrosoftCloud/MicrosoftCloudRecord.cs b/src/Bower.Source.MicrosoftCloud/MicrosoftCloudRecord.cs
new file mode 100644
index 00000000..eeb45f28
--- /dev/null
+++ b/src/Bower.Source.MicrosoftCloud/MicrosoftCloudRecord.cs
@@ -0,0 +1,230 @@
+using System.Buffers;
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+
+namespace Bower.Source.MicrosoftCloud;
+
+///
+/// Builds the flat JSON record a signed pack parser reads (PackRuntime): string values
+/// only, bounded lengths, id first so the collector recognises the Bower-computed id.
+/// The record lives in memory for one submission; it is never logged or persisted, and only
+/// the fields the pack parser maps can reach the envelope, after redaction.
+///
+internal sealed class MicrosoftCloudRecord(MicrosoftCloudInputOptions input)
+{
+ /// Longest value written; a pack parser refuses longer mapped values.
+ public const int MaximumValueLength = 1_024;
+
+ private readonly List> fields = [];
+
+ ///
+ /// The envelope limit of the field this value maps to (for example 128 for an action or
+ /// target type, 256 for labels and identities), so a long value is clipped here rather
+ /// than refused by the pack parser.
+ ///
+ public MicrosoftCloudRecord Add(string name, string? value, int maximumLength = MaximumValueLength)
+ {
+ if (!string.IsNullOrWhiteSpace(value) && budget > 0)
+ {
+ string clipped = Clip(value.Trim(), Math.Min(Math.Min(maximumLength, MaximumValueLength), budget / 6));
+ if (clipped.Length > 0)
+ {
+ budget -= clipped.Length * 6;
+ fields.Add(new KeyValuePair(name, clipped));
+ }
+ }
+
+ return this;
+ }
+
+ ///
+ /// An IP address in canonical form, or null. Strips an IPv4 :port and brackets, so
+ /// an unusual address never makes the pack parser refuse the whole event.
+ ///
+ public static string? Address(string? value)
+ {
+ if (string.IsNullOrWhiteSpace(value) || value.Length > 64)
+ {
+ return null;
+ }
+
+ string text = value.Trim();
+ if (text.StartsWith('['))
+ {
+ // [IPv6] or [IPv6]:port.
+ int close = text.IndexOf(']', StringComparison.Ordinal);
+ if (close < 0 || (close != text.Length - 1 && !IsPort(text.AsSpan(close + 1))))
+ {
+ return null;
+ }
+
+ text = text[1..close];
+ }
+ else if (text.Count(character => character == ':') == 1)
+ {
+ // IPv4:port. A bare IPv6 address always has two or more colons.
+ int colon = text.IndexOf(':', StringComparison.Ordinal);
+ if (!IsPort(text.AsSpan(colon)))
+ {
+ return null;
+ }
+
+ text = text[..colon];
+ }
+
+ if (text.Contains('%', StringComparison.Ordinal)
+ || !System.Net.IPAddress.TryParse(text, out System.Net.IPAddress? address))
+ {
+ return null;
+ }
+
+ string canonical = address.ToString();
+ // IPv4 must already be in canonical dotted form (no leading zeros, no short forms),
+ // which is exactly what the pack runtime accepts.
+ return address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && canonical != text
+ ? null
+ : canonical;
+
+ static bool IsPort(ReadOnlySpan suffix) =>
+ suffix.Length is >= 2 and <= 6 && suffix[0] == ':'
+ && int.TryParse(suffix[1..], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int port)
+ && port is >= 1 and <= 65_535;
+ }
+
+ ///
+ /// The record with its event id: mscloud- and 32 hex characters of SHA-256 over the
+ /// input, the source record id and the record content. Re-reading an unchanged record (window
+ /// overlap, a re-read page after a crash) gives the same id, so the queue deduplicates it; a
+ /// record whose content changed is a new event rather than an identity conflict.
+ ///
+ public string Build(string sourceRecordId)
+ {
+ string content = Write(null);
+ string material = string.Join(
+ '\u001f',
+ "bower-mscloud-v1",
+ input.Id,
+ input.SourceKind,
+ input.TenantId,
+ sourceRecordId,
+ content);
+ string id = "mscloud-" + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(material)))[..32];
+ return Write(id);
+ }
+
+ ///
+ /// Escaped bytes all values of one record may use. JSON escaping is at most 6 bytes per
+ /// UTF-16 unit, so values are clipped against this budget as they are added and a record
+ /// always stays below the pack parser's 32 KiB limit. Clipping depends only on the input,
+ /// so a re-read gives the same record and the same event id.
+ ///
+ public const int MaximumValueBytes = 28_672;
+
+ private int budget = MaximumValueBytes;
+
+ private string Write(string? id)
+ {
+ ArrayBufferWriter buffer = new();
+ using (Utf8JsonWriter writer = new(buffer))
+ {
+ writer.WriteStartObject();
+ if (id is not null)
+ {
+ writer.WriteString("id", id);
+ }
+
+ writer.WriteString("input", input.Id);
+ writer.WriteString("sourceKind", input.SourceKind);
+ writer.WriteString("tenantId", input.TenantId);
+ foreach (KeyValuePair field in fields)
+ {
+ writer.WriteString(field.Key, field.Value);
+ }
+
+ writer.WriteEndObject();
+ }
+
+ return Encoding.UTF8.GetString(buffer.WrittenSpan);
+ }
+
+ public static string? String(JsonElement item, string name) =>
+ item.ValueKind == JsonValueKind.Object && item.TryGetProperty(name, out JsonElement value)
+ ? value.ValueKind switch
+ {
+ JsonValueKind.String => value.GetString(),
+ JsonValueKind.Number => value.GetRawText(),
+ JsonValueKind.True => "true",
+ JsonValueKind.False => "false",
+ _ => null
+ }
+ : null;
+
+ public static JsonElement Object(JsonElement item, string name) =>
+ item.ValueKind == JsonValueKind.Object && item.TryGetProperty(name, out JsonElement value)
+ && value.ValueKind == JsonValueKind.Object
+ ? value
+ : default;
+
+ public static IEnumerable Array(JsonElement item, string name) =>
+ item.ValueKind == JsonValueKind.Object && item.TryGetProperty(name, out JsonElement value)
+ && value.ValueKind == JsonValueKind.Array
+ ? value.EnumerateArray()
+ : [];
+
+ /// Canonical UTC text, or null for a missing or unparseable time.
+ public static string? Time(string? value) =>
+ value is not null && DateTimeOffset.TryParse(
+ value,
+ CultureInfo.InvariantCulture,
+ DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
+ out DateTimeOffset parsed)
+ ? MicrosoftCloudSourceConfigurationLoader.Format(parsed)
+ : null;
+
+ /// Comma-joined distinct values, cut at a whole value so the result never exceeds the cap (envelope labels hold 256 characters).
+ public static string? Join(IEnumerable values, int maximumLength = 256)
+ {
+ StringBuilder builder = new();
+ HashSet seen = new(StringComparer.Ordinal);
+ foreach (string? value in values)
+ {
+ if (string.IsNullOrWhiteSpace(value) || value.Contains(',') || !seen.Add(value))
+ {
+ continue;
+ }
+
+ int length = builder.Length + (builder.Length == 0 ? 0 : 1) + value.Length;
+ if (length > maximumLength)
+ {
+ break;
+ }
+
+ builder.Append(builder.Length == 0 ? string.Empty : ",").Append(value);
+ }
+
+ return builder.Length == 0 ? null : builder.ToString();
+ }
+
+ internal static string Clip(string value, int maximumLength)
+ {
+ if (value.Length <= maximumLength)
+ {
+ return value;
+ }
+
+ if (maximumLength <= 0)
+ {
+ return string.Empty;
+ }
+
+ int end = maximumLength;
+ if (char.IsHighSurrogate(value[end - 1]))
+ {
+ end--;
+ }
+
+ return value[..end];
+ }
+}
diff --git a/src/Bower.Source.MicrosoftCloud/MicrosoftCloudSource.cs b/src/Bower.Source.MicrosoftCloud/MicrosoftCloudSource.cs
new file mode 100644
index 00000000..94cea6c4
--- /dev/null
+++ b/src/Bower.Source.MicrosoftCloud/MicrosoftCloudSource.cs
@@ -0,0 +1,568 @@
+using Bower.Abstractions;
+
+namespace Bower.Source.MicrosoftCloud;
+
+/// What happened to one record handed to the collector.
+public enum MicrosoftCloudSubmitOutcome
+{
+ /// Durably enqueued. Only then can the cursor move past the page.
+ Queued,
+ Duplicate,
+ Suppressed,
+
+ /// The pack parser's filter did not select the record: counted and dropped.
+ NotSelected,
+
+ /// Policy rejected or quarantined the event.
+ Rejected,
+
+ /// The record does not satisfy the pack parser's field types.
+ Invalid,
+ TooLarge,
+
+ /// Queue at capacity or ingest gated: stop and read the same page again later.
+ Unavailable
+}
+
+/// Collector side of the source: pack parser, redaction, policy and durable enqueue.
+public interface IMicrosoftCloudSink
+{
+ ValueTask SubmitAsync(
+ MicrosoftCloudInputOptions input,
+ string record,
+ CancellationToken cancellationToken);
+}
+
+/// Per-input counters since start. Metadata only: no record content, URL or token, ever.
+/// starting, running, idle (caught up), backpressure, stopped or a failure code.
+/// Window kinds: every record before this time is durably handled.
+/// Snapshot kinds: the last UTC day whose snapshot finished.
+/// API items the kind never turns into records (for example compliant devices): dropped in memory.
+/// Windows that had to start later than the cursor because the API keeps no older data.
+/// Stored page links the API refused (expired); the window was read again from its first page.
+public sealed record MicrosoftCloudInputStatus(
+ string Id,
+ string SourceKind,
+ string State,
+ DateTimeOffset? Committed,
+ string? CompletedDate,
+ long Pages,
+ long Items,
+ long Queued,
+ long Duplicates,
+ long Suppressed,
+ long NotSelected,
+ long Rejected,
+ long ParserErrors,
+ long TooLarge,
+ long OutOfScope,
+ long Backpressure,
+ long Gaps,
+ long PageRestarts,
+ long Retries,
+ long Throttled,
+ long Failures,
+ DateTimeOffset? LastPollAt,
+ DateTimeOffset? LastRecordAt);
+
+/// Records handed to the sink.
+/// The queue could not take a record; the page is read again next time.
+/// A limit stopped the poll or a backlog remains; poll again without waiting.
+public sealed record MicrosoftCloudPollResult(int Records, bool Backpressure, bool More);
+
+///
+/// Pull source for Microsoft cloud admin and audit APIs (Intune and, later, Power Platform
+/// and Entra provisioning). Each input reads one API for one tenant, and every record goes
+/// through its route's signed pack parser, then redaction, policy and the durable queue.
+/// This is not a log shipper: there is no collect-everything form and no default route.
+///
+/// The cursor moves past a page only once every record in it is durably enqueued or
+/// definitively dropped, and is committed after each page. A full queue stops the poll and
+/// keeps the page; nothing is dropped for backpressure. A crash between enqueue and commit
+/// re-reads that page; deterministic event ids make the queue drop the copies as duplicates.
+/// Windows trail now by a settle delay and start an overlap before the committed bound, so
+/// late-arriving records are read; the overlap's re-reads deduplicate the same way.
+///
+///
+public sealed class MicrosoftCloudSource : IAsyncDisposable
+{
+ private readonly MicrosoftCloudSourceConfiguration configuration;
+ private readonly IMicrosoftCloudSink sink;
+ private readonly ISourceCursorStore cursors;
+ private readonly MicrosoftCloudHttp http;
+ private readonly TimeProvider clock;
+ private readonly Dictionary inputs;
+ private readonly CancellationTokenSource stopping = new();
+ private readonly List running = [];
+ private int started;
+ private int disposed;
+
+ public MicrosoftCloudSource(
+ MicrosoftCloudSourceConfiguration configuration,
+ IMicrosoftCloudSink sink,
+ ISourceCursorStore cursors,
+ MicrosoftCloudHttp http,
+ TimeProvider? clock = null)
+ {
+ ArgumentNullException.ThrowIfNull(configuration);
+ ArgumentNullException.ThrowIfNull(sink);
+ ArgumentNullException.ThrowIfNull(cursors);
+ ArgumentNullException.ThrowIfNull(http);
+ this.configuration = configuration;
+ this.sink = sink;
+ this.cursors = cursors;
+ this.http = http;
+ this.clock = clock ?? TimeProvider.System;
+ inputs = configuration.Inputs.ToDictionary(
+ input => input.Id,
+ input => new Input(input, MicrosoftCloudReader.For(input.SourceKind)),
+ StringComparer.Ordinal);
+ }
+
+ /// Pages read in one poll before it yields (the cursor is committed after each).
+ public const int MaximumPagesPerPoll = 100;
+
+ /// Wait after a backpressure stop before the page is read again.
+ public TimeSpan RetryDelay { get; init; } = TimeSpan.FromSeconds(5);
+
+ /// Longest wait between failed polls (permission, throttling, outage).
+ public TimeSpan MaximumBackoff { get; init; } = TimeSpan.FromMinutes(30);
+
+ /// An HTTP client this source owns and disposes with itself (the production client).
+ public IDisposable? OwnedClient { get; init; }
+
+ /// Busy queue database (for example during a retention batch): treated as backpressure.
+ public Func IsTransientStorageFailure { get; init; } = static _ => false;
+
+ /// Starts one poll loop per input. Failures are retried with backoff and reported in .
+ public Task StartAsync(CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ ObjectDisposedException.ThrowIf(Volatile.Read(ref disposed) != 0, this);
+ if (Interlocked.Exchange(ref started, 1) != 0)
+ {
+ throw new InvalidOperationException("Microsoft cloud source is already started.");
+ }
+
+ CancellationToken token = stopping.Token;
+ lock (running)
+ {
+ foreach (Input input in inputs.Values)
+ {
+ running.Add(Task.Run(() => RunAsync(input, token), CancellationToken.None));
+ }
+ }
+
+ return Task.CompletedTask;
+ }
+
+ public IReadOnlyList Snapshot() =>
+ [.. inputs.Values.Select(input => input.Snapshot(http.Counters(input.Options.Id)))];
+
+ ///
+ /// One poll of one input: resume the open window or snapshot, hand each record to the
+ /// sink and commit after every completed page. Throws
+ /// on an API, cursor or response failure; pages committed before it stay committed.
+ ///
+ public async Task PollOnceAsync(string inputId, CancellationToken cancellationToken)
+ {
+ ObjectDisposedException.ThrowIf(Volatile.Read(ref disposed) != 0, this);
+ Input input = inputs[inputId];
+ await input.Gate.WaitAsync(cancellationToken);
+ if (Volatile.Read(ref disposed) != 0)
+ {
+ // Disposal took the gate after this call checked: never poll a stopped source.
+ input.Gate.Release();
+ throw new ObjectDisposedException(nameof(MicrosoftCloudSource));
+ }
+
+ try
+ {
+ return await PollAsync(input, cancellationToken);
+ }
+ catch (MicrosoftCloudException exception)
+ {
+ input.State = exception.Code;
+ Interlocked.Increment(ref input.Counters.Failures);
+ throw;
+ }
+ finally
+ {
+ input.Gate.Release();
+ }
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ if (Interlocked.Exchange(ref disposed, 1) != 0)
+ {
+ return;
+ }
+
+ await stopping.CancelAsync();
+ Task[] loops;
+ lock (running)
+ {
+ loops = [.. running];
+ }
+
+ try
+ {
+ await Task.WhenAll(loops);
+ }
+ catch (OperationCanceledException)
+ {
+ // Stopping.
+ }
+
+ foreach (Input input in inputs.Values)
+ {
+ // Wait for any poll still holding the gate (a direct PollOnceAsync), then leave the
+ // semaphore undisposed: it holds no unmanaged handle unless a wait handle was
+ // requested, and disposing it would race a late Release.
+ await input.Gate.WaitAsync(CancellationToken.None);
+ input.State = "stopped";
+ }
+
+ OwnedClient?.Dispose();
+
+ stopping.Dispose();
+ }
+
+ private async Task RunAsync(Input input, CancellationToken cancellationToken)
+ {
+ TimeSpan interval = TimeSpan.FromSeconds(configuration.PollIntervalSeconds);
+ int failures = 0;
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ TimeSpan wait;
+ try
+ {
+ MicrosoftCloudPollResult result = await PollOnceAsync(input.Options.Id, cancellationToken);
+ failures = 0;
+ wait = result.Backpressure ? RetryDelay : result.More ? TimeSpan.Zero : interval;
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ break;
+ }
+ catch (Exception exception) when (IsTransientStorageFailure(exception))
+ {
+ input.State = "backpressure";
+ Interlocked.Increment(ref input.Counters.Backpressure);
+ failures = 0;
+ wait = RetryDelay;
+ }
+ catch (Exception exception)
+ {
+ // Keep the cursor, back off and retry. The state carries the code; nothing else
+ // is reported, so a body, URL or token can never reach status or logs.
+ if (exception is not MicrosoftCloudException)
+ {
+ input.State = MicrosoftCloudFailures.SourceFailed;
+ Interlocked.Increment(ref input.Counters.Failures);
+ }
+
+ failures = Math.Min(failures + 1, 16);
+ TimeSpan first = TimeSpan.FromSeconds(30);
+ wait = TimeSpan.FromTicks(Math.Min(first.Ticks << Math.Min(failures - 1, 10), MaximumBackoff.Ticks));
+ }
+
+ try
+ {
+ await Task.Delay(wait, clock, cancellationToken);
+ }
+ catch (OperationCanceledException)
+ {
+ break;
+ }
+ }
+ }
+
+ private async Task PollAsync(Input input, CancellationToken cancellationToken)
+ {
+ MicrosoftCloudInputOptions options = input.Options;
+ DateTimeOffset now = clock.GetUtcNow();
+ Interlocked.Exchange(ref input.LastPollTicks, now.UtcTicks);
+ SourceCursorSnapshot? snapshot = await cursors.ReadAsync(options.SourceId, cancellationToken);
+ MicrosoftCloudCursor cursor;
+ if (snapshot is null)
+ {
+ cursor = new MicrosoftCloudCursor(MicrosoftCloudCursor.CurrentSchemaVersion, options.SourceKind);
+ }
+ else
+ {
+ cursor = MicrosoftCloudCursor.Deserialize(snapshot.Value, options.SourceKind)
+ ?? throw new MicrosoftCloudException(MicrosoftCloudFailures.CursorInvalid);
+ }
+
+ long version = snapshot?.Version ?? 0;
+ input.Observe(cursor);
+ MicrosoftCloudCursor opened = Open(input, cursor, now, out MicrosoftCloudSpan? span, out bool gap);
+ if (span is null)
+ {
+ input.State = "idle";
+ return new MicrosoftCloudPollResult(0, false, false);
+ }
+
+ if (opened != cursor)
+ {
+ // Store a new window before reading it, so a failure or backpressure resumes this
+ // exact window (and a gap is counted once, when the window is first opened).
+ cursor = opened;
+ version = await CommitAsync(input, cursor, version, cancellationToken);
+ if (gap)
+ {
+ Interlocked.Increment(ref input.Counters.Gaps);
+ }
+ }
+
+ input.State = "running";
+ int submitted = 0;
+ int pages = 0;
+ bool restarted = false;
+ HashSet visited = new(StringComparer.Ordinal);
+ while (true)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ MicrosoftCloudPage page;
+ try
+ {
+ page = await input.Reader.ReadPageAsync(http, options, span, cursor.Page, cancellationToken);
+ }
+ catch (MicrosoftCloudException exception) when (
+ exception.Code == MicrosoftCloudFailures.RequestRefused && cursor.Page is not null && !restarted)
+ {
+ // A stored page link expired (skip tokens do). Restart the same window or
+ // snapshot from its first page once per poll; records already queued
+ // deduplicate. A second refusal in the same poll fails it, so the loop backs off.
+ restarted = true;
+ Interlocked.Increment(ref input.Counters.PageRestarts);
+ cursor = cursor with { Page = null };
+ version = await CommitAsync(input, cursor, version, cancellationToken);
+ visited.Clear();
+ continue;
+ }
+
+ if (page.Next is not null && !visited.Add(page.Next))
+ {
+ // A next link the API already returned in this poll: a cycle that would never end.
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.ResponseInvalid);
+ }
+
+ Interlocked.Increment(ref input.Counters.Pages);
+ Interlocked.Add(ref input.Counters.Items, page.Items);
+ Interlocked.Add(ref input.Counters.OutOfScope, page.OutOfScope);
+ foreach (string record in page.Records)
+ {
+ MicrosoftCloudSubmitOutcome outcome = await sink.SubmitAsync(options, record, cancellationToken);
+ if (outcome == MicrosoftCloudSubmitOutcome.Unavailable)
+ {
+ // Keep the page: what was queued from it deduplicates when it is read again.
+ input.State = "backpressure";
+ Interlocked.Increment(ref input.Counters.Backpressure);
+ return new MicrosoftCloudPollResult(submitted, true, false);
+ }
+
+ submitted++;
+ input.Count(outcome, clock.GetUtcNow());
+ }
+
+ cursor = page.Next is null ? Close(cursor) : cursor with { Page = page.Next };
+ version = await CommitAsync(input, cursor, version, cancellationToken);
+ input.Observe(cursor);
+ if (page.Next is null)
+ {
+ // A window ended. Poll again at once only while the backlog exceeds one interval,
+ // so a caught-up input never spins on second-long windows.
+ DateTimeOffset settled = clock.GetUtcNow() - TimeSpan.FromSeconds(options.SettleDelaySeconds);
+ bool more = !input.Reader.IsSnapshot
+ && settled - span.End > TimeSpan.FromSeconds(configuration.PollIntervalSeconds);
+ return new MicrosoftCloudPollResult(submitted, false, more);
+ }
+
+ // Pages with nothing in scope (for example all compliant devices) still count,
+ // so one poll is bounded in requests as well as records.
+ if (submitted >= options.MaxRecordsPerPoll || ++pages >= MaximumPagesPerPoll)
+ {
+ return new MicrosoftCloudPollResult(submitted, false, true);
+ }
+ }
+ }
+
+ /// The open window or snapshot, or a new one when one is due; null span when caught up.
+ private static MicrosoftCloudCursor Open(Input input, MicrosoftCloudCursor cursor, DateTimeOffset now, out MicrosoftCloudSpan? span, out bool gap)
+ {
+ gap = false;
+ MicrosoftCloudInputOptions options = input.Options;
+ MicrosoftCloudReader reader = input.Reader;
+ if (reader.IsSnapshot)
+ {
+ if (cursor.SnapshotDate is { } open)
+ {
+ span = new MicrosoftCloudSpan(cursor.SnapshotAt!.Value, cursor.SnapshotAt.Value, open);
+ return cursor;
+ }
+
+ string today = now.UtcDateTime.ToString("yyyy'-'MM'-'dd", System.Globalization.CultureInfo.InvariantCulture);
+ // Ordinal order of yyyy-MM-dd is date order: a clock stepped back across midnight
+ // never re-runs a day that already completed.
+ if (cursor.CompletedDate is not null && string.CompareOrdinal(today, cursor.CompletedDate) <= 0)
+ {
+ span = null;
+ return cursor;
+ }
+
+ span = new MicrosoftCloudSpan(now, now, today);
+ return cursor with { SnapshotDate = today, SnapshotAt = now, Page = null };
+ }
+
+ if (cursor.WindowStart is { } start && cursor.WindowEnd is { } end)
+ {
+ span = new MicrosoftCloudSpan(start, end);
+ return cursor;
+ }
+
+ DateTimeOffset floor = now - reader.MaximumLookback;
+ DateTimeOffset lower = cursor.Committed is { } committed
+ ? committed - TimeSpan.FromSeconds(options.OverlapSeconds)
+ : now - TimeSpan.FromHours(options.StartLookbackHours);
+ if (lower < floor)
+ {
+ // The API keeps no older data. Only a committed bound before the floor loses
+ // records; an overlap reaching past it does not.
+ gap = cursor.Committed < floor;
+ lower = floor;
+ }
+
+ DateTimeOffset upper = now - TimeSpan.FromSeconds(options.SettleDelaySeconds);
+ if (upper - lower > reader.MaximumWindow)
+ {
+ upper = lower + reader.MaximumWindow;
+ }
+
+ // Nothing new to read until the settled bound passes the committed one.
+ if (upper <= lower || (cursor.Committed is { } done && upper <= done))
+ {
+ span = null;
+ gap = false;
+ return cursor;
+ }
+
+ span = new MicrosoftCloudSpan(lower, upper);
+ return cursor with { WindowStart = lower, WindowEnd = upper, Page = null };
+ }
+
+ private static MicrosoftCloudCursor Close(MicrosoftCloudCursor cursor) =>
+ cursor.SnapshotDate is { } date
+ ? cursor with { CompletedDate = date, SnapshotDate = null, SnapshotAt = null, Page = null }
+ : cursor with
+ {
+ Committed = cursor.Committed is { } committed && committed > cursor.WindowEnd ? committed : cursor.WindowEnd,
+ WindowStart = null,
+ WindowEnd = null,
+ Page = null
+ };
+
+ private async Task CommitAsync(Input input, MicrosoftCloudCursor cursor, long version, CancellationToken cancellationToken)
+ {
+ bool advanced = await cursors.TryAdvanceAsync(
+ input.Options.SourceId, version, cursor.Serialize(), clock.GetUtcNow(), cancellationToken);
+ if (!advanced)
+ {
+ throw new MicrosoftCloudException(MicrosoftCloudFailures.CursorConflict);
+ }
+
+ return version + 1;
+ }
+
+ private sealed class Input(MicrosoftCloudInputOptions options, MicrosoftCloudReader reader)
+ {
+ public MicrosoftCloudInputOptions Options { get; } = options;
+
+ public MicrosoftCloudReader Reader { get; } = reader;
+
+ public SemaphoreSlim Gate { get; } = new(1, 1);
+
+ public Counters Counters { get; } = new();
+
+ public volatile string State = "starting";
+
+ public long LastPollTicks;
+
+ public long LastRecordTicks;
+
+ private long committedTicks;
+ private volatile string? completedDate;
+
+ public void Observe(MicrosoftCloudCursor cursor)
+ {
+ Interlocked.Exchange(ref committedTicks, cursor.Committed?.UtcTicks ?? 0);
+ completedDate = cursor.CompletedDate;
+ }
+
+ public void Count(MicrosoftCloudSubmitOutcome outcome, DateTimeOffset at)
+ {
+ Interlocked.Exchange(ref LastRecordTicks, at.UtcTicks);
+ switch (outcome)
+ {
+ case MicrosoftCloudSubmitOutcome.Queued: Interlocked.Increment(ref Counters.Queued); break;
+ case MicrosoftCloudSubmitOutcome.Duplicate: Interlocked.Increment(ref Counters.Duplicates); break;
+ case MicrosoftCloudSubmitOutcome.Suppressed: Interlocked.Increment(ref Counters.Suppressed); break;
+ case MicrosoftCloudSubmitOutcome.NotSelected: Interlocked.Increment(ref Counters.NotSelected); break;
+ case MicrosoftCloudSubmitOutcome.Invalid: Interlocked.Increment(ref Counters.ParserErrors); break;
+ case MicrosoftCloudSubmitOutcome.TooLarge: Interlocked.Increment(ref Counters.TooLarge); break;
+ default: Interlocked.Increment(ref Counters.Rejected); break;
+ }
+ }
+
+ public MicrosoftCloudInputStatus Snapshot(MicrosoftCloudRetryCounters retries)
+ {
+ long committed = Interlocked.Read(ref committedTicks);
+ long poll = Interlocked.Read(ref LastPollTicks);
+ long record = Interlocked.Read(ref LastRecordTicks);
+ return new MicrosoftCloudInputStatus(
+ Options.Id,
+ Options.SourceKind,
+ State,
+ committed == 0 ? null : new DateTimeOffset(committed, TimeSpan.Zero),
+ completedDate,
+ Interlocked.Read(ref Counters.Pages),
+ Interlocked.Read(ref Counters.Items),
+ Interlocked.Read(ref Counters.Queued),
+ Interlocked.Read(ref Counters.Duplicates),
+ Interlocked.Read(ref Counters.Suppressed),
+ Interlocked.Read(ref Counters.NotSelected),
+ Interlocked.Read(ref Counters.Rejected),
+ Interlocked.Read(ref Counters.ParserErrors),
+ Interlocked.Read(ref Counters.TooLarge),
+ Interlocked.Read(ref Counters.OutOfScope),
+ Interlocked.Read(ref Counters.Backpressure),
+ Interlocked.Read(ref Counters.Gaps),
+ Interlocked.Read(ref Counters.PageRestarts),
+ Interlocked.Read(ref retries.Retries),
+ Interlocked.Read(ref retries.Throttled),
+ Interlocked.Read(ref Counters.Failures),
+ poll == 0 ? null : new DateTimeOffset(poll, TimeSpan.Zero),
+ record == 0 ? null : new DateTimeOffset(record, TimeSpan.Zero));
+ }
+ }
+
+ private sealed class Counters
+ {
+ public long Pages;
+ public long Items;
+ public long Queued;
+ public long Duplicates;
+ public long Suppressed;
+ public long NotSelected;
+ public long Rejected;
+ public long ParserErrors;
+ public long TooLarge;
+ public long OutOfScope;
+ public long Backpressure;
+ public long Gaps;
+ public long PageRestarts;
+ public long Failures;
+ }
+}
diff --git a/src/Bower.Source.MicrosoftCloud/MicrosoftCloudSourceConfiguration.cs b/src/Bower.Source.MicrosoftCloud/MicrosoftCloudSourceConfiguration.cs
new file mode 100644
index 00000000..d4297918
--- /dev/null
+++ b/src/Bower.Source.MicrosoftCloud/MicrosoftCloudSourceConfiguration.cs
@@ -0,0 +1,261 @@
+using System.Globalization;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Bower.Source.MicrosoftCloud;
+
+///
+/// BOWER_MICROSOFT_CONFIG: the Microsoft cloud sources an operator selected for security
+/// signal, each routed to one signed pack parser. There is no collect-everything form:
+/// every input names one source kind, one tenant and one parser.
+///
+/// Wait between polls once an input has caught up.
+public sealed record MicrosoftCloudSourceConfiguration(
+ string ApiVersion,
+ string Kind,
+ IReadOnlyList Inputs,
+ int PollIntervalSeconds = 300);
+
+/// The active parser of a loaded signed pack that maps this input's records.
+public sealed record MicrosoftCloudRoute(string Pack, int Parser);
+
+///
+/// An app registration that reads one tenant with a certificate (for example an MSP reading
+/// a customer tenant). Client secrets are not supported: the certificate file is the only
+/// credential, and it stays on disk with the collector's own file permissions.
+///
+public sealed record MicrosoftCloudCertificateCredential(string ClientId, string CertificatePath);
+
+/// 1 to 63 lowercase letters, digits or hyphens; names the cursor (mscloud:<id>).
+/// One of .
+/// The Entra tenant the input reads (a GUID).
+/// Null: the collector's own Azure credential (BOWER_AZURE_CREDENTIAL).
+/// How far back the first poll reads (no cursor yet).
+/// A window ends this long before now, so late-written records are in the next one.
+/// Each window starts this long before the last committed bound; re-read records deduplicate.
+/// Records handed to the pack parser per poll before the cursor is committed.
+/// intune-device-compliance only: the device compliance states that become records.
+/// dataverse-audit only: the environment's Web API host (https://org.crm6.dynamics.com).
+/// dataverse-audit only: Dataverse audit action codes to request (default security-relevant).
+/// power-platform-activity only: Office 365 audit record types to keep (default all Power Platform types).
+/// power-platform-activity only: the publisher GUID sent for throttling quota.
+/// power-platform-activity only: start the Audit.General subscription if it is missing. Never stopped.
+public sealed record MicrosoftCloudInputOptions(
+ string Id,
+ string SourceKind,
+ string TenantId,
+ MicrosoftCloudRoute Route,
+ MicrosoftCloudCertificateCredential? Credential = null,
+ int StartLookbackHours = 24,
+ int SettleDelaySeconds = 300,
+ int OverlapSeconds = 600,
+ int MaxRecordsPerPoll = 1_000,
+ IReadOnlyList? ComplianceStates = null,
+ string? EnvironmentUrl = null,
+ IReadOnlyList? AuditActions = null,
+ IReadOnlyList? RecordTypes = null,
+ string? PublisherIdentifier = null,
+ bool StartSubscription = false)
+{
+ /// Durable cursor key in the queue database's source cursor table.
+ [JsonIgnore]
+ public string SourceId => "mscloud:" + Id;
+}
+
+/// Source kinds. Each kind names one API and one record shape.
+public static class MicrosoftCloudKinds
+{
+ /// Microsoft Graph deviceManagement/auditEvents.
+ public const string IntuneAudit = "intune-audit";
+
+ /// Daily Microsoft Graph deviceManagement/managedDevices compliance snapshot.
+ public const string IntuneDeviceCompliance = "intune-device-compliance";
+
+ public static readonly IReadOnlyList All = [IntuneAudit, IntuneDeviceCompliance];
+}
+
+public static class MicrosoftCloudSourceConfigurationLoader
+{
+ public const int MaximumInputs = 16;
+ public const int MaximumOverlapSeconds = 43_200;
+ private const int MaximumBytes = 262_144;
+
+ /// Default compliance states kept by the compliance snapshot: everything that needs attention.
+ public static readonly IReadOnlyList DefaultComplianceStates = ["noncompliant", "inGracePeriod", "conflict", "error"];
+
+ private static readonly HashSet ComplianceStateNames = new(
+ // compliant is deliberately absent: compliant devices are never collected.
+ ["unknown", "noncompliant", "conflict", "error", "inGracePeriod", "configManager"],
+ StringComparer.Ordinal);
+
+ public static MicrosoftCloudSourceConfiguration LoadFile(string path)
+ {
+ FileInfo info = new(path);
+ if (!info.Exists)
+ {
+ throw new FileNotFoundException("Microsoft cloud source configuration file does not exist.", path);
+ }
+
+ if (info.Length > MaximumBytes)
+ {
+ throw new InvalidDataException("Microsoft cloud source configuration file exceeds 256 KiB.");
+ }
+
+ return Parse(File.ReadAllText(path));
+ }
+
+ public static MicrosoftCloudSourceConfiguration Parse(string json)
+ {
+ MicrosoftCloudSourceConfiguration? configuration;
+ try
+ {
+ configuration = JsonSerializer.Deserialize(json, MicrosoftCloudJsonContext.Default.MicrosoftCloudSourceConfiguration);
+ }
+ catch (JsonException exception)
+ {
+ throw new InvalidDataException($"Microsoft cloud source configuration is invalid: {exception.Message}", exception);
+ }
+
+ if (configuration is null
+ || !string.Equals(configuration.ApiVersion, "bower.security/v1", StringComparison.Ordinal)
+ || !string.Equals(configuration.Kind, "MicrosoftCloudSource", StringComparison.Ordinal))
+ {
+ throw new InvalidDataException(
+ "Microsoft cloud source configuration needs apiVersion bower.security/v1 and kind MicrosoftCloudSource.");
+ }
+
+ if (configuration.Inputs is not { Count: >= 1 and <= MaximumInputs })
+ {
+ throw new InvalidDataException($"Microsoft cloud source configuration must list 1 to {MaximumInputs} inputs.");
+ }
+
+ if (configuration.PollIntervalSeconds is < 60 or > 86_400)
+ {
+ throw new InvalidDataException("Microsoft cloud pollIntervalSeconds must be between 60 and 86400.");
+ }
+
+ HashSet ids = new(StringComparer.Ordinal);
+ foreach (MicrosoftCloudInputOptions input in configuration.Inputs)
+ {
+ Validate(input);
+ if (!ids.Add(input.Id))
+ {
+ throw new InvalidDataException($"Microsoft cloud input {input.Id} is listed more than once.");
+ }
+ }
+
+ return configuration;
+ }
+
+ private static void Validate(MicrosoftCloudInputOptions input)
+ {
+ if (input is null || !IsInputId(input.Id))
+ {
+ throw new InvalidDataException(
+ "Microsoft cloud input id must be 1 to 63 lowercase letters, digits or hyphens and start with a letter or digit.");
+ }
+
+ string id = input.Id;
+ if (!MicrosoftCloudKinds.All.Contains(input.SourceKind, StringComparer.Ordinal))
+ {
+ throw Invalid(id, $"sourceKind must be one of {string.Join(", ", MicrosoftCloudKinds.All)}.");
+ }
+
+ if (!Guid.TryParseExact(input.TenantId, "D", out Guid tenant) || tenant == Guid.Empty
+ || !string.Equals(input.TenantId, tenant.ToString("D"), StringComparison.Ordinal))
+ {
+ throw Invalid(id, "tenantId must be a lowercase GUID.");
+ }
+
+ if (input.Route is null || string.IsNullOrWhiteSpace(input.Route.Pack) || input.Route.Parser < 0)
+ {
+ throw Invalid(id, "route needs a pack and a parser index of 0 or more.");
+ }
+
+ if (input.Credential is { } credential)
+ {
+ if (!Guid.TryParseExact(credential.ClientId, "D", out Guid client) || client == Guid.Empty)
+ {
+ throw Invalid(id, "credential.clientId must be a GUID.");
+ }
+
+ if (string.IsNullOrWhiteSpace(credential.CertificatePath) || !Path.IsPathFullyQualified(credential.CertificatePath))
+ {
+ throw Invalid(id, "credential.certificatePath must be an absolute path to a PEM or PFX certificate with its private key.");
+ }
+ }
+
+ if (input.StartLookbackHours is < 1 or > 168)
+ {
+ throw Invalid(id, "startLookbackHours must be between 1 and 168.");
+ }
+
+ if (input.SettleDelaySeconds is < 0 or > 86_400)
+ {
+ throw Invalid(id, "settleDelaySeconds must be between 0 and 86400.");
+ }
+
+ // Windows are at most 24 hours: an overlap near that would stop the committed bound
+ // advancing (each window would end at or before it), so it is capped at 12 hours.
+ if (input.OverlapSeconds is < 0 or > MaximumOverlapSeconds)
+ {
+ throw Invalid(id, $"overlapSeconds must be between 0 and {MaximumOverlapSeconds}.");
+ }
+
+ if (input.MaxRecordsPerPoll is < 1 or > 10_000)
+ {
+ throw Invalid(id, "maxRecordsPerPoll must be between 1 and 10000.");
+ }
+
+ bool compliance = input.SourceKind == MicrosoftCloudKinds.IntuneDeviceCompliance;
+ if (input.ComplianceStates is not null)
+ {
+ if (!compliance)
+ {
+ throw Invalid(id, "complianceStates applies to intune-device-compliance only.");
+ }
+
+ if (input.ComplianceStates.Count is < 1 or > 6
+ || input.ComplianceStates.Any(state => state is null || !ComplianceStateNames.Contains(state))
+ || input.ComplianceStates.Distinct(StringComparer.Ordinal).Count() != input.ComplianceStates.Count)
+ {
+ throw Invalid(id, $"complianceStates must list distinct values from {string.Join(", ", ComplianceStateNames.Order(StringComparer.Ordinal))}.");
+ }
+ }
+
+ if (input.EnvironmentUrl is not null || input.AuditActions is not null)
+ {
+ throw Invalid(id, "environmentUrl and auditActions apply to dataverse-audit only.");
+ }
+
+ if (input.RecordTypes is not null || input.PublisherIdentifier is not null || input.StartSubscription)
+ {
+ throw Invalid(id, "recordTypes, publisherIdentifier and startSubscription apply to power-platform-activity only.");
+ }
+ }
+
+ internal static IReadOnlyList ComplianceStates(MicrosoftCloudInputOptions input) =>
+ input.ComplianceStates ?? DefaultComplianceStates;
+
+ private static bool IsInputId(string? id) =>
+ id is { Length: >= 1 and <= 63 }
+ && (char.IsAsciiLetterLower(id[0]) || char.IsAsciiDigit(id[0]))
+ && id.All(character => char.IsAsciiLetterLower(character) || char.IsAsciiDigit(character) || character == '-');
+
+ private static InvalidDataException Invalid(string id, string message) => new($"Microsoft cloud input {id}: {message}");
+
+ internal static string Format(DateTimeOffset value) =>
+ value.UtcDateTime.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff'Z'", CultureInfo.InvariantCulture);
+}
+
+[JsonSourceGenerationOptions(
+ JsonSerializerDefaults.Web,
+ NumberHandling = JsonNumberHandling.Strict,
+ PropertyNameCaseInsensitive = false,
+ AllowDuplicateProperties = false,
+ UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
+ RespectRequiredConstructorParameters = true,
+ RespectNullableAnnotations = true)]
+[JsonSerializable(typeof(MicrosoftCloudSourceConfiguration))]
+[JsonSerializable(typeof(IReadOnlyList))]
+internal sealed partial class MicrosoftCloudJsonContext : JsonSerializerContext;
diff --git a/src/Bower.Source.MicrosoftCloud/packages.lock.json b/src/Bower.Source.MicrosoftCloud/packages.lock.json
new file mode 100644
index 00000000..668a49ec
--- /dev/null
+++ b/src/Bower.Source.MicrosoftCloud/packages.lock.json
@@ -0,0 +1,22 @@
+{
+ "version": 2,
+ "dependencies": {
+ "net11.0": {
+ "Microsoft.NET.ILLink.Tasks": {
+ "type": "Direct",
+ "requested": "[11.0.0, )",
+ "resolved": "11.0.0",
+ "contentHash": "gK2aq4XvChj5kvozpPHrkfKkr7zc5Z4xoTrJb4GPZzDEPMlCk0TX632bwY3LsWcX2UVcVRQBBGzsBGC2lq6YhA=="
+ },
+ "bower.abstractions": {
+ "type": "Project",
+ "dependencies": {
+ "Bower.Contracts": "[1.0.0, )"
+ }
+ },
+ "bower.contracts": {
+ "type": "Project"
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/tests/Bower.UnitTests/Bower.UnitTests.csproj b/tests/Bower.UnitTests/Bower.UnitTests.csproj
index 60dae8c3..263dd977 100644
--- a/tests/Bower.UnitTests/Bower.UnitTests.csproj
+++ b/tests/Bower.UnitTests/Bower.UnitTests.csproj
@@ -19,6 +19,7 @@
+
@@ -58,6 +59,10 @@
PreserveNewest
+
+ fixtures/microsoft-cloud/%(Filename)%(Extension)
+ PreserveNewest
+
s3-output/%(Filename)%(Extension)
PreserveNewest
diff --git a/tests/Bower.UnitTests/MicrosoftCloudCollectorTests.cs b/tests/Bower.UnitTests/MicrosoftCloudCollectorTests.cs
new file mode 100644
index 00000000..be91189b
--- /dev/null
+++ b/tests/Bower.UnitTests/MicrosoftCloudCollectorTests.cs
@@ -0,0 +1,298 @@
+using System.Net.Http.Headers;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using Bower.Abstractions;
+using Bower.Collector;
+using Bower.Contracts;
+using Bower.Detection;
+using Bower.Integrity;
+using Bower.Packs;
+using Bower.Persistence;
+using Bower.Redaction.Privacy;
+using Bower.Source.MicrosoftCloud;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.TestHost;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Bower.UnitTests;
+
+///
+/// The Microsoft cloud source inside the collector: Intune audit events and compliance
+/// records from a fake Graph become durable events only through the signed
+/// microsoft-intune parsers (transforms, match filter), redaction and policy.
+///
+[Collection(SerialHostTests.Name)]
+public sealed class MicrosoftCloudCollectorTests
+{
+ private const string Token = "microsoft-cloud-collector-test-token-0123456789";
+ private static string PackSource => Path.Combine(AppContext.BaseDirectory, "packs", "microsoft-intune");
+
+ [Fact]
+ public void Pack_BuildsSignsAndPassesItsSamples()
+ {
+ LoadedPack pack = Build(out _);
+
+ IReadOnlyList results = PackTester.Run(pack, PackArchive.TestPrivacyPolicy(pack.PrivacyProfileYaml));
+
+ Assert.Equal("microsoft-intune", pack.Manifest.Id);
+ Assert.Equal(2, pack.Policies.Count);
+ Assert.Equal(2, pack.Parsers.Count);
+ Assert.Equal(4, pack.Detections.Count);
+ Assert.Null(pack.PrivacyProfileYaml);
+ Assert.All(results, result => Assert.True(result.Passed, $"{result.Name}: {string.Join(" ", result.Problems)}"));
+ }
+
+ [Fact]
+ public async Task IntuneAuditAndCompliance_AreRedactedQueuedAndDeduplicatedAcrossRestart()
+ {
+ CancellationToken cancellation = TestContext.Current.CancellationToken;
+ using TemporaryDirectory directory = new();
+ // Real time plus an offset: collector timers keep running, and the restart can be moved
+ // past the settle delay so the audit input really re-reads its overlap.
+ ShiftedClock clock = new();
+ DateTimeOffset now = clock.GetUtcNow();
+ MicrosoftCloudSourceTests.FakeGraph graph = new();
+ graph.AuditPages(now);
+ graph.Respond(uri => uri.AbsolutePath.EndsWith("/managedDevices", StringComparison.Ordinal),
+ MicrosoftCloudSourceTests.Fixture("intune-managed-devices.json", now));
+ List rows;
+ await using (WebApplication app = await Start(directory, graph, clock, cancellation))
+ {
+ MicrosoftCloudSource source = app.Services.GetRequiredService();
+ await WaitFor(source, items => items.All(item => item.Queued + item.Duplicates >= 2), cancellation);
+ MicrosoftCloudInputStatus[] statuses = [.. source.Snapshot().OrderBy(item => item.Id, StringComparer.Ordinal)];
+ Assert.Equal(2, statuses[0].Queued);
+ Assert.Equal(1, statuses[0].OutOfScope);
+ Assert.Equal(2, statuses[1].Queued);
+ Assert.Equal(1, statuses[1].OutOfScope);
+
+ using HttpClient client = app.GetTestClient();
+ client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
+ using JsonDocument status = JsonDocument.Parse(await client.GetStringAsync("/v1/status", cancellation));
+ JsonElement reported = status.RootElement.GetProperty("microsoftCloud");
+ Assert.Equal(2, reported.GetArrayLength());
+ Assert.DoesNotContain("contoso.example", reported.GetRawText(), StringComparison.Ordinal);
+ Assert.DoesNotContain("graph.microsoft.com", reported.GetRawText(), StringComparison.Ordinal);
+
+ rows = [.. await app.Services.GetRequiredService().LeaseAsync(10, TimeSpan.FromMinutes(1), cancellation)];
+ }
+
+ Assert.Equal(4, rows.Count);
+ SecurityEventEnvelope[] events = [.. rows.Select(row => JsonSerializer.Deserialize(row.Payload, BowerJson.Envelope)!)];
+ foreach (QueuedEvent row in rows)
+ {
+ Assert.DoesNotContain("megan.bowen@contoso.example", row.Payload, StringComparison.Ordinal);
+ Assert.DoesNotContain("adele.vance@contoso.example", row.Payload, StringComparison.Ordinal);
+ Assert.DoesNotContain("MEGAN-LAPTOP", row.Payload, StringComparison.Ordinal);
+ Assert.DoesNotContain("KIOSK-03", row.Payload, StringComparison.Ordinal);
+ Assert.DoesNotContain("secret-", row.Payload, StringComparison.Ordinal);
+ }
+
+ SecurityEventEnvelope wipe = Assert.Single(events, item => item.EventAction == "Wipe ManagedDevice");
+ Assert.Equal("intune_audit", wipe.EventType);
+ Assert.Equal("microsoft-intune", wipe.Application.Name);
+ Assert.Equal("203.0.113.40", wipe.Source!.IpAddress);
+ Assert.Equal("mscloud:intune-audit:microsoft-intune:0", wipe.Collector!.SourceAdapter);
+ Assert.StartsWith("mscloud-", wipe.EventId, StringComparison.Ordinal);
+ Assert.StartsWith("hmac-sha256:", wipe.Actor!.Username, StringComparison.Ordinal);
+ Assert.Contains(wipe.Attributes!["bowerDetections"].EnumerateArray(),
+ item => item.GetProperty("ruleId").GetString() == "bower-pack-intune-device-wipe-001");
+ SecurityEventEnvelope kiosk = Assert.Single(events, item => item.EventAction == "device.compliance.inGracePeriod");
+ Assert.Equal("True", kiosk.Labels!["jailBroken"]);
+ Assert.Equal("22222222-0000-4000-8000-000000000803", kiosk.Target!.Id);
+
+ // Restart both inputs 15 minutes later (same UTC day unless the test runs just before
+ // midnight, which the snapshot assertion allows for). The audit window re-reads its
+ // 10 minute overlap, which holds the role change: it must be a queue duplicate.
+ int requestsBefore = graph.Requests.Count;
+ clock.Offset = TimeSpan.FromMinutes(15);
+ bool sameDay = clock.GetUtcNow().UtcDateTime.Date == now.UtcDateTime.Date;
+ await using (WebApplication again = await Start(directory, graph, clock, cancellation))
+ {
+ MicrosoftCloudSource source = again.Services.GetRequiredService();
+ await WaitFor(source, items => items.Single(item => item.Id == "intune-audit").Duplicates >= 1
+ && items.Single(item => item.Id == "intune-compliance").State == (sameDay ? "idle" : "running"), cancellation);
+ MicrosoftCloudInputStatus audit = source.Snapshot().Single(item => item.Id == "intune-audit");
+ Assert.Equal(0, audit.Queued);
+ Assert.True(graph.Requests.Count > requestsBefore);
+ if (sameDay)
+ {
+ Assert.Equal(0, source.Snapshot().Single(item => item.Id == "intune-compliance").Pages);
+ }
+
+ // Exactly the four rows from the first run, whatever state the leases left them in.
+ QueueSnapshot queue = await again.Services.GetRequiredService().GetSnapshotAsync(cancellation);
+ Assert.Equal(4, queue.Queued + queue.Uploading + queue.Retrying + queue.Delivered + queue.DeadLettered);
+ }
+ }
+
+ /// System time plus an adjustable offset.
+ private sealed class ShiftedClock : TimeProvider
+ {
+ public TimeSpan Offset { get; set; }
+
+ public override DateTimeOffset GetUtcNow() => System.GetUtcNow() + Offset;
+ }
+
+ [Fact]
+ public async Task RouteToAMissingParser_StopsStartUp()
+ {
+ using TemporaryDirectory directory = new();
+ CollectorSettings settings = Settings(directory, parser: 7);
+
+ InvalidOperationException failure = Assert.Throws(
+ () => CollectorApplication.Build(settings, builder => builder.WebHost.UseTestServer()));
+
+ Assert.Contains("is not an active parser of a loaded pack", failure.Message, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Setting_IsReadAndChangesTheConfigurationHash()
+ {
+ CollectorSettings plain = CollectorSettings.FromEnvironment(name => name switch
+ {
+ "BOWER_LISTEN_URL" => "http://127.0.0.1:4319",
+ _ => null
+ });
+ CollectorSettings configured = CollectorSettings.FromEnvironment(name => name switch
+ {
+ "BOWER_LISTEN_URL" => "http://127.0.0.1:4319",
+ "BOWER_MICROSOFT_CONFIG" => "/etc/bower/microsoft.json",
+ _ => null
+ });
+
+ Assert.Null(plain.MicrosoftCloudConfigPath);
+ Assert.Equal("/etc/bower/microsoft.json", configured.MicrosoftCloudConfigPath);
+ Assert.NotEqual(plain.ConfigurationHash(), configured.ConfigurationHash());
+ }
+
+ [Fact]
+ public void MicrosoftCloudProfile_PseudonymisesPeopleAndResourceNames()
+ {
+ string yaml = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "deploy", "privacy", "microsoft-cloud.yaml"));
+ PrivacyEngine engine = new(PrivacyProfileLoader.Load(yaml, new byte[32], "k1").Policy);
+ SecurityEventEnvelope envelope = TestEvents.AuthenticationFailure(TestEvents.Now) with
+ {
+ Actor = new ActorContext { Username = "megan.bowen@contoso.example", UserId = "0b7c1d3e-0000-4000-8000-000000000101" },
+ Target = new TargetContext { Type = "RoleAssignment", Id = "5a5a5a5a-0000-4000-8000-000000000301", Name = "Helpdesk operators" }
+ };
+
+ string redacted = engine.RedactJson(JsonSerializer.Serialize(envelope, BowerJson.Options)).RedactedJson!;
+
+ string other = engine.RedactJson(JsonSerializer.Serialize(envelope with
+ {
+ Actor = new ActorContext { Username = "mark.smith@contoso.example" }
+ }, BowerJson.Options)).RedactedJson!;
+ using JsonDocument first = JsonDocument.Parse(redacted);
+ using JsonDocument second = JsonDocument.Parse(other);
+ string megan = first.RootElement.GetProperty("actor").GetProperty("username").GetString()!;
+ string mark = second.RootElement.GetProperty("actor").GetProperty("username").GetString()!;
+ // Same initial and domain: the pseudonyms must still differ (no mask-then-hash collapse).
+ Assert.StartsWith("hmac-sha256:", megan, StringComparison.Ordinal);
+ Assert.StartsWith("hmac-sha256:", mark, StringComparison.Ordinal);
+ Assert.NotEqual(megan, mark);
+ Assert.DoesNotContain("***", megan, StringComparison.Ordinal);
+
+ Assert.DoesNotContain("megan.bowen", redacted, StringComparison.Ordinal);
+ Assert.DoesNotContain("0b7c1d3e-0000-4000-8000-000000000101", redacted, StringComparison.Ordinal);
+ Assert.DoesNotContain("Helpdesk operators", redacted, StringComparison.Ordinal);
+ Assert.Contains("5a5a5a5a-0000-4000-8000-000000000301", redacted, StringComparison.Ordinal);
+ }
+
+ private static async Task WaitFor(MicrosoftCloudSource source, Func, bool> condition, CancellationToken cancellation)
+ {
+ DateTime deadline = DateTime.UtcNow.AddSeconds(20);
+ while (true)
+ {
+ IReadOnlyList status = source.Snapshot();
+ if (condition(status))
+ {
+ return;
+ }
+
+ if (DateTime.UtcNow > deadline)
+ {
+ Assert.Fail("Timed out waiting for the Microsoft cloud inputs: " + JsonSerializer.Serialize(status));
+ }
+
+ await Task.Delay(25, cancellation);
+ }
+ }
+
+ private static async Task Start(TemporaryDirectory directory, MicrosoftCloudSourceTests.FakeGraph graph, TimeProvider clock, CancellationToken cancellation)
+ {
+ WebApplication app = CollectorApplication.Build(Settings(directory), builder =>
+ {
+ builder.WebHost.UseTestServer();
+ builder.Services.AddSingleton(clock);
+ builder.Services.AddSingleton(new MicrosoftCloudSourceTests.FakeTokens());
+ builder.Services.AddSingleton(new MicrosoftCloudHttpClient(new HttpClient(graph)));
+ });
+ await CollectorApplication.InitializeAsync(app, cancellation);
+ await app.StartAsync(cancellation);
+ return app;
+ }
+
+ private static CollectorSettings Settings(TemporaryDirectory directory, int parser = 0)
+ {
+ string archive = Path.Combine(directory.Path, "microsoft-intune.bowerpack");
+ string trust = Path.Combine(directory.Path, "trusted.pem");
+ if (!File.Exists(archive))
+ {
+ (string privateKey, string publicKey, _) = DetachedSigner.GenerateKeyPair();
+ File.Move(PackArchive.Build(PackSource, privateKey, directory.Path), archive);
+ File.WriteAllText(trust, publicKey);
+ File.WriteAllText(Path.Combine(directory.Path, "hmac.key"), Convert.ToBase64String(new byte[32]));
+ }
+
+ JsonArray inputs =
+ [
+ new JsonObject
+ {
+ ["id"] = "intune-audit",
+ ["sourceKind"] = "intune-audit",
+ ["tenantId"] = "a1b2c3d4-0000-4000-8000-00000000aaaa",
+ ["route"] = new JsonObject { ["pack"] = "microsoft-intune", ["parser"] = parser }
+ }
+ ];
+ inputs.Add(new JsonObject
+ {
+ ["id"] = "intune-compliance",
+ ["sourceKind"] = "intune-device-compliance",
+ ["tenantId"] = "a1b2c3d4-0000-4000-8000-00000000aaaa",
+ ["route"] = new JsonObject { ["pack"] = "microsoft-intune", ["parser"] = 1 }
+ });
+
+ string configuration = Path.Combine(directory.Path, "microsoft.json");
+ File.WriteAllText(configuration, new JsonObject
+ {
+ ["apiVersion"] = "bower.security/v1",
+ ["kind"] = "MicrosoftCloudSource",
+ ["inputs"] = inputs
+ }.ToJsonString());
+ return new CollectorSettings
+ {
+ CollectorId = "microsoft-cloud-collector-test",
+ ListenUrl = "http://127.0.0.1:4319",
+ QueuePath = Path.Combine(directory.Path, "queue.db"),
+ PolicyDirectory = Path.Combine(directory.Path, "no-defaults"),
+ Packs = [archive],
+ PackTrustedKeyFiles = [trust],
+ PrivacyProfilePath = Path.Combine(AppContext.BaseDirectory, "deploy", "privacy", "microsoft-cloud.yaml"),
+ PrivacyHmacKeyFile = Path.Combine(directory.Path, "hmac.key"),
+ MaximumQueueBytes = 4_194_304,
+ IngestToken = Token,
+ SingleTrustDomain = true,
+ MicrosoftCloudConfigPath = configuration
+ };
+ }
+
+ private static LoadedPack Build(out string publicPem)
+ {
+ using TemporaryDirectory output = new();
+ (string privatePem, string publicKey, _) = DetachedSigner.GenerateKeyPair();
+ publicPem = publicKey;
+ return PackArchive.Load(PackArchive.Build(PackSource, privatePem, output.Path), [publicPem]);
+ }
+}
diff --git a/tests/Bower.UnitTests/MicrosoftCloudSourceTests.cs b/tests/Bower.UnitTests/MicrosoftCloudSourceTests.cs
new file mode 100644
index 00000000..a0555976
--- /dev/null
+++ b/tests/Bower.UnitTests/MicrosoftCloudSourceTests.cs
@@ -0,0 +1,910 @@
+using System.Collections.Concurrent;
+using System.Net;
+using System.Text;
+using System.Text.Json;
+using Bower.Abstractions;
+using Bower.Source.MicrosoftCloud;
+
+namespace Bower.UnitTests;
+
+///
+/// The Microsoft cloud pull source against a fake Graph: bounded records, durable window and
+/// snapshot cursors, backpressure, crash recovery, retry and the token host allow-list.
+/// Fixtures are synthetic (tests/fixtures/microsoft-cloud). No live tenant calls.
+///
+public sealed class MicrosoftCloudSourceTests
+{
+ private const string Tenant = "a1b2c3d4-0000-4000-8000-00000000aaaa";
+ private static readonly DateTimeOffset Now = new(2026, 11, 22, 10, 0, 0, TimeSpan.Zero);
+
+ [Fact]
+ public async Task AuditWindow_PagesRecordsAndCommitsTheWindowWithoutModifiedValues()
+ {
+ CancellationToken cancellation = TestContext.Current.CancellationToken;
+ FakeGraph graph = new();
+ graph.AuditPages(Now);
+ MemorySink sink = new();
+ FileTailSourceTests.MemoryCursors cursors = new();
+ MicrosoftCloudSource source = Source(graph, sink, cursors, Audit());
+
+ MicrosoftCloudPollResult result = await source.PollOnceAsync("intune-audit", cancellation);
+
+ Assert.False(result.Backpressure);
+ Assert.Equal(2, sink.Records.Count);
+ Assert.All(sink.Records, record => Assert.DoesNotContain("secret-", record, StringComparison.Ordinal));
+ using JsonDocument wipe = JsonDocument.Parse(sink.Records[0]);
+ JsonElement root = wipe.RootElement;
+ Assert.StartsWith("mscloud-", root.GetProperty("id").GetString(), StringComparison.Ordinal);
+ Assert.Equal("Wipe ManagedDevice", root.GetProperty("activity").GetString());
+ Assert.Equal("WipeKeepEnrollmentData", root.GetProperty("modifiedProperties").GetString());
+ Assert.Equal("203.0.113.40", root.GetProperty("actorIpAddress").GetString());
+ Assert.Equal("1", root.GetProperty("resourceCount").GetString());
+ using JsonDocument role = JsonDocument.Parse(sink.Records[1]);
+ Assert.Equal("Members,ScopeTags", role.RootElement.GetProperty("modifiedProperties").GetString());
+
+ // The second page's third item had no time: out of scope, never a record.
+ MicrosoftCloudInputStatus status = Assert.Single(source.Snapshot());
+ Assert.Equal(2, status.Pages);
+ Assert.Equal(3, status.Items);
+ Assert.Equal(1, status.OutOfScope);
+ Assert.Equal(2, status.Queued);
+ MicrosoftCloudCursor cursor = MicrosoftCloudCursor.Deserialize(cursors.Value("mscloud:intune-audit")!, MicrosoftCloudKinds.IntuneAudit)!;
+ Assert.Equal(Now - TimeSpan.FromSeconds(300), cursor.Committed);
+ Assert.Null(cursor.WindowStart);
+ Assert.Null(cursor.Page);
+
+ // The first request filtered the window; the bearer token went only to Graph.
+ Uri first = graph.Requests[0];
+ string filter = Uri.UnescapeDataString(first.Query);
+ Assert.Contains("activityDateTime ge 2026-11-21T10:00:00Z and activityDateTime lt 2026-11-22T09:55:00Z", filter, StringComparison.Ordinal);
+ Assert.All(graph.Requests, uri => Assert.Equal("graph.microsoft.com", uri.Host));
+ }
+
+ [Fact]
+ public async Task NextPoll_StartsOneOverlapBeforeTheCommittedBoundAndWaitsForTheSettleDelay()
+ {
+ CancellationToken cancellation = TestContext.Current.CancellationToken;
+ FakeGraph graph = new();
+ graph.AuditPages(Now);
+ FakeClock clock = new(Now);
+ FileTailSourceTests.MemoryCursors cursors = new();
+ MicrosoftCloudSource source = Source(graph, new MemorySink(), cursors, Audit(), clock);
+ await source.PollOnceAsync("intune-audit", cancellation);
+
+ // Caught up: nothing to read until the settled bound passes the committed one.
+ MicrosoftCloudPollResult idle = await source.PollOnceAsync("intune-audit", cancellation);
+ Assert.Equal(0, idle.Records);
+ Assert.Equal("idle", Assert.Single(source.Snapshot()).State);
+ Assert.Equal(2, graph.Requests.Count);
+
+ clock.Advance(TimeSpan.FromMinutes(15));
+ graph.Respond(_ => true, """{"value":[]}""");
+ await source.PollOnceAsync("intune-audit", cancellation);
+ string filter = Uri.UnescapeDataString(graph.Requests[^1].Query);
+ // Committed 09:55; overlap 600 s gives 09:45; settle 300 s gives 10:10.
+ Assert.Contains("activityDateTime ge 2026-11-22T09:45:00Z and activityDateTime lt 2026-11-22T10:10:00Z", filter, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task OverlapReRead_GivesTheSameEventIds()
+ {
+ CancellationToken cancellation = TestContext.Current.CancellationToken;
+ FakeGraph graph = new();
+ graph.AuditPages(Now);
+ MemorySink first = new();
+ await Source(graph, first, new FileTailSourceTests.MemoryCursors(), Audit()).PollOnceAsync("intune-audit", cancellation);
+ FakeGraph again = new();
+ again.AuditPages(Now);
+ MemorySink second = new();
+
+ await Source(again, second, new FileTailSourceTests.MemoryCursors(), Audit()).PollOnceAsync("intune-audit", cancellation);
+
+ Assert.Equal(first.Records.Select(Id), second.Records.Select(Id));
+ Assert.Equal(2, first.Records.Select(Id).Distinct(StringComparer.Ordinal).Count());
+ }
+
+ [Fact]
+ public async Task Backpressure_KeepsThePageAndTheNextPollReadsItAgain()
+ {
+ CancellationToken cancellation = TestContext.Current.CancellationToken;
+ FakeGraph graph = new();
+ graph.AuditPages(Now);
+ MemorySink sink = new() { RefuseAfter = 1 };
+ FileTailSourceTests.MemoryCursors cursors = new();
+ MicrosoftCloudSource source = Source(graph, sink, cursors, Audit());
+
+ MicrosoftCloudPollResult refused = await source.PollOnceAsync("intune-audit", cancellation);
+
+ Assert.True(refused.Backpressure);
+ Assert.Equal("backpressure", Assert.Single(source.Snapshot()).State);
+ // Page 1 (one record) completed and was committed; page 2 was refused and is kept.
+ MicrosoftCloudCursor open = MicrosoftCloudCursor.Deserialize(cursors.Value("mscloud:intune-audit")!, MicrosoftCloudKinds.IntuneAudit)!;
+ Assert.NotNull(open.WindowStart);
+ Assert.Contains("skiptoken=page2", open.Page, StringComparison.Ordinal);
+ Assert.Null(open.Committed);
+ Assert.Single(sink.Records);
+
+ sink.RefuseAfter = null;
+ await source.PollOnceAsync("intune-audit", cancellation);
+
+ // Page 2 was read again from its stored link; page 1 was not re-read and nothing was lost.
+ Assert.Equal(2, sink.Records.Count);
+ Assert.Equal(2, graph.Requests.Count(uri => uri.Query.Contains("skiptoken=page2", StringComparison.Ordinal)));
+ Assert.NotNull(MicrosoftCloudCursor.Deserialize(cursors.Value("mscloud:intune-audit")!, MicrosoftCloudKinds.IntuneAudit)!.Committed);
+ }
+
+ [Fact]
+ public async Task BackpressureOnTheFirstRecord_StoresTheOpenWindowAndReReadsTheSamePage()
+ {
+ CancellationToken cancellation = TestContext.Current.CancellationToken;
+ FakeGraph graph = new();
+ graph.AuditPages(Now);
+ MemorySink sink = new() { RefuseAfter = 0 };
+ FileTailSourceTests.MemoryCursors cursors = new();
+ FakeClock clock = new(Now);
+ MicrosoftCloudSource source = Source(graph, sink, cursors, Audit(), clock);
+
+ Assert.True((await source.PollOnceAsync("intune-audit", cancellation)).Backpressure);
+ MicrosoftCloudCursor open = MicrosoftCloudCursor.Deserialize(cursors.Value("mscloud:intune-audit")!, MicrosoftCloudKinds.IntuneAudit)!;
+ Assert.Null(open.Page);
+ Assert.Empty(sink.Records);
+
+ // Later polls keep the stored window even though the clock moved on.
+ clock.Advance(TimeSpan.FromMinutes(30));
+ sink.RefuseAfter = null;
+ await source.PollOnceAsync("intune-audit", cancellation);
+
+ Assert.Equal(2, sink.Records.Count);
+ Uri[] firstPages = [.. graph.Requests.Where(uri => !uri.Query.Contains("skiptoken", StringComparison.Ordinal))];
+ Assert.Equal(2, firstPages.Length);
+ Assert.Equal(firstPages[0], firstPages[1]);
+ }
+
+ [Fact]
+ public async Task CrashBeforePageCommit_ReReadsOnlyThatPageAfterRestart()
+ {
+ CancellationToken cancellation = TestContext.Current.CancellationToken;
+ FakeGraph graph = new();
+ graph.AuditPages(Now);
+ FileTailSourceTests.MemoryCursors durable = new();
+ MemorySink sink = new();
+ // Commits: open window (1), page 1 (2); the page 2 commit fails as a crash would.
+ CrashingCursors crashing = new(durable, failOnCommit: 3);
+ MicrosoftCloudSource first = Source(graph, sink, crashing, Audit());
+ await Assert.ThrowsAsync(() => first.PollOnceAsync("intune-audit", cancellation));
+ MicrosoftCloudCursor afterCrash = MicrosoftCloudCursor.Deserialize(durable.Value("mscloud:intune-audit")!, MicrosoftCloudKinds.IntuneAudit)!;
+ Assert.Contains("skiptoken=page2", afterCrash.Page, StringComparison.Ordinal);
+
+ MicrosoftCloudSource restarted = Source(graph, sink, durable, Audit());
+ await restarted.PollOnceAsync("intune-audit", cancellation);
+
+ // Page 2 was read twice (before and after the crash); page 1 was never read again.
+ Assert.Equal(3, sink.Records.Count);
+ Assert.Equal(sink.Records[1], sink.Records[2]);
+ Assert.Equal(2, graph.Requests.Count(uri => uri.Query.Contains("skiptoken=page2", StringComparison.Ordinal)));
+ Assert.Equal(1, graph.Requests.Count(uri => uri.AbsolutePath.EndsWith("/auditEvents", StringComparison.Ordinal) && !uri.Query.Contains("skiptoken", StringComparison.Ordinal)));
+ }
+
+ [Fact]
+ public async Task ExpiredPageLink_RestartsTheWindowFromItsFirstPage()
+ {
+ CancellationToken cancellation = TestContext.Current.CancellationToken;
+ FakeGraph graph = new();
+ graph.AuditPages(Now);
+ FileTailSourceTests.MemoryCursors cursors = new();
+ MemorySink sink = new();
+ await cursors.TryAdvanceAsync(
+ "mscloud:intune-audit",
+ 0,
+ new MicrosoftCloudCursor(1, MicrosoftCloudKinds.IntuneAudit, null, Now.AddHours(-2), Now.AddHours(-1),
+ "https://graph.microsoft.com/v1.0/deviceManagement/auditEvents?$skiptoken=expired").Serialize(),
+ Now,
+ cancellation);
+ graph.Respond(uri => uri.Query.Contains("expired", StringComparison.Ordinal), "{}", HttpStatusCode.BadRequest, first: true);
+
+ MicrosoftCloudSource source = Source(graph, sink, cursors, Audit());
+ await source.PollOnceAsync("intune-audit", cancellation);
+
+ Assert.Equal(2, sink.Records.Count);
+ Assert.Equal(1, Assert.Single(source.Snapshot()).PageRestarts);
+ }
+
+ [Fact]
+ public async Task ComplianceSnapshot_KeepsOnlyAttentionStatesAndRunsOncePerDay()
+ {
+ CancellationToken cancellation = TestContext.Current.CancellationToken;
+ FakeGraph graph = new();
+ graph.Respond(uri => uri.AbsolutePath.EndsWith("/managedDevices", StringComparison.Ordinal), Fixture("intune-managed-devices.json", Now));
+ FakeClock clock = new(Now);
+ MemorySink sink = new();
+ FileTailSourceTests.MemoryCursors cursors = new();
+ MicrosoftCloudSource source = Source(graph, sink, cursors, Compliance(), clock);
+
+ await source.PollOnceAsync("intune-compliance", cancellation);
+
+ Assert.Equal(2, sink.Records.Count);
+ Assert.DoesNotContain(sink.Records, record => record.Contains("ADELE-PHONE", StringComparison.Ordinal));
+ using JsonDocument device = JsonDocument.Parse(sink.Records[0]);
+ Assert.Equal("2026-11-22", device.RootElement.GetProperty("snapshotDate").GetString());
+ Assert.Equal("false", device.RootElement.GetProperty("isEncrypted").GetString());
+ Assert.Equal(1, Assert.Single(source.Snapshot()).OutOfScope);
+ string select = Uri.UnescapeDataString(graph.Requests[0].Query);
+ Assert.Contains("$select=id,complianceState", select, StringComparison.Ordinal);
+ Assert.DoesNotContain("deviceName", select, StringComparison.Ordinal);
+ Assert.DoesNotContain("imei", select, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("serialNumber", select, StringComparison.Ordinal);
+ Assert.DoesNotContain("phoneNumber", select, StringComparison.Ordinal);
+
+ clock.Advance(TimeSpan.FromHours(6));
+ await source.PollOnceAsync("intune-compliance", cancellation);
+ Assert.Single(graph.Requests);
+
+ clock.Advance(TimeSpan.FromHours(10));
+ await source.PollOnceAsync("intune-compliance", cancellation);
+ Assert.Equal(2, graph.Requests.Count);
+ using JsonDocument nextDay = JsonDocument.Parse(sink.Records[^1]);
+ Assert.Equal("2026-11-23", nextDay.RootElement.GetProperty("snapshotDate").GetString());
+ // A new day is a new event for the same device.
+ Assert.NotEqual(Id(sink.Records[0]), Id(sink.Records[2]));
+ }
+
+ [Fact]
+ public async Task Throttling_HonoursRetryAfterThenSucceeds()
+ {
+ CancellationToken cancellation = TestContext.Current.CancellationToken;
+ FakeGraph graph = new();
+ graph.AuditPages(Now);
+ graph.Respond(_ => true, "{}", HttpStatusCode.TooManyRequests, first: true, retryAfterSeconds: 7);
+ ManualTimeProvider clock = new(Now);
+ MemorySink sink = new();
+ MicrosoftCloudSource source = Source(graph, sink, new FileTailSourceTests.MemoryCursors(), Audit(), clock);
+
+ Task poll = source.PollOnceAsync("intune-audit", cancellation);
+ await Polling.UntilAsync(() => clock.ActiveTimers > 0, cancellation);
+ clock.Advance(TimeSpan.FromSeconds(6));
+ Assert.False(poll.IsCompleted);
+ clock.Advance(TimeSpan.FromSeconds(1));
+ await poll;
+
+ Assert.Equal(2, sink.Records.Count);
+ MicrosoftCloudInputStatus status = Assert.Single(source.Snapshot());
+ Assert.Equal(1, status.Throttled);
+ Assert.Equal(1, status.Retries);
+ }
+
+ [Fact]
+ public async Task Forbidden_FailsAtOnceWithThePermissionCodeAndNoRetry()
+ {
+ CancellationToken cancellation = TestContext.Current.CancellationToken;
+ FakeGraph graph = new();
+ graph.Respond(_ => true, """{"error":{"code":"Forbidden","message":"secret-body-marker"}}""", HttpStatusCode.Forbidden);
+ FileTailSourceTests.MemoryCursors cursors = new();
+ MicrosoftCloudSource source = Source(graph, new MemorySink(), cursors, Audit());
+
+ MicrosoftCloudException failure = await Assert.ThrowsAsync(
+ () => source.PollOnceAsync("intune-audit", cancellation));
+
+ Assert.Equal(MicrosoftCloudFailures.PermissionDenied, failure.Code);
+ Assert.DoesNotContain("secret-body-marker", failure.Message, StringComparison.Ordinal);
+ Assert.Single(graph.Requests);
+ Assert.Equal(MicrosoftCloudFailures.PermissionDenied, Assert.Single(source.Snapshot()).State);
+ Assert.Null(MicrosoftCloudCursor.Deserialize(cursors.Value("mscloud:intune-audit")!, MicrosoftCloudKinds.IntuneAudit)!.Committed);
+ }
+
+ [Fact]
+ public async Task Unauthorised_RefreshesTheTokenOnce()
+ {
+ CancellationToken cancellation = TestContext.Current.CancellationToken;
+ FakeGraph graph = new();
+ graph.AuditPages(Now);
+ graph.Respond(_ => true, "{}", HttpStatusCode.Unauthorized, first: true);
+ FakeTokens tokens = new();
+ MicrosoftCloudSource source = Source(graph, new MemorySink(), new FileTailSourceTests.MemoryCursors(), Audit(), tokens: tokens);
+
+ await source.PollOnceAsync("intune-audit", cancellation);
+
+ Assert.Equal(1, tokens.Refreshes);
+ }
+
+ [Theory]
+ [InlineData("https://evil.example/v1.0/deviceManagement/auditEvents?$skiptoken=x")]
+ [InlineData("http://graph.microsoft.com/v1.0/deviceManagement/auditEvents?$skiptoken=x")]
+ [InlineData("https://graph.microsoft.com:8443/v1.0/deviceManagement/auditEvents?$skiptoken=x")]
+ [InlineData("https://user@graph.microsoft.com/v1.0/deviceManagement/auditEvents?$skiptoken=x")]
+ public async Task NextLinkOffTheAllowedHost_IsRefusedAndNoTokenIsSent(string link)
+ {
+ CancellationToken cancellation = TestContext.Current.CancellationToken;
+ FakeGraph graph = new();
+ graph.Respond(_ => true, JsonSerializer.Serialize(new Dictionary { ["value"] = Array.Empty