mirror of
https://github.com/okieselbach/AutopilotMonitor.git
synced 2026-10-24 20:53:06 +00:00
Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f607e21c13 | |||
| 5940e9fc6a | |||
| 98cfd76232 | |||
| 09e68a614f | |||
| 88290caadc | |||
| f442dce9a4 | |||
| 4f03f39e9a | |||
| 38b667799c | |||
| a5f74d6abc | |||
| d0e09301a1 | |||
| 177915ea6b | |||
| b89008e745 | |||
| cfa1cbbed2 | |||
| aa1881ec44 | |||
| 744e35ee9b | |||
| 884b74cb8c | |||
| 67316a0fbd | |||
| 501f994c7a | |||
| c38f0cf2b0 | |||
| 729ee56bde | |||
| f0a3f04398 | |||
| 49013c3cc4 | |||
| 32cbc3620e | |||
| ae9c1b0744 |
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Agent Directives
|
||||
|
||||
- **Plan first.** Enter plan mode for any non-trivial task (3+ steps or an architectural decision) and write the spec before building. If something goes sideways, stop and re-plan instead of pushing on.
|
||||
- **Plan first.** Enter plan mode for any non-trivial task (3+ steps or an architectural decision) and write the spec before building. The plan file is `internal/work/plans/<slug>.md` from the first draft; the harness plan folder outside the repo is never the storage place, at most a copy for the approval dialog. If something goes sideways, stop and re-plan instead of pushing on.
|
||||
- **Use subagents liberally** for research, exploration, and parallel analysis — one focus each — to keep the main context clean.
|
||||
- **Verify before claiming done.** Run the tests, check the logs, show the evidence. Diff against `main` where behaviour could regress.
|
||||
- **Fix bugs autonomously.** Given a report, a failing test, or an error, resolve it — no hand-holding.
|
||||
|
||||
+1
-1
Submodule .claude/commands updated: 4bb1f7142f...6b39d14ed0
@@ -27,6 +27,10 @@ on:
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
release_notes:
|
||||
description: 'Customer-facing notes for the GitHub Release (Markdown bullets). Empty = generic fallback linking to the docs changelog'
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -326,7 +330,13 @@ jobs:
|
||||
|
||||
# First-party `gh` instead of a third-party action: this job holds contents:write,
|
||||
# id-token:write and attestations:write, so no code we do not control runs here.
|
||||
# --generate-notes appends the auto-generated notes below the body.
|
||||
# The "What's new" section comes ONLY from the release_notes input -- CI never
|
||||
# composes customer-facing text from commits. An empty input writes a generic
|
||||
# fallback that links to the docs changelog and carries the HTML-comment marker
|
||||
# below; the operator tooling scans release bodies for that marker to find the
|
||||
# last release with real notes, so the next noted release covers the gap.
|
||||
# Never rename the marker. --generate-notes is not used: it lists pull requests
|
||||
# only (Dependabot noise); the compare link to the previous tag replaces it.
|
||||
- name: Create GitHub Release
|
||||
if: inputs.create_release
|
||||
shell: pwsh
|
||||
@@ -336,19 +346,8 @@ jobs:
|
||||
RELEASE_NAME: Autopilot Monitor Agent ${{ steps.version.outputs.version }}
|
||||
RELEASE_PRERELEASE: ${{ inputs.prerelease }}
|
||||
RELEASE_ZIP: ${{ steps.artifact.outputs.versioned_zip_release }}
|
||||
RELEASE_BODY: |
|
||||
## Autopilot Monitor Agent ${{ steps.version.outputs.version }}
|
||||
|
||||
### Installation
|
||||
1. Download `AutopilotMonitor-Agent-v${{ steps.version.outputs.version }}.zip`
|
||||
2. Extract to `C:\ProgramData\AutopilotMonitor\Agent\`
|
||||
3. Run `AutopilotMonitor.Agent.exe --install` to register the Scheduled Task
|
||||
|
||||
### Included Components
|
||||
- **AutopilotMonitor.Agent.exe** - Monitoring agent (V2 release line)
|
||||
- **AutopilotMonitor.SummaryDialog.exe** - Enrollment summary dialog (WPF)
|
||||
- **version-v2.json** - Per-line version manifest
|
||||
|
||||
RELEASE_NOTES: ${{ inputs.release_notes }}
|
||||
RELEASE_BODY_TAIL: |
|
||||
### Version Info
|
||||
- **Version:** ${{ steps.version.outputs.version }}
|
||||
- **Build Number:** ${{ steps.version.outputs.build_number }}
|
||||
@@ -363,8 +362,29 @@ jobs:
|
||||
```
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$notes = "$env:RELEASE_NOTES".Trim()
|
||||
if ($notes -eq '') {
|
||||
$notes = "Minor enhancements and bug fixes. See the [Agent Changelog](https://docs.autopilotmonitor.com/changelog/agent-changelog) for details.`n<!-- release-notes: none -->"
|
||||
}
|
||||
|
||||
# Previous release for the compare link. Fail-soft: the first release has none,
|
||||
# and a listing hiccup must never fail a release.
|
||||
$prevTag = ''
|
||||
$eap = $ErrorActionPreference
|
||||
$ErrorActionPreference = 'Continue'
|
||||
try {
|
||||
$prevTag = "$(gh release list --repo $env:GITHUB_REPOSITORY --limit 1 --exclude-drafts --json tagName -q '.[0].tagName' 2>$null)".Trim()
|
||||
} catch { $prevTag = '' }
|
||||
$ErrorActionPreference = $eap
|
||||
$compare = ''
|
||||
if ($prevTag -ne '' -and $prevTag -ne $env:RELEASE_TAG) {
|
||||
$compare = "`n`n**Full changelog:** https://github.com/$env:GITHUB_REPOSITORY/compare/$prevTag...$env:RELEASE_TAG`n"
|
||||
}
|
||||
|
||||
$body = "### What's new`n$notes`n`n" + "$env:RELEASE_BODY_TAIL".TrimEnd() + $compare
|
||||
$notesFile = Join-Path $env:RUNNER_TEMP 'release-notes.md'
|
||||
Set-Content -Path $notesFile -Value $env:RELEASE_BODY -Encoding utf8 -NoNewline
|
||||
Set-Content -Path $notesFile -Value $body -Encoding utf8 -NoNewline
|
||||
|
||||
$ghArgs = @(
|
||||
'release', 'create', $env:RELEASE_TAG,
|
||||
@@ -372,8 +392,7 @@ jobs:
|
||||
'--repo', $env:GITHUB_REPOSITORY,
|
||||
'--target', $env:GITHUB_SHA,
|
||||
'--title', $env:RELEASE_NAME,
|
||||
'--notes-file', $notesFile,
|
||||
'--generate-notes'
|
||||
'--notes-file', $notesFile
|
||||
)
|
||||
if ($env:RELEASE_PRERELEASE -eq 'true') { $ghArgs += '--prerelease' }
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ name: CI
|
||||
# red run reports rather than blocks. Read the result and follow up.
|
||||
#
|
||||
# Path filters: commits that only bump a private submodule gitlink (internal/, infra/,
|
||||
# .claude/commands) or touch prose cannot change anything the suites cover, so they are
|
||||
# skipped instead of burning ~15 runner-minutes each. A gitlink bump reports the bare
|
||||
# .claude/commands), touch prose or edit another workflow cannot change anything the
|
||||
# suites cover, so they are skipped instead of burning ~15 runner-minutes each. A gitlink bump reports the bare
|
||||
# path ('internal', no trailing slash), which 'internal/**' does NOT match — both forms
|
||||
# are listed. GitHub skips only when EVERY changed path matches; a commit that touches
|
||||
# docs AND code still runs.
|
||||
@@ -30,6 +30,23 @@ on:
|
||||
- '.github/FUNDING.yml'
|
||||
- '.github/dependabot.yml'
|
||||
- '.github/assets/**'
|
||||
- '.github/codeql/**'
|
||||
- '.github/scripts/**'
|
||||
# Every other workflow: nothing here builds or tests anything CI covers. paths-ignore
|
||||
# cannot negate, so they are listed one by one; ci.yml itself stays out of the list
|
||||
# so a change to CI runs CI. A new workflow file is opt-in — add it here too.
|
||||
- '.github/workflows/bootstrap-script-gates.yml'
|
||||
- '.github/workflows/build-agent.yml'
|
||||
- '.github/workflows/build-msi.yml'
|
||||
- '.github/workflows/codeql.yml'
|
||||
- '.github/workflows/combine-rules.yml'
|
||||
- '.github/workflows/deploy-backend.yml'
|
||||
- '.github/workflows/deploy-mcp.yml'
|
||||
- '.github/workflows/deploy-web.yml'
|
||||
- '.github/workflows/indexnow-notify.yml'
|
||||
- '.github/workflows/oidc-login-test.yml'
|
||||
- '.github/workflows/pester.yml'
|
||||
- '.github/workflows/publish-scripts.yml'
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
@@ -45,6 +62,23 @@ on:
|
||||
- '.github/FUNDING.yml'
|
||||
- '.github/dependabot.yml'
|
||||
- '.github/assets/**'
|
||||
- '.github/codeql/**'
|
||||
- '.github/scripts/**'
|
||||
# Every other workflow: nothing here builds or tests anything CI covers. paths-ignore
|
||||
# cannot negate, so they are listed one by one; ci.yml itself stays out of the list
|
||||
# so a change to CI runs CI. A new workflow file is opt-in — add it here too.
|
||||
- '.github/workflows/bootstrap-script-gates.yml'
|
||||
- '.github/workflows/build-agent.yml'
|
||||
- '.github/workflows/build-msi.yml'
|
||||
- '.github/workflows/codeql.yml'
|
||||
- '.github/workflows/combine-rules.yml'
|
||||
- '.github/workflows/deploy-backend.yml'
|
||||
- '.github/workflows/deploy-mcp.yml'
|
||||
- '.github/workflows/deploy-web.yml'
|
||||
- '.github/workflows/indexnow-notify.yml'
|
||||
- '.github/workflows/oidc-login-test.yml'
|
||||
- '.github/workflows/pester.yml'
|
||||
- '.github/workflows/publish-scripts.yml'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -6,7 +6,7 @@ name: CodeQL
|
||||
# A gitlink bump reports the bare path ('internal', no trailing slash), which
|
||||
# 'internal/**' does NOT match — both forms are listed. A commit that touches docs
|
||||
# AND code still runs: GitHub skips only when EVERY changed path matches the filter.
|
||||
# Same list as ci.yml; keep them in step.
|
||||
# Same list as ci.yml except that each file leaves itself out; keep them in step.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
@@ -23,6 +23,22 @@ on:
|
||||
- '.github/FUNDING.yml'
|
||||
- '.github/dependabot.yml'
|
||||
- '.github/assets/**'
|
||||
- '.github/scripts/**'
|
||||
# Every other workflow: none of them changes the C# or TypeScript CodeQL analyzes.
|
||||
# paths-ignore cannot negate, so they are listed one by one; codeql.yml itself and
|
||||
# .github/codeql/ stay out of the list. A new workflow file is opt-in — add it here too.
|
||||
- '.github/workflows/bootstrap-script-gates.yml'
|
||||
- '.github/workflows/build-agent.yml'
|
||||
- '.github/workflows/build-msi.yml'
|
||||
- '.github/workflows/ci.yml'
|
||||
- '.github/workflows/combine-rules.yml'
|
||||
- '.github/workflows/deploy-backend.yml'
|
||||
- '.github/workflows/deploy-mcp.yml'
|
||||
- '.github/workflows/deploy-web.yml'
|
||||
- '.github/workflows/indexnow-notify.yml'
|
||||
- '.github/workflows/oidc-login-test.yml'
|
||||
- '.github/workflows/pester.yml'
|
||||
- '.github/workflows/publish-scripts.yml'
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
@@ -38,6 +54,22 @@ on:
|
||||
- '.github/FUNDING.yml'
|
||||
- '.github/dependabot.yml'
|
||||
- '.github/assets/**'
|
||||
- '.github/scripts/**'
|
||||
# Every other workflow: none of them changes the C# or TypeScript CodeQL analyzes.
|
||||
# paths-ignore cannot negate, so they are listed one by one; codeql.yml itself and
|
||||
# .github/codeql/ stay out of the list. A new workflow file is opt-in — add it here too.
|
||||
- '.github/workflows/bootstrap-script-gates.yml'
|
||||
- '.github/workflows/build-agent.yml'
|
||||
- '.github/workflows/build-msi.yml'
|
||||
- '.github/workflows/ci.yml'
|
||||
- '.github/workflows/combine-rules.yml'
|
||||
- '.github/workflows/deploy-backend.yml'
|
||||
- '.github/workflows/deploy-mcp.yml'
|
||||
- '.github/workflows/deploy-web.yml'
|
||||
- '.github/workflows/indexnow-notify.yml'
|
||||
- '.github/workflows/oidc-login-test.yml'
|
||||
- '.github/workflows/pester.yml'
|
||||
- '.github/workflows/publish-scripts.yml'
|
||||
schedule:
|
||||
# Weekly, so advisories published after a merge still surface. Deliberately
|
||||
# unfiltered — it re-analyzes the whole tree regardless of what changed, which
|
||||
|
||||
+1
-1
Submodule infra updated: 3bab9bbf83...2c2687b6ab
+1
-1
Submodule internal updated: cd935442a2...9f75da246a
@@ -2,10 +2,10 @@
|
||||
"$schema": "../schema/analyze-rule.schema.json",
|
||||
"ruleId": "ANALYZE-DEV-012",
|
||||
"title": "Device Entered Standby During Enrollment",
|
||||
"description": "Detects that the device completed a sleep, hibernate or Modern Standby episode of at least 5 minutes while the enrollment was running (system_sleep_episode event from the agent's system timeline watcher, recorded retroactively at wake from the Windows event log — pre-agent episodes are backfilled). Uses a single required condition on the episode's durationSeconds so the match is pinned to one event instance and the interpolated duration is the matched value. Short Modern Standby screen-off scenarios (under 60 s of real sleep) never emit the event, and this rule adds a 5-minute floor so brief lid-close moments do not fire it.",
|
||||
"description": "Detects that the device completed a sleep, hibernate or Modern Standby episode of at least 5 minutes while the enrollment was running (system_sleep_episode event from the agent's system timeline watcher, recorded retroactively at wake from the Windows event log). The watcher also backfills pre-agent episodes from the last 24 h for timeline context (backfilled=true); those ended before the enrollment started and are excluded via the same-event filter backfilled equals false — a separate condition could not do that, because each condition scans all events on its own and a pre-session hibernate would still satisfy the duration test. A single required condition keeps the match pinned to one event instance so the interpolated duration is the matched value. Short Modern Standby screen-off scenarios (under 60 s of real sleep) never emit the event, and this rule adds a 5-minute floor so brief lid-close moments do not fire it.",
|
||||
"severity": "info",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
@@ -23,6 +23,9 @@
|
||||
"dataField": "durationSeconds",
|
||||
"operator": "gte",
|
||||
"value": "300",
|
||||
"filterField": "backfilled",
|
||||
"filterOperator": "equals",
|
||||
"filterValue": "false",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
"$schema": "../schema/analyze-rule.schema.json",
|
||||
"ruleId": "ANALYZE-ID-004",
|
||||
"title": "Hybrid Sign-In Never Establishes Entra User Affinity",
|
||||
"description": "On a hybrid-joined device the real user reached the desktop, but the Autopilot provisioning placeholder stayed active in JoinInfo and the agent repeatedly reported the hybrid sign-in as overdue. The user session never establishes Entra user affinity (no PRT), so the Account Setup ESP re-runs on every logon and the enrollment never completes.",
|
||||
"description": "On a hybrid-joined device the real user reached the desktop, but the Intune Management Extension never acquired a Microsoft Entra user token for that user within the wait window — repeatedly across reboots when the warning recurs. Without a user token the signed-in user has no Entra user affinity: user-targeted apps and policies cannot apply, Windows Hello for Business cannot provision, and with a user ESP the Account Setup page re-runs on every logon.",
|
||||
"severity": "high",
|
||||
"category": "identity",
|
||||
"version": "1.2.0",
|
||||
"version": "2.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"trigger": "correlation",
|
||||
"evaluateOn": ["enrollment_end", "on_event:hybrid_login_pending"],
|
||||
"evaluateOn": ["enrollment_end", "on_event:entra_user_affinity_pending"],
|
||||
"baseConfidence": 60,
|
||||
"confidenceThreshold": 75,
|
||||
"preconditions": [
|
||||
@@ -17,14 +17,14 @@
|
||||
"source": "event_data",
|
||||
"eventType": "enrollment_complete",
|
||||
"operator": "not_exists",
|
||||
"description": "Suppress when the session eventually completed — a single overdue-login warning followed by a successful sign-in is normal hybrid latency, not a broken affinity."
|
||||
"description": "Suppress when the session eventually completed — a single pending-affinity warning followed by a successful token acquisition is hybrid latency, not a broken affinity."
|
||||
}
|
||||
],
|
||||
"conditions": [
|
||||
{
|
||||
"signal": "hybrid_login_overdue",
|
||||
"signal": "user_affinity_pending",
|
||||
"source": "event_type",
|
||||
"eventType": "hybrid_login_pending",
|
||||
"eventType": "entra_user_affinity_pending",
|
||||
"operator": "exists",
|
||||
"value": "",
|
||||
"required": true
|
||||
@@ -38,28 +38,27 @@
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "placeholder_still_active",
|
||||
"signal": "no_user_token",
|
||||
"source": "event_type",
|
||||
"eventType": "aad_placeholder_user_detected",
|
||||
"operator": "exists",
|
||||
"eventType": "ime_user_token_acquired",
|
||||
"operator": "not_exists",
|
||||
"value": "",
|
||||
"required": false
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"confidenceFactors": [
|
||||
{ "signal": "hybrid_login_pending", "condition": "count >= 2", "weight": 20 },
|
||||
{ "signal": "hybrid_login_pending", "condition": "count >= 3", "weight": 10 },
|
||||
{ "signal": "aad_placeholder_user_detected", "condition": "count >= 3", "weight": 10 }
|
||||
{ "signal": "entra_user_affinity_pending", "condition": "count >= 2", "weight": 20 },
|
||||
{ "signal": "entra_user_affinity_pending", "condition": "count >= 3", "weight": 10 }
|
||||
],
|
||||
"explanation": "A real user signed in and reached the desktop, but the device kept reporting the **Autopilot provisioning placeholder** as the active identity in JoinInfo and the hybrid sign-in as **overdue** — across multiple reboots. This means the signed-in user never established **Microsoft Entra user affinity** (no Primary Refresh Token), so:\n\n- the Account Setup ESP page re-appears on every logon,\n- user-targeted required apps and policies cannot settle,\n- the enrollment never reaches completion.\n\nAfter this many hours this is not normal Entra Connect sync latency — something is structurally preventing the user (or the computer object) from registering:\n\n- the computer object's `userCertificate` attribute is not syncing to Entra ID (sync scope / OU filtering),\n- the signing-in user is not synced, or their UPN does not match a verified Entra domain,\n- the device has no line of sight to a domain controller **at logon time**, so the hybrid PRT flow cannot finish,\n- time skew or a proxy blocking `login.microsoftonline.com` / `enterpriseregistration.windows.net` from the user context.\n\nA frequent variant: the user's **first sign-in happens without domain-controller reachability** — for example when a pre-logon VPN tunnel (GlobalProtect, Always On VPN, Zscaler ZPA) is not established yet at the logon screen. Windows falls back to cached credentials, the hybrid PRT flow silently never runs, and later reboots do not fix it — sessions in this state typically show repeated reboots and network flapping while the placeholder identity stays active.\n\nA visible side effect: **the Windows Hello for Business wizard never appears**, because Hello provisioning requires an Entra user token (PRT). Hello is a downstream symptom here, not the cause.",
|
||||
"explanation": "**What was measured.** A real user signed in and reached the desktop (`desktop_arrived`), and by the end of the agent's wait window the Intune Management Extension (IME) had still not acquired a **Microsoft Entra user token** for that user (`entra_user_affinity_pending`). That event lists the IME token error codes observed after the desktop (`tokenFailureCodes`) and how often the acquisition failed (`tokenFailureCount`). Each agent run reports this at most once, so a second or third occurrence means the same outcome across reboots — that repetition is what raises the confidence of this finding. No `ime_user_token_acquired` event followed in this session.\n\n**Why this means no user affinity.** IME's user check-in acquires the user token through the Windows web account manager (WAM), which needs the signed-in user's Entra identity — the Primary Refresh Token (PRT) that a hybrid sign-in establishes at logon. When that PRT was never issued, every token request fails and the user has **no Entra user affinity** on this device. Consequences:\n\n- user-targeted required apps and policies cannot apply,\n- Windows Hello for Business cannot provision (it requires a user token),\n- with a user ESP the Account Setup page re-appears on every logon instead of completing.\n\n**What this diagnosis does not use.** The Autopilot provisioning placeholder in JoinInfo (`aad_placeholder_user_detected`) is not part of this finding — on hybrid devices it can stay present through a perfectly healthy sign-in. Likewise, `dsregcmd /status` collected by the agent runs as SYSTEM and shows only the **device** join state; the per-user PRT state is visible only when the command runs as the signed-in user.\n\n**Typical causes** — something structurally prevents the user (or the computer object) from registering:\n\n- the computer object's `userCertificate` attribute is not syncing to Entra ID (sync scope / OU filtering),\n- the signing-in user is not synced, or their UPN does not match a verified Entra domain,\n- the device has no line of sight to a domain controller **at logon time**, so the hybrid PRT flow cannot finish,\n- time skew or a proxy blocking `login.microsoftonline.com` / `enterpriseregistration.windows.net` from the user context.\n\nA frequent variant: the user's **first sign-in happens without domain-controller reachability** — for example when a pre-logon VPN tunnel (GlobalProtect, Always On VPN, Zscaler ZPA) is not established yet at the logon screen. Windows falls back to cached credentials, the hybrid PRT flow silently never runs, and later reboots do not fix it.\n\nThe `device_registration_event` entries in the timeline (User Device Registration events 304/305) carry the OS-side record of the failed registration; the error codes in `entra_user_affinity_pending` carry the token side. A missing Windows Hello for Business wizard is a downstream symptom here, not the cause.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Verify user affinity on the device",
|
||||
"steps": [
|
||||
"Sign in as the affected user and run: dsregcmd /status — under 'SSO State' the value AzureAdPrt must be YES. NO means the user has no Entra token and this diagnosis is confirmed.",
|
||||
"Also check 'Device State': AzureAdJoined = YES and DomainJoined = YES are expected for hybrid join.",
|
||||
"Check Event Viewer: Applications and Services Logs > Microsoft > Windows > User Device Registration > Admin for PRT / registration errors (e.g. event 304/305/362).",
|
||||
"Enable the gather rules 'Collect dsregcmd join status' so future sessions capture this state automatically."
|
||||
"Also check 'Device State': AzureAdJoined = YES and DomainJoined = YES are expected for hybrid join — they prove the device join only, not the user's registration.",
|
||||
"Check Event Viewer: Applications and Services Logs > Microsoft > Windows > User Device Registration > Admin for PRT / registration errors (e.g. event 304/305/362). The device_registration_event entries (304/305) in the session timeline carry the same OS-side failure record.",
|
||||
"Enable the gather rule GATHER-DEVICE-006 (dsregcmd /status at the moment of the finding — device state only, the agent runs as SYSTEM). GATHER-DEVICE-007 and GATHER-DEVICE-008 (Microsoft-Windows-AAD/Operational events 1098 and 1097 at the same moment) are on by default."
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
+21
-23
@@ -1772,10 +1772,10 @@
|
||||
{
|
||||
"ruleId": "ANALYZE-DEV-012",
|
||||
"title": "Device Entered Standby During Enrollment",
|
||||
"description": "Detects that the device completed a sleep, hibernate or Modern Standby episode of at least 5 minutes while the enrollment was running (system_sleep_episode event from the agent's system timeline watcher, recorded retroactively at wake from the Windows event log — pre-agent episodes are backfilled). Uses a single required condition on the episode's durationSeconds so the match is pinned to one event instance and the interpolated duration is the matched value. Short Modern Standby screen-off scenarios (under 60 s of real sleep) never emit the event, and this rule adds a 5-minute floor so brief lid-close moments do not fire it.",
|
||||
"description": "Detects that the device completed a sleep, hibernate or Modern Standby episode of at least 5 minutes while the enrollment was running (system_sleep_episode event from the agent's system timeline watcher, recorded retroactively at wake from the Windows event log). The watcher also backfills pre-agent episodes from the last 24 h for timeline context (backfilled=true); those ended before the enrollment started and are excluded via the same-event filter backfilled equals false — a separate condition could not do that, because each condition scans all events on its own and a pre-session hibernate would still satisfy the duration test. A single required condition keeps the match pinned to one event instance so the interpolated duration is the matched value. Short Modern Standby screen-off scenarios (under 60 s of real sleep) never emit the event, and this rule adds a 5-minute floor so brief lid-close moments do not fire it.",
|
||||
"severity": "info",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
@@ -1793,6 +1793,9 @@
|
||||
"dataField": "durationSeconds",
|
||||
"operator": "gte",
|
||||
"value": "300",
|
||||
"filterField": "backfilled",
|
||||
"filterOperator": "equals",
|
||||
"filterValue": "false",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
@@ -2937,16 +2940,16 @@
|
||||
{
|
||||
"ruleId": "ANALYZE-ID-004",
|
||||
"title": "Hybrid Sign-In Never Establishes Entra User Affinity",
|
||||
"description": "On a hybrid-joined device the real user reached the desktop, but the Autopilot provisioning placeholder stayed active in JoinInfo and the agent repeatedly reported the hybrid sign-in as overdue. The user session never establishes Entra user affinity (no PRT), so the Account Setup ESP re-runs on every logon and the enrollment never completes.",
|
||||
"description": "On a hybrid-joined device the real user reached the desktop, but the Intune Management Extension never acquired a Microsoft Entra user token for that user within the wait window — repeatedly across reboots when the warning recurs. Without a user token the signed-in user has no Entra user affinity: user-targeted apps and policies cannot apply, Windows Hello for Business cannot provision, and with a user ESP the Account Setup page re-runs on every logon.",
|
||||
"severity": "high",
|
||||
"category": "identity",
|
||||
"version": "1.2.0",
|
||||
"version": "2.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"trigger": "correlation",
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
"on_event:hybrid_login_pending"
|
||||
"on_event:entra_user_affinity_pending"
|
||||
],
|
||||
"baseConfidence": 60,
|
||||
"confidenceThreshold": 75,
|
||||
@@ -2955,14 +2958,14 @@
|
||||
"source": "event_data",
|
||||
"eventType": "enrollment_complete",
|
||||
"operator": "not_exists",
|
||||
"description": "Suppress when the session eventually completed — a single overdue-login warning followed by a successful sign-in is normal hybrid latency, not a broken affinity."
|
||||
"description": "Suppress when the session eventually completed — a single pending-affinity warning followed by a successful token acquisition is hybrid latency, not a broken affinity."
|
||||
}
|
||||
],
|
||||
"conditions": [
|
||||
{
|
||||
"signal": "hybrid_login_overdue",
|
||||
"signal": "user_affinity_pending",
|
||||
"source": "event_type",
|
||||
"eventType": "hybrid_login_pending",
|
||||
"eventType": "entra_user_affinity_pending",
|
||||
"operator": "exists",
|
||||
"value": "",
|
||||
"required": true
|
||||
@@ -2976,40 +2979,35 @@
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "placeholder_still_active",
|
||||
"signal": "no_user_token",
|
||||
"source": "event_type",
|
||||
"eventType": "aad_placeholder_user_detected",
|
||||
"operator": "exists",
|
||||
"eventType": "ime_user_token_acquired",
|
||||
"operator": "not_exists",
|
||||
"value": "",
|
||||
"required": false
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"confidenceFactors": [
|
||||
{
|
||||
"signal": "hybrid_login_pending",
|
||||
"signal": "entra_user_affinity_pending",
|
||||
"condition": "count >= 2",
|
||||
"weight": 20
|
||||
},
|
||||
{
|
||||
"signal": "hybrid_login_pending",
|
||||
"condition": "count >= 3",
|
||||
"weight": 10
|
||||
},
|
||||
{
|
||||
"signal": "aad_placeholder_user_detected",
|
||||
"signal": "entra_user_affinity_pending",
|
||||
"condition": "count >= 3",
|
||||
"weight": 10
|
||||
}
|
||||
],
|
||||
"explanation": "A real user signed in and reached the desktop, but the device kept reporting the **Autopilot provisioning placeholder** as the active identity in JoinInfo and the hybrid sign-in as **overdue** — across multiple reboots. This means the signed-in user never established **Microsoft Entra user affinity** (no Primary Refresh Token), so:\n\n- the Account Setup ESP page re-appears on every logon,\n- user-targeted required apps and policies cannot settle,\n- the enrollment never reaches completion.\n\nAfter this many hours this is not normal Entra Connect sync latency — something is structurally preventing the user (or the computer object) from registering:\n\n- the computer object's `userCertificate` attribute is not syncing to Entra ID (sync scope / OU filtering),\n- the signing-in user is not synced, or their UPN does not match a verified Entra domain,\n- the device has no line of sight to a domain controller **at logon time**, so the hybrid PRT flow cannot finish,\n- time skew or a proxy blocking `login.microsoftonline.com` / `enterpriseregistration.windows.net` from the user context.\n\nA frequent variant: the user's **first sign-in happens without domain-controller reachability** — for example when a pre-logon VPN tunnel (GlobalProtect, Always On VPN, Zscaler ZPA) is not established yet at the logon screen. Windows falls back to cached credentials, the hybrid PRT flow silently never runs, and later reboots do not fix it — sessions in this state typically show repeated reboots and network flapping while the placeholder identity stays active.\n\nA visible side effect: **the Windows Hello for Business wizard never appears**, because Hello provisioning requires an Entra user token (PRT). Hello is a downstream symptom here, not the cause.",
|
||||
"explanation": "**What was measured.** A real user signed in and reached the desktop (`desktop_arrived`), and by the end of the agent's wait window the Intune Management Extension (IME) had still not acquired a **Microsoft Entra user token** for that user (`entra_user_affinity_pending`). That event lists the IME token error codes observed after the desktop (`tokenFailureCodes`) and how often the acquisition failed (`tokenFailureCount`). Each agent run reports this at most once, so a second or third occurrence means the same outcome across reboots — that repetition is what raises the confidence of this finding. No `ime_user_token_acquired` event followed in this session.\n\n**Why this means no user affinity.** IME's user check-in acquires the user token through the Windows web account manager (WAM), which needs the signed-in user's Entra identity — the Primary Refresh Token (PRT) that a hybrid sign-in establishes at logon. When that PRT was never issued, every token request fails and the user has **no Entra user affinity** on this device. Consequences:\n\n- user-targeted required apps and policies cannot apply,\n- Windows Hello for Business cannot provision (it requires a user token),\n- with a user ESP the Account Setup page re-appears on every logon instead of completing.\n\n**What this diagnosis does not use.** The Autopilot provisioning placeholder in JoinInfo (`aad_placeholder_user_detected`) is not part of this finding — on hybrid devices it can stay present through a perfectly healthy sign-in. Likewise, `dsregcmd /status` collected by the agent runs as SYSTEM and shows only the **device** join state; the per-user PRT state is visible only when the command runs as the signed-in user.\n\n**Typical causes** — something structurally prevents the user (or the computer object) from registering:\n\n- the computer object's `userCertificate` attribute is not syncing to Entra ID (sync scope / OU filtering),\n- the signing-in user is not synced, or their UPN does not match a verified Entra domain,\n- the device has no line of sight to a domain controller **at logon time**, so the hybrid PRT flow cannot finish,\n- time skew or a proxy blocking `login.microsoftonline.com` / `enterpriseregistration.windows.net` from the user context.\n\nA frequent variant: the user's **first sign-in happens without domain-controller reachability** — for example when a pre-logon VPN tunnel (GlobalProtect, Always On VPN, Zscaler ZPA) is not established yet at the logon screen. Windows falls back to cached credentials, the hybrid PRT flow silently never runs, and later reboots do not fix it.\n\nThe `device_registration_event` entries in the timeline (User Device Registration events 304/305) carry the OS-side record of the failed registration; the error codes in `entra_user_affinity_pending` carry the token side. A missing Windows Hello for Business wizard is a downstream symptom here, not the cause.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Verify user affinity on the device",
|
||||
"steps": [
|
||||
"Sign in as the affected user and run: dsregcmd /status — under 'SSO State' the value AzureAdPrt must be YES. NO means the user has no Entra token and this diagnosis is confirmed.",
|
||||
"Also check 'Device State': AzureAdJoined = YES and DomainJoined = YES are expected for hybrid join.",
|
||||
"Check Event Viewer: Applications and Services Logs > Microsoft > Windows > User Device Registration > Admin for PRT / registration errors (e.g. event 304/305/362).",
|
||||
"Enable the gather rules 'Collect dsregcmd join status' so future sessions capture this state automatically."
|
||||
"Also check 'Device State': AzureAdJoined = YES and DomainJoined = YES are expected for hybrid join — they prove the device join only, not the user's registration.",
|
||||
"Check Event Viewer: Applications and Services Logs > Microsoft > Windows > User Device Registration > Admin for PRT / registration errors (e.g. event 304/305/362). The device_registration_event entries (304/305) in the session timeline carry the same OS-side failure record.",
|
||||
"Enable the gather rule GATHER-DEVICE-006 (dsregcmd /status at the moment of the finding — device state only, the agent runs as SYSTEM). GATHER-DEVICE-007 and GATHER-DEVICE-008 (Microsoft-Windows-AAD/Operational events 1098 and 1097 at the same moment) are on by default."
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
+52
-4
@@ -130,16 +130,16 @@
|
||||
},
|
||||
{
|
||||
"ruleId": "GATHER-DEVICE-006",
|
||||
"title": "Collect dsregcmd join status on overdue hybrid sign-in",
|
||||
"description": "Runs dsregcmd /status the moment the agent reports a hybrid sign-in as overdue (hybrid_login_pending), capturing the Entra join and registration state at exactly the point where the problem is detected. Complements GATHER-DEVICE-001 (snapshot on entering Account Setup). Note: the agent runs as SYSTEM, so the output shows device join state — the per-user SSO/PRT state still requires running dsregcmd as the signed-in user.",
|
||||
"title": "Collect dsregcmd join status on pending user affinity",
|
||||
"description": "Runs dsregcmd /status the moment the agent reports that the signed-in user still has no Entra user token (entra_user_affinity_pending), capturing the device join and registration state at exactly the point where ANALYZE-ID-004 draws its evidence. Complements GATHER-DEVICE-001 (snapshot on entering Account Setup). Note: the agent runs as SYSTEM, so the output shows device join state — the per-user SSO/PRT state still requires running dsregcmd as the signed-in user.",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": false,
|
||||
"collectorType": "command_allowlisted",
|
||||
"target": "dsregcmd /status",
|
||||
"trigger": "on_event",
|
||||
"triggerEventType": "hybrid_login_pending",
|
||||
"triggerEventType": "entra_user_affinity_pending",
|
||||
"outputEventType": "gather_dsregcmd_status",
|
||||
"outputSeverity": "Info",
|
||||
"tags": [
|
||||
@@ -149,6 +149,54 @@
|
||||
"hybrid"
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "GATHER-DEVICE-007",
|
||||
"title": "Collect Entra operational log on pending user affinity (event 1098)",
|
||||
"description": "Collects the most recent Entra token-broker operational events with ID 1098 from Microsoft-Windows-AAD/Operational the moment the agent reports that the signed-in user still has no Entra user token (entra_user_affinity_pending). Captures the OS-side token-broker record at exactly the point where ANALYZE-ID-004 draws its evidence. The event log collector filters on one event ID per rule; GATHER-DEVICE-008 collects event 1097 from the same channel.",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"collectorType": "eventlog",
|
||||
"target": "Microsoft-Windows-AAD/Operational",
|
||||
"parameters": {
|
||||
"eventId": "1098",
|
||||
"maxEntries": "20"
|
||||
},
|
||||
"trigger": "on_event",
|
||||
"triggerEventType": "entra_user_affinity_pending",
|
||||
"outputEventType": "gather_aad_operational_events",
|
||||
"outputSeverity": "Warning",
|
||||
"tags": [
|
||||
"device",
|
||||
"entra",
|
||||
"hybrid"
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "GATHER-DEVICE-008",
|
||||
"title": "Collect Entra operational log on pending user affinity (event 1097)",
|
||||
"description": "Collects the most recent Entra token-broker operational events with ID 1097 from Microsoft-Windows-AAD/Operational the moment the agent reports that the signed-in user still has no Entra user token (entra_user_affinity_pending). Captures the OS-side token-broker record at exactly the point where ANALYZE-ID-004 draws its evidence. The event log collector filters on one event ID per rule; GATHER-DEVICE-007 collects event 1098 from the same channel.",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"collectorType": "eventlog",
|
||||
"target": "Microsoft-Windows-AAD/Operational",
|
||||
"parameters": {
|
||||
"eventId": "1097",
|
||||
"maxEntries": "20"
|
||||
},
|
||||
"trigger": "on_event",
|
||||
"triggerEventType": "entra_user_affinity_pending",
|
||||
"outputEventType": "gather_aad_operational_events",
|
||||
"outputSeverity": "Warning",
|
||||
"tags": [
|
||||
"device",
|
||||
"entra",
|
||||
"hybrid"
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "GATHER-ENROLL-001",
|
||||
"title": "MDM enrollment diagnostic events",
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
{
|
||||
"$schema": "../schema/gather-rule.schema.json",
|
||||
"ruleId": "GATHER-DEVICE-006",
|
||||
"title": "Collect dsregcmd join status on overdue hybrid sign-in",
|
||||
"description": "Runs dsregcmd /status the moment the agent reports a hybrid sign-in as overdue (hybrid_login_pending), capturing the Entra join and registration state at exactly the point where the problem is detected. Complements GATHER-DEVICE-001 (snapshot on entering Account Setup). Note: the agent runs as SYSTEM, so the output shows device join state — the per-user SSO/PRT state still requires running dsregcmd as the signed-in user.",
|
||||
"title": "Collect dsregcmd join status on pending user affinity",
|
||||
"description": "Runs dsregcmd /status the moment the agent reports that the signed-in user still has no Entra user token (entra_user_affinity_pending), capturing the device join and registration state at exactly the point where ANALYZE-ID-004 draws its evidence. Complements GATHER-DEVICE-001 (snapshot on entering Account Setup). Note: the agent runs as SYSTEM, so the output shows device join state — the per-user SSO/PRT state still requires running dsregcmd as the signed-in user.",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": false,
|
||||
"collectorType": "command_allowlisted",
|
||||
"target": "dsregcmd /status",
|
||||
"trigger": "on_event",
|
||||
"triggerEventType": "hybrid_login_pending",
|
||||
"triggerEventType": "entra_user_affinity_pending",
|
||||
"outputEventType": "gather_dsregcmd_status",
|
||||
"outputSeverity": "Info",
|
||||
"tags": ["device", "entra", "join", "hybrid"]
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "../schema/gather-rule.schema.json",
|
||||
"ruleId": "GATHER-DEVICE-007",
|
||||
"title": "Collect Entra operational log on pending user affinity (event 1098)",
|
||||
"description": "Collects the most recent Entra token-broker operational events with ID 1098 from Microsoft-Windows-AAD/Operational the moment the agent reports that the signed-in user still has no Entra user token (entra_user_affinity_pending). Captures the OS-side token-broker record at exactly the point where ANALYZE-ID-004 draws its evidence. The event log collector filters on one event ID per rule; GATHER-DEVICE-008 collects event 1097 from the same channel.",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"collectorType": "eventlog",
|
||||
"target": "Microsoft-Windows-AAD/Operational",
|
||||
"parameters": {
|
||||
"eventId": "1098",
|
||||
"maxEntries": "20"
|
||||
},
|
||||
"trigger": "on_event",
|
||||
"triggerEventType": "entra_user_affinity_pending",
|
||||
"outputEventType": "gather_aad_operational_events",
|
||||
"outputSeverity": "Warning",
|
||||
"tags": ["device", "entra", "hybrid"]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "../schema/gather-rule.schema.json",
|
||||
"ruleId": "GATHER-DEVICE-008",
|
||||
"title": "Collect Entra operational log on pending user affinity (event 1097)",
|
||||
"description": "Collects the most recent Entra token-broker operational events with ID 1097 from Microsoft-Windows-AAD/Operational the moment the agent reports that the signed-in user still has no Entra user token (entra_user_affinity_pending). Captures the OS-side token-broker record at exactly the point where ANALYZE-ID-004 draws its evidence. The event log collector filters on one event ID per rule; GATHER-DEVICE-007 collects event 1098 from the same channel.",
|
||||
"category": "device",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"collectorType": "eventlog",
|
||||
"target": "Microsoft-Windows-AAD/Operational",
|
||||
"parameters": {
|
||||
"eventId": "1097",
|
||||
"maxEntries": "20"
|
||||
},
|
||||
"trigger": "on_event",
|
||||
"triggerEventType": "entra_user_affinity_pending",
|
||||
"outputEventType": "gather_aad_operational_events",
|
||||
"outputSeverity": "Warning",
|
||||
"tags": ["device", "entra", "hybrid"]
|
||||
}
|
||||
@@ -168,7 +168,7 @@
|
||||
},
|
||||
"source": {
|
||||
"type": "string",
|
||||
"description": "Source of the signal.",
|
||||
"description": "Source of the signal. phase_duration and app_install_duration never derive a duration from an IME-log timestamp whose sourceOffsetOrigin is reader-zone-fallback (writer timezone unknown to the agent): such a condition evaluates false with evidence timestampProvenance=reader-zone-fallback.",
|
||||
"enum": ["event_type", "event_data", "event_data_array", "phase_duration", "event_count", "app_install_duration", "event_correlation", "clock_skew"]
|
||||
},
|
||||
"skewMetric": {
|
||||
@@ -204,16 +204,16 @@
|
||||
},
|
||||
"filterField": {
|
||||
"type": "string",
|
||||
"description": "For event_count only: optional value filter — only events whose filterField satisfies filterOperator/filterValue are counted (e.g. count only performance_snapshot events with memory_used_percent > 90). Applies before counting for both count_gte and count_per_group_gte."
|
||||
"description": "Optional same-event value filter for event_count, event_data and event_data_array: only events whose filterField satisfies filterOperator/filterValue are considered. For event_count it applies before counting (both count_gte and count_per_group_gte, e.g. count only performance_snapshot events with memory_used_percent > 90). For event_data/event_data_array the filter and the main dataField/operator test are evaluated on the SAME event instance — the only way to pin two fields of one event together, since separate conditions each scan all events independently (e.g. system_sleep_episode with durationSeconds gte 300 AND backfilled equals false)."
|
||||
},
|
||||
"filterOperator": {
|
||||
"type": "string",
|
||||
"description": "Operator for the event_count value filter.",
|
||||
"description": "Operator for the same-event value filter. Same vocabulary as operator.",
|
||||
"enum": ["equals", "not_equals", "contains", "not_contains", "regex", "not_regex", "gt", "lt", "gte", "lte", "exists", "not_exists", "in", "not_in"]
|
||||
},
|
||||
"filterValue": {
|
||||
"type": "string",
|
||||
"description": "Value for the event_count value filter."
|
||||
"description": "Value for the same-event value filter. Boolean values are stringified (\"true\"/\"false\")."
|
||||
},
|
||||
"correlateEventType": {
|
||||
"type": "string",
|
||||
|
||||
@@ -34,6 +34,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests
|
||||
new Regex("\\[\"eventType\"\\]\\s*=\\s*\"([a-z][a-z0-9_]*)\"", RegexOptions.Compiled),
|
||||
};
|
||||
|
||||
// Multi-line callback shape (2026-09-04, D-072 gap): `OnTraceEvent?.Invoke(` at the end
|
||||
// of one line, the event-type literal alone on the NEXT line. The single-line patterns
|
||||
// above never saw `desktop_real_user_detected` / `desktop_excluded_user` this way.
|
||||
private static readonly Regex InvokeOpener = new Regex("\\.Invoke\\(\\s*$", RegexOptions.Compiled);
|
||||
private static readonly Regex BareLiteralLine = new Regex("^\\s*\"([a-z][a-z0-9_]*)\"\\s*,?\\s*$", RegexOptions.Compiled);
|
||||
|
||||
// The reducer/param key name itself ("eventType") and the like are not event types.
|
||||
private static readonly HashSet<string> NotEventTypes = new(StringComparer.Ordinal)
|
||||
{
|
||||
@@ -59,33 +65,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests
|
||||
Assert.True(Directory.Exists(full), $"V2 source dir not found: {full}");
|
||||
|
||||
foreach (var file in EnumerateSourceFiles(full))
|
||||
{
|
||||
var lines = File.ReadAllLines(file);
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
var line = lines[i];
|
||||
var trimmed = line.TrimStart();
|
||||
|
||||
// Skip comments and const DEFINITIONS (Constants/DeadlineNames key names etc.).
|
||||
if (trimmed.StartsWith("//") || trimmed.StartsWith("*") || trimmed.StartsWith("///"))
|
||||
continue;
|
||||
if (line.Contains("const ")) continue;
|
||||
|
||||
foreach (var pattern in EmitPatterns)
|
||||
{
|
||||
foreach (Match m in pattern.Matches(line))
|
||||
{
|
||||
var literal = m.Groups[1].Value;
|
||||
if (NotEventTypes.Contains(literal)) continue;
|
||||
if (!known.Contains(literal))
|
||||
{
|
||||
offenders.Add(
|
||||
$"{Path.GetFileName(file)}:{i + 1} \"{literal}\" -> {line.Trim()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
offenders.AddRange(FindOffenders(Path.GetFileName(file), File.ReadAllLines(file), known));
|
||||
}
|
||||
|
||||
Assert.True(
|
||||
@@ -95,6 +75,65 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests
|
||||
string.Join("\n ", offenders));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Guard_detects_multiline_Invoke_literal()
|
||||
{
|
||||
// Mutation proof for the multi-line shape: a synthetic emit site with an unknown
|
||||
// literal on the line after `OnTraceEvent?.Invoke(` must be reported; the same
|
||||
// shape with a known type must not.
|
||||
var known = new HashSet<string>(StringComparer.Ordinal) { "desktop_arrived" };
|
||||
string[] bad =
|
||||
{
|
||||
" OnTraceEvent?.Invoke(",
|
||||
" \"desktop_not_a_real_type\",",
|
||||
" $\"Real user desktop detected\",",
|
||||
};
|
||||
string[] good =
|
||||
{
|
||||
" OnTraceEvent?.Invoke(",
|
||||
" \"desktop_arrived\",",
|
||||
};
|
||||
|
||||
var offender = Assert.Single(FindOffenders("X.cs", bad, known));
|
||||
Assert.Contains("desktop_not_a_real_type", offender);
|
||||
Assert.Empty(FindOffenders("X.cs", good, known));
|
||||
}
|
||||
|
||||
private static List<string> FindOffenders(string fileName, string[] lines, HashSet<string> known)
|
||||
{
|
||||
var offenders = new List<string>();
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
var line = lines[i];
|
||||
var trimmed = line.TrimStart();
|
||||
|
||||
// Skip comments and const DEFINITIONS (Constants/DeadlineNames key names etc.).
|
||||
if (trimmed.StartsWith("//") || trimmed.StartsWith("*") || trimmed.StartsWith("///"))
|
||||
continue;
|
||||
if (line.Contains("const ")) continue;
|
||||
|
||||
foreach (var pattern in EmitPatterns)
|
||||
{
|
||||
foreach (Match m in pattern.Matches(line))
|
||||
Check(m.Groups[1].Value, line, i);
|
||||
}
|
||||
|
||||
if (i > 0 && InvokeOpener.IsMatch(lines[i - 1]))
|
||||
{
|
||||
var bare = BareLiteralLine.Match(line);
|
||||
if (bare.Success) Check(bare.Groups[1].Value, line, i);
|
||||
}
|
||||
}
|
||||
return offenders;
|
||||
|
||||
void Check(string literal, string line, int index)
|
||||
{
|
||||
if (NotEventTypes.Contains(literal)) return;
|
||||
if (!known.Contains(literal))
|
||||
offenders.Add($"{fileName}:{index + 1} \"{literal}\" -> {line.Trim()}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>All string-const values declared on <see cref="Constants.EventTypes"/>.</summary>
|
||||
private static HashSet<string> KnownEventTypes()
|
||||
{
|
||||
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Linq;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals;
|
||||
using AutopilotMonitor.Agent.V2.Core.Orchestration;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Orchestration;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using SharedEventTypes = AutopilotMonitor.Shared.Constants.EventTypes;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring
|
||||
{
|
||||
/// <summary>
|
||||
/// Entra user affinity after the real-user desktop (2026-09-04, session a7140f98). The
|
||||
/// contracts that matter: arm only on Hybrid devices and only at the desktop; the first
|
||||
/// IME user-token line AFTER the desktop cancels and posts <c>ime_user_token_acquired</c>;
|
||||
/// token lines from before the desktop (device phase) are ignored; the timer posts
|
||||
/// <c>entra_user_affinity_pending</c> with the failure codes seen since the desktop; both
|
||||
/// emissions are single-shot per process.
|
||||
/// </summary>
|
||||
public sealed class EntraUserAffinityDetectorTests
|
||||
{
|
||||
private static readonly DateTime Fixed = new DateTime(2026, 9, 4, 13, 54, 6, DateTimeKind.Utc);
|
||||
|
||||
private sealed class Fixture : IDisposable
|
||||
{
|
||||
public TempDirectory Tmp { get; } = new TempDirectory();
|
||||
public AgentLogger Logger { get; }
|
||||
public FakeSignalIngressSink Ingress { get; } = new FakeSignalIngressSink();
|
||||
public VirtualClock Clock { get; } = new VirtualClock(Fixed);
|
||||
public InformationalEventPost Post { get; }
|
||||
public bool Hybrid { get; set; } = true;
|
||||
public bool PlaceholderActive { get; set; } = true;
|
||||
|
||||
public Fixture()
|
||||
{
|
||||
Logger = new AgentLogger(Tmp.Path, AgentLogLevel.Info);
|
||||
Post = new InformationalEventPost(Ingress, Clock);
|
||||
}
|
||||
|
||||
public EntraUserAffinityDetector Build() => new EntraUserAffinityDetector(
|
||||
Post, Logger,
|
||||
isHybridJoinProbe: () => Hybrid,
|
||||
placeholderActiveProbe: () => PlaceholderActive,
|
||||
delay: TimeSpan.FromMinutes(10),
|
||||
utcNow: () => Clock.UtcNow);
|
||||
|
||||
public void Dispose() => Tmp.Dispose();
|
||||
}
|
||||
|
||||
private static FakeSignalIngressSink.PostedSignal? Find(FakeSignalIngressSink ingress, string eventType) =>
|
||||
ingress.Posted.FirstOrDefault(p =>
|
||||
p.Kind == DecisionSignalKind.InformationalEvent
|
||||
&& p.Payload != null
|
||||
&& p.Payload.TryGetValue(SignalPayloadKeys.EventType, out var et)
|
||||
&& et == eventType);
|
||||
|
||||
[Fact]
|
||||
public void Desktop_on_hybrid_device_arms()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
|
||||
Assert.True(d.IsArmedForTest);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Desktop_on_non_hybrid_device_does_not_arm()
|
||||
{
|
||||
using var f = new Fixture { Hybrid = false };
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.TriggerFromTest();
|
||||
|
||||
Assert.False(d.IsArmedForTest);
|
||||
Assert.Null(Find(f.Ingress, SharedEventTypes.EntraUserAffinityPending));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Timer_without_token_emits_pending_with_failure_codes()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.NotifyTokenFailureLine("3399548929", f.Clock.UtcNow.AddMinutes(1));
|
||||
d.NotifyTokenFailureLine("3399548929", f.Clock.UtcNow.AddMinutes(3));
|
||||
d.NotifyTokenFailureLine("3400073247", f.Clock.UtcNow.AddMinutes(5));
|
||||
f.Clock.Advance(TimeSpan.FromMinutes(10));
|
||||
d.TriggerFromTest();
|
||||
|
||||
var pending = Find(f.Ingress, SharedEventTypes.EntraUserAffinityPending);
|
||||
Assert.NotNull(pending);
|
||||
Assert.Equal("Warning", pending!.Payload![SignalPayloadKeys.Severity]);
|
||||
Assert.Equal("true", pending.Payload[SignalPayloadKeys.ImmediateUpload]);
|
||||
Assert.Equal("EntraUserAffinityDetector", pending.Payload[SignalPayloadKeys.Source]);
|
||||
Assert.Equal("10", pending.Payload["delayMinutes"]);
|
||||
Assert.Equal("timer_fired", pending.Payload["reason"]);
|
||||
Assert.Equal("3", pending.Payload["tokenFailureCount"]);
|
||||
Assert.Equal("3399548929,3400073247", pending.Payload["tokenFailureCodes"]);
|
||||
Assert.Equal("true", pending.Payload["placeholderActive"]);
|
||||
Assert.Equal("10.0", pending.Payload["minutesSinceDesktop"]);
|
||||
Assert.True(d.HasFiredForTest);
|
||||
Assert.Null(Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Token_after_desktop_cancels_and_posts_token_acquired()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.NotifyTokenFailureLine("3399548929", f.Clock.UtcNow.AddSeconds(30));
|
||||
var tokenAt = f.Clock.UtcNow.AddMinutes(3.7);
|
||||
d.NotifyUserTokenAcquired(tokenAt);
|
||||
f.Clock.Advance(TimeSpan.FromMinutes(10));
|
||||
d.TriggerFromTest();
|
||||
|
||||
var acquired = Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired);
|
||||
Assert.NotNull(acquired);
|
||||
Assert.Equal("Info", acquired!.Payload![SignalPayloadKeys.Severity]);
|
||||
Assert.Equal("3.7", acquired.Payload["minutesAfterDesktop"]);
|
||||
Assert.Equal("1", acquired.Payload["tokenFailuresBeforeSuccess"]);
|
||||
Assert.Equal(tokenAt, acquired.OccurredAtUtc);
|
||||
Assert.True(d.TokenAcquiredPostedForTest);
|
||||
Assert.False(d.HasFiredForTest);
|
||||
Assert.Null(Find(f.Ingress, SharedEventTypes.EntraUserAffinityPending));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Token_lines_from_before_the_desktop_are_ignored()
|
||||
{
|
||||
// Device-phase token lines ("Failed to get AAD token" is routine there; a success
|
||||
// can be the device check-in) must neither count nor cancel — the 2-min tolerance
|
||||
// only covers the desktop poll interval.
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.NotifyUserTokenAcquired(f.Clock.UtcNow.AddMinutes(-20));
|
||||
d.NotifyTokenFailureLine("3399548929", f.Clock.UtcNow.AddMinutes(-15));
|
||||
f.Clock.Advance(TimeSpan.FromMinutes(10));
|
||||
d.TriggerFromTest();
|
||||
|
||||
Assert.Null(Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired));
|
||||
var pending = Find(f.Ingress, SharedEventTypes.EntraUserAffinityPending);
|
||||
Assert.NotNull(pending);
|
||||
Assert.Equal("0", pending!.Payload!["tokenFailureCount"]);
|
||||
Assert.Equal(string.Empty, pending.Payload["tokenFailureCodes"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Token_within_desktop_poll_tolerance_counts_as_after_desktop()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.NotifyUserTokenAcquired(f.Clock.UtcNow.AddSeconds(-90));
|
||||
|
||||
Assert.NotNull(Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired));
|
||||
Assert.Equal("0.0", Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired)!.Payload!["minutesAfterDesktop"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Token_without_arm_is_ignored()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyUserTokenAcquired(f.Clock.UtcNow);
|
||||
|
||||
Assert.Null(Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pending_fires_once_and_a_late_token_still_resolves_it_once()
|
||||
{
|
||||
// A token that arrives AFTER the warning is the most useful thing the timeline can
|
||||
// show ("affinity came late") and lets the backend rule drop the finding — so it is
|
||||
// posted, but like the warning only once per process.
|
||||
using var f = new Fixture();
|
||||
using var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.NotifyRealUserDesktop();
|
||||
f.Clock.Advance(TimeSpan.FromMinutes(10));
|
||||
d.TriggerFromTest();
|
||||
d.TriggerFromTest();
|
||||
d.NotifyUserTokenAcquired(f.Clock.UtcNow);
|
||||
d.NotifyUserTokenAcquired(f.Clock.UtcNow.AddMinutes(1));
|
||||
|
||||
Assert.Single(f.Ingress.Posted, p =>
|
||||
p.Payload != null && p.Payload.TryGetValue(SignalPayloadKeys.EventType, out var et)
|
||||
&& et == SharedEventTypes.EntraUserAffinityPending);
|
||||
Assert.Single(f.Ingress.Posted, p =>
|
||||
p.Payload != null && p.Payload.TryGetValue(SignalPayloadKeys.EventType, out var et)
|
||||
&& et == SharedEventTypes.ImeUserTokenAcquired);
|
||||
Assert.Equal("10.0", Find(f.Ingress, SharedEventTypes.ImeUserTokenAcquired)!.Payload!["minutesAfterDesktop"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Hybrid_probe_throwing_does_not_arm()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var d = new EntraUserAffinityDetector(
|
||||
f.Post, f.Logger,
|
||||
isHybridJoinProbe: () => throw new InvalidOperationException("registry"),
|
||||
utcNow: () => f.Clock.UtcNow);
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
|
||||
Assert.False(d.IsArmedForTest);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_after_arm_does_not_throw_and_blocks_emission()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
var d = f.Build();
|
||||
|
||||
d.NotifyRealUserDesktop();
|
||||
d.Dispose();
|
||||
d.TriggerFromTest();
|
||||
|
||||
Assert.Null(Find(f.Ingress, SharedEventTypes.EntraUserAffinityPending));
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
@@ -73,6 +73,27 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring
|
||||
Assert.Equal("true", info.Payload![SignalPayloadKeys.ImmediateUpload]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(304, "join phase")]
|
||||
[InlineData(305, "authentication phase")]
|
||||
public void ProcessHelloEvent_304_305_emit_device_registration_event_with_immediate_upload(int eventId, string phaseLabel)
|
||||
{
|
||||
// Hybrid affinity companion (2026-09-04): UDR 304/305 ride the already-armed
|
||||
// watcher and surface as device_registration_event — a Warning, flushed at once,
|
||||
// and never a Hello completion.
|
||||
using var f = new Fixture();
|
||||
|
||||
f.Tracker.ProcessHelloEvent(eventId, Fixed, "Microsoft-Windows-User Device Registration", isBackfill: false);
|
||||
|
||||
var info = f.InfoEvent("device_registration_event");
|
||||
Assert.Equal("Warning", info.Payload![SignalPayloadKeys.Severity]);
|
||||
Assert.Equal("true", info.Payload[SignalPayloadKeys.ImmediateUpload]);
|
||||
Assert.Contains(phaseLabel, info.Payload[SignalPayloadKeys.Message]);
|
||||
Assert.DoesNotContain(f.Ingress.Posted, p =>
|
||||
p.Payload != null && p.Payload.TryGetValue(SignalPayloadKeys.EventType, out var et)
|
||||
&& et.StartsWith("hello_provisioning"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProcessHelloEvent_358_willlaunch_is_suppressed()
|
||||
{
|
||||
|
||||
+52
@@ -194,6 +194,58 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring
|
||||
Assert.NotNull(FindHybridLoginPending(f.Ingress));
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Real-user desktop cancel path (2026-09-04, session a7140f98)
|
||||
// ============================================================================
|
||||
|
||||
[Fact]
|
||||
public void Real_user_desktop_after_Arm_cancels_emission()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var detector = new HybridLoginPendingDetector(f.Watcher, f.Post, f.Logger);
|
||||
|
||||
detector.Arm();
|
||||
detector.NotifyRealUserDesktop();
|
||||
detector.TriggerFromTest();
|
||||
|
||||
Assert.True(detector.IsCancelledByDesktopForTest);
|
||||
Assert.False(detector.HasFiredForTest);
|
||||
Assert.Null(FindHybridLoginPending(f.Ingress));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Real_user_desktop_before_Arm_short_circuits_Arm()
|
||||
{
|
||||
// The DAD first poll runs seconds after start; the arm request comes from the
|
||||
// runtime host slightly later. A desktop seen first must make the arm a no-op.
|
||||
using var f = new Fixture();
|
||||
using var detector = new HybridLoginPendingDetector(f.Watcher, f.Post, f.Logger);
|
||||
|
||||
detector.NotifyRealUserDesktop();
|
||||
detector.Arm();
|
||||
detector.TriggerFromTest();
|
||||
|
||||
Assert.False(detector.IsArmedForTest);
|
||||
Assert.Null(FindHybridLoginPending(f.Ingress));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Emission_reports_desktop_absence_and_placeholder_as_fact()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var detector = new HybridLoginPendingDetector(f.Watcher, f.Post, f.Logger);
|
||||
|
||||
detector.Arm();
|
||||
detector.TriggerFromTest();
|
||||
|
||||
var info = FindHybridLoginPending(f.Ingress);
|
||||
Assert.NotNull(info);
|
||||
Assert.Equal("false", info!.Payload!["realUserDesktopSeen"]);
|
||||
Assert.Equal("false", info.Payload["placeholderActive"]); // watcher never saw JoinInfo in this fixture
|
||||
Assert.Contains("no real-user desktop", info.Payload[SignalPayloadKeys.Message]);
|
||||
Assert.DoesNotContain("placeholder still active", info.Payload[SignalPayloadKeys.Message]);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Lifecycle / Dispose
|
||||
// ============================================================================
|
||||
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// Backlog era anchoring (2026-09-04, session a7140f98). The property under test: the
|
||||
/// bootstrap execution record — stdout in AgentExecutor.log, policy result in the service
|
||||
/// log — measured against the install marker anchors exactly the era it sits in; a SKIP
|
||||
/// re-run, a missing marker, an MSI bootstrap and an off-grid residual anchor nothing; the
|
||||
/// anchor never crosses an "EMS Agent Started" boundary; sibling files join by local time
|
||||
/// only while the service eras are unambiguous.
|
||||
/// </summary>
|
||||
public sealed class ImeLogEraPreScanTests
|
||||
{
|
||||
private static readonly DateTime Deployed = new DateTime(2026, 9, 4, 13, 31, 49, 100, DateTimeKind.Utc);
|
||||
private static readonly TimeSpan Pacific = TimeSpan.FromHours(-7);
|
||||
private static readonly TimeSpan Eastern = TimeSpan.FromHours(-4);
|
||||
private const string PolicyId = "93d9df23-1111-2222-3333-444455556666";
|
||||
|
||||
private static string Entry(string message, DateTime utcInstant, TimeSpan writerOffset)
|
||||
{
|
||||
var local = utcInstant + writerOffset;
|
||||
return $"<![LOG[{message}]LOG]!><time=\"{local:HH:mm:ss.fffffff}\" date=\"{local:M-d-yyyy}\" " +
|
||||
"component=\"X\" context=\"\" type=\"1\" thread=\"1\" file=\"\">";
|
||||
}
|
||||
|
||||
private static string ScriptStart(DateTime utc, TimeSpan offset) =>
|
||||
Entry($@"Adding argument powershell with value C:\Program Files (x86)\Microsoft Intune Management Extension\Policies\Scripts\00000000-0000-0000-0000-000000000000_{PolicyId}.ps1", utc, offset);
|
||||
|
||||
private static string BootstrapStdout(DateTime utc, TimeSpan offset, string tail = "===== Bootstrap Completed Successfully =====") =>
|
||||
Entry("write output done. output = ===== Autopilot Monitor Bootstrap Started =====\nBootstrap script version: v2.0\nAgent install mode completed successfully\n" + tail + ", error = ", utc, offset);
|
||||
|
||||
private static string PolicyResult(DateTime utc, TimeSpan offset, string policyId = PolicyId) =>
|
||||
Entry($"[PowerShell] User Id = 00000000-0000-0000-0000-000000000000, Policy id = {policyId}, policy result = Success", utc, offset);
|
||||
|
||||
private static string ServiceStarted(DateTime utc, TimeSpan offset) => Entry("EMS Agent Started", utc, offset);
|
||||
|
||||
private sealed class Fixture : IDisposable
|
||||
{
|
||||
public TempDirectory Tmp { get; } = new TempDirectory();
|
||||
private readonly List<ImeLogEraPreScan.ScanInput> _inputs = new List<ImeLogEraPreScan.ScanInput>();
|
||||
|
||||
public string Write(string fileName, params string[] entries)
|
||||
{
|
||||
var path = Path.Combine(Tmp.Path, fileName);
|
||||
File.WriteAllText(path, string.Join(Environment.NewLine, entries) + Environment.NewLine);
|
||||
_inputs.Add(new ImeLogEraPreScan.ScanInput(path, 0));
|
||||
return path;
|
||||
}
|
||||
|
||||
public long OffsetOfLine(string fileName, int lineIndex)
|
||||
{
|
||||
// Entries are written line by line; the byte offset of entry N is the sum of the
|
||||
// preceding lines (CRLF-agnostic through Environment.NewLine).
|
||||
var path = Path.Combine(Tmp.Path, fileName);
|
||||
var lines = File.ReadAllLines(path);
|
||||
long offset = 0;
|
||||
for (var i = 0; i < lineIndex; i++)
|
||||
offset += System.Text.Encoding.UTF8.GetByteCount(lines[i]) + Environment.NewLine.Length;
|
||||
return offset;
|
||||
}
|
||||
|
||||
public CmTraceEraTable Build(DateTime? deployed) =>
|
||||
ImeLogEraPreScan.Build(_inputs, deployed, ImeLogTracker.MaxEntryBytes, null);
|
||||
|
||||
public void Dispose() => Tmp.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Bootstrap_record_anchors_service_era_and_executor_block_only_within_their_boundaries()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
f.Write("AgentExecutor.log",
|
||||
ScriptStart(Deployed.AddSeconds(-20), Pacific),
|
||||
BootstrapStdout(Deployed.AddMilliseconds(200), Pacific),
|
||||
Entry("Adding argument powershell with value C:\\x\\Policies\\Scripts\\u_aaaaaaaa-0000-0000-0000-000000000000.ps1", Deployed.AddMinutes(5), Pacific),
|
||||
Entry("write output done. output = other script, error = ", Deployed.AddMinutes(5).AddSeconds(2), Pacific));
|
||||
f.Write("IntuneManagementExtension.log",
|
||||
Entry("In EspPhase: DeviceSetup", Deployed.AddMinutes(-1), Pacific), // line 0, era 0
|
||||
PolicyResult(Deployed.AddMilliseconds(260), Pacific), // line 1, anchor
|
||||
Entry("In EspPhase: DeviceSetup", Deployed.AddMinutes(10), Pacific), // line 2, era 0
|
||||
ServiceStarted(Deployed.AddMinutes(20), Eastern), // line 3, era 1 (post-boot, new zone)
|
||||
Entry("Successfully get the token", Deployed.AddMinutes(21), Eastern)); // line 4, era 1
|
||||
|
||||
var table = f.Build(Deployed);
|
||||
|
||||
Assert.Equal(2, table.AnchoredEraCount);
|
||||
Assert.False(table.TransferAmbiguous);
|
||||
|
||||
// Service era 0: every offset before "EMS Agent Started" resolves to the Pacific offset.
|
||||
Assert.True(table.TryResolveByOffset("IntuneManagementExtension.log", f.OffsetOfLine("IntuneManagementExtension.log", 0), out var off0, out var kind0));
|
||||
Assert.Equal(Pacific, off0);
|
||||
Assert.Equal(ImeLogEraPreScan.AnchorKindBootstrapPolicyResult, kind0);
|
||||
Assert.True(table.TryResolveByOffset("IntuneManagementExtension.log", f.OffsetOfLine("IntuneManagementExtension.log", 2), out var off2, out _));
|
||||
Assert.Equal(Pacific, off2);
|
||||
|
||||
// Era 1 has no anchor of its own — the Pacific anchor must not leak across the boundary.
|
||||
Assert.False(table.TryResolveByOffset("IntuneManagementExtension.log", f.OffsetOfLine("IntuneManagementExtension.log", 3), out _, out _));
|
||||
Assert.False(table.TryResolveByOffset("IntuneManagementExtension.log", f.OffsetOfLine("IntuneManagementExtension.log", 4), out _, out _));
|
||||
|
||||
// Executor: only the bootstrap execution block is anchored, not the next script's block.
|
||||
Assert.True(table.TryResolveByOffset("AgentExecutor.log", f.OffsetOfLine("AgentExecutor.log", 0), out var offX, out var kindX));
|
||||
Assert.Equal(Pacific, offX);
|
||||
Assert.Equal(ImeLogEraPreScan.AnchorKindBootstrapStdout, kindX);
|
||||
Assert.False(table.TryResolveByOffset("AgentExecutor.log", f.OffsetOfLine("AgentExecutor.log", 5), out _, out _));
|
||||
|
||||
// Transfer for in-process sibling files: a local time inside era 0's range resolves,
|
||||
// one inside era 1's range does not.
|
||||
Assert.True(table.TryResolveByLocalTime(Deployed.AddMinutes(5) + Pacific, out var offT, out var kindT));
|
||||
Assert.Equal(Pacific, offT);
|
||||
Assert.EndsWith("/service-era-transfer", kindT);
|
||||
Assert.False(table.TryResolveByLocalTime(Deployed.AddMinutes(25) + Eastern, out _, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Without_deployed_marker_nothing_is_anchored()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
f.Write("AgentExecutor.log", ScriptStart(Deployed.AddSeconds(-20), Pacific), BootstrapStdout(Deployed.AddMilliseconds(200), Pacific));
|
||||
f.Write("IntuneManagementExtension.log", PolicyResult(Deployed.AddMilliseconds(260), Pacific));
|
||||
|
||||
var table = f.Build(null);
|
||||
|
||||
Assert.Equal(0, table.AnchoredEraCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Msi_bootstrap_without_stdout_record_anchors_nothing()
|
||||
{
|
||||
// The MSI runner never passes through AgentExecutor; without the policy id the
|
||||
// service log's result lines cannot be told apart from any other script's.
|
||||
using var f = new Fixture();
|
||||
f.Write("AgentExecutor.log", Entry("Adding argument powershell with value C:\\x\\Policies\\Scripts\\u_aaaaaaaa-0000-0000-0000-000000000000.ps1", Deployed.AddMinutes(3), Pacific));
|
||||
f.Write("IntuneManagementExtension.log", PolicyResult(Deployed.AddMilliseconds(260), Pacific));
|
||||
|
||||
var table = f.Build(Deployed);
|
||||
|
||||
Assert.Equal(0, table.AnchoredEraCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Skip_rerun_record_is_never_offered_and_first_record_off_grid_anchors_nothing()
|
||||
{
|
||||
// The install run is the FIRST bootstrap record; a SKIP re-run 15 minutes later
|
||||
// would round onto the grid with zero residual and anchor a wrong offset.
|
||||
using var f = new Fixture();
|
||||
f.Write("AgentExecutor.log",
|
||||
ScriptStart(Deployed.AddMinutes(-9), Pacific),
|
||||
BootstrapStdout(Deployed.AddMinutes(-8), Pacific), // first record: residual 8 min → rejected
|
||||
ScriptStart(Deployed.AddMinutes(15).AddSeconds(-2), Pacific),
|
||||
BootstrapStdout(Deployed.AddMinutes(15), Pacific)); // would be a perfect (wrong) grid hit
|
||||
f.Write("IntuneManagementExtension.log",
|
||||
PolicyResult(Deployed.AddMinutes(-8), Pacific),
|
||||
PolicyResult(Deployed.AddMinutes(15), Pacific));
|
||||
|
||||
var table = f.Build(Deployed);
|
||||
|
||||
Assert.Equal(0, table.AnchoredEraCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Service_era_continues_across_a_log_rotation()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
f.Write("AgentExecutor.log", ScriptStart(Deployed.AddSeconds(-20), Pacific), BootstrapStdout(Deployed.AddMilliseconds(200), Pacific));
|
||||
f.Write("IntuneManagementExtension-20260904-133000.log",
|
||||
PolicyResult(Deployed.AddMilliseconds(260), Pacific),
|
||||
Entry("In EspPhase: DeviceSetup", Deployed.AddMinutes(2), Pacific));
|
||||
f.Write("IntuneManagementExtension.log",
|
||||
Entry("In EspPhase: DeviceSetup", Deployed.AddMinutes(12), Pacific), // same process, rotated file
|
||||
ServiceStarted(Deployed.AddMinutes(20), Eastern));
|
||||
|
||||
var table = f.Build(Deployed);
|
||||
|
||||
Assert.True(table.TryResolveByOffset("IntuneManagementExtension.log", 0, out var off, out _));
|
||||
Assert.Equal(Pacific, off);
|
||||
Assert.False(table.TryResolveByOffset("IntuneManagementExtension.log", f.OffsetOfLine("IntuneManagementExtension.log", 1), out _, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Overlapping_service_era_local_ranges_disable_the_transfer()
|
||||
{
|
||||
// A westward zone change between two service starts makes era 1 start "before"
|
||||
// era 0 in local time; the sibling-file transfer must refuse rather than guess.
|
||||
using var f = new Fixture();
|
||||
f.Write("AgentExecutor.log", ScriptStart(Deployed.AddSeconds(-20), TimeSpan.FromHours(2)), BootstrapStdout(Deployed.AddMilliseconds(200), TimeSpan.FromHours(2)));
|
||||
f.Write("IntuneManagementExtension.log",
|
||||
ServiceStarted(Deployed.AddMinutes(-30), TimeSpan.FromHours(2)),
|
||||
PolicyResult(Deployed.AddMilliseconds(260), TimeSpan.FromHours(2)),
|
||||
ServiceStarted(Deployed.AddMinutes(20), TimeSpan.FromHours(-7)));
|
||||
|
||||
var table = f.Build(Deployed);
|
||||
|
||||
Assert.True(table.TransferAmbiguous);
|
||||
Assert.False(table.TryResolveByLocalTime(Deployed.AddMinutes(5) + TimeSpan.FromHours(2), out _, out _));
|
||||
// Offset-based lookup is unaffected.
|
||||
Assert.True(table.TryResolveByOffset("IntuneManagementExtension.log", f.OffsetOfLine("IntuneManagementExtension.log", 1), out var off, out _));
|
||||
Assert.Equal(TimeSpan.FromHours(2), off);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deployment_marker_parses_roundtrip_utc()
|
||||
{
|
||||
Assert.Equal(Deployed, AutopilotMonitor.Agent.V2.Core.Security.DeploymentMarker.Parse("2026-09-04T13:31:49.1000000Z"));
|
||||
Assert.Null(AutopilotMonitor.Agent.V2.Core.Security.DeploymentMarker.Parse(""));
|
||||
Assert.Null(AutopilotMonitor.Agent.V2.Core.Security.DeploymentMarker.Parse("not a date"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// End-to-end through the tracker: a restart/first-sight backlog whose pre-reboot era was
|
||||
/// written under the OOBE default zone (a7140f98: Pacific) while the agent believes the
|
||||
/// zone Windows set later (Eastern). With the bootstrap record anchoring that era, every
|
||||
/// pre-reboot line resolves to its true instant with origin <c>era-anchored</c>; the
|
||||
/// post-reboot era without an anchor keeps the marked fallback; in-process sibling files
|
||||
/// join by local time; a fresh pass still self-anchors per line.
|
||||
/// </summary>
|
||||
public sealed class ImeLogTrackerEraAnchoringTests
|
||||
{
|
||||
private static readonly DateTime Deployed = new DateTime(2026, 9, 4, 13, 31, 49, 100, DateTimeKind.Utc);
|
||||
private static readonly TimeSpan Pacific = TimeSpan.FromHours(-7);
|
||||
private static readonly TimeSpan Eastern = TimeSpan.FromHours(-4);
|
||||
private const string PolicyId = "93d9df23-1111-2222-3333-444455556666";
|
||||
|
||||
private static List<ImeLogPattern> Patterns() => new List<ImeLogPattern>
|
||||
{
|
||||
new ImeLogPattern
|
||||
{
|
||||
PatternId = "T-ALL", Category = "always", Enabled = true,
|
||||
Pattern = @"marker (?<n>\d+)",
|
||||
Action = "noop",
|
||||
Parameters = new Dictionary<string, string>(),
|
||||
},
|
||||
};
|
||||
|
||||
private static string Entry(string message, DateTime utcInstant, TimeSpan writerOffset)
|
||||
{
|
||||
var local = utcInstant + writerOffset;
|
||||
return $"<![LOG[{message}]LOG]!><time=\"{local:HH:mm:ss.fffffff}\" date=\"{local:M-d-yyyy}\" " +
|
||||
"component=\"X\" context=\"\" type=\"1\" thread=\"1\" file=\"\">";
|
||||
}
|
||||
|
||||
private sealed class Harness : IDisposable
|
||||
{
|
||||
private readonly TempDirectory _tmp = new TempDirectory();
|
||||
public ImeLogTracker Tracker { get; }
|
||||
public DateTime Now { get; set; } = Deployed.AddMinutes(30);
|
||||
public List<(string Message, DateTime? Ts, CmTraceOffsetOrigin Origin, int? Offset, string Anchor)> Resolved { get; } =
|
||||
new List<(string, DateTime?, CmTraceOffsetOrigin, int?, string)>();
|
||||
|
||||
public Harness()
|
||||
{
|
||||
Tracker = new ImeLogTracker(
|
||||
logFolder: _tmp.Path,
|
||||
patterns: Patterns(),
|
||||
logger: new AgentLogger(_tmp.Path, AgentLogLevel.Info));
|
||||
Tracker.UtcNowProvider = () => Now;
|
||||
Tracker.DeployedUtcProvider = () => Deployed;
|
||||
Tracker.OnPatternMatched += _ => Resolved.Add((
|
||||
Tracker.LastMatchedPatternId ?? string.Empty,
|
||||
Tracker.LastMatchedLogTimestamp,
|
||||
Tracker.LastMatchedSourceOffsetOrigin,
|
||||
Tracker.LastMatchedSourceOffsetMinutes,
|
||||
Tracker.LastMatchedEraAnchorKind));
|
||||
}
|
||||
|
||||
public void Append(string fileName, params string[] lines)
|
||||
=> File.AppendAllText(Path.Combine(_tmp.Path, fileName), string.Join(Environment.NewLine, lines) + Environment.NewLine);
|
||||
|
||||
public Task Pass() => Tracker.CheckLogFilesAsync(CancellationToken.None);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Tracker.Dispose();
|
||||
_tmp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Backlog_lines_of_the_bootstrap_era_resolve_through_the_anchor_and_the_next_era_stays_on_fallback()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Append("AgentExecutor.log",
|
||||
Entry($@"Adding argument powershell with value C:\x\Policies\Scripts\u_{PolicyId}.ps1", Deployed.AddSeconds(-20), Pacific),
|
||||
Entry("write output done. output = ===== Autopilot Monitor Bootstrap Started =====\n===== Bootstrap Completed Successfully =====, error = ", Deployed.AddMilliseconds(200), Pacific),
|
||||
Entry("marker 10", Deployed.AddSeconds(1), Pacific));
|
||||
h.Append("IntuneManagementExtension.log",
|
||||
Entry("marker 1", Deployed.AddMinutes(-1), Pacific),
|
||||
Entry($"[PowerShell] User Id = 00000000-0000-0000-0000-000000000000, Policy id = {PolicyId}, policy result = Success", Deployed.AddMilliseconds(260), Pacific),
|
||||
Entry("marker 2", Deployed.AddMinutes(10), Pacific),
|
||||
Entry("EMS Agent Started", Deployed.AddMinutes(20), Eastern),
|
||||
Entry("marker 3", Deployed.AddMinutes(21), Eastern));
|
||||
h.Append("AppWorkload.log",
|
||||
Entry("marker 4", Deployed.AddMinutes(5), Pacific),
|
||||
Entry("marker 5", Deployed.AddMinutes(25), Eastern));
|
||||
|
||||
h.Tracker.PreScanEras();
|
||||
await h.Pass(); // first sight: backlog, never fresh
|
||||
|
||||
var byMarker = new Dictionary<string, (string Message, DateTime? Ts, CmTraceOffsetOrigin Origin, int? Offset, string Anchor)>();
|
||||
foreach (var r in h.Resolved) byMarker[r.Message] = r;
|
||||
Assert.Equal(6, h.Resolved.Count);
|
||||
|
||||
// Marker text is the pattern id (T-ALL) — index by resolution order instead.
|
||||
var r1 = h.Resolved[0]; // AgentExecutor marker 10 (files sort: AgentExecutor < AppWorkload < IntuneManagementExtension)
|
||||
Assert.Equal(CmTraceOffsetOrigin.EraAnchored, r1.Origin);
|
||||
Assert.Equal(Deployed.AddSeconds(1), r1.Ts);
|
||||
Assert.Equal(-420, r1.Offset);
|
||||
Assert.Equal(ImeLogEraPreScan.AnchorKindBootstrapStdout, r1.Anchor);
|
||||
|
||||
var r4 = h.Resolved[1]; // AppWorkload marker 4 — transfer by local time into the service era
|
||||
Assert.Equal(CmTraceOffsetOrigin.EraAnchored, r4.Origin);
|
||||
Assert.Equal(Deployed.AddMinutes(5), r4.Ts);
|
||||
Assert.EndsWith("/service-era-transfer", r4.Anchor);
|
||||
|
||||
var r5 = h.Resolved[2]; // AppWorkload marker 5 — post-boot era, unanchored
|
||||
Assert.Equal(CmTraceOffsetOrigin.None, r5.Origin);
|
||||
Assert.Equal(string.Empty, r5.Anchor);
|
||||
|
||||
var rm1 = h.Resolved[3]; // IME marker 1
|
||||
Assert.Equal(CmTraceOffsetOrigin.EraAnchored, rm1.Origin);
|
||||
Assert.Equal(Deployed.AddMinutes(-1), rm1.Ts);
|
||||
Assert.Equal(ImeLogEraPreScan.AnchorKindBootstrapPolicyResult, rm1.Anchor);
|
||||
|
||||
var rm2 = h.Resolved[4]; // IME marker 2
|
||||
Assert.Equal(CmTraceOffsetOrigin.EraAnchored, rm2.Origin);
|
||||
Assert.Equal(Deployed.AddMinutes(10), rm2.Ts);
|
||||
|
||||
var rm3 = h.Resolved[5]; // IME marker 3 — after "EMS Agent Started", no anchor
|
||||
Assert.Equal(CmTraceOffsetOrigin.None, rm3.Origin);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Fresh_lines_still_self_anchor_after_the_pre_scan()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Append("IntuneManagementExtension.log", Entry("marker 1", h.Now, Eastern));
|
||||
h.Tracker.PreScanEras();
|
||||
await h.Pass();
|
||||
|
||||
h.Now = h.Now.AddSeconds(10);
|
||||
var writtenAt = h.Now.AddMilliseconds(-80);
|
||||
h.Append("IntuneManagementExtension.log", Entry("marker 2", writtenAt, Eastern));
|
||||
await h.Pass();
|
||||
|
||||
var last = h.Resolved[h.Resolved.Count - 1];
|
||||
Assert.Equal(CmTraceOffsetOrigin.LineAnchored, last.Origin);
|
||||
Assert.Equal(writtenAt, last.Ts);
|
||||
Assert.Equal(string.Empty, last.Anchor);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Without_marker_the_backlog_keeps_the_reader_zone_fallback()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Tracker.DeployedUtcProvider = () => null;
|
||||
h.Append("IntuneManagementExtension.log", Entry("marker 1", Deployed.AddMinutes(-1), Pacific));
|
||||
h.Tracker.PreScanEras();
|
||||
await h.Pass();
|
||||
|
||||
Assert.Single(h.Resolved);
|
||||
Assert.Equal(CmTraceOffsetOrigin.None, h.Resolved[0].Origin);
|
||||
Assert.Equal(0, h.Tracker.EraTable.AnchoredEraCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// Raw per-line token callbacks for the Entra user-affinity detector (2026-09-04).
|
||||
/// <c>OnUserTokenAcquired</c> fires on EVERY IME-TOKEN-SUCCESS line — independent of the
|
||||
/// phase-change dedup that swallows the second AccountSetup detection — and
|
||||
/// <c>OnTokenFailureLine</c> on every failure line; both honour the historic-replay gate.
|
||||
/// </summary>
|
||||
public sealed class ImeLogTrackerTokenLineCallbackTests
|
||||
{
|
||||
private static readonly DateTime Now = new DateTime(2026, 9, 4, 14, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private static List<ImeLogPattern> Patterns() => new List<ImeLogPattern>
|
||||
{
|
||||
new ImeLogPattern
|
||||
{
|
||||
PatternId = "IME-TOKEN-SUCCESS", Category = "always", Enabled = true,
|
||||
Pattern = "^Successfully get the token",
|
||||
Action = "espPhaseDetected",
|
||||
Parameters = new Dictionary<string, string> { ["phase"] = "AccountSetup" },
|
||||
},
|
||||
new ImeLogPattern
|
||||
{
|
||||
PatternId = "IME-TOKEN-FAILURE", Category = "always", Enabled = true,
|
||||
Pattern = @"^Failed to get AAD token\..*?errorCode = (?<errorCode>.*?)$",
|
||||
Action = "imeTokenFailure",
|
||||
Parameters = new Dictionary<string, string>(),
|
||||
},
|
||||
};
|
||||
|
||||
private static ImeLogTracker Build(TempDirectory tmp)
|
||||
{
|
||||
var tracker = new ImeLogTracker(
|
||||
logFolder: tmp.Path,
|
||||
patterns: Patterns(),
|
||||
logger: new AgentLogger(tmp.Path, AgentLogLevel.Info));
|
||||
tracker.UtcNowProvider = () => Now;
|
||||
return tracker;
|
||||
}
|
||||
|
||||
private const string Success = "Successfully get the token with client id fc0f3af4-6835-4174-b806-f7db311fd2f3 and resource id 26a4ae64-5862-427f-a9b0-044e62572a4f";
|
||||
private const string Failure = "Failed to get AAD token. len = 34 using client id fc0f3af4-6835-4174-b806-f7db311fd2f3 and resource id 26a4ae64-5862-427f-a9b0-044e62572a4f, errorCode = 3399548929";
|
||||
|
||||
[Fact]
|
||||
public void Every_token_success_line_invokes_callback_even_when_phase_is_deduplicated()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
using var tracker = Build(tmp);
|
||||
var tokens = new List<DateTime?>();
|
||||
tracker.OnUserTokenAcquired = ts => tokens.Add(ts);
|
||||
|
||||
// The phase-change dedup lives in the adapter (AccountSetup is emitted once);
|
||||
// the raw token callback must fire for BOTH lines regardless.
|
||||
tracker.ProcessLogMessageForTest(Success, Now.AddMinutes(-6));
|
||||
tracker.ProcessLogMessageForTest(Success, Now.AddMinutes(-2));
|
||||
|
||||
Assert.Equal(2, tokens.Count);
|
||||
Assert.Equal(Now.AddMinutes(-6), tokens[0]);
|
||||
Assert.Equal(Now.AddMinutes(-2), tokens[1]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Every_failure_line_invokes_callback_with_error_code()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
using var tracker = Build(tmp);
|
||||
var failures = new List<(string code, DateTime? ts)>();
|
||||
tracker.OnTokenFailureLine = (code, ts) => failures.Add((code, ts));
|
||||
|
||||
tracker.ProcessLogMessageForTest(Failure, Now.AddMinutes(-5));
|
||||
tracker.ProcessLogMessageForTest(Failure, Now.AddMinutes(-4));
|
||||
|
||||
Assert.Equal(2, failures.Count);
|
||||
Assert.All(failures, f => Assert.Equal("3399548929", f.code));
|
||||
Assert.Equal(Now.AddMinutes(-5), failures[0].ts);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Historic_replay_lines_do_not_invoke_either_callback()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
using var tracker = Build(tmp);
|
||||
var tokens = 0;
|
||||
var failures = 0;
|
||||
tracker.OnUserTokenAcquired = _ => tokens++;
|
||||
tracker.OnTokenFailureLine = (_, __) => failures++;
|
||||
|
||||
tracker.ProcessLogMessageForTest(Success, Now.AddDays(-3));
|
||||
tracker.ProcessLogMessageForTest(Failure, Now.AddDays(-3));
|
||||
|
||||
Assert.Equal(0, tokens);
|
||||
Assert.Equal(0, failures);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Callback_exception_does_not_break_the_drain()
|
||||
{
|
||||
using var tmp = new TempDirectory();
|
||||
using var tracker = Build(tmp);
|
||||
tracker.OnUserTokenAcquired = _ => throw new InvalidOperationException("boom");
|
||||
tracker.OnTokenFailureLine = (_, __) => throw new InvalidOperationException("boom");
|
||||
|
||||
tracker.ProcessLogMessageForTest(Success, Now.AddMinutes(-1));
|
||||
tracker.ProcessLogMessageForTest(Failure, Now.AddMinutes(-1));
|
||||
}
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
using System;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals;
|
||||
using AutopilotMonitor.Agent.V2.Core.Orchestration;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Orchestration;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
{
|
||||
/// <summary>
|
||||
/// Backlog q8n — pins the two AccountSetup probes side by side.
|
||||
/// <para>
|
||||
/// <see cref="ProvisioningStatusTracker.HasAccountSetupActivity"/> keeps PRESENCE semantics:
|
||||
/// Windows writes <c>AccountSetupCategory.Status</c> with every subcategory <c>notStarted</c>
|
||||
/// before the Device-ESP page exits, and about one in five Classic sessions sees only that
|
||||
/// single Shell-Core 62407 for the whole enrollment — those resolve AccountSetup solely via
|
||||
/// the user-apps-settled synthesis, which needs the exit remembered as the edge. Tightening
|
||||
/// this property strands them (verified on 485 SkipUser=false sessions, 2026-09-01..04).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <see cref="ProvisioningStatusTracker.HasAccountSetupProgress"/> is the additive PROGRESS
|
||||
/// probe for the User-ESP keep-awake host: true only once a subcategory left
|
||||
/// <c>notStarted</c>, so the host can tell the real user-ESP page exit (session a2256107:
|
||||
/// 09:47:12) from the Device→Account handoff exit (09:37:53) that released the hold early.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class ProvisioningStatusTrackerAccountSetupActivityTests
|
||||
{
|
||||
private static readonly DateTime Fixed = new DateTime(2026, 9, 4, 9, 37, 42, DateTimeKind.Utc);
|
||||
|
||||
// Verbatim shape of the pre-written registry JSON seen at first_seen on 25H2/26200.
|
||||
private const string AllNotStartedJson = @"{
|
||||
""categoryState"":""notStarted"",
|
||||
""AccountSetup.WaitingForAadRegistrationSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.PrepareMultifactorAuth"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.SecurityPoliciesSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.CertificatesSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.NetworkConnectionsSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.AppsSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.SendResultsToMdmServer"":{""subcategoryState"":""notStarted""}
|
||||
}";
|
||||
|
||||
private const string FirstProgressJson = @"{
|
||||
""categoryState"":""inProgress"",
|
||||
""AccountSetup.WaitingForAadRegistrationSubcategory"":{""subcategoryState"":""succeeded"",""subcategoryStatusText"":""succeeded""},
|
||||
""AccountSetup.PrepareMultifactorAuth"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.SecurityPoliciesSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.CertificatesSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.NetworkConnectionsSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.AppsSubcategory"":{""subcategoryState"":""notStarted""},
|
||||
""AccountSetup.SendResultsToMdmServer"":{""subcategoryState"":""notStarted""}
|
||||
}";
|
||||
|
||||
private sealed class Fixture : IDisposable
|
||||
{
|
||||
public TempDirectory Tmp { get; } = new TempDirectory();
|
||||
public FakeSignalIngressSink Sink { get; } = new FakeSignalIngressSink();
|
||||
public ProvisioningStatusTracker Tracker { get; }
|
||||
|
||||
public Fixture()
|
||||
{
|
||||
var clock = new VirtualClock(Fixed);
|
||||
var post = new InformationalEventPost(Sink, clock);
|
||||
var logger = new AgentLogger(Tmp.Path, AgentLogLevel.Info);
|
||||
Tracker = new ProvisioningStatusTracker(
|
||||
sessionId: "S1",
|
||||
tenantId: "T1",
|
||||
post: post,
|
||||
logger: logger);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Tracker.Dispose();
|
||||
Tmp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NothingTracked_NeitherActivityNorProgress()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
Assert.False(f.Tracker.HasAccountSetupActivity);
|
||||
Assert.False(f.Tracker.HasAccountSetupProgress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PreWrittenAllNotStartedJson_IsActivity_ButNotProgress()
|
||||
{
|
||||
// The registry JSON exists (7 subcategories) but nothing has started — the state at
|
||||
// the intermediate Device-ESP exit. Activity (presence) must stay true so the
|
||||
// completion guards keep remembering single-exit sessions; progress must be false so
|
||||
// the keep-awake host does not treat this exit as the user-ESP page exit.
|
||||
using var f = new Fixture();
|
||||
f.Tracker.ProcessCategoryStatusForTest("AccountSetupCategory.Status", AllNotStartedJson);
|
||||
|
||||
Assert.True(f.Tracker.HasAccountSetupActivity);
|
||||
Assert.False(f.Tracker.HasAccountSetupProgress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FirstSubcategoryLeavingNotStarted_IsProgress()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
f.Tracker.ProcessCategoryStatusForTest("AccountSetupCategory.Status", AllNotStartedJson);
|
||||
f.Tracker.ProcessCategoryStatusForTest("AccountSetupCategory.Status", FirstProgressJson);
|
||||
|
||||
Assert.True(f.Tracker.HasAccountSetupActivity);
|
||||
Assert.True(f.Tracker.HasAccountSetupProgress);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("inProgress")]
|
||||
[InlineData("in_progress")]
|
||||
[InlineData("failed")]
|
||||
[InlineData("notRequired")]
|
||||
public void AnyNonNotStartedState_IsProgress(string state)
|
||||
{
|
||||
using var f = new Fixture();
|
||||
f.Tracker.ProcessCategoryStatusForTest("AccountSetupCategory.Status",
|
||||
"{\"categoryState\":\"inProgress\"," +
|
||||
"\"AccountSetup.AppsSubcategory\":{\"subcategoryState\":\"" + state + "\"}," +
|
||||
"\"AccountSetup.CertificatesSubcategory\":{\"subcategoryState\":\"notStarted\"}}");
|
||||
|
||||
Assert.True(f.Tracker.HasAccountSetupProgress);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeviceSetupProgress_DoesNotCountAsAccountSetupProgress()
|
||||
{
|
||||
// Adversarial: a fully progressed DeviceSetup category must not leak into the
|
||||
// AccountSetup answer.
|
||||
using var f = new Fixture();
|
||||
f.Tracker.ProcessCategoryStatusForTest("DeviceSetupCategory.Status",
|
||||
"{\"categoryState\":\"succeeded\",\"DeviceSetup.AppsSubcategory\":{\"subcategoryState\":\"succeeded\"}}");
|
||||
f.Tracker.ProcessCategoryStatusForTest("AccountSetupCategory.Status", AllNotStartedJson);
|
||||
|
||||
Assert.False(f.Tracker.HasAccountSetupProgress);
|
||||
}
|
||||
}
|
||||
}
|
||||
+96
-4
@@ -114,14 +114,80 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
ing.Stop();
|
||||
}
|
||||
|
||||
private static void PostEspExiting(SignalIngress ing) =>
|
||||
ing.Post(DecisionSignalKind.EspExiting, At, "EspAndHelloTracker", Raw("exit"));
|
||||
|
||||
[Fact]
|
||||
public void Releases_on_AccountSetupProvisioningComplete()
|
||||
public void Releases_on_EspExiting_once_AccountSetup_shows_progress()
|
||||
{
|
||||
// q8n: the real user-ESP page exit is a 62407 that arrives after the AccountSetup
|
||||
// registry left notStarted (session a2256107: 09:47:12, progress since 09:38:25).
|
||||
var clock = new VirtualClock(At);
|
||||
using var ing = BuildIngress(clock);
|
||||
var api = new FakeKeepAwakeApi();
|
||||
var controller = new KeepAwakeController(NewLogger(), api);
|
||||
var host = new UserEspKeepAwakeHost("S1", "T1", ing, clock, NewLogger(), controller: controller, espTimeoutProvider: () => null);
|
||||
var progress = false;
|
||||
var host = new UserEspKeepAwakeHost("S1", "T1", ing, clock, NewLogger(), controller: controller,
|
||||
espTimeoutProvider: () => null, accountSetupProgressProbe: () => Volatile.Read(ref progress));
|
||||
|
||||
ing.Start();
|
||||
host.Start();
|
||||
PostAccountSetupPhase(ing);
|
||||
Assert.True(WaitFor(() => api.PreventCount == 1));
|
||||
|
||||
Volatile.Write(ref progress, true);
|
||||
PostEspExiting(ing);
|
||||
|
||||
Assert.True(WaitFor(() => api.AllowCount == 1), "AllowSleep should be called once on the user-ESP page exit");
|
||||
Assert.False(controller.IsEngaged);
|
||||
|
||||
host.Dispose();
|
||||
ing.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handoff_exit_before_AccountSetup_progress_keeps_the_hold()
|
||||
{
|
||||
// The Device→Account handoff 62407 (a2256107: 09:37:53) precedes any AccountSetup
|
||||
// progress — Windows pre-writes the AccountSetup JSON all-notStarted — and must not
|
||||
// release. The later exit with progress does.
|
||||
var clock = new VirtualClock(At);
|
||||
using var ing = BuildIngress(clock);
|
||||
var api = new FakeKeepAwakeApi();
|
||||
var controller = new KeepAwakeController(NewLogger(), api);
|
||||
var progress = false;
|
||||
var host = new UserEspKeepAwakeHost("S1", "T1", ing, clock, NewLogger(), controller: controller,
|
||||
espTimeoutProvider: () => null, accountSetupProgressProbe: () => Volatile.Read(ref progress));
|
||||
|
||||
ing.Start();
|
||||
host.Start();
|
||||
PostAccountSetupPhase(ing);
|
||||
Assert.True(WaitFor(() => api.PreventCount == 1));
|
||||
|
||||
PostEspExiting(ing); // handoff exit, no progress yet
|
||||
Assert.False(WaitFor(() => api.AllowCount > 0, 500), "the handoff exit must not release the hold");
|
||||
Assert.True(controller.IsEngaged);
|
||||
|
||||
Volatile.Write(ref progress, true);
|
||||
PostEspExiting(ing); // the real user-ESP page exit
|
||||
Assert.True(WaitFor(() => api.AllowCount == 1));
|
||||
Assert.False(controller.IsEngaged);
|
||||
|
||||
host.Dispose();
|
||||
ing.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AccountSetupProvisioningComplete_no_longer_releases()
|
||||
{
|
||||
// The synthesized completion fired a median 3 min before the page closed in 77 % of
|
||||
// keep-awake sessions (q8n) — it is no longer a release trigger; the cap/stop/exit are.
|
||||
var clock = new VirtualClock(At);
|
||||
using var ing = BuildIngress(clock);
|
||||
var api = new FakeKeepAwakeApi();
|
||||
var controller = new KeepAwakeController(NewLogger(), api);
|
||||
var host = new UserEspKeepAwakeHost("S1", "T1", ing, clock, NewLogger(), controller: controller,
|
||||
espTimeoutProvider: () => null, accountSetupProgressProbe: () => true);
|
||||
|
||||
ing.Start();
|
||||
host.Start();
|
||||
@@ -130,8 +196,34 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
|
||||
ing.Post(DecisionSignalKind.AccountSetupProvisioningComplete, At, "ProvisioningStatusTracker", Raw("done"));
|
||||
|
||||
Assert.True(WaitFor(() => api.AllowCount == 1), "AllowSleep should be called once on AccountSetup completion");
|
||||
Assert.False(controller.IsEngaged);
|
||||
Assert.False(WaitFor(() => api.AllowCount > 0, 500), "completion must not release the hold any more");
|
||||
Assert.True(controller.IsEngaged);
|
||||
|
||||
host.Dispose();
|
||||
ing.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EspExiting_before_engage_is_ignored()
|
||||
{
|
||||
// Exit signals while idle (e.g. a Device-ESP exit before AccountSetup) neither release
|
||||
// nor poison the later engage.
|
||||
var clock = new VirtualClock(At);
|
||||
using var ing = BuildIngress(clock);
|
||||
var api = new FakeKeepAwakeApi();
|
||||
var controller = new KeepAwakeController(NewLogger(), api);
|
||||
var host = new UserEspKeepAwakeHost("S1", "T1", ing, clock, NewLogger(), controller: controller,
|
||||
espTimeoutProvider: () => null, accountSetupProgressProbe: () => true);
|
||||
|
||||
ing.Start();
|
||||
host.Start();
|
||||
PostEspExiting(ing);
|
||||
Assert.False(WaitFor(() => api.AllowCount > 0, 300));
|
||||
|
||||
PostAccountSetupPhase(ing);
|
||||
Assert.True(WaitFor(() => api.PreventCount == 1));
|
||||
Assert.True(controller.IsEngaged);
|
||||
Assert.Equal(0, api.AllowCount);
|
||||
|
||||
host.Dispose();
|
||||
ing.Stop();
|
||||
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// A writer era: the stretch of log written by ONE process lifetime, i.e. under one
|
||||
/// timezone belief. For the IME service family (IntuneManagementExtension*.log) an era
|
||||
/// starts at an "EMS Agent Started" entry and may continue across a log rotation into the
|
||||
/// next file; for AgentExecutor.log every script execution is its own short-lived process
|
||||
/// and therefore its own era. An era carries an offset only when an anchor inside it was
|
||||
/// matched against an instant the agent knows in UTC (<see cref="ImeLogEraPreScan"/>).
|
||||
/// </summary>
|
||||
internal sealed class CmTraceEra
|
||||
{
|
||||
/// <summary>File segments (file name → [start, end) byte range) that belong to this era, in write order.</summary>
|
||||
public List<CmTraceEraSegment> Segments { get; } = new List<CmTraceEraSegment>();
|
||||
|
||||
/// <summary>Local time of the era's first entry as written (null for a leading era whose start predates the scanned region).</summary>
|
||||
public DateTime? StartLocal { get; set; }
|
||||
|
||||
/// <summary>Local time of the next era's first entry (null for the last era).</summary>
|
||||
public DateTime? EndLocal { get; set; }
|
||||
|
||||
/// <summary>The writer's UTC offset (local = UTC + offset) when anchored.</summary>
|
||||
public TimeSpan? Offset { get; set; }
|
||||
|
||||
/// <summary>What established <see cref="Offset"/> ("bootstrap-policy-result", "bootstrap-stdout", …).</summary>
|
||||
public string? AnchorKind { get; set; }
|
||||
|
||||
public bool IsAnchored => Offset.HasValue;
|
||||
}
|
||||
|
||||
internal sealed class CmTraceEraSegment
|
||||
{
|
||||
public CmTraceEraSegment(string fileName, long startOffset, long endOffset)
|
||||
{
|
||||
FileName = fileName;
|
||||
StartOffset = startOffset;
|
||||
EndOffset = endOffset;
|
||||
}
|
||||
|
||||
public string FileName { get; }
|
||||
public long StartOffset { get; }
|
||||
/// <summary><c>long.MaxValue</c> while the era is still open in this file.</summary>
|
||||
public long EndOffset { get; set; }
|
||||
|
||||
public bool Contains(string fileName, long offset) =>
|
||||
string.Equals(FileName, fileName, StringComparison.OrdinalIgnoreCase)
|
||||
&& offset >= StartOffset && offset < EndOffset;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Era lookup for backlog lines (2026-09-04, session a7140f98). Two lookups:
|
||||
/// <list type="bullet">
|
||||
/// <item><description><see cref="TryResolveByOffset"/> — the line's own file and byte offset
|
||||
/// (IME service family and AgentExecutor.log: eras are byte ranges).</description></item>
|
||||
/// <item><description><see cref="TryResolveByLocalTime"/> — transfer for files written by the
|
||||
/// SAME process as the IME service log but without their own era marker (AppWorkload.log,
|
||||
/// AppActionProcessor.log: plugins hosted in IntuneManagementExtension.exe, verified in the
|
||||
/// decompiled build). Within one process every file shares the zone belief, so a local
|
||||
/// timestamp places the line in the service era whose local range contains it. Disabled
|
||||
/// entirely when the service eras' local ranges are not monotonic (a westward zone change
|
||||
/// between two service starts makes the ranges overlap) — ambiguity must never anchor.</description></item>
|
||||
/// </list>
|
||||
/// Everything not resolvable here stays on the marked reader-zone fallback; a partially
|
||||
/// corrected era is never produced because an anchor applies to a whole era or not at all.
|
||||
/// </summary>
|
||||
internal sealed class CmTraceEraTable
|
||||
{
|
||||
private readonly List<CmTraceEra> _offsetEras = new List<CmTraceEra>();
|
||||
private readonly List<CmTraceEra> _serviceEras = new List<CmTraceEra>();
|
||||
private bool _transferAmbiguous;
|
||||
|
||||
public IReadOnlyList<CmTraceEra> ServiceEras => _serviceEras;
|
||||
public bool TransferAmbiguous => _transferAmbiguous;
|
||||
public int AnchoredEraCount
|
||||
{
|
||||
get
|
||||
{
|
||||
var n = 0;
|
||||
foreach (var e in _offsetEras) if (e.IsAnchored) n++;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Register an era addressable by (file, offset). Service eras also take part in the local-time transfer.</summary>
|
||||
public void Add(CmTraceEra era, bool isServiceEra)
|
||||
{
|
||||
_offsetEras.Add(era);
|
||||
if (isServiceEra) _serviceEras.Add(era);
|
||||
}
|
||||
|
||||
/// <summary>Call once after all service eras are added: validates the local ranges used by the transfer.</summary>
|
||||
public void Seal()
|
||||
{
|
||||
_transferAmbiguous = false;
|
||||
DateTime? previousStart = null;
|
||||
foreach (var era in _serviceEras)
|
||||
{
|
||||
if (!era.StartLocal.HasValue) continue;
|
||||
if (previousStart.HasValue && era.StartLocal.Value <= previousStart.Value)
|
||||
{
|
||||
_transferAmbiguous = true;
|
||||
break;
|
||||
}
|
||||
previousStart = era.StartLocal;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryResolveByOffset(string fileName, long offset, out TimeSpan writerOffset, out string anchorKind)
|
||||
{
|
||||
writerOffset = TimeSpan.Zero;
|
||||
anchorKind = string.Empty;
|
||||
if (string.IsNullOrEmpty(fileName) || offset < 0) return false;
|
||||
|
||||
foreach (var era in _offsetEras)
|
||||
{
|
||||
if (!era.IsAnchored) continue;
|
||||
foreach (var seg in era.Segments)
|
||||
{
|
||||
if (seg.Contains(fileName, offset))
|
||||
{
|
||||
writerOffset = era.Offset!.Value;
|
||||
anchorKind = era.AnchorKind ?? string.Empty;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool TryResolveByLocalTime(DateTime localTimestamp, out TimeSpan writerOffset, out string anchorKind)
|
||||
{
|
||||
writerOffset = TimeSpan.Zero;
|
||||
anchorKind = string.Empty;
|
||||
if (_transferAmbiguous) return false;
|
||||
|
||||
var local = DateTime.SpecifyKind(localTimestamp, DateTimeKind.Unspecified);
|
||||
foreach (var era in _serviceEras)
|
||||
{
|
||||
if (!era.IsAnchored) continue;
|
||||
// A leading era with unknown start covers everything before its end.
|
||||
var afterStart = !era.StartLocal.HasValue || local >= era.StartLocal.Value;
|
||||
var beforeEnd = !era.EndLocal.HasValue || local < era.EndLocal.Value;
|
||||
if (afterStart && beforeEnd)
|
||||
{
|
||||
writerOffset = era.Offset!.Value;
|
||||
anchorKind = era.AnchorKind + "/service-era-transfer";
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
@@ -27,6 +27,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
/// <see cref="CmTraceOffsetCalibrator.TryMeasureOffset"/>.
|
||||
/// </summary>
|
||||
LineAnchored = 3,
|
||||
|
||||
/// <summary>
|
||||
/// A backlog line resolved through its writer ERA: the stretch of log written by one
|
||||
/// process lifetime, anchored by an entry inside that era whose UTC instant the agent
|
||||
/// knows exactly (the install marker vs. the IME's own record of the bootstrap script's
|
||||
/// result — a few hundred milliseconds apart). An anchor applies to a whole era or not
|
||||
/// at all, never across an "EMS Agent Started" boundary. See <c>ImeLogEraPreScan</c>
|
||||
/// (2026-09-04, session a7140f98).
|
||||
/// </summary>
|
||||
EraAnchored = 4,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Shared.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// Builds the <see cref="CmTraceEraTable"/> for the backlog the tracker is about to read
|
||||
/// (2026-09-04, session a7140f98: the IME service wrote the whole device-ESP era under the
|
||||
/// OOBE default zone, Windows moved the zone before the agent started, and the restart
|
||||
/// replay put every pre-reboot line three hours early — a 20-minute DeviceSetup became a
|
||||
/// "blocking app timeout").
|
||||
/// <para>
|
||||
/// Backlog lines can never self-anchor (their age would round onto the offset grid), so an
|
||||
/// era needs an entry whose UTC instant is known independently. The one such entry every
|
||||
/// platform-script bootstrap leaves behind is the bootstrap script's own execution: the
|
||||
/// install marker (<c>HKLM\SOFTWARE\AutopilotMonitor\Deployed</c>, UTC) is written
|
||||
/// milliseconds before the script exits, and the IME logs that exit twice — AgentExecutor.log
|
||||
/// records the script's stdout ("Bootstrap Completed Successfully"), and the service log
|
||||
/// records "[PowerShell] … Policy id = <bootstrap>, policy result = …". Field measurement
|
||||
/// (4 sessions, 2026-09-04): 0.13–0.28 s between marker and stdout record, 0.02–0.08 s more to
|
||||
/// the service record — against a 15-minute grid with a 2-minute residual guard.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Rules that keep this sound: only the FIRST bootstrap record of each file is offered (a
|
||||
/// SKIP re-run minutes later could round onto the grid); the residual guard is
|
||||
/// <see cref="CmTraceOffsetCalibrator.TryMeasureOffset"/>; an anchor applies to the whole
|
||||
/// era between two "EMS Agent Started" entries (service) or one script execution
|
||||
/// (AgentExecutor) and never beyond; nothing is anchored without a marker (MSI bootstrap,
|
||||
/// replay tooling). Everything else stays on the marked reader-zone fallback.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
internal static class ImeLogEraPreScan
|
||||
{
|
||||
internal const string AnchorKindBootstrapStdout = "bootstrap-stdout";
|
||||
internal const string AnchorKindBootstrapPolicyResult = "bootstrap-policy-result";
|
||||
|
||||
private const string ServiceStartedPrefix = "EMS Agent Started";
|
||||
private const string ExecutorScriptStartPrefix = "Adding argument powershell with value ";
|
||||
private const string ExecutorOutputPrefix = "write output done.";
|
||||
private const string BootstrapInstallRunMarker = "Bootstrap Completed Successfully";
|
||||
private const string BootstrapInstallRunMarkerAlt = "Agent install mode completed successfully";
|
||||
|
||||
private static readonly Regex ExecutorScriptPolicyId = new Regex(
|
||||
@"Policies\\Scripts\\[a-z0-9\-]+_(?<id>[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.ps1",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));
|
||||
|
||||
private static readonly Regex ServicePolicyResult = new Regex(
|
||||
@"^\[PowerShell\] User Id = [a-f0-9\-]+, Policy id = (?<id>[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}), policy result = ",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));
|
||||
|
||||
private const int MaxEntryLines = 100;
|
||||
|
||||
public sealed class ScanInput
|
||||
{
|
||||
public ScanInput(string filePath, long startOffset)
|
||||
{
|
||||
FilePath = filePath;
|
||||
StartOffset = startOffset;
|
||||
}
|
||||
|
||||
public string FilePath { get; }
|
||||
public long StartOffset { get; }
|
||||
}
|
||||
|
||||
public static bool IsServiceLogFile(string fileName) =>
|
||||
fileName.StartsWith("IntuneManagementExtension", StringComparison.OrdinalIgnoreCase)
|
||||
|| fileName.StartsWith("_IntuneManagementExtension", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
public static bool IsExecutorLogFile(string fileName) =>
|
||||
fileName.StartsWith("AgentExecutor", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Files written in-process by the IME service without an era marker of their own (transfer by local time).</summary>
|
||||
public static bool IsServiceHostedFile(string fileName) =>
|
||||
fileName.StartsWith("AppWorkload", StringComparison.OrdinalIgnoreCase)
|
||||
|| fileName.StartsWith("AppActionProcessor", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Scan the given files (sort order = write order; archived before current) from their
|
||||
/// start offsets to EOF and return the era table. Never throws; a file that cannot be
|
||||
/// read contributes no eras.
|
||||
/// </summary>
|
||||
public static CmTraceEraTable Build(
|
||||
IReadOnlyList<ScanInput> files,
|
||||
DateTime? deployedUtc,
|
||||
int maxEntryBytes,
|
||||
AgentLogger? logger)
|
||||
{
|
||||
var table = new CmTraceEraTable();
|
||||
if (!deployedUtc.HasValue)
|
||||
{
|
||||
logger?.Info("ImeLogEraPreScan: no Deployed marker — backlog eras stay on the reader-zone fallback");
|
||||
return table;
|
||||
}
|
||||
|
||||
string? bootstrapPolicyId = null;
|
||||
|
||||
// AgentExecutor first: it is where the bootstrap policy id becomes known.
|
||||
foreach (var input in files)
|
||||
{
|
||||
if (!IsExecutorLogFile(Path.GetFileName(input.FilePath))) continue;
|
||||
try { ScanExecutorFile(input, deployedUtc.Value, maxEntryBytes, table, ref bootstrapPolicyId, logger); }
|
||||
catch (Exception ex) { logger?.Debug($"ImeLogEraPreScan: {Path.GetFileName(input.FilePath)} skipped: {ex.Message}"); }
|
||||
}
|
||||
|
||||
var serviceFiles = new List<ScanInput>();
|
||||
foreach (var input in files)
|
||||
if (IsServiceLogFile(Path.GetFileName(input.FilePath))) serviceFiles.Add(input);
|
||||
|
||||
try { ScanServiceFiles(serviceFiles, deployedUtc.Value, maxEntryBytes, table, bootstrapPolicyId, logger); }
|
||||
catch (Exception ex) { logger?.Debug($"ImeLogEraPreScan: service scan aborted: {ex.Message}"); }
|
||||
|
||||
table.Seal();
|
||||
|
||||
logger?.Info(
|
||||
$"ImeLogEraPreScan: {table.AnchoredEraCount} anchored era(s), {table.ServiceEras.Count} service era(s), " +
|
||||
$"bootstrapPolicyId={(bootstrapPolicyId ?? "(unknown)")}, transfer={(table.TransferAmbiguous ? "ambiguous-disabled" : "enabled")}");
|
||||
return table;
|
||||
}
|
||||
|
||||
private static void ScanExecutorFile(
|
||||
ScanInput input, DateTime deployedUtc, int maxEntryBytes, CmTraceEraTable table,
|
||||
ref string? bootstrapPolicyId, AgentLogger? logger)
|
||||
{
|
||||
var fileName = Path.GetFileName(input.FilePath);
|
||||
CmTraceEra? current = null;
|
||||
string? currentPolicyId = null;
|
||||
var anchored = false;
|
||||
|
||||
foreach (var e in ReadEntries(input, maxEntryBytes))
|
||||
{
|
||||
if (e.Message.StartsWith(ExecutorScriptStartPrefix, StringComparison.Ordinal))
|
||||
{
|
||||
if (current != null) current.Segments[0].EndOffset = e.Offset;
|
||||
current = new CmTraceEra();
|
||||
current.Segments.Add(new CmTraceEraSegment(fileName, e.Offset, long.MaxValue));
|
||||
current.StartLocal = e.HasTimestamp ? e.LocalTimestamp : (DateTime?)null;
|
||||
table.Add(current, isServiceEra: false);
|
||||
var m = ExecutorScriptPolicyId.Match(e.Message);
|
||||
currentPolicyId = m.Success ? m.Groups["id"].Value : null;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (anchored || current == null || !e.HasTimestamp) continue;
|
||||
if (!e.Message.StartsWith(ExecutorOutputPrefix, StringComparison.Ordinal)) continue;
|
||||
if (e.Message.IndexOf(BootstrapInstallRunMarker, StringComparison.OrdinalIgnoreCase) < 0
|
||||
&& e.Message.IndexOf(BootstrapInstallRunMarkerAlt, StringComparison.OrdinalIgnoreCase) < 0)
|
||||
continue;
|
||||
|
||||
// First bootstrap install record of this file, offered once — accepted or not.
|
||||
anchored = true;
|
||||
if (CmTraceOffsetCalibrator.TryMeasureOffset(e.LocalTimestamp, deployedUtc, out var offset))
|
||||
{
|
||||
current.Offset = offset;
|
||||
current.AnchorKind = AnchorKindBootstrapStdout;
|
||||
if (bootstrapPolicyId == null) bootstrapPolicyId = currentPolicyId;
|
||||
logger?.Info($"ImeLogEraPreScan: {fileName} bootstrap execution anchored at {offset} (stdout local={e.LocalTimestamp:yyyy-MM-ddTHH:mm:ss.fff}, policy={currentPolicyId ?? "?"})");
|
||||
}
|
||||
else
|
||||
{
|
||||
logger?.Info($"ImeLogEraPreScan: {fileName} bootstrap stdout record rejected by the residual guard (local={e.LocalTimestamp:yyyy-MM-ddTHH:mm:ss.fff}, deployed={deployedUtc:HH:mm:ss}Z)");
|
||||
if (bootstrapPolicyId == null) bootstrapPolicyId = currentPolicyId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ScanServiceFiles(
|
||||
IReadOnlyList<ScanInput> files, DateTime deployedUtc, int maxEntryBytes, CmTraceEraTable table,
|
||||
string? bootstrapPolicyId, AgentLogger? logger)
|
||||
{
|
||||
if (files.Count == 0) return;
|
||||
|
||||
// The leading era: whatever process was writing when the scanned region begins.
|
||||
var current = new CmTraceEra();
|
||||
table.Add(current, isServiceEra: true);
|
||||
var resultOffered = false;
|
||||
|
||||
foreach (var input in files)
|
||||
{
|
||||
var fileName = Path.GetFileName(input.FilePath);
|
||||
var segment = new CmTraceEraSegment(fileName, input.StartOffset, long.MaxValue);
|
||||
current.Segments.Add(segment);
|
||||
|
||||
foreach (var e in ReadEntries(input, maxEntryBytes))
|
||||
{
|
||||
if (e.Message.StartsWith(ServiceStartedPrefix, StringComparison.Ordinal))
|
||||
{
|
||||
segment.EndOffset = e.Offset;
|
||||
var next = new CmTraceEra { StartLocal = e.HasTimestamp ? e.LocalTimestamp : (DateTime?)null };
|
||||
current.EndLocal = next.StartLocal;
|
||||
segment = new CmTraceEraSegment(fileName, e.Offset, long.MaxValue);
|
||||
next.Segments.Add(segment);
|
||||
table.Add(next, isServiceEra: true);
|
||||
current = next;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (resultOffered || bootstrapPolicyId == null || !e.HasTimestamp) continue;
|
||||
if (!e.Message.StartsWith("[PowerShell] User Id = ", StringComparison.Ordinal)) continue;
|
||||
var m = ServicePolicyResult.Match(e.Message);
|
||||
if (!m.Success || !string.Equals(m.Groups["id"].Value, bootstrapPolicyId, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
|
||||
// First result record for the bootstrap policy, offered once.
|
||||
resultOffered = true;
|
||||
if (CmTraceOffsetCalibrator.TryMeasureOffset(e.LocalTimestamp, deployedUtc, out var offset))
|
||||
{
|
||||
current.Offset = offset;
|
||||
current.AnchorKind = AnchorKindBootstrapPolicyResult;
|
||||
logger?.Info($"ImeLogEraPreScan: {fileName} service era anchored at {offset} (policy result local={e.LocalTimestamp:yyyy-MM-ddTHH:mm:ss.fff})");
|
||||
}
|
||||
else
|
||||
{
|
||||
logger?.Info($"ImeLogEraPreScan: {fileName} bootstrap policy result rejected by the residual guard (local={e.LocalTimestamp:yyyy-MM-ddTHH:mm:ss.fff}, deployed={deployedUtc:HH:mm:ss}Z)");
|
||||
}
|
||||
}
|
||||
|
||||
// The era continues into the next (newer) file: close this file's segment at EOF.
|
||||
try { segment.EndOffset = new FileInfo(input.FilePath).Length; } catch { segment.EndOffset = long.MaxValue; }
|
||||
}
|
||||
|
||||
// The last era stays open in its last file.
|
||||
var last = current.Segments[current.Segments.Count - 1];
|
||||
last.EndOffset = long.MaxValue;
|
||||
}
|
||||
|
||||
private sealed class ScannedEntry
|
||||
{
|
||||
public long Offset;
|
||||
public bool HasTimestamp;
|
||||
public DateTime LocalTimestamp;
|
||||
public string Message = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enumerate CMTrace entries with their file offsets. Same multiline assembly as the
|
||||
/// tracker's read loop (an AgentExecutor stdout record spans many lines; the closing tag
|
||||
/// carries the time); oversized or over-long entries are dropped, never partially used.
|
||||
/// </summary>
|
||||
private static IEnumerable<ScannedEntry> ReadEntries(ScanInput input, int maxEntryBytes)
|
||||
{
|
||||
using (var stream = new FileStream(input.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
{
|
||||
if (input.StartOffset > 0 && input.StartOffset < stream.Length)
|
||||
stream.Seek(input.StartOffset, SeekOrigin.Begin);
|
||||
else if (input.StartOffset >= stream.Length)
|
||||
yield break;
|
||||
|
||||
var reader = new BoundedLineReader(stream, maxEntryBytes);
|
||||
StringBuilder? buffer = null;
|
||||
var bufferLines = 0;
|
||||
long entryStart = input.StartOffset;
|
||||
var skipping = false;
|
||||
|
||||
while (true)
|
||||
{
|
||||
var line = reader.ReadLineAsync(System.Threading.CancellationToken.None).GetAwaiter().GetResult();
|
||||
if (line == null) yield break;
|
||||
if (buffer == null) entryStart = reader.LastLineStart;
|
||||
|
||||
if (reader.LastLineTruncated)
|
||||
{
|
||||
buffer = null; bufferLines = 0; skipping = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (skipping)
|
||||
{
|
||||
if (line.StartsWith("<![LOG[", StringComparison.Ordinal)) skipping = false;
|
||||
else
|
||||
{
|
||||
if (line.Contains("]LOG]!>")) skipping = false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (buffer != null)
|
||||
{
|
||||
buffer.Append('\n').Append(line);
|
||||
bufferLines++;
|
||||
if (line.Contains("]LOG]!>"))
|
||||
{
|
||||
line = buffer.ToString();
|
||||
buffer = null; bufferLines = 0;
|
||||
}
|
||||
else if (bufferLines >= MaxEntryLines || buffer.Length >= maxEntryBytes)
|
||||
{
|
||||
buffer = null; bufferLines = 0; skipping = true;
|
||||
continue;
|
||||
}
|
||||
else continue;
|
||||
}
|
||||
else if (line.StartsWith("<![LOG[", StringComparison.Ordinal) && !line.Contains("]LOG]!>"))
|
||||
{
|
||||
buffer = new StringBuilder(line);
|
||||
bufferLines = 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!CmTraceLogParser.TryParseLine(line, out var entry) || entry == null) continue;
|
||||
yield return new ScannedEntry
|
||||
{
|
||||
Offset = entryStart,
|
||||
HasTimestamp = entry.HasTimestamp && !entry.BiasMinutes.HasValue,
|
||||
LocalTimestamp = entry.LocalTimestamp,
|
||||
Message = entry.Message ?? string.Empty,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
@@ -263,6 +263,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// --- Normal processing (single-line or completed multiline) ---
|
||||
CmTraceLogEntry entry;
|
||||
string messageToMatch;
|
||||
_currentEntryOffset = entryStart;
|
||||
if (CmTraceLogParser.TryParseLine(line, out entry))
|
||||
{
|
||||
messageToMatch = entry.Message;
|
||||
@@ -312,6 +313,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// flagged as such.
|
||||
if (hadPreviousObservation && calibrationAnchor != null)
|
||||
CalibrateFrom(_currentSourceFileName, Path.GetFileName(filePath), calibrationAnchor);
|
||||
_currentEntryOffset = -1;
|
||||
}
|
||||
}
|
||||
catch (FileNotFoundException) { }
|
||||
@@ -509,6 +511,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
LastMatchedSourceOffsetMinutes = null;
|
||||
LastMatchedSourceOffsetOrigin = CmTraceOffsetOrigin.None;
|
||||
LastMatchedMeasuredWriterOffsetMinutes = null;
|
||||
LastMatchedEraAnchorKind = string.Empty;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -518,6 +521,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
LastMatchedSourceLocalTimestamp = entry.HasTimestamp ? entry.LocalTimestamp : (DateTime?)null;
|
||||
LastMatchedSourceOffsetMinutes = offsetMinutes;
|
||||
LastMatchedSourceOffsetOrigin = origin;
|
||||
LastMatchedEraAnchorKind = origin == CmTraceOffsetOrigin.EraAnchored ? _lastEraAnchorKind : string.Empty;
|
||||
|
||||
// Observational: what the calibrator measured for this file, distinct from what
|
||||
// was applied above.
|
||||
@@ -555,7 +559,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// Placed after the staleness gate so a success replayed from a previous
|
||||
// enrollment's log cannot clear a genuine current outage.
|
||||
if (!isStaleReplayLine && string.Equals(pattern.PatternId, "IME-TOKEN-SUCCESS", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
ClearPendingTokenFailure();
|
||||
// Raw user-token observation for the Entra user-affinity detector (2026-09-04).
|
||||
// Deliberately NOT routed through espPhaseDetected: that path deduplicates once
|
||||
// AccountSetup is set, so a FullESP session would never report the token that
|
||||
// followed the real-user desktop.
|
||||
try { OnUserTokenAcquired?.Invoke(LastMatchedLogTimestamp); }
|
||||
catch (Exception ex) { _logger?.Warning($"OnUserTokenAcquired handler threw: {ex.Message}"); }
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
@@ -617,6 +629,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
|
||||
case "imetokenfailure":
|
||||
HandleImeTokenFailure(match.Groups["errorCode"]?.Value, message);
|
||||
// Raw per-line observation (staleness already enforced above via
|
||||
// AppMutatingActions) — the affinity detector counts failures after
|
||||
// the real-user desktop; the grace-window Warning stays separate.
|
||||
try { OnTokenFailureLine?.Invoke(match.Groups["errorCode"]?.Value, LastMatchedLogTimestamp); }
|
||||
catch (Exception ex) { _logger?.Warning($"OnTokenFailureLine handler threw: {ex.Message}"); }
|
||||
break;
|
||||
|
||||
case "imeimpersonation":
|
||||
@@ -941,6 +958,29 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
}
|
||||
}
|
||||
|
||||
// ERA ANCHOR (2026-09-04, session a7140f98): a backlog line whose writer era was
|
||||
// anchored by the bootstrap execution record resolves through that era's offset.
|
||||
// Whole era or nothing — the anchor never crosses an "EMS Agent Started" boundary,
|
||||
// and in-process sibling files (AppWorkload, AppActionProcessor) join by local
|
||||
// time only while the service eras' local ranges are unambiguous. See
|
||||
// ImeLogEraPreScan for why this is the one anchor a backlog line can trust.
|
||||
_lastEraAnchorKind = string.Empty;
|
||||
if (_currentSourceFileName != null && _currentEntryOffset >= 0)
|
||||
{
|
||||
TimeSpan eraOffset;
|
||||
string anchorKind;
|
||||
var resolved = EraTable.TryResolveByOffset(_currentSourceFileName, _currentEntryOffset, out eraOffset, out anchorKind)
|
||||
|| (ImeLogEraPreScan.IsServiceHostedFile(_currentSourceFileName)
|
||||
&& EraTable.TryResolveByLocalTime(entry.LocalTimestamp, out eraOffset, out anchorKind));
|
||||
if (resolved)
|
||||
{
|
||||
origin = CmTraceOffsetOrigin.EraAnchored;
|
||||
offsetMinutes = (int)eraOffset.TotalMinutes;
|
||||
_lastEraAnchorKind = anchorKind;
|
||||
return DateTime.SpecifyKind(entry.LocalTimestamp - eraOffset, DateTimeKind.Utc);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for everything not provably fresh: assume the reader's zone, UNIFORMLY.
|
||||
// Wrong in absolute terms whenever the writer held a different belief, but
|
||||
// self-consistent — both ends of a duration are wrong by the same amount, so derived
|
||||
|
||||
@@ -400,6 +400,27 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
/// <summary>How that offset was arrived at — declared, measured, or neither.</summary>
|
||||
public CmTraceOffsetOrigin LastMatchedSourceOffsetOrigin { get; internal set; }
|
||||
|
||||
/// <summary>
|
||||
/// For <see cref="CmTraceOffsetOrigin.EraAnchored"/>: which anchor established the era's
|
||||
/// offset ("bootstrap-policy-result", "bootstrap-stdout", with "/service-era-transfer"
|
||||
/// when the line came from an in-process sibling file). Empty otherwise.
|
||||
/// </summary>
|
||||
public string LastMatchedEraAnchorKind { get; internal set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Source of the install marker's UTC instant for the backlog era pre-scan
|
||||
/// (<see cref="ImeLogEraPreScan"/>). Defaults to the registry marker; tests inject.
|
||||
/// </summary>
|
||||
internal Func<DateTime?> DeployedUtcProvider { get; set; } = Security.DeploymentMarker.TryReadDeployedUtc;
|
||||
|
||||
/// <summary>Era table built by <see cref="PreScanEras"/> at <see cref="Start"/>; empty until then.</summary>
|
||||
internal CmTraceEraTable EraTable { get; private set; } = new CmTraceEraTable();
|
||||
|
||||
// Byte offset of the entry currently being resolved in the read loop (-1 outside it) —
|
||||
// the key for the era lookup. Set next to _currentSourceFileName.
|
||||
private long _currentEntryOffset = -1;
|
||||
private string _lastEraAnchorKind = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// The offset the calibrator MEASURED for the source file, which is not necessarily the
|
||||
/// one applied.
|
||||
@@ -425,6 +446,21 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// Args: errorCode (may be empty when IME logged none), raw failure line excerpt.
|
||||
// Fired once per distinct errorCode per tracker lifetime (see HandleImeTokenFailure).
|
||||
public Action<string, string> OnImeTokenFailure { get; set; }
|
||||
/// <summary>
|
||||
/// Fires on EVERY IME-TOKEN-SUCCESS line that passes the historic-replay gate, with the
|
||||
/// line's resolved UTC (null when the line carried no timestamp). Unlike
|
||||
/// <see cref="OnEspPhaseChanged"/> (deduplicated once AccountSetup is set) and unlike the
|
||||
/// grace-window model behind <see cref="OnImeTokenFailure"/>, this is the raw observation:
|
||||
/// "Successfully get the token" is IntuneTokenManager acquiring the signed-in user's token
|
||||
/// through WAM, i.e. the only SYSTEM-visible proof of Entra user affinity (2026-09-04).
|
||||
/// </summary>
|
||||
public Action<DateTime?> OnUserTokenAcquired { get; set; }
|
||||
/// <summary>
|
||||
/// Fires on EVERY IME-TOKEN-FAILURE line that passes the historic-replay gate:
|
||||
/// errorCode (may be empty) and the line's resolved UTC. Raw observation — the
|
||||
/// deduplicated Warning stays on <see cref="OnImeTokenFailure"/>.
|
||||
/// </summary>
|
||||
public Action<string, DateTime?> OnTokenFailureLine { get; set; }
|
||||
// Second arg: the [DO TEL] source log line's timestamp when the DO data came from a
|
||||
// log line, null when the DO collector observed the completion live via polling. The
|
||||
// consumer must stamp poll-driven telemetry with the clock — inheriting an unrelated
|
||||
@@ -839,6 +875,44 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
ActivatePatterns(_logPhaseIsCurrentPhase, force: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Build the backlog era table from the files the first pass will read, each from the
|
||||
/// position the pass will start at. Never throws — a failure leaves the table empty and
|
||||
/// every backlog line on the reader-zone fallback, exactly as before.
|
||||
/// </summary>
|
||||
internal void PreScanEras()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(_logFolder)) return;
|
||||
var inputs = new List<ImeLogEraPreScan.ScanInput>();
|
||||
var files = new List<string>();
|
||||
foreach (var filePath in Directory.EnumerateFiles(_logFolder))
|
||||
{
|
||||
if (MatchesLogFilePattern(Path.GetFileName(filePath)))
|
||||
files.Add(filePath);
|
||||
}
|
||||
files.Sort(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var filePath in files)
|
||||
{
|
||||
var info = new FileInfo(filePath);
|
||||
if (!info.Exists) continue;
|
||||
inputs.Add(new ImeLogEraPreScan.ScanInput(filePath, _positionTracker.GetSafePosition(filePath, info.Length)));
|
||||
}
|
||||
|
||||
DateTime? deployedUtc = null;
|
||||
try { deployedUtc = DeployedUtcProvider?.Invoke(); }
|
||||
catch (Exception ex) { _logger.Debug($"ImeLogTracker: Deployed marker read failed: {ex.Message}"); }
|
||||
|
||||
EraTable = ImeLogEraPreScan.Build(inputs, deployedUtc, MaxEntryBytes, _logger);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Warning($"ImeLogTracker: era pre-scan failed — backlog stays on the reader-zone fallback: {ex.Message}");
|
||||
EraTable = new CmTraceEraTable();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts the background polling task
|
||||
/// </summary>
|
||||
@@ -851,6 +925,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// exactly where we left off — no re-parsing, no device-phase bleeding.
|
||||
LoadState();
|
||||
|
||||
// Era anchors for the backlog the first pass is about to read (2026-09-04). Runs
|
||||
// before the poll loop so every replayed line already finds its era; read-only on
|
||||
// the position tracker. Replay tooling anchors nothing — its logs did not come from
|
||||
// this device's bootstrap.
|
||||
if (!SimulationMode) PreScanEras();
|
||||
|
||||
_cts = new CancellationTokenSource();
|
||||
var token = _cts.Token;
|
||||
|
||||
|
||||
+11
@@ -67,6 +67,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
public event EventHandler<AadPlaceholderUserDetectedEventArgs> PlaceholderUserDetected;
|
||||
public event EventHandler<AadUserJoinedEventArgs> AadUserJoined;
|
||||
|
||||
/// <summary>
|
||||
/// <c>true</c> while a provisioning placeholder (foouser@/autopilot@) is the JoinInfo
|
||||
/// user and no real user has replaced it. On a Hybrid join this stays true through the
|
||||
/// whole user sign-in — the AD sign-in never touches JoinInfo — so consumers report it
|
||||
/// as a fact, never as sign-in evidence (2026-09-04).
|
||||
/// </summary>
|
||||
internal bool PlaceholderObservedWithoutRealUser
|
||||
{
|
||||
get { lock (_stateLock) return _placeholderFired && !_realUserFired; }
|
||||
}
|
||||
|
||||
public AadJoinWatcher(AgentLogger logger)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
|
||||
+2
-2
@@ -234,7 +234,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
try
|
||||
{
|
||||
OnTraceEvent?.Invoke(
|
||||
"desktop_excluded_user",
|
||||
SharedEventTypes.DesktopExcludedUser,
|
||||
$"explorer.exe found but owned by excluded user '{owner}' — not a real user desktop",
|
||||
new Dictionary<string, object> { { "pid", proc.Id }, { "session", proc.SessionId }, { "owner", owner } });
|
||||
}
|
||||
@@ -250,7 +250,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
try
|
||||
{
|
||||
OnTraceEvent?.Invoke(
|
||||
"desktop_real_user_detected",
|
||||
SharedEventTypes.DesktopRealUserDetected,
|
||||
$"Real user desktop detected (explorer.exe PID {proc.Id}, user '[redacted]')",
|
||||
new Dictionary<string, object> { { "pid", proc.Id }, { "session", proc.SessionId }, { "owner", "[redacted]" } });
|
||||
}
|
||||
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Orchestration;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using SharedConstants = AutopilotMonitor.Shared.Constants;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
{
|
||||
/// <summary>
|
||||
/// Single-shot detector for Entra user affinity on Hybrid Azure AD Join devices
|
||||
/// (2026-09-04, session a7140f98). After the real user signs in, IME acquires that user's
|
||||
/// token through WAM and logs "Successfully get the token" (IntuneTokenManager,
|
||||
/// <c>IME-TOKEN-SUCCESS</c>). That line is the only SYSTEM-visible proof that the user
|
||||
/// session carries an Entra identity (PRT); a session whose user never gets one shows only
|
||||
/// "Failed to get AAD token" lines after the desktop.
|
||||
/// <para>
|
||||
/// Contract: <see cref="NotifyRealUserDesktop"/> arms the timer when the device is a Hybrid
|
||||
/// join (probe injected by the host). The first token success stamped after the desktop
|
||||
/// cancels the timer and emits <c>ime_user_token_acquired</c>; the timer emits
|
||||
/// <c>entra_user_affinity_pending</c> with the failure codes observed since the desktop.
|
||||
/// A token that arrives after the timer fired is still posted once — it tells the
|
||||
/// timeline (and the backend rule) that affinity came late rather than never.
|
||||
/// Both emissions happen at most once per agent process — a reboot starts a new process,
|
||||
/// whose repeat is exactly the confidence signal the backend rule counts. Token lines older
|
||||
/// than the desktop (minus a small tolerance for the 30 s desktop poll) belong to the
|
||||
/// device phase and are ignored: they appear in every enrollment.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Not a decision signal. Never influences completion. The JoinInfo placeholder is reported
|
||||
/// as a fact in the payload because it is NOT a login signal on a Hybrid join — the AD
|
||||
/// sign-in never replaces it; only the later Entra device registration does.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
internal sealed class EntraUserAffinityDetector : IDisposable
|
||||
{
|
||||
internal const int DefaultDelayMinutes = 10;
|
||||
internal const string SourceLabel = "EntraUserAffinityDetector";
|
||||
/// <summary>Token lines this much older than the desktop observation still count as post-desktop.</summary>
|
||||
internal static readonly TimeSpan DesktopPollTolerance = TimeSpan.FromMinutes(2);
|
||||
|
||||
private readonly InformationalEventPost _post;
|
||||
private readonly AgentLogger _logger;
|
||||
private readonly Func<bool> _isHybridJoinProbe;
|
||||
private readonly Func<bool>? _placeholderActiveProbe;
|
||||
private readonly Func<DateTime> _utcNow;
|
||||
private readonly TimeSpan _delay;
|
||||
private readonly object _lock = new object();
|
||||
private readonly List<string> _failureCodesSinceDesktop = new List<string>();
|
||||
|
||||
private Timer? _timer;
|
||||
private DateTime? _desktopObservedUtc;
|
||||
private bool _armed;
|
||||
private bool _fired;
|
||||
private bool _tokenAcquiredPosted;
|
||||
private int _failureCountSinceDesktop;
|
||||
private int _disposed;
|
||||
|
||||
internal EntraUserAffinityDetector(
|
||||
InformationalEventPost post,
|
||||
AgentLogger logger,
|
||||
Func<bool> isHybridJoinProbe,
|
||||
Func<bool>? placeholderActiveProbe = null,
|
||||
TimeSpan? delay = null,
|
||||
Func<DateTime>? utcNow = null)
|
||||
{
|
||||
_post = post ?? throw new ArgumentNullException(nameof(post));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_isHybridJoinProbe = isHybridJoinProbe ?? throw new ArgumentNullException(nameof(isHybridJoinProbe));
|
||||
_placeholderActiveProbe = placeholderActiveProbe;
|
||||
_delay = delay ?? TimeSpan.FromMinutes(DefaultDelayMinutes);
|
||||
_utcNow = utcNow ?? (() => DateTime.UtcNow);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The DesktopArrivalDetector resolved explorer.exe under a real (non-placeholder,
|
||||
/// non-system) user. Arms the timer on Hybrid devices; idempotent; no-op after a
|
||||
/// token success or after the timer fired.
|
||||
/// </summary>
|
||||
public void NotifyRealUserDesktop()
|
||||
{
|
||||
bool hybrid;
|
||||
try { hybrid = _isHybridJoinProbe(); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Warning($"EntraUserAffinityDetector: hybrid probe threw — not arming: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
if (_disposed != 0 || _armed || _fired || _tokenAcquiredPosted) return;
|
||||
if (!hybrid)
|
||||
{
|
||||
_logger.Debug("EntraUserAffinityDetector: real-user desktop on a non-Hybrid device — not armed");
|
||||
return;
|
||||
}
|
||||
|
||||
_desktopObservedUtc = _utcNow();
|
||||
_armed = true;
|
||||
_logger.Info(
|
||||
$"EntraUserAffinityDetector: armed at real-user desktop — will emit {SharedConstants.EventTypes.EntraUserAffinityPending} in {_delay.TotalMinutes:F0} min unless IME acquires a user token");
|
||||
_timer = new Timer(OnTimer, null, _delay, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>IME-TOKEN-SUCCESS line observed; <paramref name="lineUtc"/> is the line's resolved time.</summary>
|
||||
public void NotifyUserTokenAcquired(DateTime? lineUtc)
|
||||
{
|
||||
DateTime desktop;
|
||||
double minutesAfterDesktop;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_disposed != 0 || !_armed || _tokenAcquiredPosted) return;
|
||||
desktop = _desktopObservedUtc!.Value;
|
||||
if (!IsAfterDesktop(lineUtc, desktop)) return;
|
||||
|
||||
_tokenAcquiredPosted = true;
|
||||
_timer?.Dispose();
|
||||
_timer = null;
|
||||
minutesAfterDesktop = ((lineUtc ?? _utcNow()) - desktop).TotalMinutes;
|
||||
}
|
||||
|
||||
var data = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["minutesAfterDesktop"] = Math.Max(0, minutesAfterDesktop).ToString("F1", System.Globalization.CultureInfo.InvariantCulture),
|
||||
["tokenFailuresBeforeSuccess"] = _failureCountSinceDesktop.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
["isHybridJoin"] = "true",
|
||||
};
|
||||
|
||||
_post.Emit(
|
||||
eventType: SharedConstants.EventTypes.ImeUserTokenAcquired,
|
||||
source: SourceLabel,
|
||||
message: "Entra user token acquired by IME after the real-user desktop — user affinity established",
|
||||
severity: EventSeverity.Info,
|
||||
immediateUpload: false,
|
||||
data: data,
|
||||
occurredAtUtc: lineUtc);
|
||||
|
||||
_logger.Info($"EntraUserAffinityDetector: user token observed {minutesAfterDesktop:F1} min after desktop — timer cancelled");
|
||||
}
|
||||
|
||||
/// <summary>IME-TOKEN-FAILURE line observed; counted only when stamped after the desktop.</summary>
|
||||
public void NotifyTokenFailureLine(string? errorCode, DateTime? lineUtc)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_disposed != 0 || !_armed || _fired || _tokenAcquiredPosted) return;
|
||||
if (!IsAfterDesktop(lineUtc, _desktopObservedUtc!.Value)) return;
|
||||
|
||||
_failureCountSinceDesktop++;
|
||||
var code = string.IsNullOrWhiteSpace(errorCode) ? "unknown" : errorCode!.Trim();
|
||||
if (!_failureCodesSinceDesktop.Contains(code, StringComparer.OrdinalIgnoreCase))
|
||||
_failureCodesSinceDesktop.Add(code);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
|
||||
lock (_lock)
|
||||
{
|
||||
_timer?.Dispose();
|
||||
_timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Test seams — same lock and state guards as the production paths.
|
||||
internal void TriggerFromTest() => OnTimer(null);
|
||||
internal bool IsArmedForTest { get { lock (_lock) { return _armed; } } }
|
||||
internal bool HasFiredForTest { get { lock (_lock) { return _fired; } } }
|
||||
internal bool TokenAcquiredPostedForTest { get { lock (_lock) { return _tokenAcquiredPosted; } } }
|
||||
|
||||
private static bool IsAfterDesktop(DateTime? lineUtc, DateTime desktopUtc)
|
||||
{
|
||||
// A line without a timestamp cannot be placed — treat it as current (the tracker
|
||||
// only hands us lines it just read), which is after the desktop by construction.
|
||||
if (!lineUtc.HasValue) return true;
|
||||
return lineUtc.Value >= desktopUtc - DesktopPollTolerance;
|
||||
}
|
||||
|
||||
private void OnTimer(object? state)
|
||||
{
|
||||
string codes;
|
||||
int count;
|
||||
double minutesSinceDesktop;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_disposed != 0 || !_armed || _fired || _tokenAcquiredPosted) return;
|
||||
_fired = true;
|
||||
_timer?.Dispose();
|
||||
_timer = null;
|
||||
codes = string.Join(",", _failureCodesSinceDesktop);
|
||||
count = _failureCountSinceDesktop;
|
||||
minutesSinceDesktop = (_utcNow() - _desktopObservedUtc!.Value).TotalMinutes;
|
||||
}
|
||||
|
||||
var placeholderActive = "unknown";
|
||||
try
|
||||
{
|
||||
if (_placeholderActiveProbe != null)
|
||||
placeholderActive = _placeholderActiveProbe() ? "true" : "false";
|
||||
}
|
||||
catch { /* observational */ }
|
||||
|
||||
var data = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["delayMinutes"] = ((int)_delay.TotalMinutes).ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
["reason"] = "timer_fired",
|
||||
["minutesSinceDesktop"] = Math.Max(0, minutesSinceDesktop).ToString("F1", System.Globalization.CultureInfo.InvariantCulture),
|
||||
["tokenFailureCount"] = count.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
["tokenFailureCodes"] = codes,
|
||||
["placeholderActive"] = placeholderActive,
|
||||
["isHybridJoin"] = "true",
|
||||
};
|
||||
|
||||
_post.Emit(
|
||||
eventType: SharedConstants.EventTypes.EntraUserAffinityPending,
|
||||
source: SourceLabel,
|
||||
message: $"Hybrid AAD Join: {(int)_delay.TotalMinutes} min after the real-user desktop IME has not acquired an Entra user token — user affinity pending"
|
||||
+ (count > 0 ? $" ({count} token failure(s): {codes})" : string.Empty),
|
||||
severity: EventSeverity.Warning,
|
||||
immediateUpload: true,
|
||||
data: data);
|
||||
|
||||
_logger.Warning($"EntraUserAffinityDetector: emitted {SharedConstants.EventTypes.EntraUserAffinityPending} (failures={count}, codes={codes})");
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -202,9 +202,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
|
||||
/// <summary>
|
||||
/// True when any AccountSetup subcategory has been tracked (resolved or in progress).
|
||||
/// Presence semantics — see <see cref="ProvisioningStatusTracker.HasAccountSetupActivity"/>
|
||||
/// for why this must stay that way.
|
||||
/// </summary>
|
||||
public bool HasAccountSetupActivity => _provisioningTracker?.HasAccountSetupActivity ?? false;
|
||||
|
||||
/// <summary>
|
||||
/// True once an AccountSetup subcategory has left <c>notStarted</c> — see
|
||||
/// <see cref="ProvisioningStatusTracker.HasAccountSetupProgress"/>. Keep-awake input only.
|
||||
/// </summary>
|
||||
public bool HasAccountSetupProgress => _provisioningTracker?.HasAccountSetupProgress ?? false;
|
||||
|
||||
/// <summary>
|
||||
/// True once WhiteGlove start has been detected (EventID 509 or persisted from prior run).
|
||||
/// Forwarded from ModernDeploymentTracker.
|
||||
|
||||
+21
-1
@@ -36,6 +36,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
internal const int EventId_ProvisioningWillNotLaunch = 360;
|
||||
internal const int EventId_ProvisioningBlocked = 362;
|
||||
internal const int EventId_PinStatus = 376;
|
||||
// Automatic device registration failed at the join / authentication phase (Hybrid Join
|
||||
// affinity diagnosis, 2026-09-04). Not Hello events — they ride the same UDR watcher
|
||||
// because the channel is already armed; surfaced as device_registration_event.
|
||||
internal const int EventId_AutoRegistrationFailedJoin = 304;
|
||||
internal const int EventId_AutoRegistrationFailedAuth = 305;
|
||||
|
||||
internal const int EventId_HelloForBusiness_ProcessingStarted = 3024;
|
||||
internal const int EventId_HelloForBusiness_ProcessingStopped = 6045;
|
||||
@@ -47,6 +52,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
|
||||
private static readonly HashSet<int> TrackedUdrEventIds = new HashSet<int>
|
||||
{
|
||||
EventId_AutoRegistrationFailedJoin,
|
||||
EventId_AutoRegistrationFailedAuth,
|
||||
EventId_NgcKeyRegistered,
|
||||
EventId_NgcKeyRegistrationFailed,
|
||||
EventId_ProvisioningWillLaunch,
|
||||
@@ -547,7 +554,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
var query = new EventLogQuery(
|
||||
UdrEventLogChannel,
|
||||
PathType.LogName,
|
||||
"*[System[(EventID=300 or EventID=301 or EventID=358 or EventID=360 or EventID=362 or EventID=376)]]");
|
||||
"*[System[(EventID=300 or EventID=301 or EventID=304 or EventID=305 or EventID=358 or EventID=360 or EventID=362 or EventID=376)]]");
|
||||
|
||||
_udrWatcher = new EventLogWatcher(query);
|
||||
_udrWatcher.EventRecordWritten += OnUdrEventRecordWritten;
|
||||
@@ -654,6 +661,18 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
message = "Windows Hello PIN status update";
|
||||
break;
|
||||
|
||||
case EventId_AutoRegistrationFailedJoin: // 304
|
||||
case EventId_AutoRegistrationFailedAuth: // 305
|
||||
// OS-side record that the automatic device registration failed (join or
|
||||
// authentication phase). Companion evidence for entra_user_affinity_pending —
|
||||
// no Hello state involved, so no MarkHelloCompleted().
|
||||
eventType = Constants.EventTypes.DeviceRegistrationEvent;
|
||||
severity = EventSeverity.Warning;
|
||||
message = $"User Device Registration: automatic registration failed (event {eventId}, "
|
||||
+ (eventId == EventId_AutoRegistrationFailedJoin ? "join phase)" : "authentication phase)");
|
||||
_logger.Info($"User Device Registration failure event {eventId} observed");
|
||||
break;
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
@@ -691,6 +710,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
// flip state multiple times — keep batched.
|
||||
ImmediateUpload = shouldTriggerHelloCompleted
|
||||
|| eventType == Constants.EventTypes.HelloProvisioningFailed
|
||||
|| eventType == Constants.EventTypes.DeviceRegistrationEvent
|
||||
});
|
||||
|
||||
_logger.Info($"Hello event detected: {eventType} (EventID {eventId}{(isBackfill ? ", backfill" : "")})");
|
||||
|
||||
+52
-17
@@ -10,19 +10,27 @@ using SharedConstants = AutopilotMonitor.Shared.Constants;
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
{
|
||||
/// <summary>
|
||||
/// Single-shot detector for the Hybrid User-Driven completion-gap (2026-05-01 trigger:
|
||||
/// session e58bcfdb-3e68-4f23-a3c2-437429ca9e78). After a Hybrid AAD-Join reboot the
|
||||
/// agent restarts and waits for the user to log in with their real AD/AAD account
|
||||
/// (which replaces the foouser/autopilot placeholder in JoinInfo). When that login is
|
||||
/// overdue the agent today goes silent until the backend 5-h watchdog fires; this
|
||||
/// detector emits a <c>hybrid_login_pending</c> warning event after a short single-shot
|
||||
/// timer so the operator sees an explicit "stuck waiting for AD login" signal in the
|
||||
/// timeline.
|
||||
/// Single-shot detector for the Hybrid User-Driven sign-in gap (2026-05-01 trigger:
|
||||
/// session e58bcfdb-3e68-4f23-a3c2-437429ca9e78). After the Hybrid AAD-Join reboot the
|
||||
/// agent restarts and waits for the user to sign in with their AD account. When nobody
|
||||
/// signs in the agent goes silent until the backend watchdog fires; this detector emits a
|
||||
/// <c>hybrid_login_pending</c> warning after a short single-shot timer so the operator sees
|
||||
/// an explicit "still waiting for the sign-in" signal in the timeline.
|
||||
/// <para>
|
||||
/// Conditions checked at <see cref="Arm"/>: composition root must have already
|
||||
/// confirmed a) post-reboot, b) <c>isHybridJoin == true</c>. The detector itself only
|
||||
/// owns the timer + <see cref="AadJoinWatcher.AadUserJoined"/> cancel-path. No polling.
|
||||
/// No periodicity. Fires at most once per agent process.
|
||||
/// What it measures (rewritten 2026-09-04, session a7140f98): the ABSENCE of a real-user
|
||||
/// desktop. Two cancel paths: the DesktopArrivalDetector resolving explorer.exe under a
|
||||
/// real user (the actual sign-in evidence), and the AadJoinWatcher seeing a real user in
|
||||
/// JoinInfo (the Entra-join flavour, where the OOBE sign-in completes the join). On a
|
||||
/// Hybrid join the AD sign-in never replaces the JoinInfo placeholder — only the later
|
||||
/// Entra device registration does — so the placeholder state is reported as a fact in the
|
||||
/// payload, never as the reason for the warning.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Conditions checked at <see cref="Arm"/> by the composition root: post-reboot,
|
||||
/// <c>isHybridJoin == true</c>, and not a WhiteGlove device (a sealed device legitimately
|
||||
/// waits days for its user; the session status AwaitingUser already describes that).
|
||||
/// The detector owns only the timer and the cancel paths. No polling. Fires at most once
|
||||
/// per agent process.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
internal sealed class HybridLoginPendingDetector : IDisposable
|
||||
@@ -40,6 +48,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
private bool _armed;
|
||||
private bool _fired;
|
||||
private bool _cancelledByRealUser;
|
||||
private bool _cancelledByDesktop;
|
||||
private int _disposed;
|
||||
|
||||
internal HybridLoginPendingDetector(
|
||||
@@ -60,8 +69,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
|
||||
/// <summary>
|
||||
/// Starts the single-shot timer. Idempotent — repeated calls after the first arm
|
||||
/// are no-ops. Has no effect if the watcher already saw a real AAD user (the
|
||||
/// arming was racy and the cancel won), or if the detector already fired.
|
||||
/// are no-ops. Has no effect if a real-user desktop or a real AAD user was already
|
||||
/// observed (the arming was racy and the cancel won), or if the detector already fired.
|
||||
/// </summary>
|
||||
public void Arm()
|
||||
{
|
||||
@@ -69,6 +78,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
{
|
||||
if (_disposed != 0) return;
|
||||
if (_armed || _fired) return;
|
||||
if (_cancelledByDesktop)
|
||||
{
|
||||
_logger.Info("HybridLoginPendingDetector: arm requested but a real-user desktop was already observed — skipped");
|
||||
return;
|
||||
}
|
||||
if (_cancelledByRealUser)
|
||||
{
|
||||
_logger.Info("HybridLoginPendingDetector: arm requested but real AAD user already joined — skipped");
|
||||
@@ -77,12 +91,29 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
|
||||
_armed = true;
|
||||
_logger.Info(
|
||||
$"HybridLoginPendingDetector: armed — will emit hybrid_login_pending in {_delay.TotalMinutes:F0} min if real AAD user has not joined by then");
|
||||
$"HybridLoginPendingDetector: armed — will emit hybrid_login_pending in {_delay.TotalMinutes:F0} min if no real-user desktop appears by then");
|
||||
|
||||
_timer = new Timer(OnTimer, null, _delay, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The DesktopArrivalDetector resolved explorer.exe under a real user — the sign-in
|
||||
/// happened. Cancels a running timer; remembered so a later <see cref="Arm"/> is a no-op.
|
||||
/// </summary>
|
||||
public void NotifyRealUserDesktop()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
_cancelledByDesktop = true;
|
||||
if (!_armed || _fired) return;
|
||||
|
||||
_timer?.Dispose();
|
||||
_timer = null;
|
||||
_logger.Info("HybridLoginPendingDetector: cancelled — real-user desktop observed before timeout");
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
|
||||
@@ -106,6 +137,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
|
||||
internal bool IsArmedForTest { get { lock (_lock) { return _armed; } } }
|
||||
internal bool IsCancelledByRealUserForTest { get { lock (_lock) { return _cancelledByRealUser; } } }
|
||||
internal bool IsCancelledByDesktopForTest { get { lock (_lock) { return _cancelledByDesktop; } } }
|
||||
internal bool HasFiredForTest { get { lock (_lock) { return _fired; } } }
|
||||
|
||||
private void OnTimer(object? state) => EmitInternal(reason: "timer_fired");
|
||||
@@ -130,23 +162,26 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
// _armed guard (Codex review 2026-05-01): production is safe because the
|
||||
// timer is only created in Arm(), but explicit guard makes the contract
|
||||
// unambiguous — emission requires a deliberate Arm(), full stop.
|
||||
if (!_armed || _fired || _cancelledByRealUser || _disposed != 0) return;
|
||||
if (!_armed || _fired || _cancelledByRealUser || _cancelledByDesktop || _disposed != 0) return;
|
||||
_fired = true;
|
||||
_timer?.Dispose();
|
||||
_timer = null;
|
||||
}
|
||||
|
||||
var placeholderActive = _watcher.PlaceholderObservedWithoutRealUser ? "true" : "false";
|
||||
var data = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["delayMinutes"] = ((int)_delay.TotalMinutes).ToString(),
|
||||
["reason"] = reason,
|
||||
["isHybridJoin"] = "true", // armed only when composition root verified this
|
||||
["realUserDesktopSeen"] = "false",
|
||||
["placeholderActive"] = placeholderActive,
|
||||
};
|
||||
|
||||
_post.Emit(
|
||||
eventType: SharedConstants.EventTypes.HybridLoginPending,
|
||||
source: SourceLabel,
|
||||
message: $"Hybrid AAD Join: {(int)_delay.TotalMinutes} min after reboot still no real AD user — login overdue (placeholder still active in JoinInfo)",
|
||||
message: $"Hybrid AAD Join: {(int)_delay.TotalMinutes} min after reboot still no real-user desktop — sign-in overdue",
|
||||
severity: EventSeverity.Warning,
|
||||
immediateUpload: true,
|
||||
data: data);
|
||||
|
||||
+41
@@ -209,6 +209,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
|
||||
/// <summary>
|
||||
/// True when any AccountSetup subcategory has been tracked (resolved or in progress).
|
||||
/// <para>
|
||||
/// PRESENCE semantics, deliberately (backlog q8n, 2026-09-04): Windows writes
|
||||
/// <c>AccountSetupCategory.Status</c> with every subcategory <c>notStarted</c> before the
|
||||
/// Device-ESP page exits, so this is true at the Device→Account handoff 62407 already.
|
||||
/// That is load-bearing for completion: about one in five Classic sessions sees only ONE
|
||||
/// Shell-Core 62407 for the whole enrollment (no separate user-ESP page exit), and those
|
||||
/// sessions resolve AccountSetup solely through the user-apps-settled synthesis, which
|
||||
/// needs that single exit to be remembered as the edge. Tightening this to "progress"
|
||||
/// would strand them. Callers that need "the user ESP page has demonstrably started"
|
||||
/// use <see cref="HasAccountSetupProgress"/> instead.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public bool HasAccountSetupActivity
|
||||
{
|
||||
@@ -225,6 +236,36 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True once at least one AccountSetup subcategory has left <c>notStarted</c> — the user
|
||||
/// ESP page (or its background tracking) has demonstrably started working. Unlike
|
||||
/// <see cref="HasAccountSetupActivity"/> this is NOT satisfied by the pre-written
|
||||
/// all-<c>notStarted</c> JSON that precedes the Device-ESP exit (session a2256107: JSON at
|
||||
/// 09:37:42, intermediate 62407 at 09:37:53, first progress at 09:38:25; fleet: progress
|
||||
/// precedes the real user-ESP exit by at least ~1 min). Used by the User-ESP keep-awake
|
||||
/// host to tell the real user-ESP page exit from the Device→Account handoff exit; not a
|
||||
/// completion input.
|
||||
/// </summary>
|
||||
public bool HasAccountSetupProgress
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_stateLock)
|
||||
{
|
||||
if (_lastSubcategoryStates == null)
|
||||
return false;
|
||||
if (!_lastSubcategoryStates.TryGetValue("AccountSetupCategory.Status", out var subs) || subs == null)
|
||||
return false;
|
||||
foreach (var state in subs.Values)
|
||||
{
|
||||
if (!string.Equals(state, "notStarted", StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when DeviceSetup registry JSON contains a SaveWhiteGloveSuccessResult property
|
||||
/// with subcategoryState=succeeded. NOT a WhiteGlove indicator: on Win11 25H2 (build
|
||||
|
||||
@@ -11,6 +11,7 @@ using AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Office;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Periodic;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Transport;
|
||||
using AutopilotMonitor.Agent.V2.Core.Security;
|
||||
using AutopilotMonitor.Agent.V2.Core.SignalAdapters;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
@@ -312,6 +313,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
// later before the detector can fire). When the real-user desktop arrives, Shift+F10 is no
|
||||
// longer possible, so the console watcher is stopped to avoid post-enrollment false positives.
|
||||
ConsoleBypassHost? consoleBypassHost = null;
|
||||
// Captured likewise (assigned right after this host). The real-user desktop is the
|
||||
// sign-in evidence for the Hybrid detectors: it cancels hybrid_login_pending and arms
|
||||
// the Entra user-affinity timer (2026-09-04, session a7140f98).
|
||||
AadJoinHost? aadJoinHostRef = null;
|
||||
var desktopArrivalHost = new DesktopArrivalHost(
|
||||
logger,
|
||||
ingress,
|
||||
@@ -326,6 +331,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
// Shift+F10 works — stop the console watcher (no-op if not created / already stopped).
|
||||
consoleBypassHost?.StopForDesktopArrival();
|
||||
|
||||
aadJoinHostRef?.NotifyRealUserDesktop();
|
||||
|
||||
if (realmJoinHost == null) return;
|
||||
if (UserSidResolver.TryResolveSid(owner, out var sid) && !string.IsNullOrEmpty(sid))
|
||||
{
|
||||
@@ -340,8 +347,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
|
||||
var aadJoinHost = new AadJoinHost(
|
||||
logger, ingress, clock,
|
||||
onRealUserJoined: desktopArrivalHost.RequestResetForRealUserSwitch);
|
||||
onRealUserJoined: desktopArrivalHost.RequestResetForRealUserSwitch,
|
||||
isHybridJoinProbe: EnrollmentRegistryDetector.DetectHybridJoin);
|
||||
hosts.Add(aadJoinHost);
|
||||
aadJoinHostRef = aadJoinHost;
|
||||
|
||||
// RealmJoin support is opt-in per tenant (portal toggle → AnalyzerConfiguration.
|
||||
// EnableRealmJoinWatcher, default off). When disabled, leave realmJoinHost null:
|
||||
@@ -372,7 +381,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
tenantId: tenantId,
|
||||
ingress: ingress,
|
||||
clock: clock,
|
||||
logger: logger));
|
||||
logger: logger,
|
||||
// q8n: release on the user-ESP page exit, i.e. a Shell-Core 62407 that arrives
|
||||
// after the AccountSetup registry left notStarted — never on the handoff exit.
|
||||
accountSetupProgressProbe: () => espAndHelloHost.HasAccountSetupProgress));
|
||||
}
|
||||
|
||||
// OOBE-console / Shift+F10 detection — opt-OUT per tenant (portal toggle →
|
||||
@@ -436,6 +448,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
hosts.Add(imeLogHost);
|
||||
imeLogHostRef = imeLogHost;
|
||||
|
||||
// Entra user affinity (2026-09-04): the raw IME token lines feed the AadJoinHost's
|
||||
// affinity detector. New callbacks — nothing chained before us, so direct assignment.
|
||||
imeLogHost.Tracker.OnUserTokenAcquired = lineUtc => aadJoinHost.NotifyUserTokenAcquired(lineUtc);
|
||||
imeLogHost.Tracker.OnTokenFailureLine = (code, lineUtc) => aadJoinHost.NotifyTokenFailureLine(code, lineUtc);
|
||||
|
||||
// sits-d Cloud-PC fix (2026-08-19): the user-apps-settled AccountSetup synthesis used
|
||||
// to run ONLY on the EspExited edge. On a tenant with a large required-app set the ESP
|
||||
// page exits while apps are still in flight, the single attempt misses, and nothing
|
||||
|
||||
@@ -258,6 +258,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
/// </summary>
|
||||
public bool IsWhiteGlovePart2 => _isWhiteGlovePart2;
|
||||
|
||||
/// <summary>
|
||||
/// <c>true</c> when this device ever resumed a WhiteGlove Part 2 in this session — the
|
||||
/// state folder holds a <c>.part1-<ts>/</c> archive. Unlike
|
||||
/// <see cref="IsWhiteGlovePart2"/> (this start only) it survives later reboots within
|
||||
/// Part 2; see <see cref="StateArchiver.HasPart1Archive"/>.
|
||||
/// </summary>
|
||||
public bool HasWhiteGlovePart1Archive => StateArchiver.HasPart1Archive(_stateDirectory);
|
||||
|
||||
/// <summary>
|
||||
/// <c>true</c> wenn der Start auf einen korrupten State-Segment traf und
|
||||
/// Snapshot + Log-Segmente nach <c>.quarantine/{ts}/</c> bewegt wurden.
|
||||
|
||||
@@ -8,6 +8,13 @@ using AutopilotMonitor.DecisionCore.Engine;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
{
|
||||
/// <summary>
|
||||
/// Hybrid-identity host: the JoinInfo watcher plus the two single-shot detectors that
|
||||
/// describe the user side of a Hybrid Azure AD Join — sign-in overdue
|
||||
/// (<see cref="HybridLoginPendingDetector"/>) and Entra user affinity after the sign-in
|
||||
/// (<see cref="EntraUserAffinityDetector"/>). The composition root feeds it the
|
||||
/// DesktopArrivalDetector's real-user observation and the ImeLogTracker's raw token lines.
|
||||
/// </summary>
|
||||
internal sealed class AadJoinHost : ICollectorHost
|
||||
{
|
||||
public string Name => "AadJoinWatcher";
|
||||
@@ -15,41 +22,87 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
private readonly AadJoinWatcher _watcher;
|
||||
private readonly AadJoinWatcherAdapter _adapter;
|
||||
private readonly HybridLoginPendingDetector _hybridLoginPendingDetector;
|
||||
private readonly EntraUserAffinityDetector _userAffinityDetector;
|
||||
private int _disposed;
|
||||
|
||||
public AadJoinHost(
|
||||
AgentLogger logger,
|
||||
ISignalIngressSink ingress,
|
||||
IClock clock,
|
||||
Action? onRealUserJoined = null)
|
||||
Action? onRealUserJoined = null,
|
||||
Func<bool>? isHybridJoinProbe = null)
|
||||
{
|
||||
_watcher = new AadJoinWatcher(logger);
|
||||
_adapter = new AadJoinWatcherAdapter(_watcher, ingress, clock, onRealUserJoined: onRealUserJoined);
|
||||
var post = new InformationalEventPost(ingress, clock);
|
||||
_hybridLoginPendingDetector = new HybridLoginPendingDetector(
|
||||
watcher: _watcher,
|
||||
post: new InformationalEventPost(ingress, clock),
|
||||
post: post,
|
||||
logger: logger);
|
||||
_userAffinityDetector = new EntraUserAffinityDetector(
|
||||
post: post,
|
||||
logger: logger,
|
||||
isHybridJoinProbe: isHybridJoinProbe ?? (() => false),
|
||||
placeholderActiveProbe: () => _watcher.PlaceholderObservedWithoutRealUser,
|
||||
utcNow: () => clock.UtcNow);
|
||||
}
|
||||
|
||||
public void Start() => _watcher.Start();
|
||||
public void Stop() => _watcher.Stop();
|
||||
|
||||
/// <summary>
|
||||
/// Composition-root entry point for the Hybrid User-Driven completion-gap fix
|
||||
/// (2026-05-01). Only call when both prerequisites hold: a) the prior agent process
|
||||
/// was killed by an OS reboot (<c>previousExitType=reboot_kill</c>), b) the
|
||||
/// Autopilot profile is Hybrid AAD Join (<c>isHybridJoin=true</c>). The detector
|
||||
/// itself enforces single-shot semantics + cancel-on-real-user — repeated calls or
|
||||
/// late calls after a real user joined are safe no-ops.
|
||||
/// Composition-root entry point for the Hybrid User-Driven sign-in-overdue warning
|
||||
/// (2026-05-01, semantics 2026-09-04). Only call when all prerequisites hold: a) the
|
||||
/// prior agent process was killed by an OS reboot (<c>previousExitType=reboot_kill</c>),
|
||||
/// b) the Autopilot profile is Hybrid AAD Join (<c>isHybridJoin=true</c>), c) the device
|
||||
/// is not a WhiteGlove device (neither resuming Part 2 nor carrying a Part-1 archive).
|
||||
/// The detector itself enforces single-shot semantics and both cancel paths —
|
||||
/// repeated calls or late calls after a desktop / real user are safe no-ops.
|
||||
/// </summary>
|
||||
public void ArmHybridLoginPendingDetector() => _hybridLoginPendingDetector.Arm();
|
||||
|
||||
// Test seam — exposes the detector for unit tests in the V2.Core.Tests project.
|
||||
/// <summary>
|
||||
/// The DesktopArrivalDetector resolved explorer.exe under a real user: cancels the
|
||||
/// sign-in-overdue timer and arms the user-affinity timer (Hybrid devices only).
|
||||
/// </summary>
|
||||
public void NotifyRealUserDesktop()
|
||||
{
|
||||
try { _hybridLoginPendingDetector.NotifyRealUserDesktop(); }
|
||||
catch (Exception ex) { LogCallbackFailure("HybridLoginPendingDetector.NotifyRealUserDesktop", ex); }
|
||||
try { _userAffinityDetector.NotifyRealUserDesktop(); }
|
||||
catch (Exception ex) { LogCallbackFailure("EntraUserAffinityDetector.NotifyRealUserDesktop", ex); }
|
||||
}
|
||||
|
||||
/// <summary>ImeLogTracker observed an IME-TOKEN-SUCCESS line (raw, every line).</summary>
|
||||
public void NotifyUserTokenAcquired(DateTime? lineUtc)
|
||||
{
|
||||
try { _userAffinityDetector.NotifyUserTokenAcquired(lineUtc); }
|
||||
catch (Exception ex) { LogCallbackFailure("EntraUserAffinityDetector.NotifyUserTokenAcquired", ex); }
|
||||
}
|
||||
|
||||
/// <summary>ImeLogTracker observed an IME-TOKEN-FAILURE line (raw, every line).</summary>
|
||||
public void NotifyTokenFailureLine(string? errorCode, DateTime? lineUtc)
|
||||
{
|
||||
try { _userAffinityDetector.NotifyTokenFailureLine(errorCode, lineUtc); }
|
||||
catch (Exception ex) { LogCallbackFailure("EntraUserAffinityDetector.NotifyTokenFailureLine", ex); }
|
||||
}
|
||||
|
||||
// Test seams — expose the detectors for unit tests in the V2.Core.Tests project.
|
||||
internal HybridLoginPendingDetector HybridLoginPendingDetectorForTest => _hybridLoginPendingDetector;
|
||||
internal EntraUserAffinityDetector UserAffinityDetectorForTest => _userAffinityDetector;
|
||||
|
||||
private static void LogCallbackFailure(string what, Exception ex)
|
||||
{
|
||||
// Host callbacks are best-effort — a detector fault must never break the caller
|
||||
// (DesktopArrivalDetector poll / ImeLogTracker drain). Swallowed on purpose; the
|
||||
// detectors log their own state transitions.
|
||||
_ = what; _ = ex;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
|
||||
try { _userAffinityDetector.Dispose(); } catch { }
|
||||
try { _hybridLoginPendingDetector.Dispose(); } catch { }
|
||||
try { _adapter.Dispose(); } catch { }
|
||||
try { _watcher.Dispose(); } catch { }
|
||||
|
||||
@@ -55,6 +55,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
/// </summary>
|
||||
public System.Collections.Generic.IReadOnlyCollection<string> StarvedAppsReported => _tracker.StarvedAppsReported;
|
||||
|
||||
/// <summary>
|
||||
/// True once an AccountSetup subcategory has left <c>notStarted</c> — the probe the
|
||||
/// User-ESP keep-awake host uses to tell the real user-ESP page exit from the
|
||||
/// Device→Account handoff exit (see <see cref="EspAndHelloTracker.HasAccountSetupProgress"/>).
|
||||
/// </summary>
|
||||
public bool HasAccountSetupProgress => _tracker.HasAccountSetupProgress;
|
||||
|
||||
/// <summary>L6 — atomic claim for the termination sweep (see EspAndHelloTracker.TryClaimStarvedAppReport).</summary>
|
||||
public bool TryClaimStarvedAppReport(string appId) => _tracker.TryClaimStarvedAppReport(appId);
|
||||
|
||||
|
||||
+51
-9
@@ -22,15 +22,31 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
/// hook <c>GatherRuleExecutorHost</c> uses for phase_change triggers):
|
||||
/// <list type="bullet">
|
||||
/// <item><b>Engage</b> when a signal reports the ESP phase as <c>AccountSetup</c>.</item>
|
||||
/// <item><b>Release</b> on <see cref="DecisionSignalKind.AccountSetupProvisioningComplete"/>
|
||||
/// (User-ESP done), on <see cref="Stop"/> (session teardown), or on the safety-cap timer
|
||||
/// (a backstop in case the completion signal is missed, so a device is never held awake
|
||||
/// for the agent's full max-lifetime).</item>
|
||||
/// <item><b>Release</b> on <see cref="DecisionSignalKind.EspExiting"/> once the AccountSetup
|
||||
/// registry shows progress (the real user-ESP page exit — see below), on
|
||||
/// <see cref="Stop"/> (session teardown), or on the safety-cap timer (a backstop so a
|
||||
/// device is never held awake for the agent's full max-lifetime).</item>
|
||||
/// </list>
|
||||
/// The hold itself is owned by <see cref="KeepAwakeController"/>; the OS also auto-clears it
|
||||
/// on process exit / reboot, so it can never leak.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Why the ESP exit and not <see cref="DecisionSignalKind.AccountSetupProvisioningComplete"/></b>
|
||||
/// (backlog q8n, 2026-09-04): that completion signal is, fleet-wide, almost always the
|
||||
/// user-apps-settled synthesis (Windows no longer writes <c>categorySucceeded</c>), and the
|
||||
/// synthesis builds on the Device→Account handoff 62407 — so it fired a median 3 min before
|
||||
/// the user-ESP page actually closed in 77 % of keep-awake sessions, and a device on battery
|
||||
/// dropped into Modern Standby with the page still up (session a2256107). The page itself is
|
||||
/// the truth: a Shell-Core 62407 that arrives after the AccountSetup registry left
|
||||
/// <c>notStarted</c> is the user-ESP page exit (progress precedes it by ≥ 1 min across the
|
||||
/// fleet), whereas the handoff exit always precedes any progress. Desktop arrival is NOT a
|
||||
/// substitute — explorer.exe already runs under the real user while the page is still up.
|
||||
/// Sessions that only ever see the handoff exit (about one in five) keep the hold until the
|
||||
/// safety cap; that is the advertised behaviour ("awake during User-ESP") erring long, never
|
||||
/// early. The completion guards in <c>EspAndHelloTracker</c> deliberately stay on presence
|
||||
/// semantics — see <c>ProvisioningStatusTracker.HasAccountSetupActivity</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Safety-cap sizing</b>: rather than a fixed product assumption, the cap is derived at
|
||||
/// engage time from the tenant's own ESP policy — the Intune
|
||||
/// <c>SyncFailureTimeout</c> ("show error when installation takes longer than X minutes",
|
||||
@@ -62,8 +78,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
/// </summary>
|
||||
internal const int EspCapMarginMinutes = 30;
|
||||
|
||||
// Release reasons (carried on the keep_awake_released event payload).
|
||||
internal const string ReasonAccountSetupComplete = "account_setup_complete";
|
||||
// Release reasons (carried on the keep_awake_released event payload). "account_setup_complete"
|
||||
// (release on the synthesized completion signal) was retired with q8n — see the class doc.
|
||||
internal const string ReasonUserEspExited = "user_esp_exited";
|
||||
internal const string ReasonHostStop = "host_stop";
|
||||
internal const string ReasonSafetyCap = "safety_cap";
|
||||
|
||||
@@ -83,6 +100,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
private readonly int _fallbackCapMinutes;
|
||||
private readonly TimeSpan? _safetyCapOverride;
|
||||
private readonly Func<int?> _espTimeoutProvider;
|
||||
private readonly Func<bool> _accountSetupProgressProbe;
|
||||
|
||||
private enum HoldState { Idle, Engaging, Engaged, Released }
|
||||
|
||||
@@ -102,7 +120,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
int fallbackCapMinutes = DefaultFallbackCapMinutes,
|
||||
KeepAwakeController? controller = null,
|
||||
TimeSpan? safetyCapOverride = null,
|
||||
Func<int?>? espTimeoutProvider = null)
|
||||
Func<int?>? espTimeoutProvider = null,
|
||||
Func<bool>? accountSetupProgressProbe = null)
|
||||
{
|
||||
if (ingress == null) throw new ArgumentNullException(nameof(ingress));
|
||||
if (clock == null) throw new ArgumentNullException(nameof(clock));
|
||||
@@ -118,6 +137,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
// The ESP SyncFailureTimeout is read at engage time (the ESP policy is present by then).
|
||||
_espTimeoutProvider = espTimeoutProvider
|
||||
?? (() => EspSkipConfigurationProbe.ReadFull(_logger).SyncFailureTimeoutMinutes);
|
||||
// Without a probe no exit can be told apart from the handoff exit — the hold then
|
||||
// lasts until the safety cap (erring long, never early). Production always wires the
|
||||
// EspAndHelloHost probe (DefaultComponentFactory).
|
||||
_accountSetupProgressProbe = accountSetupProgressProbe ?? (() => false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -163,9 +186,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
// (which briefly waits on the keep-awake thread) is dispatched to the ThreadPool.
|
||||
try
|
||||
{
|
||||
if (kind == DecisionSignalKind.AccountSetupProvisioningComplete)
|
||||
if (kind == DecisionSignalKind.EspExiting)
|
||||
{
|
||||
ThreadPool.QueueUserWorkItem(_ => SafeRelease(ReasonAccountSetupComplete, EventSeverity.Info));
|
||||
// Only the user-ESP page exit releases: the Device→Account handoff 62407 arrives
|
||||
// before any AccountSetup subcategory has left notStarted, the real exit after.
|
||||
// Cheap to skip while idle; the probe is a locked dictionary scan.
|
||||
if (IsEngagedOrEngaging() && ProbeAccountSetupProgress())
|
||||
ThreadPool.QueueUserWorkItem(_ => SafeRelease(ReasonUserEspExited, EventSeverity.Info));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -188,6 +215,21 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
catch (Exception ex) { _logger.Error("UserEspKeepAwakeHost: engage failed.", ex); }
|
||||
}
|
||||
|
||||
private bool IsEngagedOrEngaging()
|
||||
{
|
||||
lock (_gate) { return _state == HoldState.Engaging || _state == HoldState.Engaged; }
|
||||
}
|
||||
|
||||
private bool ProbeAccountSetupProgress()
|
||||
{
|
||||
try { return _accountSetupProgressProbe(); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Debug($"UserEspKeepAwakeHost: AccountSetup progress probe threw: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void SafeRelease(string reason, EventSeverity severity)
|
||||
{
|
||||
try { Release(reason, severity, emit: true); }
|
||||
|
||||
@@ -37,6 +37,29 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
/// </summary>
|
||||
public static class StateArchiver
|
||||
{
|
||||
internal const string Part1BucketPrefix = ".part1-";
|
||||
|
||||
/// <summary>
|
||||
/// <c>true</c> when <paramref name="stateDirectory"/> holds at least one archived
|
||||
/// <c>.part1-<ts>/</c> bucket — i.e. this device already went through a WhiteGlove
|
||||
/// Part-1/Part-2 resume in this session. Durable across later reboots, unlike the
|
||||
/// <c>whiteglove.complete</c> marker (cleared on resume) and the orchestrator's
|
||||
/// in-memory Part-2 flag. Used to keep sign-in-overdue warnings off pre-provisioned
|
||||
/// devices that legitimately wait days for their user (2026-09-04).
|
||||
/// </summary>
|
||||
public static bool HasPart1Archive(string stateDirectory)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(stateDirectory) || !Directory.Exists(stateDirectory)) return false;
|
||||
return Directory.GetDirectories(stateDirectory, Part1BucketPrefix + "*").Length > 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reducer-state segment files moved into the <c>.part1-<ts>/</c> bucket on
|
||||
/// archive. <c>event-sequence.json</c> is intentionally NOT in this list — see the
|
||||
@@ -86,7 +109,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
if (!hasAny) return null;
|
||||
|
||||
var stamp = utcNow().ToString("yyyyMMdd'T'HHmmssfff'Z'");
|
||||
var bucket = Path.Combine(stateDirectory, ".part1-" + stamp);
|
||||
var bucket = Path.Combine(stateDirectory, Part1BucketPrefix + stamp);
|
||||
Directory.CreateDirectory(bucket);
|
||||
|
||||
foreach (var name in KnownSegmentFiles)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Security
|
||||
{
|
||||
/// <summary>
|
||||
/// The install-time deployment marker: <c>HKLM\SOFTWARE\AutopilotMonitor\Deployed</c>, an
|
||||
/// ISO-8601 UTC instant written by <c>--install</c> right after the runtime was handed off
|
||||
/// (writer: <c>Program.InstallMode</c> in the runtime project). It is the bootstrap script's
|
||||
/// re-entry lock and — since 2026-09-04 — the one instant the agent knows in UTC that also
|
||||
/// appears in the IME logs: the Intune Management Extension logs the bootstrap script's
|
||||
/// result a few hundred milliseconds later, which anchors the timezone of the pre-agent log
|
||||
/// era (<c>ImeLogEraPreScan</c>). Read-only here; never written from Core.
|
||||
/// </summary>
|
||||
public static class DeploymentMarker
|
||||
{
|
||||
public const string RegistryKeyPath = @"SOFTWARE\AutopilotMonitor";
|
||||
public const string RegistryValueName = "Deployed";
|
||||
|
||||
/// <summary>The marker's UTC instant, or <c>null</c> when absent or unparseable.</summary>
|
||||
public static DateTime? TryReadDeployedUtc()
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var key = Registry.LocalMachine.OpenSubKey(RegistryKeyPath))
|
||||
{
|
||||
var raw = key?.GetValue(RegistryValueName) as string;
|
||||
return Parse(raw);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Pure parse of the marker text (round-trip "O" format); exposed for tests.</summary>
|
||||
public static DateTime? Parse(string? raw)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(raw)) return null;
|
||||
if (!DateTime.TryParse(raw, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed))
|
||||
return null;
|
||||
return parsed.Kind == DateTimeKind.Utc ? parsed : parsed.ToUniversalTime();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -464,6 +464,11 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
if (offsetMinutes.HasValue)
|
||||
data["sourceOffsetMinutes"] = offsetMinutes.Value.ToString(culture);
|
||||
|
||||
// Which era anchor the offset came from — forensics for the era-anchored origin.
|
||||
var anchorKind = _tracker.LastMatchedEraAnchorKind;
|
||||
if (!string.IsNullOrEmpty(anchorKind))
|
||||
data["sourceOffsetAnchor"] = anchorKind;
|
||||
|
||||
// Observational only — what the calibrator measured, which since the 2026-08-20
|
||||
// revert is deliberately NOT what was applied. Kept separate so the two can never
|
||||
// be read as the same thing.
|
||||
@@ -489,6 +494,9 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
// The line anchored itself: read provably fresh, its own distance to the agent
|
||||
// clock (grid-rounded) was applied as the writer's offset. Era-safe per line.
|
||||
case CmTraceOffsetOrigin.LineAnchored: return "line-anchored";
|
||||
// A backlog line resolved through its writer era, anchored by the bootstrap
|
||||
// execution record against the install marker (ImeLogEraPreScan, 2026-09-04).
|
||||
case CmTraceOffsetOrigin.EraAnchored: return "era-anchored";
|
||||
// The line was not provably fresh (backlog, restart catch-up, replay), so this
|
||||
// process's own zone was assumed — correct only if the writer happens to share it.
|
||||
default: return "reader-zone-fallback";
|
||||
|
||||
@@ -37,8 +37,10 @@ namespace AutopilotMonitor.Agent.V2
|
||||
/// </summary>
|
||||
public static partial class Program
|
||||
{
|
||||
internal const string DeploymentRegistryKey = @"SOFTWARE\AutopilotMonitor";
|
||||
internal const string DeploymentRegistryValue = "Deployed";
|
||||
// Shared with the Core reader (DeploymentMarker) — the marker's UTC instant anchors the
|
||||
// pre-agent IME log era, so writer and reader must agree on key, value and format.
|
||||
internal const string DeploymentRegistryKey = AutopilotMonitor.Agent.V2.Core.Security.DeploymentMarker.RegistryKeyPath;
|
||||
internal const string DeploymentRegistryValue = AutopilotMonitor.Agent.V2.Core.Security.DeploymentMarker.RegistryValueName;
|
||||
internal const string BootstrapConfigFileName = "bootstrap-config.json";
|
||||
internal const string AwaitEnrollmentConfigFileName = "await-enrollment.json";
|
||||
private const string InstalledAgentExeName = "AutopilotMonitor.Agent.exe";
|
||||
|
||||
@@ -494,14 +494,19 @@ namespace AutopilotMonitor.Agent.V2.Runtime
|
||||
{
|
||||
LifecycleEmitters.PostSystemRebootObserved(orchestrator.IngressSink, previousExit, logger);
|
||||
|
||||
// Hybrid User-Driven completion-gap fix (2026-05-01): the reboot is the
|
||||
// expected switch from foouser/autopilot OOBE to the real AD account.
|
||||
// If the user never logs in we go silent until the 5-h backend watchdog;
|
||||
// arm a single-shot 10-min detector that emits hybrid_login_pending
|
||||
// once if the AAD user join is overdue. Cancelled when AadJoinWatcher
|
||||
// sees the real user. Only armed for actual Hybrid devices — non-Hybrid
|
||||
// reboots don't have the placeholder→real-user flow that motivates this.
|
||||
if (!isWhiteGloveResume && EnrollmentRegistryDetector.DetectHybridJoin())
|
||||
// Hybrid User-Driven sign-in gap (2026-05-01, semantics 2026-09-04): after
|
||||
// the Hybrid reboot the user has to sign in with the AD account. If nobody
|
||||
// does, the agent goes silent until the backend watchdog; arm a single-shot
|
||||
// 10-min detector that emits hybrid_login_pending once when no real-user
|
||||
// desktop appeared by then. Cancelled by the DesktopArrivalDetector (the
|
||||
// sign-in evidence) or by the AadJoinWatcher seeing a real user (Entra-join
|
||||
// flavour). Never on WhiteGlove devices: a sealed device legitimately waits
|
||||
// days for its user, and AwaitingUser already describes that — the Part-1
|
||||
// archive check covers reboots inside Part 2 after the resume marker is gone.
|
||||
if (!isWhiteGloveResume
|
||||
&& !orchestrator.IsWhiteGlovePart2
|
||||
&& !orchestrator.HasWhiteGlovePart1Archive
|
||||
&& EnrollmentRegistryDetector.DetectHybridJoin())
|
||||
{
|
||||
try { orchestrator.CollectorSurfaces?.AadJoinHost?.ArmHybridLoginPendingDetector(); }
|
||||
catch (Exception ex)
|
||||
|
||||
+2
-1
@@ -80,7 +80,8 @@ public class AdminIdentityBindingAuthorizationTests
|
||||
{
|
||||
Middleware = new PolicyEnforcementMiddleware(
|
||||
NullLogger<PolicyEnforcementMiddleware>.Instance, globalAdmin, delegatedAdmin,
|
||||
new TenantMemberRoleResolver(tenantAdmins, tenantConfig), tenantConfig),
|
||||
new TenantMemberRoleResolver(tenantAdmins, tenantConfig), tenantConfig,
|
||||
new RecordingDenialReporter()),
|
||||
Repo = repo,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Text.Json;
|
||||
using AutopilotMonitor.Functions.Functions.Raw;
|
||||
using AutopilotMonitor.Functions.Middleware;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using Xunit;
|
||||
@@ -6,26 +8,13 @@ namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the <c>POST /api/global/raw/logs</c> KQL-proxy endpoint served by
|
||||
/// <see cref="AutopilotMonitor.Functions.Functions.Raw.AppInsightsQueryFunction"/> — an operator tool
|
||||
/// that forwards an operator-supplied KQL query VERBATIM to the Application Insights REST API. Because
|
||||
/// the query is passed through un-sandboxed and the App Insights workspace can surface secret-bearing
|
||||
/// backend traces, the TRUST BOUNDARY for this endpoint is its authorization gate: only a platform
|
||||
/// Global Admin may call it. These tests pin that gate.
|
||||
///
|
||||
/// SCOPE / WHAT IS AND IS NOT COVERED HERE (deliberate):
|
||||
/// The function's own in-request behavior — appId-not-configured → 503, empty/whitespace query →
|
||||
/// 400 BadRequest, App-Insights-error → 502 BadGateway structured error (innererror message + code +
|
||||
/// SyntaxError/SemanticError hint), happy path → 200 with the raw AI tables JSON — is NOT exercised
|
||||
/// here. The entrypoint <c>Run</c> sits directly on the abstract <c>HttpRequestData</c> /
|
||||
/// <c>HttpResponseData</c> pair (whose <c>HttpResponseData.Cookies</c> returns the abstract
|
||||
/// <c>HttpCookies</c>), reads the body via <c>ReadFromJsonAsync</c> and writes via
|
||||
/// <c>CreateResponse</c>/<c>WriteAsJsonAsync</c> (all of which need a live worker serializer resolved
|
||||
/// from <c>FunctionContext.InstanceServices</c>), and calls Application Insights through a PRIVATE
|
||||
/// STATIC <c>HttpClient</c> + <c>DefaultAzureCredential</c> with no injection seam. Faking that whole
|
||||
/// pipeline + a live Managed Identity is "more setup than the test is worth" — the exact rationale the
|
||||
/// sibling function tests cite (see DeviceBlockFunctionTests / GetAllBlockedDevicesFunctionTests,
|
||||
/// which likewise test the reachable seam instead of the HTTP entrypoint). The authorization gate
|
||||
/// below IS the security-relevant, compilable seam for this endpoint.
|
||||
/// <see cref="AppInsightsQueryFunction"/> — an operator tool that forwards an operator-supplied KQL
|
||||
/// query VERBATIM to one of three telemetry stores (backend / web App Insights, MCP Log Analytics).
|
||||
/// Because the query is passed through un-sandboxed and the stores surface secret-bearing traces and
|
||||
/// portal user telemetry, the TRUST BOUNDARY for this endpoint is its authorization gate: only a
|
||||
/// platform Global Admin may call it. These tests pin that gate, plus the pure pieces of the proxy
|
||||
/// (budget clamp, Kusto body parsing incl. partial results, error extraction). The HTTP entrypoint
|
||||
/// itself (worker serializer, managed identity) is not exercised — the seams are.
|
||||
///
|
||||
/// The gate is asserted through <see cref="EndpointAccessPolicyCatalog.FindPolicy"/> (the single source
|
||||
/// of truth the running middleware consults) and <see cref="AuthenticationMiddleware.SkipsJwtValidation"/>.
|
||||
@@ -34,6 +23,112 @@ public class AppInsightsQueryFunctionTests
|
||||
{
|
||||
private const string LogsRoute = "/api/global/raw/logs";
|
||||
|
||||
// ── Budget: null/0 → default, otherwise clamped into [5, 180] ──
|
||||
[Theory]
|
||||
[InlineData(null, 30)]
|
||||
[InlineData(0, 30)]
|
||||
[InlineData(-7, 30)]
|
||||
[InlineData(1, 5)]
|
||||
[InlineData(30, 30)]
|
||||
[InlineData(120, 120)]
|
||||
[InlineData(180, 180)]
|
||||
[InlineData(600, 180)]
|
||||
public void Budget_is_defaulted_and_clamped(int? requested, int expected)
|
||||
{
|
||||
Assert.Equal(expected, AppInsightsQueryFunction.ClampBudget(requested));
|
||||
}
|
||||
|
||||
// ── Upstream failure → status the caller sees. Query errors are the caller's (400, rendered in full
|
||||
// by the MCP); a missing managed-identity grant (401/403) and store failures (5xx) are 502. ──
|
||||
[Theory]
|
||||
[InlineData(400, System.Net.HttpStatusCode.BadRequest)] // SyntaxError / SemanticError / BadArgumentError
|
||||
[InlineData(404, System.Net.HttpStatusCode.BadRequest)] // unknown app id in the setting: still a config/caller problem, not the store
|
||||
[InlineData(401, System.Net.HttpStatusCode.BadGateway)]
|
||||
[InlineData(403, System.Net.HttpStatusCode.BadGateway)]
|
||||
[InlineData(429, System.Net.HttpStatusCode.BadRequest)]
|
||||
[InlineData(500, System.Net.HttpStatusCode.BadGateway)]
|
||||
[InlineData(503, System.Net.HttpStatusCode.BadGateway)]
|
||||
public void Upstream_failures_map_to_400_for_the_query_and_502_for_grant_or_store(int upstream, System.Net.HttpStatusCode expected)
|
||||
{
|
||||
Assert.Equal(expected, AppInsightsQueryFunction.MapUpstreamFailure((System.Net.HttpStatusCode)upstream));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Hints_name_the_query_problem_or_the_missing_grant()
|
||||
{
|
||||
Assert.Contains("syntax error", AppInsightsQueryFunction.UpstreamHint(System.Net.HttpStatusCode.BadRequest, "SyntaxError", "backend")!);
|
||||
Assert.Contains("getschema", AppInsightsQueryFunction.UpstreamHint(System.Net.HttpStatusCode.BadRequest, "SemanticError", "web")!);
|
||||
Assert.Contains("Log Analytics Reader", AppInsightsQueryFunction.UpstreamHint(System.Net.HttpStatusCode.Forbidden, null, "mcp")!);
|
||||
Assert.Null(AppInsightsQueryFunction.UpstreamHint(System.Net.HttpStatusCode.InternalServerError, "InternalError", "backend"));
|
||||
}
|
||||
|
||||
// ── Kusto body → typed tables; cells forwarded as the JSON the store produced ──
|
||||
[Fact]
|
||||
public void Kusto_body_is_parsed_cell_for_cell_and_complete_results_carry_no_partial()
|
||||
{
|
||||
const string body = """
|
||||
{"tables":[{"name":"PrimaryResult","columns":[{"name":"timestamp","type":"datetime"},{"name":"count_","type":"long"},{"name":"customDimensions","type":"dynamic"},{"name":"note","type":"string"}],
|
||||
"rows":[["2026-09-04T10:00:00Z",42,"{\"TenantId\":\"t1\"}",null]]}]}
|
||||
""";
|
||||
|
||||
var (tables, partial) = AppInsightsQueryFunction.ParseKustoBody(body);
|
||||
|
||||
Assert.Null(partial);
|
||||
var table = Assert.Single(tables);
|
||||
Assert.Equal("PrimaryResult", table.Name);
|
||||
Assert.Equal(new[] { "timestamp", "count_", "customDimensions", "note" }, table.Columns.Select(c => c.Name));
|
||||
Assert.Equal(new[] { "datetime", "long", "dynamic", "string" }, table.Columns.Select(c => c.Type));
|
||||
var row = Assert.Single(table.Rows);
|
||||
Assert.Equal(JsonValueKind.String, row[0].ValueKind);
|
||||
Assert.Equal(42, row[1].GetInt64());
|
||||
// customDimensions stays the JSON STRING App Insights emits — not re-parsed, not re-encoded.
|
||||
Assert.Equal(JsonValueKind.String, row[2].ValueKind);
|
||||
Assert.Equal("{\"TenantId\":\"t1\"}", row[2].GetString());
|
||||
Assert.Equal(JsonValueKind.Null, row[3].ValueKind);
|
||||
// Cloned cells outlive the parsed document.
|
||||
Assert.Equal("42", row[1].GetRawText());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_200_with_a_PartialError_next_to_tables_is_surfaced_not_swallowed()
|
||||
{
|
||||
const string body = """
|
||||
{"tables":[{"name":"PrimaryResult","columns":[{"name":"n","type":"long"}],"rows":[[1]]}],
|
||||
"error":{"code":"PartialError","message":"There were some errors when processing your query.","innererror":{"code":"E_QUERY_RESULT_SET_TOO_LARGE","message":"Query result set has exceeded the internal record count limit 500000."}}}
|
||||
""";
|
||||
|
||||
var (tables, partial) = AppInsightsQueryFunction.ParseKustoBody(body);
|
||||
|
||||
Assert.Single(tables);
|
||||
Assert.Equal("E_QUERY_RESULT_SET_TOO_LARGE: Query result set has exceeded the internal record count limit 500000.", partial);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Empty_or_shapeless_body_yields_no_tables_and_no_partial()
|
||||
{
|
||||
var (tables, partial) = AppInsightsQueryFunction.ParseKustoBody("{}");
|
||||
Assert.Empty(tables);
|
||||
Assert.Null(partial);
|
||||
}
|
||||
|
||||
// ── Error extraction: innererror first, then outer; tolerant of non-JSON ──
|
||||
[Fact]
|
||||
public void Error_extraction_prefers_innererror_and_tolerates_non_json()
|
||||
{
|
||||
var (msg, code) = AppInsightsQueryFunction.ExtractError(
|
||||
"""{"error":{"message":"The request had some invalid properties","code":"BadArgumentError","innererror":{"code":"SyntaxError","message":"Query could not be parsed at 'foo'"}}}""");
|
||||
Assert.Equal("SyntaxError", code);
|
||||
Assert.Equal("Query could not be parsed at 'foo'", msg);
|
||||
|
||||
var (outerMsg, outerCode) = AppInsightsQueryFunction.ExtractError("""{"error":{"message":"Forbidden","code":"InsufficientAccessError"}}""");
|
||||
Assert.Equal("InsufficientAccessError", outerCode);
|
||||
Assert.Equal("Forbidden", outerMsg);
|
||||
|
||||
var (plainMsg, plainCode) = AppInsightsQueryFunction.ExtractError("<html>502 Bad Gateway</html>");
|
||||
Assert.Null(plainCode);
|
||||
Assert.Equal("Telemetry store query failed", plainMsg);
|
||||
}
|
||||
|
||||
// ── Authorization gate: the KQL proxy is Global-Admin-only ──
|
||||
[Fact]
|
||||
public void RawLogs_post_is_registered_as_GlobalAdminOnly()
|
||||
@@ -51,6 +146,8 @@ public class AppInsightsQueryFunctionTests
|
||||
[InlineData("POST", "/api/global/raw/logs")]
|
||||
[InlineData("GET", "/api/global/raw/tables")]
|
||||
[InlineData("GET", "/api/global/raw/tables/TenantConfiguration")]
|
||||
// The MCP's assume-breach probe: its whole value is that a non-GA caller is DENIED here.
|
||||
[InlineData("GET", "/api/global/raw/access-probe")]
|
||||
public void Raw_family_endpoints_are_GlobalAdminOnly_not_global_reader(string method, string path)
|
||||
{
|
||||
var entry = EndpointAccessPolicyCatalog.FindPolicy(method, path);
|
||||
@@ -70,6 +167,14 @@ public class AppInsightsQueryFunctionTests
|
||||
Assert.False(AuthenticationMiddleware.SkipsJwtValidation("POST", LogsRoute));
|
||||
}
|
||||
|
||||
// ── The access probe must sit behind the SAME JWT gate: an anonymous hit is a 401 (no probe
|
||||
// event), only an authenticated non-GA caller reaches the 403 that raises PrivilegedRouteDenied. ──
|
||||
[Fact]
|
||||
public void AccessProbe_requires_jwt_and_is_not_exempt()
|
||||
{
|
||||
Assert.False(AuthenticationMiddleware.SkipsJwtValidation("GET", "/api/global/raw/access-probe"));
|
||||
}
|
||||
|
||||
// ── Verb binding: the KQL proxy is POST-only. A GET to the same path is unregistered and therefore
|
||||
// fail-closed (FindPolicy == null → the middleware denies). Guards against a future GET alias that
|
||||
// would carry the KQL in the query string (and into logs/URLs). ──
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
using System.Security.Claims;
|
||||
using AutopilotMonitor.Functions.Extensions;
|
||||
using AutopilotMonitor.Functions.Middleware;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Application principals — a service principal presenting an app-only token (idtyp=app, typically behind a
|
||||
/// federated credential) — flow through the same role tables as a person under the key
|
||||
/// <c>app:<client-id></c>. These tests pin the four places where that is decided: the classification
|
||||
/// (<see cref="ClaimsPrincipalExtensions.GetUserPrincipalName"/>), the authentication gate
|
||||
/// (<see cref="AuthenticationMiddleware.ValidateApplicationPrincipal"/>: the access_as_application
|
||||
/// permission is mandatory), the roleless-tier deny in the policy middleware (an application is never
|
||||
/// "some authenticated person"), and the caps — Viewer in a tenant, DelegatedReader on managed tenants,
|
||||
/// never a platform role — enforced at resolution rather than only at grant time.
|
||||
/// </summary>
|
||||
public class ApplicationPrincipalTests
|
||||
{
|
||||
private const string TenantA = "11111111-1111-1111-1111-111111111111";
|
||||
private const string TenantB = "22222222-2222-2222-2222-222222222222";
|
||||
private const string AppId = "AAAAAAAA-0000-0000-0000-00000000AAAA";
|
||||
private const string AppOid = "bbbbbbbb-0000-0000-0000-0000bbbbbbbb";
|
||||
private static readonly string AppKey = Constants.PrincipalKeys.ForApplication(AppId);
|
||||
|
||||
private static ClaimsPrincipal AppPrincipal(
|
||||
string tenantId = TenantA, string? appId = AppId, string? oid = AppOid, bool withPermission = true,
|
||||
string appIdClaim = "appid", bool idtyp = true)
|
||||
{
|
||||
var claims = new List<Claim> { new("tid", tenantId) };
|
||||
if (idtyp) claims.Add(new Claim("idtyp", "app"));
|
||||
if (appId != null) claims.Add(new Claim(appIdClaim, appId));
|
||||
if (oid != null) claims.Add(new Claim("oid", oid));
|
||||
if (withPermission) claims.Add(new Claim("roles", Constants.ApplicationPermissions.AccessAsApplication));
|
||||
return new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
|
||||
}
|
||||
|
||||
private static ClaimsPrincipal UserPrincipal(string upn = "alice@contoso.example", string tenantId = TenantA)
|
||||
=> new(new ClaimsIdentity(new[]
|
||||
{
|
||||
new Claim("tid", tenantId), new Claim("upn", upn), new Claim("oid", "cccccccc-0000-0000-0000-0000cccccccc"),
|
||||
new Claim("scp", "access_as_user"),
|
||||
}, "TestAuth"));
|
||||
|
||||
// ── Classification: the principal key ───────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData("appid")]
|
||||
[InlineData("azp")]
|
||||
public void AppOnlyToken_YieldsTheApplicationKey_FromV1AndV2Claims(string claim)
|
||||
{
|
||||
var principal = AppPrincipal(appIdClaim: claim);
|
||||
|
||||
Assert.True(principal.IsApplicationPrincipal());
|
||||
Assert.Equal(AppId.ToLowerInvariant(), principal.GetApplicationId());
|
||||
Assert.Equal($"app:{AppId.ToLowerInvariant()}", principal.GetUserPrincipalName());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TokenWithoutIdtyp_IsNotAnApplication_AndHasNoKey()
|
||||
{
|
||||
// Fail-closed classification: no idtyp ⇒ a person, who then needs a UPN like everyone else.
|
||||
var principal = AppPrincipal(idtyp: false);
|
||||
|
||||
Assert.False(principal.IsApplicationPrincipal());
|
||||
Assert.Null(principal.GetUserPrincipalName());
|
||||
Assert.Null(AdminIdentity.FromPrincipal(principal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserToken_KeepsItsUpn_EvenWhenAnAppIdIsPresent()
|
||||
{
|
||||
var principal = new ClaimsPrincipal(new ClaimsIdentity(new[]
|
||||
{
|
||||
new Claim("tid", TenantA), new Claim("upn", "Alice@Contoso.Example"), new Claim("appid", AppId),
|
||||
}, "TestAuth"));
|
||||
|
||||
Assert.Equal("Alice@Contoso.Example", principal.GetUserPrincipalName());
|
||||
Assert.False(principal.IsApplicationPrincipal());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AdminIdentity_OfAnApplication_IsFlagged()
|
||||
{
|
||||
var identity = AdminIdentity.FromPrincipal(AppPrincipal());
|
||||
|
||||
Assert.NotNull(identity);
|
||||
Assert.True(identity!.IsApplication);
|
||||
Assert.Equal(AppKey, identity.Upn);
|
||||
Assert.Equal(AppOid, identity.ObjectId);
|
||||
Assert.False(AdminIdentity.FromPrincipal(UserPrincipal())!.IsApplication);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PrincipalKeys_CannotCollideWithAUpn()
|
||||
{
|
||||
Assert.True(Constants.PrincipalKeys.IsApplication(AppKey));
|
||||
Assert.False(Constants.PrincipalKeys.IsApplication("app@contoso.example"));
|
||||
Assert.Equal(AppId.ToLowerInvariant(), Constants.PrincipalKeys.TryGetApplicationId(AppKey));
|
||||
Assert.Null(Constants.PrincipalKeys.TryGetApplicationId("alice@contoso.example"));
|
||||
}
|
||||
|
||||
// ── Authentication gate ─────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Gate_PassesUserTokens_Untouched()
|
||||
=> Assert.Null(AuthenticationMiddleware.ValidateApplicationPrincipal(UserPrincipal()));
|
||||
|
||||
[Fact]
|
||||
public void Gate_PassesAnAdmissibleAppToken()
|
||||
=> Assert.Null(AuthenticationMiddleware.ValidateApplicationPrincipal(AppPrincipal()));
|
||||
|
||||
[Fact]
|
||||
public void Gate_RejectsAnAppToken_WithoutTheApplicationPermission()
|
||||
{
|
||||
var reason = AuthenticationMiddleware.ValidateApplicationPrincipal(AppPrincipal(withPermission: false));
|
||||
|
||||
Assert.NotNull(reason);
|
||||
Assert.Contains(Constants.ApplicationPermissions.AccessAsApplication, reason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Gate_RejectsAnAppToken_WithoutApplicationIdOrObjectId()
|
||||
{
|
||||
Assert.Contains("application id", AuthenticationMiddleware.ValidateApplicationPrincipal(AppPrincipal(appId: null))!);
|
||||
Assert.Contains("object id", AuthenticationMiddleware.ValidateApplicationPrincipal(AppPrincipal(oid: null))!);
|
||||
}
|
||||
|
||||
// ── Policy middleware: roleless tiers and caps ──────────────────────────────
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
public required PolicyEnforcementMiddleware Middleware { get; init; }
|
||||
public required Mock<IAdminRepository> Repo { get; init; }
|
||||
|
||||
public void MemberRow(string role, bool enabled = true) =>
|
||||
Repo.Setup(r => r.GetTenantMemberAsync(TenantA, AppKey))
|
||||
.ReturnsAsync(new TenantMember { TenantId = TenantA, Upn = AppKey, Role = role, IsEnabled = enabled });
|
||||
}
|
||||
|
||||
private static Harness BuildHarness()
|
||||
{
|
||||
var repo = new Mock<IAdminRepository>();
|
||||
repo.Setup(r => r.GetGlobalRoleAsync(It.IsAny<string>())).ReturnsAsync((string?)null);
|
||||
repo.Setup(r => r.GetTenantMemberAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync((TenantMember?)null);
|
||||
repo.Setup(r => r.GetDelegatedTenantsAsync(It.IsAny<string>())).ReturnsAsync(new List<DelegatedAdminEntry>());
|
||||
repo.Setup(r => r.GetGroupAssignmentsForUpnAsync(It.IsAny<string>())).ReturnsAsync(new List<TenantGroupAssignment>());
|
||||
repo.Setup(r => r.GetIdentityBindingAsync(It.IsAny<string>()))
|
||||
.ReturnsAsync(new AdminIdentityBinding { TenantId = TenantA, ObjectId = AppOid });
|
||||
var configRepo = new Mock<IConfigRepository>();
|
||||
configRepo.Setup(r => r.GetTenantConfigurationAsync(It.IsAny<string>())).ReturnsAsync((TenantConfiguration?)null);
|
||||
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
var bindings = new AdminIdentityBindingService(repo.Object, cache, NullLogger<AdminIdentityBindingService>.Instance);
|
||||
var globalAdmin = new GlobalAdminService(repo.Object, bindings, cache, NullLogger<GlobalAdminService>.Instance);
|
||||
var delegatedAdmin = new DelegatedAdminService(
|
||||
repo.Object, bindings, new StubTenantEntitlementService(TenantEdition.Pro), cache, NullLogger<DelegatedAdminService>.Instance);
|
||||
var tenantAdmins = new TenantAdminsService(repo.Object, cache, NullLogger<TenantAdminsService>.Instance);
|
||||
var tenantConfig = new TenantConfigurationService(configRepo.Object, NullLogger<TenantConfigurationService>.Instance, cache);
|
||||
var mw = new PolicyEnforcementMiddleware(
|
||||
NullLogger<PolicyEnforcementMiddleware>.Instance, globalAdmin, delegatedAdmin,
|
||||
new TenantMemberRoleResolver(tenantAdmins, tenantConfig), tenantConfig, new RecordingDenialReporter());
|
||||
return new Harness { Middleware = mw, Repo = repo };
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("GET", "/api/feedback/status")] // AuthenticatedUser
|
||||
[InlineData("GET", "/api/auth/me")] // AuthenticatedUser
|
||||
[InlineData("POST", "/api/realtime/groups/join")] // AuthenticatedUserWithRole
|
||||
public async Task RolelessTiers_DenyAnApplication_UnlessTheEntryOptsIn(string method, string path)
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.MemberRow(Constants.TenantRoles.Viewer);
|
||||
|
||||
var r = await h.Middleware.DecideAsync(method, path, null, AppPrincipal());
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Equal(403, r.StatusCode);
|
||||
Assert.Equal("ApplicationPrincipalNotAllowed", r.LogReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheMcpFrontDoor_AdmitsAnApplication()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", "/api/auth/mcp", null, AppPrincipal());
|
||||
|
||||
Assert.True(r.Allowed);
|
||||
Assert.Equal(AppKey, r.Context!.UserPrincipalName);
|
||||
Assert.Equal(AppOid, r.Context.ObjectId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MemberRead_AdmitsAnApplicationMember_CappedToViewer()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.MemberRow(Constants.TenantRoles.Admin); // a row edited to Admin still reads as Viewer
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", "/api/sessions", null, AppPrincipal());
|
||||
|
||||
Assert.True(r.Allowed);
|
||||
Assert.Equal(Constants.TenantRoles.Viewer, r.Context!.UserRole);
|
||||
Assert.False(r.Context.IsTenantAdmin);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MemberRead_DeniesAnApplication_WithoutARow()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", "/api/sessions", null, AppPrincipal());
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Equal(403, r.StatusCode);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("POST", "/api/sessions/abc/actions")] // TenantAdminOrOperator
|
||||
[InlineData("PUT", "/api/sessions/abc/annotations/operator")]
|
||||
[InlineData("POST", "/api/config/11111111-1111-1111-1111-111111111111")] // TenantAdminOrGA
|
||||
public async Task WriteTiers_NeverAdmitAnApplication_EvenWithAnAdminRow(string method, string path)
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.MemberRow(Constants.TenantRoles.Admin);
|
||||
|
||||
var r = await h.Middleware.DecideAsync(method, path, null, AppPrincipal());
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Equal(403, r.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlatformRoleRow_IsInert_ForAnApplication()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.Repo.Setup(r => r.GetGlobalRoleAsync(AppKey)).ReturnsAsync(Constants.GlobalRoles.GlobalAdmin);
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", "/api/global/raw/access-probe", null, AppPrincipal());
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Equal(403, r.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DelegatedScope_OfAnApplication_IsCappedToReader()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.Repo.Setup(r => r.GetDelegatedTenantsAsync(AppKey)).ReturnsAsync(new List<DelegatedAdminEntry>
|
||||
{
|
||||
new()
|
||||
{
|
||||
TenantId = TenantB, Role = Constants.DelegatedRoles.DelegatedAdmin, IsEnabled = true,
|
||||
Status = Constants.DelegatedStatus.Active, Source = Constants.DelegatedSource.OperatorGranted,
|
||||
},
|
||||
});
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", $"/api/config/{TenantB}", null, AppPrincipal());
|
||||
|
||||
Assert.True(r.Allowed);
|
||||
Assert.True(r.Context!.IsDelegatedReader);
|
||||
Assert.False(r.Context.IsDelegatedAdmin);
|
||||
}
|
||||
|
||||
// ── Member-role resolver cap ────────────────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(Constants.TenantRoles.Admin)]
|
||||
[InlineData(Constants.TenantRoles.Operator)]
|
||||
[InlineData(Constants.TenantRoles.Viewer)]
|
||||
public async Task Resolver_CapsAnApplicationRow_ToViewer(string rowRole)
|
||||
{
|
||||
var repo = new Mock<IAdminRepository>();
|
||||
repo.Setup(r => r.GetTenantMemberAsync(TenantA, AppKey))
|
||||
.ReturnsAsync(new TenantMember { TenantId = TenantA, Upn = AppKey, Role = rowRole, IsEnabled = true });
|
||||
var sut = Resolver(repo);
|
||||
|
||||
var role = await sut.ResolveAsync(TenantA, AppKey, new[] { Constants.ApplicationPermissions.AccessAsApplication });
|
||||
|
||||
Assert.Equal(Constants.TenantRoles.Viewer, role?.Role);
|
||||
Assert.False(role!.CanManageBootstrapTokens);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolver_NeverDerivesAnApplicationRole_FromClaims()
|
||||
{
|
||||
var repo = new Mock<IAdminRepository>();
|
||||
repo.Setup(r => r.GetTenantMemberAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync((TenantMember?)null);
|
||||
var sut = Resolver(repo, appRolesEnabled: true);
|
||||
|
||||
// Even a (hypothetical) Admin app-role claim on an app token grants nothing without a row.
|
||||
var role = await sut.ResolveAsync(TenantA, AppKey, new[] { Constants.TenantRoles.Admin });
|
||||
|
||||
Assert.Null(role);
|
||||
}
|
||||
|
||||
private static TenantMemberRoleResolver Resolver(Mock<IAdminRepository> repo, bool appRolesEnabled = false)
|
||||
{
|
||||
var configRepo = new Mock<IConfigRepository>();
|
||||
configRepo.Setup(r => r.GetTenantConfigurationAsync(It.IsAny<string>()))
|
||||
.ReturnsAsync(new TenantConfiguration { TenantId = TenantA, EntraAppRolesEnabled = appRolesEnabled });
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
return new TenantMemberRoleResolver(
|
||||
new TenantAdminsService(repo.Object, cache, NullLogger<TenantAdminsService>.Instance),
|
||||
new TenantConfigurationService(configRepo.Object, NullLogger<TenantConfigurationService>.Instance, cache));
|
||||
}
|
||||
|
||||
// ── MCP front door ──────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task McpAccess_ForAnApplicationMember_IsAllMembers_AndNamesTheKey()
|
||||
{
|
||||
var (sut, members) = McpService();
|
||||
members.Verdict = (tid, key, _) => tid == TenantA && key == AppKey ? new MemberRoleInfo { Role = Constants.TenantRoles.Viewer } : null;
|
||||
|
||||
var result = await sut.IsAllowedAsync(AppKey, TenantA, AppOid, new[] { Constants.ApplicationPermissions.AccessAsApplication });
|
||||
|
||||
Assert.True(result.IsAllowed);
|
||||
Assert.Equal("AllMembers", result.AccessGrant);
|
||||
Assert.Equal(AppKey, result.Upn);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task McpAccess_ForAnApplication_WithoutMembership_SaysSo()
|
||||
{
|
||||
var (sut, _) = McpService();
|
||||
|
||||
var result = await sut.IsAllowedAsync(AppKey, TenantA, AppOid);
|
||||
|
||||
Assert.False(result.IsAllowed);
|
||||
Assert.Contains("Service principal", result.Reason);
|
||||
}
|
||||
|
||||
private static (McpUserService Sut, StubTenantMemberRoleResolver Members) McpService()
|
||||
{
|
||||
var adminRepo = new Mock<IAdminRepository>();
|
||||
adminRepo.Setup(x => x.GetMcpUserAsync(It.IsAny<string>())).ReturnsAsync((McpUserEntry?)null);
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
var bindings = new StubAdminIdentityBindingService(bound: true);
|
||||
var globalAdmin = new Mock<GlobalAdminService>(adminRepo.Object, bindings, cache, NullLogger<GlobalAdminService>.Instance) { CallBase = false };
|
||||
globalAdmin.Setup(x => x.GetGlobalRoleAsync(It.IsAny<AdminIdentity?>())).ReturnsAsync((string?)null);
|
||||
var delegatedAdmin = new Mock<DelegatedAdminService>(
|
||||
adminRepo.Object, bindings, new StubTenantEntitlementService(TenantEdition.Pro), cache, NullLogger<DelegatedAdminService>.Instance) { CallBase = false };
|
||||
delegatedAdmin.Setup(x => x.GetScopeAsync(It.IsAny<AdminIdentity?>())).ReturnsAsync(DelegatedScope.Empty);
|
||||
var adminConfig = new Mock<AdminConfigurationService>(Mock.Of<IConfigRepository>(), NullLogger<AdminConfigurationService>.Instance, cache) { CallBase = false };
|
||||
adminConfig.Setup(x => x.GetConfigurationAsync())
|
||||
.ReturnsAsync(new AdminConfiguration { McpAccessPolicy = McpAccessPolicy.AllMembers.ToString() });
|
||||
var members = new StubTenantMemberRoleResolver();
|
||||
var sut = new McpUserService(
|
||||
adminRepo.Object, bindings, cache, NullLogger<McpUserService>.Instance,
|
||||
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, members);
|
||||
return (sut, members);
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,7 @@ public class AuthenticationMiddlewareTests
|
||||
[InlineData("GET", "/api/bootstrap/validate/ABC123")]
|
||||
[InlineData("POST", "/api/agent/distress")]
|
||||
[InlineData("GET", "/api/diagnostics/download")]
|
||||
[InlineData("GET", "/api/global/session-reports/download")]
|
||||
// DeviceOrBootstrapAuth
|
||||
[InlineData("POST", "/api/agent/register-session")]
|
||||
[InlineData("POST", "/api/agent/telemetry")]
|
||||
|
||||
@@ -476,11 +476,13 @@ public class ConfigWireParityTests
|
||||
trialExpiresUtc,
|
||||
trialConsumed = true,
|
||||
effectiveEdition = "pro",
|
||||
editionSource = "plan",
|
||||
retentionGraceEndsUtc,
|
||||
maxDelegatedTenants = 5,
|
||||
maxDelegatedTenantsOverride = 5,
|
||||
mcpUsagePlan = "msp",
|
||||
mcpUsagePlanOverride = "msp"
|
||||
mcpUsagePlanOverride = "msp",
|
||||
payingCustomer = true
|
||||
},
|
||||
new SetTenantPlanTierResponse
|
||||
{
|
||||
@@ -489,11 +491,13 @@ public class ConfigWireParityTests
|
||||
TrialExpiresUtc = trialExpiresUtc,
|
||||
TrialConsumed = true,
|
||||
EffectiveEdition = "pro",
|
||||
EditionSource = "plan",
|
||||
RetentionGraceEndsUtc = retentionGraceEndsUtc,
|
||||
MaxDelegatedTenants = 5,
|
||||
MaxDelegatedTenantsOverride = 5,
|
||||
McpUsagePlan = "msp",
|
||||
McpUsagePlanOverride = "msp"
|
||||
McpUsagePlanOverride = "msp",
|
||||
PayingCustomer = true
|
||||
});
|
||||
}
|
||||
|
||||
@@ -514,11 +518,13 @@ public class ConfigWireParityTests
|
||||
trialExpiresUtc,
|
||||
trialConsumed = false,
|
||||
effectiveEdition = "community",
|
||||
editionSource = "community",
|
||||
retentionGraceEndsUtc,
|
||||
maxDelegatedTenants = 0,
|
||||
maxDelegatedTenantsOverride,
|
||||
mcpUsagePlan = "community",
|
||||
mcpUsagePlanOverride
|
||||
mcpUsagePlanOverride,
|
||||
payingCustomer = false
|
||||
},
|
||||
new SetTenantPlanTierResponse
|
||||
{
|
||||
@@ -527,11 +533,13 @@ public class ConfigWireParityTests
|
||||
TrialExpiresUtc = null,
|
||||
TrialConsumed = false,
|
||||
EffectiveEdition = "community",
|
||||
EditionSource = "community",
|
||||
RetentionGraceEndsUtc = null,
|
||||
MaxDelegatedTenants = 0,
|
||||
MaxDelegatedTenantsOverride = null,
|
||||
McpUsagePlan = "community",
|
||||
McpUsagePlanOverride = null
|
||||
McpUsagePlanOverride = null,
|
||||
PayingCustomer = false
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -67,6 +67,32 @@ public class DelegatedAdminEditionGateTests
|
||||
Assert.True(scope.Covers(ManagedTenantB));
|
||||
}
|
||||
|
||||
private const string ConferredProHomeTenant = "66666666-6666-6666-6666-666666666666";
|
||||
|
||||
[Fact]
|
||||
public async Task ConferredProHomeTenant_SuppressesEntireScope_NoTransitiveDelegation()
|
||||
{
|
||||
// The home tenant is Pro only because ANOTHER tenant manages it: the gate is the delegation
|
||||
// ENTITLEMENT (absent from conferred Pro), not the edition.
|
||||
var repo = new Mock<IAdminRepository>();
|
||||
repo.Setup(r => r.GetDelegatedTenantsAsync(It.IsAny<string>())).ReturnsAsync(new List<DelegatedAdminEntry> { Row(ManagedTenantA) });
|
||||
repo.Setup(r => r.GetGroupAssignmentsForUpnAsync(It.IsAny<string>())).ReturnsAsync(new List<TenantGroupAssignment>());
|
||||
var svc = new DelegatedAdminService(
|
||||
repo.Object,
|
||||
new StubAdminIdentityBindingService(bound: true),
|
||||
new StubTenantEntitlementService(
|
||||
tenantId => tenantId == ConferredProHomeTenant
|
||||
? new EditionResolution(TenantEdition.Pro, EditionSource.Msp, OwnPro: false)
|
||||
: new EditionResolution(TenantEdition.Community, EditionSource.Community, OwnPro: false),
|
||||
planOverrideResolver: null),
|
||||
new MemoryCache(new MemoryCacheOptions()),
|
||||
NullLogger<DelegatedAdminService>.Instance);
|
||||
|
||||
var scope = await svc.GetScopeAsync(Id(ConferredProHomeTenant));
|
||||
|
||||
Assert.True(scope.IsEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CommunityHomeTenant_SuppressesEntireScope()
|
||||
{
|
||||
|
||||
@@ -42,6 +42,7 @@ public class DelegationSelfServiceTests
|
||||
public required FakeSignalRNotificationService SignalR { get; init; }
|
||||
public required List<DelegationInvitation> Rows { get; init; }
|
||||
public required List<string> GroupTenants { get; init; }
|
||||
public required Mock<ProConferralService> ProConferral { get; init; }
|
||||
}
|
||||
|
||||
private static Harness Build(TenantEdition homeEdition = TenantEdition.Pro, int? slotOverride = null)
|
||||
@@ -111,9 +112,66 @@ public class DelegationSelfServiceTests
|
||||
.ReturnsAsync(true);
|
||||
var signalR = new FakeSignalRNotificationService();
|
||||
|
||||
// Conferred Pro is the projection's business — here we only pin that the accept/end paths notify it.
|
||||
var proConferral = new Mock<ProConferralService>(
|
||||
repo.Object,
|
||||
new TenantConfigurationService(configRepo.Object, NullLogger<TenantConfigurationService>.Instance, cache),
|
||||
ManagedTenantProIndex.None,
|
||||
NullLogger<ProConferralService>.Instance) { CallBase = false };
|
||||
|
||||
var svc = new DelegationSelfService(repo.Object, invitations.Object, delegatedAdmins, slots, entitlements, configRepo.Object, audit.Object, signalR,
|
||||
NullLogger<DelegationSelfService>.Instance, time);
|
||||
return new Harness { Svc = svc, Repo = repo, Invitations = invitations, Audit = audit, SignalR = signalR, Rows = rows, GroupTenants = groupTenants };
|
||||
proConferral.Object, NullLogger<DelegationSelfService>.Instance, time);
|
||||
return new Harness { Svc = svc, Repo = repo, Invitations = invitations, Audit = audit, SignalR = signalR, Rows = rows, GroupTenants = groupTenants, ProConferral = proConferral };
|
||||
}
|
||||
|
||||
// ── Conferred Pro hooks ───────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Accept_NotifiesConferredProProjection_ForTheCustomer()
|
||||
{
|
||||
var h = Build();
|
||||
h.Rows.Add(Pending());
|
||||
|
||||
var r = await h.Svc.AcceptAsync(Token(), Customer, CustomerAdmin);
|
||||
|
||||
Assert.True(r.Ok);
|
||||
h.ProConferral.Verify(p => p.NotifyDelegationChangedAsync(Customer), Times.Once);
|
||||
h.ProConferral.Verify(p => p.RecordLossAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveManaged_RecordsConferredProLoss_WithTheAuditReason()
|
||||
{
|
||||
var h = Build();
|
||||
h.GroupTenants.Add(Customer);
|
||||
|
||||
var r = await h.Svc.RemoveManagedAsync(Home, Customer, MspAdmin);
|
||||
|
||||
Assert.True(r.Ok);
|
||||
h.ProConferral.Verify(p => p.RecordLossAsync(Customer, Home, "customer-removed-by-manager"), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RevokeManager_RecordsConferredProLoss_WithTheAuditReason()
|
||||
{
|
||||
var h = Build();
|
||||
h.GroupTenants.Add(Customer);
|
||||
|
||||
var r = await h.Svc.RevokeManagerAsync(Customer, Home, CustomerAdmin);
|
||||
|
||||
Assert.True(r.Ok);
|
||||
h.ProConferral.Verify(p => p.RecordLossAsync(Customer, Home, "customer-revoked"), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveManaged_NotAMember_RecordsNoLoss()
|
||||
{
|
||||
var h = Build();
|
||||
|
||||
var r = await h.Svc.RemoveManagedAsync(Home, Customer, MspAdmin);
|
||||
|
||||
Assert.False(r.Ok);
|
||||
h.ProConferral.Verify(p => p.RecordLossAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
private static DelegationInvitation Pending(string id = "inv1", DateTime? expires = null) => new()
|
||||
|
||||
@@ -31,6 +31,37 @@ public class DiagnosticsDownloadTicketTests
|
||||
Assert.Equal("CustomerSas", dst);
|
||||
}
|
||||
|
||||
// ── Purpose separation: a ticket for one download surface never opens another ──
|
||||
[Fact]
|
||||
public void Diagnostics_ticket_is_rejected_on_the_report_surface_and_vice_versa()
|
||||
{
|
||||
var diag = DiagnosticsDownloadTicket.Encode(TenantA, BlobA, "Hosted");
|
||||
var report = DiagnosticsDownloadTicket.Encode(TenantA, "t_s_diag_request_20260904_120000.zip", "SessionReports",
|
||||
purpose: DiagnosticsDownloadTicket.SessionReportPurpose);
|
||||
|
||||
// Each decodes on its own surface …
|
||||
Assert.True(DiagnosticsDownloadTicket.TryDecode(diag, out _, out _, out _, out _));
|
||||
Assert.True(DiagnosticsDownloadTicket.TryDecode(report, out _, out var reportBlob, out var reportDst, out _,
|
||||
purpose: DiagnosticsDownloadTicket.SessionReportPurpose));
|
||||
Assert.Equal("t_s_diag_request_20260904_120000.zip", reportBlob);
|
||||
Assert.Equal("SessionReports", reportDst);
|
||||
|
||||
// … and is refused on the other, with the signature intact (purpose is signed, not filtered).
|
||||
Assert.False(DiagnosticsDownloadTicket.TryDecode(diag, out _, out _, out _, out var r1,
|
||||
purpose: DiagnosticsDownloadTicket.SessionReportPurpose));
|
||||
Assert.Equal("wrong_purpose", r1);
|
||||
Assert.False(DiagnosticsDownloadTicket.TryDecode(report, out _, out _, out _, out var r2));
|
||||
Assert.Equal("wrong_purpose", r2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Default_purpose_is_diagnostics()
|
||||
{
|
||||
var token = DiagnosticsDownloadTicket.Encode(TenantA, BlobA, "Hosted");
|
||||
Assert.True(DiagnosticsDownloadTicket.TryDecode(token, out _, out _, out _, out _,
|
||||
purpose: DiagnosticsDownloadTicket.DiagnosticsPurpose));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RoundTrip_HostedBlobName_Preserved()
|
||||
{
|
||||
|
||||
@@ -366,6 +366,8 @@ public class EndpointPolicyCatalogCompletenessTests
|
||||
[InlineData("GET", "/api/diagnostics/download", true)] // PublicAnonymous (ticket-gated)
|
||||
[InlineData("GET", "/api/diagnostics/download-url", false)] // MemberRead (JWT)
|
||||
[InlineData("POST", "/api/diagnostics/download-ticket", false)]// MemberRead (JWT) — mints the ticket
|
||||
[InlineData("GET", "/api/global/session-reports/download", true)] // PublicAnonymous (ticket-gated report stream)
|
||||
[InlineData("POST", "/api/global/session-reports/download-ticket", false)] // GlobalReadOrAdmin (JWT) — mints the ticket
|
||||
[InlineData("GET", "/api/health", true)] // PublicAnonymous
|
||||
[InlineData("POST", "/api/agent/telemetry", true)] // DeviceOrBootstrapAuth
|
||||
[InlineData("GET", "/api/bootstrap/validate/ABC123", true)] // PublicAnonymous (param route)
|
||||
|
||||
@@ -27,7 +27,10 @@ public class FeatureEntitlementCatalogTests
|
||||
[InlineData(" enterprise ")]
|
||||
public void ResolveEdition_ProOrLegacyEnterpriseTier_IsPro(string tier)
|
||||
{
|
||||
Assert.Equal(TenantEdition.Pro, FeatureEntitlementCatalog.ResolveEdition(tier, null, Now));
|
||||
var r = FeatureEntitlementCatalog.Resolve(tier, null, null, Now);
|
||||
Assert.Equal(TenantEdition.Pro, r.Edition);
|
||||
Assert.Equal(EditionSource.Plan, r.Source);
|
||||
Assert.True(r.OwnPro);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -38,14 +41,20 @@ public class FeatureEntitlementCatalogTests
|
||||
[InlineData("premium")] // unknown value → fail-closed
|
||||
public void ResolveEdition_NonProTier_IsCommunity(string? tier)
|
||||
{
|
||||
Assert.Equal(TenantEdition.Community, FeatureEntitlementCatalog.ResolveEdition(tier, null, Now));
|
||||
var r = FeatureEntitlementCatalog.Resolve(tier, null, null, Now);
|
||||
Assert.Equal(TenantEdition.Community, r.Edition);
|
||||
Assert.Equal(EditionSource.Community, r.Source);
|
||||
Assert.False(r.OwnPro);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveEdition_ActiveTrial_IsPro_EvenOnFreeTier()
|
||||
{
|
||||
Assert.Equal(TenantEdition.Pro,
|
||||
FeatureEntitlementCatalog.ResolveEdition("free", Now.AddSeconds(1), Now));
|
||||
var r = FeatureEntitlementCatalog.Resolve("free", Now.AddSeconds(1), null, Now);
|
||||
Assert.Equal(TenantEdition.Pro, r.Edition);
|
||||
Assert.Equal(EditionSource.Trial, r.Source);
|
||||
Assert.True(r.IsTrial);
|
||||
Assert.True(r.OwnPro);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -53,14 +62,14 @@ public class FeatureEntitlementCatalogTests
|
||||
{
|
||||
// Strict '>' — a trial ending exactly now is already over.
|
||||
Assert.Equal(TenantEdition.Community,
|
||||
FeatureEntitlementCatalog.ResolveEdition("free", Now, Now));
|
||||
FeatureEntitlementCatalog.Resolve("free", Now, null, Now).Edition);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveEdition_ExpiredTrial_IsCommunity()
|
||||
{
|
||||
Assert.Equal(TenantEdition.Community,
|
||||
FeatureEntitlementCatalog.ResolveEdition(null, Now.AddDays(-1), Now));
|
||||
FeatureEntitlementCatalog.Resolve(null, Now.AddDays(-1), null, Now).Edition);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -68,8 +77,102 @@ public class FeatureEntitlementCatalogTests
|
||||
[InlineData("enterprise")]
|
||||
public void ResolveEdition_ExpiredTrial_ButPermanentProTier_StaysPro(string tier)
|
||||
{
|
||||
Assert.Equal(TenantEdition.Pro,
|
||||
FeatureEntitlementCatalog.ResolveEdition(tier, Now.AddDays(-1), Now));
|
||||
var r = FeatureEntitlementCatalog.Resolve(tier, Now.AddDays(-1), null, Now);
|
||||
Assert.Equal(TenantEdition.Pro, r.Edition);
|
||||
Assert.Equal(EditionSource.Plan, r.Source); // permanent tier beats the stale trial timestamp
|
||||
}
|
||||
|
||||
// ── Conferred Pro ("Pro (MSP)") ─────────────────────────────────────────────
|
||||
|
||||
private const string ManagingTenant = "11111111-1111-1111-1111-111111111111";
|
||||
|
||||
[Theory]
|
||||
[InlineData("free")]
|
||||
[InlineData("community")]
|
||||
[InlineData(null)]
|
||||
public void Resolve_ManagedByProTenant_IsPro_SourceMsp_NotOwnPro(string? tier)
|
||||
{
|
||||
var r = FeatureEntitlementCatalog.Resolve(tier, null, ManagingTenant, Now);
|
||||
Assert.Equal(TenantEdition.Pro, r.Edition);
|
||||
Assert.Equal(EditionSource.Msp, r.Source);
|
||||
Assert.True(r.IsViaMsp);
|
||||
Assert.False(r.IsTrial);
|
||||
Assert.False(r.OwnPro);
|
||||
Assert.Equal("msp", r.SourceName);
|
||||
Assert.Equal("pro", r.EditionName);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("pro", null)]
|
||||
[InlineData("enterprise", null)]
|
||||
[InlineData("community", 1)] // active trial
|
||||
public void Resolve_ManagedTenant_ThatIsProItself_ShowsMsp_KeepsOwnPro(string tier, int? trialDaysLeft)
|
||||
{
|
||||
// Display precedence: MSP wins even over the tenant's own Pro (badge "Pro (MSP)"); the own
|
||||
// standing survives in OwnPro so the entitlement union keeps the delegation right.
|
||||
var r = FeatureEntitlementCatalog.Resolve(tier, trialDaysLeft is int d ? Now.AddDays(d) : null, ManagingTenant, Now);
|
||||
Assert.Equal(TenantEdition.Pro, r.Edition);
|
||||
Assert.Equal(EditionSource.Msp, r.Source);
|
||||
Assert.True(r.OwnPro);
|
||||
Assert.False(r.IsTrial);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void Resolve_BlankManagedBy_IsNotManaged(string managedBy)
|
||||
{
|
||||
var r = FeatureEntitlementCatalog.Resolve("community", null, managedBy, Now);
|
||||
Assert.Equal(TenantEdition.Community, r.Edition);
|
||||
Assert.Equal(EditionSource.Community, r.Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resolve_FromConfig_ReadsTheProjection()
|
||||
{
|
||||
var config = new AutopilotMonitor.Shared.Models.TenantConfiguration
|
||||
{
|
||||
TenantId = "t", PlanTier = "community", ManagedByProTenantId = ManagingTenant,
|
||||
};
|
||||
Assert.Equal(EditionSource.Msp, FeatureEntitlementCatalog.Resolve(config, Now).Source);
|
||||
Assert.Equal(TenantEdition.Pro, FeatureEntitlementCatalog.ResolveEdition(config, Now));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Get_ConferredPro_IsProWithoutTheDelegationRight()
|
||||
{
|
||||
var conferred = FeatureEntitlementCatalog.Get(new EditionResolution(TenantEdition.Pro, EditionSource.Msp, OwnPro: false));
|
||||
var pro = FeatureEntitlementCatalog.Get(TenantEdition.Pro);
|
||||
|
||||
Assert.Equal(TenantEdition.Pro, conferred.Edition);
|
||||
Assert.False(conferred.DelegatedAdminAllowed);
|
||||
Assert.Equal(0, conferred.MaxDelegatedTenants);
|
||||
// Everything else is the Pro value.
|
||||
Assert.Equal(pro.RetentionCapDays, conferred.RetentionCapDays);
|
||||
Assert.Equal(pro.UserRateLimitPerMinute, conferred.UserRateLimitPerMinute);
|
||||
Assert.Equal(pro.DeviceRateLimitPerMinute, conferred.DeviceRateLimitPerMinute);
|
||||
Assert.Equal(pro.BootstrapIncluded, conferred.BootstrapIncluded);
|
||||
Assert.Equal(pro.UnrestrictedModeAvailable, conferred.UnrestrictedModeAvailable);
|
||||
Assert.Equal(pro.McpUsagePlanName, conferred.McpUsagePlanName);
|
||||
Assert.Equal(pro.McpDailyRequestLimit, conferred.McpDailyRequestLimit);
|
||||
Assert.Equal(pro.McpMonthlyRequestLimit, conferred.McpMonthlyRequestLimit);
|
||||
Assert.Equal(pro.McpTenantDailyRequestLimit, conferred.McpTenantDailyRequestLimit);
|
||||
Assert.Equal(pro.McpTenantMonthlyRequestLimit, conferred.McpTenantMonthlyRequestLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Get_ManagedTenantThatIsProItself_KeepsTheFullProSet()
|
||||
{
|
||||
var e = FeatureEntitlementCatalog.Get(new EditionResolution(TenantEdition.Pro, EditionSource.Msp, OwnPro: true));
|
||||
Assert.True(e.DelegatedAdminAllowed);
|
||||
Assert.Equal(2, e.MaxDelegatedTenants);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Get_CommunityResolution_IsCommunity_RegardlessOfOwnProFlag()
|
||||
{
|
||||
var e = FeatureEntitlementCatalog.Get(new EditionResolution(TenantEdition.Community, EditionSource.Community, OwnPro: true));
|
||||
Assert.Equal(TenantEdition.Community, e.Edition);
|
||||
}
|
||||
|
||||
// ── IsPermanentProTier ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -46,6 +46,9 @@ public class GetTenantFeatureFlagsPayloadTests
|
||||
"contactEmailSet",
|
||||
"diagnosticsUploadConfigured",
|
||||
"edition",
|
||||
// Non-sensitive by review: one of "community" | "plan" | "trial" | "msp" — says WHY the
|
||||
// edition applies (the "Pro (MSP)" badge), never who the managing tenant is.
|
||||
"editionSource",
|
||||
"enableIntegrityBypassAnalyzer",
|
||||
"enableSoftwareInventoryAnalyzer",
|
||||
"entitlements",
|
||||
@@ -266,11 +269,59 @@ public class GetTenantFeatureFlagsPayloadTests
|
||||
var element = Serialize(new TenantConfiguration { TrialExpiresUtc = expiry, TrialConsumed = true });
|
||||
|
||||
Assert.Equal("pro", element.GetProperty("edition").GetString());
|
||||
Assert.Equal("trial", element.GetProperty("editionSource").GetString());
|
||||
Assert.True(element.GetProperty("isTrial").GetBoolean());
|
||||
Assert.False(element.GetProperty("trialAvailable").GetBoolean());
|
||||
Assert.Equal(expiry, element.GetProperty("trialExpiresUtc").GetDateTime());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Payload_EditionSource_Plan_And_Community()
|
||||
{
|
||||
Assert.Equal("plan", Serialize(new TenantConfiguration { PlanTier = "pro" }).GetProperty("editionSource").GetString());
|
||||
Assert.Equal("community", Serialize(new TenantConfiguration()).GetProperty("editionSource").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Payload_ManagedByProTenant_IsProViaMsp_WithoutDelegationRight_NoTrialCta()
|
||||
{
|
||||
// The projection (set by the configuration loader) turns a Community tenant into "Pro (MSP)":
|
||||
// Pro entitlements minus delegation, no trial CTA, never "isTrial", no expiry key — and the
|
||||
// managing tenant's id itself is NOT part of this member-readable payload.
|
||||
var element = Serialize(new TenantConfiguration
|
||||
{
|
||||
PlanTier = "community",
|
||||
ManagedByProTenantId = "11111111-1111-1111-1111-111111111111",
|
||||
});
|
||||
|
||||
Assert.Equal("pro", element.GetProperty("edition").GetString());
|
||||
Assert.Equal("msp", element.GetProperty("editionSource").GetString());
|
||||
Assert.False(element.GetProperty("isTrial").GetBoolean());
|
||||
Assert.False(element.GetProperty("trialAvailable").GetBoolean());
|
||||
Assert.False(element.TryGetProperty("trialExpiresUtc", out _));
|
||||
Assert.True(element.GetProperty("bootstrapTokenEnabled").GetBoolean());
|
||||
var entitlements = element.GetProperty("entitlements");
|
||||
Assert.Equal(365, entitlements.GetProperty("retentionCapDays").GetInt32());
|
||||
Assert.False(entitlements.GetProperty("delegatedAdminAllowed").GetBoolean());
|
||||
Assert.Equal(0, entitlements.GetProperty("maxDelegatedTenants").GetInt32());
|
||||
Assert.Equal("pro", entitlements.GetProperty("mcpUsagePlan").GetString());
|
||||
Assert.DoesNotContain("11111111-1111-1111-1111-111111111111", element.GetRawText());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Payload_ManagedTenant_ThatIsProItself_ShowsMsp_KeepsDelegationRight()
|
||||
{
|
||||
var element = Serialize(new TenantConfiguration
|
||||
{
|
||||
PlanTier = "pro",
|
||||
ManagedByProTenantId = "11111111-1111-1111-1111-111111111111",
|
||||
});
|
||||
|
||||
Assert.Equal("msp", element.GetProperty("editionSource").GetString());
|
||||
Assert.True(element.GetProperty("entitlements").GetProperty("delegatedAdminAllowed").GetBoolean());
|
||||
Assert.Equal(2, element.GetProperty("entitlements").GetProperty("maxDelegatedTenants").GetInt32());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Payload_ExpiredTrial_DegradesToCommunity_NoTrialAvailable()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// ANALYZE-ID-004 v2.0.0 — pins the built-in that consumes the agent's user-affinity signal:
|
||||
/// the real user reached the desktop (<c>desktop_arrived</c>), IME acquired no Entra user token
|
||||
/// within the wait window (<c>entra_user_affinity_pending</c>, at most once per agent process),
|
||||
/// and no <c>ime_user_token_acquired</c> disproves it. Repetition across reboots is the
|
||||
/// confidence lever (base 60, +20 at two, threshold 75), the terminal precondition on
|
||||
/// <c>enrollment_complete</c> stays the suppression at session end, and the v1.x evidence
|
||||
/// (<c>hybrid_login_pending</c>, the JoinInfo placeholder) must no longer fire the rule.
|
||||
/// </summary>
|
||||
public class HybridUserAffinityRuleTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "77777777-8888-9999-aaaa-bbbbbbbbbbbb";
|
||||
|
||||
private static AnalyzeRule Rule() => BuiltInAnalyzeRules.GetAll().First(r => r.RuleId == "ANALYZE-ID-004");
|
||||
|
||||
[Fact]
|
||||
public void ANALYZE_ID_004_v2_shape_is_pinned()
|
||||
{
|
||||
var rule = Rule();
|
||||
Assert.Equal("2.0.0", rule.Version);
|
||||
Assert.True(rule.Enabled);
|
||||
Assert.Equal("high", rule.Severity);
|
||||
Assert.False(rule.MarkSessionAsFailedDefault);
|
||||
Assert.Equal(75, rule.ConfidenceThreshold);
|
||||
Assert.Contains("on_event:entra_user_affinity_pending", rule.EvaluateOn!);
|
||||
Assert.DoesNotContain("on_event:hybrid_login_pending", rule.EvaluateOn!);
|
||||
|
||||
// The old evidence is gone from every rule surface — trigger, conditions and factors.
|
||||
Assert.DoesNotContain(rule.Conditions, c => c.EventType is "hybrid_login_pending" or "aad_placeholder_user_detected");
|
||||
Assert.DoesNotContain(rule.ConfidenceFactors, f => f.Signal is "hybrid_login_pending" or "aad_placeholder_user_detected");
|
||||
|
||||
var noToken = Assert.Single(rule.Conditions, c => c.Signal == "no_user_token");
|
||||
Assert.Equal("event_type", noToken.Source);
|
||||
Assert.Equal("ime_user_token_acquired", noToken.EventType);
|
||||
Assert.Equal("not_exists", noToken.Operator);
|
||||
Assert.True(noToken.Required);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Fires_when_affinity_is_pending_twice_and_no_token_was_acquired()
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
DesktopArrived(sequence: 10),
|
||||
AffinityPending(sequence: 20),
|
||||
AffinityPending(sequence: 30), // second agent process after a reboot
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(Rule(), events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
Assert.Equal("ANALYZE-ID-004", result.RuleId);
|
||||
Assert.True(result.ConfidenceScore >= 75, $"confidence {result.ConfidenceScore} below threshold");
|
||||
Assert.Equal(80, result.ConfidenceScore); // base 60 + count >= 2
|
||||
|
||||
// The absence condition carries its own evidence so the matched-condition map is
|
||||
// complete for the UI, not just the two presence signals.
|
||||
Assert.True(result.MatchedConditions.ContainsKey("user_affinity_pending"));
|
||||
Assert.True(result.MatchedConditions.ContainsKey("user_desktop_reached"));
|
||||
Assert.True(result.MatchedConditions.ContainsKey("no_user_token"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Three_pending_warnings_reach_confidence_90()
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
DesktopArrived(sequence: 10),
|
||||
AffinityPending(sequence: 20),
|
||||
AffinityPending(sequence: 30),
|
||||
AffinityPending(sequence: 40),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(Rule(), events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
Assert.Equal(90, result.ConfidenceScore); // base 60 + 20 + 10
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Does_not_fire_on_a_single_pending_warning()
|
||||
{
|
||||
// One agent process without a token is hybrid latency until it repeats: 60 < 75.
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
DesktopArrived(sequence: 10),
|
||||
AffinityPending(sequence: 20),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(Rule(), events);
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Does_not_fire_when_a_user_token_was_acquired()
|
||||
{
|
||||
// A token success after the desktop disproves the diagnosis even when the warning
|
||||
// repeated (e.g. the first two processes stalled, the third one got the PRT).
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
DesktopArrived(sequence: 10),
|
||||
AffinityPending(sequence: 20),
|
||||
AffinityPending(sequence: 30),
|
||||
Event("ime_user_token_acquired", sequence: 40, new Dictionary<string, object>
|
||||
{
|
||||
["minutesAfterDesktop"] = 3,
|
||||
["tokenFailuresBeforeSuccess"] = 4,
|
||||
["isHybridJoin"] = true,
|
||||
}),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(Rule(), events);
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Is_skipped_by_the_precondition_when_the_enrollment_completed()
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
DesktopArrived(sequence: 10),
|
||||
AffinityPending(sequence: 20),
|
||||
AffinityPending(sequence: 30),
|
||||
Event("enrollment_complete", sequence: 40, new Dictionary<string, object>()),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(Rule(), events);
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Does_not_fire_on_the_v1_evidence_alone()
|
||||
{
|
||||
// hybrid_login_pending now means "no real-user desktop yet"; together with the placeholder
|
||||
// it was the v1.x evidence and must not satisfy v2 — even at the old confidence-raising count.
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
DesktopArrived(sequence: 10),
|
||||
Event("hybrid_login_pending", sequence: 20, HybridLoginPendingData()),
|
||||
Event("hybrid_login_pending", sequence: 30, HybridLoginPendingData()),
|
||||
Event("hybrid_login_pending", sequence: 40, HybridLoginPendingData()),
|
||||
Event("aad_placeholder_user_detected", sequence: 50, new Dictionary<string, object>()),
|
||||
Event("aad_placeholder_user_detected", sequence: 60, new Dictionary<string, object>()),
|
||||
Event("aad_placeholder_user_detected", sequence: 70, new Dictionary<string, object>()),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(Rule(), events);
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Does_not_fire_without_a_real_user_desktop()
|
||||
{
|
||||
// The agent only arms the detector after the desktop, but the rule must not rely on that:
|
||||
// two pending warnings without desktop_arrived are not this diagnosis.
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
AffinityPending(sequence: 20),
|
||||
AffinityPending(sequence: 30),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(Rule(), events);
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
// ===== Event builders — mirror the agent emit shapes =====
|
||||
|
||||
private static EnrollmentEvent DesktopArrived(int sequence) =>
|
||||
Event("desktop_arrived", sequence, new Dictionary<string, object>());
|
||||
|
||||
private static EnrollmentEvent AffinityPending(int sequence) =>
|
||||
Event("entra_user_affinity_pending", sequence, new Dictionary<string, object>
|
||||
{
|
||||
["delayMinutes"] = 10,
|
||||
["reason"] = "no_user_token_after_desktop",
|
||||
["minutesSinceDesktop"] = 10,
|
||||
["tokenFailureCount"] = 4,
|
||||
["tokenFailureCodes"] = "0xCAA2000C",
|
||||
["placeholderActive"] = true,
|
||||
["isHybridJoin"] = true,
|
||||
});
|
||||
|
||||
private static Dictionary<string, object> HybridLoginPendingData() => new()
|
||||
{
|
||||
["delayMinutes"] = 10,
|
||||
["reason"] = "no_real_user_desktop",
|
||||
["isHybridJoin"] = true,
|
||||
["realUserDesktopSeen"] = false,
|
||||
["placeholderActive"] = true,
|
||||
};
|
||||
|
||||
private static EnrollmentEvent Event(string eventType, int sequence, Dictionary<string, object> data) => new()
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
EventType = eventType,
|
||||
Timestamp = DateTime.UtcNow.AddMinutes(sequence),
|
||||
Sequence = sequence,
|
||||
Data = data,
|
||||
};
|
||||
|
||||
private static async Task<AnalysisOutcome> RunAsync(AnalyzeRule rule, List<EnrollmentEvent> events)
|
||||
{
|
||||
var ruleRepo = new Mock<IRuleRepository>();
|
||||
ruleRepo.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(new List<AnalyzeRule> { rule });
|
||||
ruleRepo.Setup(r => r.GetAnalyzeRulesAsync(TenantId)).ReturnsAsync(new List<AnalyzeRule>());
|
||||
ruleRepo.Setup(r => r.GetRuleStatesAsync(It.IsAny<string>())).ReturnsAsync(new Dictionary<string, RuleState>());
|
||||
ruleRepo.Setup(r => r.GetRuleResultsAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(new List<RuleResult>());
|
||||
|
||||
var sessionRepo = new Mock<ISessionRepository>();
|
||||
sessionRepo.Setup(s => s.GetSessionEventsStrictAsync(TenantId, SessionId, It.IsAny<int>())).ReturnsAsync(events);
|
||||
|
||||
var ruleService = new AnalyzeRuleService(ruleRepo.Object, NullLogger<AnalyzeRuleService>.Instance);
|
||||
var engine = new RuleEngine(ruleService, ruleRepo.Object, sessionRepo.Object, NullLogger<HybridUserAffinityRuleTests>.Instance);
|
||||
|
||||
return await engine.AnalyzeSessionAsync(TenantId, SessionId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Collections.Generic;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The operator KQL proxy resolves its <c>source</c> against app settings once: every configured
|
||||
/// store maps to its own Kusto endpoint and token scope, a known-but-unconfigured store names the
|
||||
/// missing setting (503 material), an unknown name lists the vocabulary (400 material), and the
|
||||
/// default is the backend store.
|
||||
/// </summary>
|
||||
public class LogQuerySourceCatalogTests
|
||||
{
|
||||
private static LogQuerySourceCatalog Build(params (string Key, string? Value)[] settings)
|
||||
{
|
||||
var dict = new Dictionary<string, string?>();
|
||||
foreach (var (k, v) in settings) dict[k] = v;
|
||||
var config = new ConfigurationBuilder().AddInMemoryCollection(dict).Build();
|
||||
return new LogQuerySourceCatalog(config);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Every_configured_source_resolves_to_its_own_endpoint_and_scope()
|
||||
{
|
||||
var catalog = Build(
|
||||
(LogQuerySourceCatalog.BackendAppIdSetting, "aaaa-backend"),
|
||||
(LogQuerySourceCatalog.WebAppIdSetting, "bbbb-web"),
|
||||
(LogQuerySourceCatalog.McpWorkspaceIdSetting, "cccc-workspace"));
|
||||
|
||||
Assert.True(catalog.TryResolve("backend", out var backend, out _));
|
||||
Assert.Equal("https://api.applicationinsights.io/v1/apps/aaaa-backend/query", backend!.QueryUri.ToString());
|
||||
Assert.Equal("https://api.applicationinsights.io/.default", backend.TokenScope);
|
||||
|
||||
Assert.True(catalog.TryResolve("web", out var web, out _));
|
||||
Assert.Equal("https://api.applicationinsights.io/v1/apps/bbbb-web/query", web!.QueryUri.ToString());
|
||||
|
||||
Assert.True(catalog.TryResolve("mcp", out var mcp, out _));
|
||||
Assert.Equal("https://api.loganalytics.io/v1/workspaces/cccc-workspace/query", mcp!.QueryUri.ToString());
|
||||
Assert.Equal("https://api.loganalytics.io/.default", mcp.TokenScope);
|
||||
|
||||
Assert.Equal(3, catalog.Available.Count);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void Missing_source_defaults_to_backend(string? name)
|
||||
{
|
||||
var catalog = Build((LogQuerySourceCatalog.BackendAppIdSetting, "aaaa-backend"));
|
||||
|
||||
Assert.True(catalog.TryResolve(name, out var source, out _));
|
||||
Assert.Equal(LogQuerySources.Backend, source!.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Known_but_unconfigured_source_names_the_missing_setting_and_leaves_others_intact()
|
||||
{
|
||||
var catalog = Build((LogQuerySourceCatalog.BackendAppIdSetting, "aaaa-backend"));
|
||||
|
||||
Assert.False(catalog.TryResolve("web", out var web, out var error));
|
||||
Assert.Null(web);
|
||||
Assert.Contains(LogQuerySourceCatalog.WebAppIdSetting, error);
|
||||
Assert.Contains("not configured", error);
|
||||
|
||||
Assert.True(catalog.TryResolve("backend", out _, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Unknown_source_lists_the_vocabulary()
|
||||
{
|
||||
var catalog = Build((LogQuerySourceCatalog.BackendAppIdSetting, "aaaa-backend"));
|
||||
|
||||
Assert.False(catalog.TryResolve("portal", out _, out var error));
|
||||
Assert.Contains("Unknown log source 'portal'", error);
|
||||
foreach (var s in LogQuerySources.All)
|
||||
Assert.Contains(s, error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Vocabulary_is_the_three_stores_in_declaration_order()
|
||||
{
|
||||
Assert.Equal(new[] { "backend", "web", "mcp" }, LogQuerySources.All);
|
||||
Assert.True(LogQuerySources.IsKnown("mcp"));
|
||||
Assert.False(LogQuerySources.IsKnown("MCP"));
|
||||
Assert.False(LogQuerySources.IsKnown(null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the reverse index behind conferred Pro (<see cref="ManagedTenantProIndex"/>): only OWNED groups
|
||||
/// of a PERMANENT-Pro owner confer; a trial owner and operator-created groups never do; the owner's tier is
|
||||
/// read raw (two tenants managing each other resolve without recursion); storage failure yields "nobody is
|
||||
/// managed" (fail-closed) without throwing; Invalidate forces a rebuild.
|
||||
/// </summary>
|
||||
public sealed class ManagedTenantProIndexTests
|
||||
{
|
||||
private const string Msp = "11111111-1111-1111-1111-111111111111";
|
||||
private const string TrialMsp = "22222222-2222-2222-2222-222222222222";
|
||||
private const string CustomerA = "33333333-3333-3333-3333-333333333333";
|
||||
private const string CustomerB = "44444444-4444-4444-4444-444444444444";
|
||||
private const string OperatorManaged = "55555555-5555-5555-5555-555555555555";
|
||||
|
||||
private static TenantGroup Owned(string owner, params string[] tenants) => new()
|
||||
{
|
||||
GroupId = AutopilotMonitor.Shared.Constants.TenantGroupIds.ForHomeTenant(owner),
|
||||
Name = "Customers",
|
||||
OwnerTenantId = owner,
|
||||
TenantIds = tenants.ToList(),
|
||||
};
|
||||
|
||||
private static TenantGroup Operator(params string[] tenants) => new()
|
||||
{
|
||||
GroupId = "operator-group",
|
||||
Name = "Operator bundle",
|
||||
OwnerTenantId = null,
|
||||
TenantIds = tenants.ToList(),
|
||||
};
|
||||
|
||||
private static (ManagedTenantProIndex Index, Mock<IAdminRepository> Admin, Mock<IConfigRepository> Config) Build(
|
||||
IEnumerable<TenantGroup> groups, IDictionary<string, TenantConfiguration> configs)
|
||||
{
|
||||
var admin = new Mock<IAdminRepository>();
|
||||
admin.Setup(a => a.GetAllTenantGroupsAsync()).ReturnsAsync(groups.ToList());
|
||||
var config = new Mock<IConfigRepository>();
|
||||
config.Setup(c => c.GetTenantConfigurationAsync(It.IsAny<string>()))
|
||||
.ReturnsAsync((string id) => configs.TryGetValue(id, out var cfg) ? cfg : null);
|
||||
var index = new ManagedTenantProIndex(admin.Object, config.Object, new MemoryCache(new MemoryCacheOptions()),
|
||||
NullLogger<ManagedTenantProIndex>.Instance);
|
||||
return (index, admin, config);
|
||||
}
|
||||
|
||||
private static TenantConfiguration Tenant(string id, string tier, DateTime? trial = null) =>
|
||||
new() { TenantId = id, PlanTier = tier, TrialExpiresUtc = trial };
|
||||
|
||||
[Fact]
|
||||
public async Task OwnedGroup_OfPermanentProOwner_ConfersOnMembers()
|
||||
{
|
||||
var (index, _, _) = Build(
|
||||
new[] { Owned(Msp, CustomerA, CustomerB) },
|
||||
new Dictionary<string, TenantConfiguration> { [Msp] = Tenant(Msp, "pro") });
|
||||
|
||||
Assert.Equal(Msp, await index.GetConferringOwnerAsync(CustomerA));
|
||||
Assert.Equal(Msp, await index.GetConferringOwnerAsync(CustomerB));
|
||||
Assert.Null(await index.GetConferringOwnerAsync(Msp)); // the owner never manages itself
|
||||
Assert.Null(await index.GetConferringOwnerAsync(OperatorManaged));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LegacyEnterpriseTier_CountsAsPermanentPro()
|
||||
{
|
||||
var (index, _, _) = Build(
|
||||
new[] { Owned(Msp, CustomerA) },
|
||||
new Dictionary<string, TenantConfiguration> { [Msp] = Tenant(Msp, "enterprise") });
|
||||
|
||||
Assert.Equal(Msp, await index.GetConferringOwnerAsync(CustomerA));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TrialOwner_ConfersNothing()
|
||||
{
|
||||
var (index, _, _) = Build(
|
||||
new[] { Owned(TrialMsp, CustomerA) },
|
||||
new Dictionary<string, TenantConfiguration>
|
||||
{
|
||||
[TrialMsp] = Tenant(TrialMsp, "community", trial: DateTime.UtcNow.AddDays(10)),
|
||||
});
|
||||
|
||||
Assert.Null(await index.GetConferringOwnerAsync(CustomerA));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OwnerWithoutConfigRow_ConfersNothing()
|
||||
{
|
||||
var (index, _, _) = Build(new[] { Owned(Msp, CustomerA) }, new Dictionary<string, TenantConfiguration>());
|
||||
|
||||
Assert.Null(await index.GetConferringOwnerAsync(CustomerA));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OperatorGroup_NeverConfers_EvenWhenAssigneesAreProHomed()
|
||||
{
|
||||
var (index, _, _) = Build(
|
||||
new[] { Operator(OperatorManaged) },
|
||||
new Dictionary<string, TenantConfiguration> { [Msp] = Tenant(Msp, "pro") });
|
||||
|
||||
Assert.Null(await index.GetConferringOwnerAsync(OperatorManaged));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MutualManagement_ResolvesBothWays_WithoutRecursion()
|
||||
{
|
||||
// A manages B and B manages A, both permanent Pro: each owner's tier is one RAW read — the
|
||||
// index never asks "is the owner itself managed", so there is no cycle to fall into.
|
||||
var (index, _, config) = Build(
|
||||
new[] { Owned(Msp, CustomerA), Owned(CustomerA, Msp) },
|
||||
new Dictionary<string, TenantConfiguration> { [Msp] = Tenant(Msp, "pro"), [CustomerA] = Tenant(CustomerA, "pro") });
|
||||
|
||||
Assert.Equal(Msp, await index.GetConferringOwnerAsync(CustomerA));
|
||||
Assert.Equal(CustomerA, await index.GetConferringOwnerAsync(Msp));
|
||||
config.Verify(c => c.GetTenantConfigurationAsync(Msp), Times.Once);
|
||||
config.Verify(c => c.GetTenantConfigurationAsync(CustomerA), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TwoProOwners_ResolveDeterministically_ByGroupId()
|
||||
{
|
||||
// GroupIds are "msp-{owner}", so ordinal order of the owner ids decides.
|
||||
var first = "0aaaaaaa-0000-0000-0000-000000000000";
|
||||
var second = "0bbbbbbb-0000-0000-0000-000000000000";
|
||||
var (index, _, _) = Build(
|
||||
new[] { Owned(second, CustomerA), Owned(first, CustomerA) },
|
||||
new Dictionary<string, TenantConfiguration> { [first] = Tenant(first, "pro"), [second] = Tenant(second, "pro") });
|
||||
|
||||
Assert.Equal(first, await index.GetConferringOwnerAsync(CustomerA));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IsCachedAcrossLookups_AndInvalidateRebuilds()
|
||||
{
|
||||
var (index, admin, _) = Build(
|
||||
new[] { Owned(Msp, CustomerA) },
|
||||
new Dictionary<string, TenantConfiguration> { [Msp] = Tenant(Msp, "pro") });
|
||||
|
||||
await index.GetConferringOwnerAsync(CustomerA);
|
||||
await index.GetConferringOwnerAsync(CustomerB);
|
||||
admin.Verify(a => a.GetAllTenantGroupsAsync(), Times.Once);
|
||||
|
||||
index.Invalidate();
|
||||
await index.GetConferringOwnerAsync(CustomerA);
|
||||
admin.Verify(a => a.GetAllTenantGroupsAsync(), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StorageFailure_YieldsNobodyManaged_NeverThrows()
|
||||
{
|
||||
var admin = new Mock<IAdminRepository>();
|
||||
admin.Setup(a => a.GetAllTenantGroupsAsync()).ThrowsAsync(new InvalidOperationException("storage down"));
|
||||
var index = new ManagedTenantProIndex(admin.Object, Mock.Of<IConfigRepository>(),
|
||||
new MemoryCache(new MemoryCacheOptions()), NullLogger<ManagedTenantProIndex>.Instance);
|
||||
|
||||
Assert.Null(await index.GetConferringOwnerAsync(CustomerA));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BlankTenantId_IsNull_WithoutTouchingStorage()
|
||||
{
|
||||
var (index, admin, _) = Build(Array.Empty<TenantGroup>(), new Dictionary<string, TenantConfiguration>());
|
||||
|
||||
Assert.Null(await index.GetConferringOwnerAsync(null));
|
||||
Assert.Null(await index.GetConferringOwnerAsync(" "));
|
||||
admin.Verify(a => a.GetAllTenantGroupsAsync(), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task None_ProjectsNobody()
|
||||
{
|
||||
Assert.Null(await ManagedTenantProIndex.None.GetConferringOwnerAsync(CustomerA));
|
||||
ManagedTenantProIndex.None.Invalidate(); // no-op, must not throw
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System.IO;
|
||||
using AutopilotMonitor.Functions.Middleware;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The catalog and <see cref="PolicyEnforcementMiddleware"/> are the authorization gate for every
|
||||
/// HTTP route, and the raw table/log proxies rely on the <c>RequestContext</c> it resolves. Nothing
|
||||
/// at runtime would notice if the registration in <c>Program.cs</c> were dropped or moved in front of
|
||||
/// <see cref="AuthenticationMiddleware"/> (the policy step reads the principal the auth step stores) —
|
||||
/// the routes would simply open up. This source scan pins the registration and its order.
|
||||
/// </summary>
|
||||
public class MiddlewarePipelineOrderTests
|
||||
{
|
||||
private static string RepoRoot()
|
||||
{
|
||||
var dir = new DirectoryInfo(System.AppContext.BaseDirectory);
|
||||
while (dir != null && !File.Exists(Path.Combine(dir.FullName, "AutopilotMonitor.sln")))
|
||||
dir = dir.Parent;
|
||||
Assert.NotNull(dir);
|
||||
return dir!.FullName;
|
||||
}
|
||||
|
||||
private static string ProgramSource() => File.ReadAllText(Path.Combine(
|
||||
RepoRoot(), "src", "Backend", "AutopilotMonitor.Functions", "Program.cs"));
|
||||
|
||||
[Fact]
|
||||
public void Authentication_then_policy_enforcement_are_registered_in_that_order()
|
||||
{
|
||||
var src = ProgramSource();
|
||||
|
||||
var auth = src.IndexOf($"UseMiddleware<{nameof(AuthenticationMiddleware)}>()", System.StringComparison.Ordinal);
|
||||
var policy = src.IndexOf($"UseMiddleware<{nameof(PolicyEnforcementMiddleware)}>()", System.StringComparison.Ordinal);
|
||||
var rateLimit = src.IndexOf($"UseMiddleware<{nameof(UserRateLimitMiddleware)}>()", System.StringComparison.Ordinal);
|
||||
|
||||
Assert.True(auth >= 0, "AuthenticationMiddleware is not registered in Program.cs");
|
||||
Assert.True(policy >= 0, "PolicyEnforcementMiddleware is not registered in Program.cs");
|
||||
Assert.True(auth < policy, "PolicyEnforcementMiddleware must run AFTER AuthenticationMiddleware (it reads the stored principal)");
|
||||
Assert.True(rateLimit < 0 || policy < rateLimit, "UserRateLimitMiddleware keys off the RequestContext the policy step resolves");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Each_gate_middleware_is_registered_exactly_once()
|
||||
{
|
||||
var src = ProgramSource();
|
||||
|
||||
Assert.Equal(1, Count(src, $"UseMiddleware<{nameof(AuthenticationMiddleware)}>()"));
|
||||
Assert.Equal(1, Count(src, $"UseMiddleware<{nameof(PolicyEnforcementMiddleware)}>()"));
|
||||
}
|
||||
|
||||
private static int Count(string haystack, string needle)
|
||||
{
|
||||
var count = 0;
|
||||
for (var i = haystack.IndexOf(needle, System.StringComparison.Ordinal); i >= 0;
|
||||
i = haystack.IndexOf(needle, i + needle.Length, System.StringComparison.Ordinal))
|
||||
count++;
|
||||
return count;
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,8 @@ public class NoStoreCacheMiddlewareTests
|
||||
[InlineData("/api/diagnostics/download-url")]
|
||||
[InlineData("/api/diagnostics/download-ticket")] // short-lived signed download credential
|
||||
[InlineData("/api/diagnostics/download")] // ticket-gated anonymous ZIP stream
|
||||
[InlineData("/api/global/session-reports/download-ticket")] // short-lived signed report download credential
|
||||
[InlineData("/api/global/session-reports/download")] // ticket-gated anonymous report ZIP stream
|
||||
// /api/search/* — quick, sessions, sessions-by-event, sessions-by-cve (all return session PII)
|
||||
[InlineData("/api/search/quick")]
|
||||
[InlineData("/api/search/sessions")]
|
||||
|
||||
+1
@@ -44,6 +44,7 @@ public sealed class TenantCustomsArchiveContractTests
|
||||
customsArchive: archive,
|
||||
configRepo: null!,
|
||||
farewellEmail: new FakeOffboardFarewellEmailSender(),
|
||||
proConferral: null!,
|
||||
logger: NullLogger<TenantOffboardingHandler>.Instance);
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -670,7 +670,8 @@ public class TenantOffboardingHandlerDrainContractTests
|
||||
IOffboardFarewellEmailSender farewellEmail,
|
||||
ILogger<TenantOffboardingHandler> logger)
|
||||
: base(auditRepo, enumerator, cascadeEnqueuer, expectations, drainProbe, safeWipe,
|
||||
storage, maintenance, reEnqueuer, opsEvents, customsArchive, configRepo, farewellEmail, logger)
|
||||
storage, maintenance, reEnqueuer, opsEvents, customsArchive, configRepo, farewellEmail,
|
||||
TestProConferral.Inert(), logger)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -486,7 +486,7 @@ public class TenantOffboardingHandlerOrderingTests
|
||||
TableStorageService s, IMaintenanceRepository m, ITenantOffboardingEnqueuer re,
|
||||
OpsEventService o, ITenantCustomsArchiveRepository ca, IConfigRepository cr,
|
||||
IOffboardFarewellEmailSender fe, ILogger<TenantOffboardingHandler> log)
|
||||
: base(a, e, c, exp, d, sw, s, m, re, o, ca, cr, fe, log) { }
|
||||
: base(a, e, c, exp, d, sw, s, m, re, o, ca, cr, fe, TestProConferral.Inert(), log) { }
|
||||
|
||||
internal override Task ArchiveAndWipeRulesTableAsync(
|
||||
string tableName, string tenantId, string historyRowKey, CancellationToken ct)
|
||||
|
||||
+1
-1
@@ -258,7 +258,7 @@ public class TenantOffboardingWorkerPoisonTests
|
||||
TableStorageService s, IMaintenanceRepository m, ITenantOffboardingEnqueuer re,
|
||||
OpsEventService o, ITenantCustomsArchiveRepository ca, IConfigRepository cr,
|
||||
IOffboardFarewellEmailSender fe, ILogger<TenantOffboardingHandler> log)
|
||||
: base(a, e, c, exp, d, sw, s, m, re, o, ca, cr, fe, log) { }
|
||||
: base(a, e, c, exp, d, sw, s, m, re, o, ca, cr, fe, TestProConferral.Inert(), log) { }
|
||||
|
||||
internal override Task ArchiveAndWipeRulesTableAsync(
|
||||
string tableName, string tenantId, string historyRowKey, CancellationToken ct)
|
||||
|
||||
@@ -40,6 +40,53 @@ public class PlanManagementTransitionTests
|
||||
Assert.True(changes.ContainsKey("PlanTier"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ManagedTenant_PlanTierDowngrade_IsNotAnEffectiveDowngrade_NoAnchor()
|
||||
{
|
||||
// Conferred Pro keeps the tenant effectively Pro — the plan endpoint sees Pro → Pro, so no
|
||||
// grace anchor and no downgrade event; the anchor is stamped when the delegation ends instead.
|
||||
var config = new TenantConfiguration
|
||||
{
|
||||
TenantId = "t1", PlanTier = "pro", ManagedByProTenantId = "11111111-1111-1111-1111-111111111111",
|
||||
};
|
||||
|
||||
var (before, after, changes) = Apply(config, planTier: "community");
|
||||
|
||||
Assert.Equal(TenantEdition.Pro, before);
|
||||
Assert.Equal(TenantEdition.Pro, after);
|
||||
Assert.Null(config.ProDowngradedUtc);
|
||||
Assert.False(changes.ContainsKey("ProDowngradedUtc"));
|
||||
Assert.Equal("community", config.PlanTier);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, true, true)]
|
||||
[InlineData(true, false, true)]
|
||||
[InlineData(true, true, false)]
|
||||
[InlineData(false, false, false)]
|
||||
public void ApplyPayingCustomerChange_RecordsOnlyRealChanges(bool stored, bool requested, bool expectChange)
|
||||
{
|
||||
var config = new TenantConfiguration { TenantId = "t1", PayingCustomer = stored };
|
||||
var changes = new Dictionary<string, string>();
|
||||
|
||||
PlanManagementFunction.ApplyPayingCustomerChange(config, provided: true, requested, changes);
|
||||
|
||||
Assert.Equal(requested, config.PayingCustomer);
|
||||
Assert.Equal(expectChange, changes.ContainsKey("PayingCustomer"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplyPayingCustomerChange_NotProvided_IsNoOp()
|
||||
{
|
||||
var config = new TenantConfiguration { TenantId = "t1", PayingCustomer = true };
|
||||
var changes = new Dictionary<string, string>();
|
||||
|
||||
PlanManagementFunction.ApplyPayingCustomerChange(config, provided: false, payingCustomer: false, changes);
|
||||
|
||||
Assert.True(config.PayingCustomer);
|
||||
Assert.Empty(changes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Upgrade_CommunityToPro_ClearsAnchor()
|
||||
{
|
||||
|
||||
@@ -119,11 +119,149 @@ public class PolicyEnforcementMiddlewareTests
|
||||
|
||||
var mw = new PolicyEnforcementMiddleware(
|
||||
NullLogger<PolicyEnforcementMiddleware>.Instance, globalAdmin, delegatedAdmin,
|
||||
new TenantMemberRoleResolver(tenantAdmins, tenantConfig), tenantConfig);
|
||||
new TenantMemberRoleResolver(tenantAdmins, tenantConfig), tenantConfig,
|
||||
new RecordingDenialReporter());
|
||||
|
||||
return new Harness { Middleware = mw, Repo = repo, ConfigRepo = configRepo };
|
||||
}
|
||||
|
||||
// ── ASSUME-BREACH: which denials are reported as PrivilegedRouteDenied ──────────────────
|
||||
// The deny path in Invoke reports iff the decision denied a GlobalAdminOnly route with 403 by an
|
||||
// authenticated caller. DecideAsync is the seam: it must surface the denied tier on the result.
|
||||
|
||||
[Fact]
|
||||
public async Task GlobalAdminOnly_denial_of_tenant_user_carries_the_policy_and_is_privileged()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.AsTenantAdmin(TenantA, "admin@contoso.com");
|
||||
|
||||
var r = await h.Middleware.DecideAsync("POST", "/api/global/raw/logs", null, AuthedPrincipal(TenantA, "admin@contoso.com"));
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Equal(403, r.StatusCode);
|
||||
Assert.Equal(EndpointPolicy.GlobalAdminOnly, r.Policy);
|
||||
Assert.Equal("NotGlobalAdmin", r.LogReason);
|
||||
Assert.True(PolicyEnforcementMiddleware.IsPrivilegedDenial(r));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GlobalReader_on_raw_table_is_denied_and_privileged()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.AsGlobalRole(Constants.GlobalRoles.GlobalReader);
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", "/api/global/raw/tables/TenantConfiguration", null, AuthedPrincipal(TenantA, "reader@contoso.com"));
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Equal(403, r.StatusCode);
|
||||
Assert.Equal(EndpointPolicy.GlobalAdminOnly, r.Policy);
|
||||
Assert.True(PolicyEnforcementMiddleware.IsPrivilegedDenial(r));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GlobalAdmin_on_access_probe_is_allowed_and_not_privileged()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.AsGlobalRole(Constants.GlobalRoles.GlobalAdmin);
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", "/api/global/raw/access-probe", null, AuthedPrincipal(TenantA, "ga@contoso.com"));
|
||||
|
||||
Assert.True(r.Allowed);
|
||||
Assert.True(r.Context!.IsGlobalAdmin);
|
||||
Assert.False(PolicyEnforcementMiddleware.IsPrivilegedDenial(r));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Anonymous_on_GlobalAdminOnly_route_is_401_not_a_privileged_denial()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", "/api/global/raw/access-probe", null, principal: null);
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Equal(401, r.StatusCode);
|
||||
Assert.Equal(EndpointPolicy.GlobalAdminOnly, r.Policy);
|
||||
Assert.False(PolicyEnforcementMiddleware.IsPrivilegedDenial(r));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unregistered_route_has_no_policy_and_is_not_privileged()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
|
||||
var r = await h.Middleware.DecideAsync("GET", "/api/global/raw/does-not-exist", null, AuthedPrincipal(TenantA, "x@contoso.com"));
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Null(r.Policy);
|
||||
Assert.False(PolicyEnforcementMiddleware.IsPrivilegedDenial(r));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Member_route_denial_is_not_privileged()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
// No membership anywhere → MemberRead route denies with 403, but it is not the GA-only surface.
|
||||
var r = await h.Middleware.DecideAsync("GET", $"/api/config/{TenantA}", null, AuthedPrincipal(TenantA, "nobody@contoso.com"));
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.NotEqual(EndpointPolicy.GlobalAdminOnly, r.Policy);
|
||||
Assert.False(PolicyEnforcementMiddleware.IsPrivilegedDenial(r));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildPrivilegedDenial_projects_claims_headers_role_and_correlation()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
h.AsTenantAdmin(TenantA, "admin@contoso.com");
|
||||
var principal = AuthedPrincipal(TenantA, "admin@contoso.com");
|
||||
var r = await h.Middleware.DecideAsync("POST", "/api/global/raw/logs", null, principal);
|
||||
|
||||
var d = PolicyEnforcementMiddleware.BuildPrivilegedDenial(
|
||||
r, "POST", "/api/global/raw/logs", principal, globalRole: null,
|
||||
clientSource: "mcp", mcpToolName: "query_backend_logs", correlationId: "corr-42");
|
||||
|
||||
Assert.Equal("POST", d.Method);
|
||||
Assert.Equal("/api/global/raw/logs", d.Path);
|
||||
Assert.Equal(403, d.StatusCode);
|
||||
Assert.Equal("NotGlobalAdmin", d.Reason);
|
||||
Assert.Equal("GlobalAdminOnly", d.Policy);
|
||||
Assert.Equal("admin@contoso.com", d.Upn);
|
||||
Assert.Equal(TestOid, d.ObjectId);
|
||||
Assert.Equal(TenantA, d.TenantId);
|
||||
Assert.Equal("None", d.CallerRole);
|
||||
Assert.Equal("mcp", d.ClientSource);
|
||||
Assert.Equal("query_backend_logs", d.McpToolName);
|
||||
Assert.Equal("corr-42", d.CorrelationId);
|
||||
Assert.False(string.IsNullOrEmpty(d.CallerId));
|
||||
|
||||
var reader = PolicyEnforcementMiddleware.BuildPrivilegedDenial(
|
||||
r, "POST", "/api/global/raw/logs", principal, globalRole: Constants.GlobalRoles.GlobalReader,
|
||||
clientSource: null, mcpToolName: null, correlationId: "");
|
||||
Assert.Equal(Constants.GlobalRoles.GlobalReader, reader.CallerRole);
|
||||
Assert.Null(reader.ClientSource);
|
||||
Assert.Null(reader.CorrelationId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BuildPrivilegedDenial_strips_control_characters_from_method_and_decoded_path()
|
||||
{
|
||||
var h = BuildHarness();
|
||||
var principal = AuthedPrincipal(TenantA, "admin@contoso.com");
|
||||
var r = await h.Middleware.DecideAsync("POST", "/api/global/raw/logs", null, principal);
|
||||
|
||||
// A percent-decoded path or a hand-crafted method can carry CR/LF; the record feeds log lines,
|
||||
// the ops-events table and alert channels, so the barrier sits in the projection.
|
||||
var d = PolicyEnforcementMiddleware.BuildPrivilegedDenial(
|
||||
r, "PO\r\nST", "/api/global/raw/logs\r\nforged: line" + new string('x', 400), principal, globalRole: null,
|
||||
clientSource: null, mcpToolName: null, correlationId: null);
|
||||
|
||||
Assert.Equal("POST", d.Method);
|
||||
Assert.DoesNotContain('\n', d.Path);
|
||||
Assert.DoesNotContain('\r', d.Path);
|
||||
Assert.StartsWith("/api/global/raw/logsforged: line", d.Path);
|
||||
Assert.Equal(256, d.Path.Length);
|
||||
}
|
||||
|
||||
private static ClaimsPrincipal AuthedPrincipal(string tenantId, string upn, string objectId = TestOid)
|
||||
=> new(new ClaimsIdentity(new[] { new Claim("tid", tenantId), new Claim("upn", upn), new Claim("oid", objectId) }, "TestAuth"));
|
||||
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The assume-breach alarm for the Global-Admin-only surface: a refused GlobalAdminOnly request must
|
||||
/// land as a <c>PrivilegedRouteDenied</c> Security ops event that carries the caller's identity and
|
||||
/// the MCP tool name, Critical for an outsider and Warning for a known Global Reader, throttled per
|
||||
/// caller+path so a scripted probe cannot flood the push channel.
|
||||
/// </summary>
|
||||
public class PrivilegedDenialReporterTests
|
||||
{
|
||||
private static (PrivilegedDenialReporter Reporter, List<OpsEventEntry> Saved) Rig(bool repoThrows = false)
|
||||
{
|
||||
var saved = new List<OpsEventEntry>();
|
||||
var opsRepo = new Mock<IOpsEventRepository>();
|
||||
var setup = opsRepo.Setup(r => r.SaveOpsEventAsync(It.IsAny<OpsEventEntry>()));
|
||||
if (repoThrows)
|
||||
setup.ThrowsAsync(new System.InvalidOperationException("table down"));
|
||||
else
|
||||
setup.Callback<OpsEventEntry>(e => { lock (saved) saved.Add(e); }).Returns(Task.CompletedTask);
|
||||
var adminConfig = new Mock<AdminConfigurationService>(
|
||||
Mock.Of<IConfigRepository>(), NullLogger<AdminConfigurationService>.Instance,
|
||||
new MemoryCache(new MemoryCacheOptions())) { CallBase = false };
|
||||
var opsEvents = new OpsEventService(opsRepo.Object, NullLogger<OpsEventService>.Instance,
|
||||
TestNotifications.InertOpsAlertDispatch(adminConfig.Object));
|
||||
var reporter = new PrivilegedDenialReporter(opsEvents, new MemoryCache(new MemoryCacheOptions()),
|
||||
NullLogger<PrivilegedDenialReporter>.Instance);
|
||||
return (reporter, saved);
|
||||
}
|
||||
|
||||
private static PrivilegedDenial Denial(
|
||||
string path = "/api/global/raw/logs", string callerRole = "None", string callerId = "oid-1",
|
||||
string? clientSource = "mcp", string? mcpTool = "query_backend_logs")
|
||||
=> new(
|
||||
Method: "POST", Path: path, StatusCode: 403, Reason: "NotGlobalAdmin", Policy: "GlobalAdminOnly",
|
||||
CallerId: callerId, Upn: "user@contoso.com", ObjectId: "oid-1",
|
||||
TenantId: "11111111-1111-1111-1111-111111111111", CallerRole: callerRole,
|
||||
ClientSource: clientSource, McpToolName: mcpTool, CorrelationId: "corr-1");
|
||||
|
||||
/// <summary>The write is fire-and-forget; give the completed-task continuation a moment.</summary>
|
||||
private static List<OpsEventEntry> Settle(List<OpsEventEntry> saved, int expected)
|
||||
{
|
||||
var spin = new SpinWait();
|
||||
var deadline = System.DateTime.UtcNow.AddSeconds(2);
|
||||
while (System.DateTime.UtcNow < deadline)
|
||||
{
|
||||
lock (saved) if (saved.Count >= expected) break;
|
||||
spin.SpinOnce();
|
||||
}
|
||||
lock (saved) return saved.ToList();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Outsider_lands_as_Critical_security_event_with_identity_and_tool()
|
||||
{
|
||||
var (reporter, saved) = Rig();
|
||||
|
||||
reporter.Report(Denial());
|
||||
|
||||
var evt = Assert.Single(Settle(saved, 1));
|
||||
Assert.Equal(OpsEventCategory.Security, evt.Category);
|
||||
Assert.Equal(OpsEventTypes.PrivilegedRouteDenied, evt.EventType);
|
||||
Assert.Equal(OpsEventSeverity.Critical, evt.Severity);
|
||||
Assert.Equal("11111111-1111-1111-1111-111111111111", evt.TenantId);
|
||||
Assert.Equal("user@contoso.com", evt.UserId);
|
||||
Assert.Contains("/api/global/raw/logs", evt.Message);
|
||||
Assert.Contains("query_backend_logs", evt.Message);
|
||||
|
||||
using var details = JsonDocument.Parse(evt.Details!);
|
||||
var d = details.RootElement;
|
||||
Assert.Equal("oid-1", d.GetProperty("oid").GetString());
|
||||
Assert.Equal("11111111-1111-1111-1111-111111111111", d.GetProperty("tid").GetString());
|
||||
Assert.Equal("mcp", d.GetProperty("clientSource").GetString());
|
||||
Assert.Equal("query_backend_logs", d.GetProperty("mcpToolName").GetString());
|
||||
Assert.Equal("corr-1", d.GetProperty("correlationId").GetString());
|
||||
Assert.Equal("GlobalAdminOnly", d.GetProperty("policy").GetString());
|
||||
Assert.Equal("NotGlobalAdmin", d.GetProperty("reason").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Global_reader_lands_as_Warning_not_Critical()
|
||||
{
|
||||
var (reporter, saved) = Rig();
|
||||
|
||||
reporter.Report(Denial(callerRole: Constants.GlobalRoles.GlobalReader));
|
||||
|
||||
var evt = Assert.Single(Settle(saved, 1));
|
||||
Assert.Equal(OpsEventSeverity.Warning, evt.Severity);
|
||||
Assert.Equal(OpsEventTypes.PrivilegedRouteDenied, evt.EventType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Direct_http_probe_without_mcp_headers_still_lands()
|
||||
{
|
||||
var (reporter, saved) = Rig();
|
||||
|
||||
reporter.Report(Denial(clientSource: null, mcpTool: null));
|
||||
|
||||
var evt = Assert.Single(Settle(saved, 1));
|
||||
Assert.Contains("via direct", evt.Message);
|
||||
using var details = JsonDocument.Parse(evt.Details!);
|
||||
// Absent-when-null is the wire policy for API responses, but ops-event details use the default
|
||||
// serializer: the keys are present with null so a reader can tell "no header" from "not recorded".
|
||||
Assert.Equal(JsonValueKind.Null, details.RootElement.GetProperty("mcpToolName").ValueKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void One_event_per_caller_per_window_whatever_path_another_caller_is_reported()
|
||||
{
|
||||
var (reporter, saved) = Rig();
|
||||
|
||||
reporter.Report(Denial());
|
||||
reporter.Report(Denial(mcpTool: "query_table")); // same caller → throttled
|
||||
reporter.Report(Denial(path: "/api/global/raw/tables")); // same caller, other route → throttled (a sweep is ONE event)
|
||||
reporter.Report(Denial(callerId: "oid-2")); // new caller → reported
|
||||
|
||||
var events = Settle(saved, 2);
|
||||
Assert.Equal(2, events.Count);
|
||||
Assert.DoesNotContain(events, e => e.Message.Contains("/api/global/raw/tables"));
|
||||
Assert.DoesNotContain(events, e => e.Message.Contains("query_table"));
|
||||
Assert.All(events, e => Assert.Contains("/api/global/raw/logs", e.Message));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Instance_budget_ends_in_one_storm_marker_then_silence()
|
||||
{
|
||||
var (reporter, saved) = Rig();
|
||||
|
||||
// Six distinct callers: five normal events, the sixth trips the storm marker.
|
||||
for (var i = 1; i <= 6; i++)
|
||||
reporter.Report(Denial(callerId: $"oid-{i}", path: $"/api/global/raw/route-{i}"));
|
||||
// Everything after that stays trace-only for the window — new callers included.
|
||||
for (var i = 7; i <= 40; i++)
|
||||
reporter.Report(Denial(callerId: $"oid-{i}"));
|
||||
|
||||
var events = Settle(saved, PrivilegedDenialReporter.MaxEventsPerWindow + 1);
|
||||
Assert.Equal(PrivilegedDenialReporter.MaxEventsPerWindow + 1, events.Count);
|
||||
Assert.All(events, e => Assert.Equal(OpsEventTypes.PrivilegedRouteDenied, e.EventType));
|
||||
|
||||
var normal = events.Take(PrivilegedDenialReporter.MaxEventsPerWindow).ToList();
|
||||
Assert.All(normal, e => Assert.DoesNotContain("storm", e.Message));
|
||||
|
||||
var storm = events.Last();
|
||||
Assert.Equal(OpsEventSeverity.Critical, storm.Severity);
|
||||
Assert.Contains("denial storm", storm.Message);
|
||||
Assert.Contains("/api/global/raw/route-6", storm.Message);
|
||||
using var details = JsonDocument.Parse(storm.Details!);
|
||||
Assert.True(details.RootElement.GetProperty("storm").GetBoolean());
|
||||
Assert.Equal(PrivilegedDenialReporter.MaxEventsPerWindow, details.RootElement.GetProperty("cap").GetInt32());
|
||||
Assert.Equal("oid-1", details.RootElement.GetProperty("lastOid").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reader_denials_count_against_the_budget_too()
|
||||
{
|
||||
var (reporter, saved) = Rig();
|
||||
|
||||
for (var i = 1; i <= PrivilegedDenialReporter.MaxEventsPerWindow + 3; i++)
|
||||
reporter.Report(Denial(callerId: $"reader-{i}", callerRole: Constants.GlobalRoles.GlobalReader));
|
||||
|
||||
var events = Settle(saved, PrivilegedDenialReporter.MaxEventsPerWindow + 1);
|
||||
Assert.Equal(PrivilegedDenialReporter.MaxEventsPerWindow + 1, events.Count);
|
||||
// The five Reader slips are Warning (no push under a Critical rule); the storm marker is Critical.
|
||||
Assert.Equal(PrivilegedDenialReporter.MaxEventsPerWindow, events.Count(e => e.Severity == OpsEventSeverity.Warning));
|
||||
Assert.Equal(OpsEventSeverity.Critical, events.Last().Severity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Repository_failure_never_escapes_the_deny_path()
|
||||
{
|
||||
var (reporter, _) = Rig(repoThrows: true);
|
||||
|
||||
var ex = Record.Exception(() => reporter.Report(Denial()));
|
||||
|
||||
Assert.Null(ex);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the write side of conferred Pro (<see cref="ProConferralService"/>): the ONLY thing ever written is
|
||||
/// the retention grace anchor (<see cref="TenantConfiguration.ProDowngradedUtc"/>) on the managed tenant —
|
||||
/// never a plan tier — and only when the managing tenant was a permanent-Pro tenant (a trial MSP conferred
|
||||
/// nothing). Group-wide loss stamps every member except the home tenant, and every path drops the index.
|
||||
/// </summary>
|
||||
public sealed class ProConferralServiceTests
|
||||
{
|
||||
private const string Home = "11111111-1111-1111-1111-111111111111";
|
||||
private const string CustomerA = "33333333-3333-3333-3333-333333333333";
|
||||
private const string CustomerB = "44444444-4444-4444-4444-444444444444";
|
||||
private static readonly DateTime Now = new(2026, 9, 4, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
public required ProConferralService Svc { get; init; }
|
||||
public required Dictionary<string, TenantConfiguration> Rows { get; init; }
|
||||
public required List<(TenantConfiguration Config, string? Source, string? Reason)> Saves { get; init; }
|
||||
public required StubManagedTenantProIndex Index { get; init; }
|
||||
}
|
||||
|
||||
private static Harness Build(string homeTier, params string[] members)
|
||||
{
|
||||
var rows = new Dictionary<string, TenantConfiguration>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
[Home] = new() { TenantId = Home, DomainName = "partner.example", PlanTier = homeTier },
|
||||
[CustomerA] = new() { TenantId = CustomerA, DomainName = "a.example", PlanTier = "community", DataRetentionDays = 365 },
|
||||
[CustomerB] = new() { TenantId = CustomerB, DomainName = "b.example", PlanTier = "pro" },
|
||||
};
|
||||
var saves = new List<(TenantConfiguration, string?, string?)>();
|
||||
|
||||
var configRepo = new Mock<IConfigRepository>();
|
||||
configRepo.Setup(c => c.GetTenantConfigurationAsync(It.IsAny<string>()))
|
||||
.ReturnsAsync((string id) => rows.TryGetValue(id, out var cfg) ? cfg : null);
|
||||
configRepo.Setup(c => c.SaveTenantConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()))
|
||||
.ReturnsAsync((TenantConfiguration cfg, string? source, string? reason) => { saves.Add((cfg, source, reason)); return true; });
|
||||
|
||||
var adminRepo = new Mock<IAdminRepository>();
|
||||
adminRepo.Setup(a => a.GetGroupTenantsAsync(Constants.TenantGroupIds.ForHomeTenant(Home))).ReturnsAsync(members.ToList());
|
||||
|
||||
var index = new StubManagedTenantProIndex(_ => null);
|
||||
var configs = new TenantConfigurationService(configRepo.Object, NullLogger<TenantConfigurationService>.Instance,
|
||||
new MemoryCache(new MemoryCacheOptions()), index);
|
||||
var svc = new ProConferralService(adminRepo.Object, configs, index, NullLogger<ProConferralService>.Instance, new TestTimeProvider(Now));
|
||||
return new Harness { Svc = svc, Rows = rows, Saves = saves, Index = index };
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecordLoss_PermanentProHome_StampsAnchor_NeverTouchesPlanTier()
|
||||
{
|
||||
var h = Build("pro");
|
||||
|
||||
var stamped = await h.Svc.RecordLossAsync(CustomerA, Home, "customer-revoked");
|
||||
|
||||
Assert.True(stamped);
|
||||
var save = Assert.Single(h.Saves);
|
||||
Assert.Equal(CustomerA, save.Config.TenantId);
|
||||
Assert.Equal(Now, save.Config.ProDowngradedUtc);
|
||||
Assert.Equal("community", save.Config.PlanTier);
|
||||
Assert.Equal("delegation", save.Source);
|
||||
Assert.Equal("customer-revoked", save.Reason);
|
||||
Assert.Equal($"delegation:{Home}", save.Config.UpdatedBy);
|
||||
Assert.Equal(1, h.Index.Invalidations);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecordLoss_TrialHome_StampsNothing_StillDropsCaches()
|
||||
{
|
||||
var h = Build("community");
|
||||
h.Rows[Home].TrialExpiresUtc = Now.AddDays(5);
|
||||
|
||||
var stamped = await h.Svc.RecordLossAsync(CustomerA, Home, "customer-revoked");
|
||||
|
||||
Assert.False(stamped);
|
||||
Assert.Empty(h.Saves);
|
||||
Assert.Equal(1, h.Index.Invalidations);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecordLoss_UnknownCustomerRow_IsNoOp()
|
||||
{
|
||||
var h = Build("pro");
|
||||
|
||||
Assert.False(await h.Svc.RecordLossAsync("99999999-9999-9999-9999-999999999999", Home, "customer-revoked"));
|
||||
Assert.Empty(h.Saves);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RecordLossForOwnedGroup_StampsEveryMember_ExceptHome()
|
||||
{
|
||||
var h = Build("community", CustomerA, CustomerB, Home);
|
||||
|
||||
var count = await h.Svc.RecordLossForOwnedGroupAsync(Home, "manager-lost-permanent-pro");
|
||||
|
||||
Assert.Equal(2, count);
|
||||
Assert.Equal(new[] { CustomerA, CustomerB }, h.Saves.Select(s => s.Config.TenantId).OrderBy(t => t).ToArray());
|
||||
Assert.All(h.Saves, s => Assert.Equal(Now, s.Config.ProDowngradedUtc));
|
||||
Assert.All(h.Saves, s => Assert.Equal("manager-lost-permanent-pro", s.Reason));
|
||||
Assert.Equal(1, h.Index.Invalidations);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NotifyDelegationChanged_DropsIndex()
|
||||
{
|
||||
var h = Build("pro");
|
||||
|
||||
await h.Svc.NotifyDelegationChangedAsync(CustomerA);
|
||||
|
||||
Assert.Equal(1, h.Index.Invalidations);
|
||||
Assert.Empty(h.Saves);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Functions.Raw;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using Azure.Core.Serialization;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Defense-in-depth re-check inside the raw table/log proxies and the access probe. The catalog +
|
||||
/// policy middleware are the gate; this pins that the in-body check fails CLOSED when the middleware
|
||||
/// did not run (empty <see cref="RequestContext"/>) or resolved a non-GA caller, and stays silent for
|
||||
/// a resolved Global Admin.
|
||||
/// </summary>
|
||||
public class RawGlobalAdminGateTests
|
||||
{
|
||||
private static (HttpRequestData Req, FunctionContext Ctx) BuildRequest(RequestContext? requestContext)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddOptions();
|
||||
services.Configure<WorkerOptions>(o => o.Serializer = new JsonObjectSerializer(ApiJsonOptions.Create()));
|
||||
var provider = services.BuildServiceProvider();
|
||||
|
||||
var items = new Dictionary<object, object>();
|
||||
if (requestContext != null)
|
||||
items[RequestContext.ItemsKey] = requestContext;
|
||||
|
||||
var context = new Mock<FunctionContext>();
|
||||
context.SetupGet(c => c.Items).Returns(items);
|
||||
context.SetupGet(c => c.InstanceServices).Returns(provider);
|
||||
|
||||
var req = new Mock<HttpRequestData>(context.Object);
|
||||
req.SetupGet(r => r.Headers).Returns(new HttpHeadersCollection());
|
||||
req.Setup(r => r.CreateResponse()).Returns(() => new FakeHttpResponseData(context.Object));
|
||||
return (req.Object, context.Object);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Middleware_never_ran_empty_context_is_403()
|
||||
{
|
||||
var (req, ctx) = BuildRequest(requestContext: null);
|
||||
|
||||
var denied = await RawGlobalAdminGate.DenyUnlessGlobalAdminAsync(req, ctx);
|
||||
|
||||
Assert.NotNull(denied);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, denied!.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolved_non_global_admin_is_403()
|
||||
{
|
||||
var (req, ctx) = BuildRequest(new RequestContext { IsGlobalAdmin = false, IsGlobalReader = true });
|
||||
|
||||
var denied = await RawGlobalAdminGate.DenyUnlessGlobalAdminAsync(req, ctx);
|
||||
|
||||
Assert.NotNull(denied);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, denied!.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolved_global_admin_passes()
|
||||
{
|
||||
var (req, ctx) = BuildRequest(new RequestContext { IsGlobalAdmin = true });
|
||||
|
||||
Assert.Null(await RawGlobalAdminGate.DenyUnlessGlobalAdminAsync(req, ctx));
|
||||
}
|
||||
|
||||
private sealed class FakeHttpResponseData : HttpResponseData
|
||||
{
|
||||
public FakeHttpResponseData(FunctionContext context) : base(context) { }
|
||||
public override HttpStatusCode StatusCode { get; set; } = HttpStatusCode.OK;
|
||||
public override HttpHeadersCollection Headers { get; set; } = new();
|
||||
public override Stream Body { get; set; } = new MemoryStream();
|
||||
public override HttpCookies Cookies { get; } = new Mock<HttpCookies>().Object;
|
||||
}
|
||||
}
|
||||
@@ -140,6 +140,77 @@ public class RawWireParityTests
|
||||
new ListRawTablesResponse { Count = tables.Count, Tables = tables });
|
||||
}
|
||||
|
||||
// ── AppInsightsQueryFunction — POST /api/global/raw/logs ─────────────────────────────
|
||||
// The proxy used to forward the App Insights body byte for byte (no DTO). The typed wrapper keeps
|
||||
// the Kusto `tables[].columns/rows` shape verbatim inside and adds source/budget/partial around it.
|
||||
|
||||
[Fact]
|
||||
public void QueryBackendLogs_wire_shape_keeps_kusto_tables_verbatim_and_drops_absent_partial()
|
||||
{
|
||||
using var cells = JsonDocument.Parse("[\"2026-09-04T10:00:00Z\",42,\"{\\\"TenantId\\\":\\\"t1\\\"}\",null]");
|
||||
var row = cells.RootElement.EnumerateArray().Select(c => c.Clone()).ToList();
|
||||
var response = new QueryBackendLogsResponse
|
||||
{
|
||||
Success = true,
|
||||
Source = "backend",
|
||||
Timespan = "PT1H",
|
||||
BudgetSeconds = 30,
|
||||
ElapsedMs = 812,
|
||||
Partial = null,
|
||||
PartialReason = null,
|
||||
Tables = new[]
|
||||
{
|
||||
new KqlTable
|
||||
{
|
||||
Name = "PrimaryResult",
|
||||
Columns = new[] { new KqlColumn { Name = "timestamp", Type = "datetime" }, new KqlColumn { Name = "count_", Type = "long" }, new KqlColumn { Name = "customDimensions", Type = "dynamic" }, new KqlColumn { Name = "note", Type = "string" } },
|
||||
Rows = new[] { row },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
var json = JsonSerializer.Serialize(response, WireOptions);
|
||||
|
||||
// The dynamic cell is the JSON STRING App Insights emits; the wire serializer escapes its inner
|
||||
// quotes as " (default encoder) — the same string after decoding, so consumers that
|
||||
// parse(customDimensions) are unaffected.
|
||||
Assert.Equal(
|
||||
"{\"success\":true,\"source\":\"backend\",\"timespan\":\"PT1H\",\"budgetSeconds\":30,\"elapsedMs\":812," +
|
||||
"\"tables\":[{\"name\":\"PrimaryResult\",\"columns\":[{\"name\":\"timestamp\",\"type\":\"datetime\"},{\"name\":\"count_\",\"type\":\"long\"},{\"name\":\"customDimensions\",\"type\":\"dynamic\"},{\"name\":\"note\",\"type\":\"string\"}]," +
|
||||
"\"rows\":[[\"2026-09-04T10:00:00Z\",42,\"{\\u0022TenantId\\u0022:\\u0022t1\\u0022}\",null]]}]}",
|
||||
json);
|
||||
using var roundTrip = JsonDocument.Parse(json);
|
||||
var cell = roundTrip.RootElement.GetProperty("tables")[0].GetProperty("rows")[0][2].GetString();
|
||||
Assert.Equal("{\"TenantId\":\"t1\"}", cell);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void QueryBackendLogs_partial_result_carries_flag_and_reason()
|
||||
{
|
||||
var response = new QueryBackendLogsResponse
|
||||
{
|
||||
Success = true, Source = "mcp", Timespan = "P7D", BudgetSeconds = 120, ElapsedMs = 95000,
|
||||
Partial = true, PartialReason = "E_QUERY_RESULT_SET_TOO_LARGE: too many rows",
|
||||
Tables = new List<KqlTable>(),
|
||||
};
|
||||
|
||||
var json = JsonSerializer.Serialize(response, WireOptions);
|
||||
|
||||
Assert.Contains("\"partial\":true,\"partialReason\":\"E_QUERY_RESULT_SET_TOO_LARGE: too many rows\",\"tables\":[]", json);
|
||||
}
|
||||
|
||||
// ── AccessProbeFunction — GET /api/global/raw/access-probe ───────────────────────────
|
||||
// New route (no anonymous predecessor): the wire shape is pinned as fixed JSON.
|
||||
|
||||
[Fact]
|
||||
public void AccessProbe_wire_shape()
|
||||
{
|
||||
var json = JsonSerializer.Serialize(
|
||||
new AccessProbeResponse { Success = true, Role = "GlobalAdmin" }, WireOptions);
|
||||
|
||||
Assert.Equal("{\"success\":true,\"role\":\"GlobalAdmin\"}", json);
|
||||
}
|
||||
|
||||
// ── TableQueryFunction.QueryTable — GET /api/global/raw/tables/{tableName} ───────────
|
||||
// Old literal: new { table = actualTableName, count = entities.Count, entities, nextLink }
|
||||
// (entities is List<Dictionary<string, object?>> at the call site.)
|
||||
|
||||
@@ -88,7 +88,8 @@ public class RevokeEnforcementTests
|
||||
var audit = BuildAuditRepo();
|
||||
var signalR = new FakeSignalRNotificationService();
|
||||
var fn = new TenantGroupManagementFunction(
|
||||
NullLogger<TenantGroupManagementFunction>.Instance, BuildService(repo), Resolver(), audit.Object, signalR, BuildSlots(repo));
|
||||
NullLogger<TenantGroupManagementFunction>.Instance, BuildService(repo), Resolver(), audit.Object, signalR, BuildSlots(repo),
|
||||
TestProConferral.Inert());
|
||||
return (fn, repo, audit, signalR);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Timestamp provenance in the duration evaluators (phase_duration, app_install_duration).
|
||||
/// IME-log-derived events carry <c>data.sourceOffsetOrigin</c>; <c>reader-zone-fallback</c>
|
||||
/// means the agent assumed its own timezone for the log writer, so the Timestamp can be hours
|
||||
/// off. A duration with such an endpoint is not measurable: the condition is false with a
|
||||
/// provenance reason. Other origins and agent-native events (no tag) stay measurable.
|
||||
/// Field case: a 20-minute DeviceSetup rendered as 3 h 22 min fired ANALYZE-ESP-001 (high).
|
||||
/// </summary>
|
||||
public class RuleEngineDurationProvenanceTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "77777777-8888-9999-aaaa-bbbbbbbbbbbb";
|
||||
private const string Fallback = "reader-zone-fallback";
|
||||
private const string LineAnchored = "line-anchored";
|
||||
|
||||
private static readonly DateTime T0 = new(2026, 9, 1, 13, 30, 0, DateTimeKind.Utc);
|
||||
|
||||
// ===== phase_duration =====
|
||||
|
||||
[Theory]
|
||||
[InlineData(Fallback)]
|
||||
[InlineData("Reader-Zone-Fallback")] // origin compare is case-insensitive
|
||||
public async Task PhaseDuration_StartWithFallbackProvenance_IsNotMeasurable(string origin)
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
PhaseEvent("DeviceSetup", T0, 10, origin),
|
||||
PhaseEvent("AccountSetup", T0.AddHours(3), 20, LineAnchored),
|
||||
};
|
||||
|
||||
var (dry, _, _) = await DryRunAsync(PhaseRule("DeviceSetup"), events);
|
||||
|
||||
Assert.Equal(RuleDryRunVerdict.RequiredConditionNotMet, dry.Verdict);
|
||||
var condition = Assert.Single(dry.Conditions);
|
||||
Assert.False(condition.Matched);
|
||||
var evidence = AsDict(condition.Evidence!);
|
||||
Assert.Contains("not measurable", AsString(evidence["reason"]));
|
||||
Assert.Contains("start timestamp derived from reader-zone fallback", AsString(evidence["reason"]));
|
||||
Assert.Equal(Fallback, AsString(evidence["timestampProvenance"]));
|
||||
Assert.Equal("start", AsString(evidence["provenanceEndpoint"]));
|
||||
Assert.Equal(events[0].EventId, AsString(evidence["eventId"]));
|
||||
Assert.Equal(10L, Convert.ToInt64(evidence["sequence"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PhaseDuration_EndWithFallbackProvenance_IsNotMeasurable()
|
||||
{
|
||||
// The end of a phase is the NEXT esp_phase_changed of any phase — its provenance counts too.
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
PhaseEvent("DeviceSetup", T0, 10, LineAnchored),
|
||||
PhaseEvent("AccountSetup", T0.AddHours(3), 20, Fallback),
|
||||
};
|
||||
|
||||
var (dry, _, _) = await DryRunAsync(PhaseRule("DeviceSetup"), events);
|
||||
|
||||
var condition = Assert.Single(dry.Conditions);
|
||||
Assert.False(condition.Matched);
|
||||
var evidence = AsDict(condition.Evidence!);
|
||||
Assert.Contains("end timestamp derived from reader-zone fallback", AsString(evidence["reason"]));
|
||||
Assert.Equal(Fallback, AsString(evidence["timestampProvenance"]));
|
||||
Assert.Equal("end", AsString(evidence["provenanceEndpoint"]));
|
||||
Assert.Equal(events[1].EventId, AsString(evidence["provenanceEventId"]));
|
||||
Assert.Equal(events[0].EventId, AsString(evidence["eventId"])); // the phase event stays the anchor
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(LineAnchored)]
|
||||
[InlineData("bias")]
|
||||
[InlineData("calibrated")]
|
||||
[InlineData("era-anchored")] // backlog line resolved through its anchored writer era (agent 2026-09-04)
|
||||
public async Task PhaseDuration_TrustedProvenanceOnBothEnds_IsComputed(string origin)
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
PhaseEvent("DeviceSetup", T0, 10, origin),
|
||||
PhaseEvent("AccountSetup", T0.AddHours(3), 20, origin),
|
||||
};
|
||||
|
||||
var (dry, _, _) = await DryRunAsync(PhaseRule("DeviceSetup"), events);
|
||||
|
||||
var condition = Assert.Single(dry.Conditions);
|
||||
Assert.True(condition.Matched);
|
||||
var evidence = AsDict(condition.Evidence!);
|
||||
Assert.Equal(3 * 3600d, Convert.ToDouble(evidence["durationSeconds"]));
|
||||
Assert.Equal(events[1].EventId, AsString(evidence["phaseEndEventId"]));
|
||||
Assert.False(evidence.ContainsKey("timestampProvenance"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PhaseDuration_NoProvenanceAtAll_IsComputed()
|
||||
{
|
||||
// Agent-native events carry no sourceOffsetOrigin — nothing to distrust.
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
PhaseEvent("DeviceSetup", T0, 10, origin: null),
|
||||
PhaseEvent("AccountSetup", T0.AddMinutes(20), 20, origin: null),
|
||||
};
|
||||
|
||||
var (dry, _, _) = await DryRunAsync(PhaseRule("DeviceSetup"), events);
|
||||
|
||||
var condition = Assert.Single(dry.Conditions);
|
||||
Assert.True(condition.Matched);
|
||||
Assert.Equal(20 * 60d, Convert.ToDouble(AsDict(condition.Evidence!)["durationSeconds"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PhaseDuration_OpenPhase_OnlyTheStartProvenanceMatters()
|
||||
{
|
||||
// No next phase event: the end is "now" and has no provenance. A trusted start measures,
|
||||
// a fallback start does not.
|
||||
var trusted = new List<EnrollmentEvent> { PhaseEvent("DeviceSetup", DateTime.UtcNow.AddMinutes(-5), 10, LineAnchored) };
|
||||
var (dryTrusted, _, _) = await DryRunAsync(PhaseRule("DeviceSetup"), trusted);
|
||||
var trustedCondition = Assert.Single(dryTrusted.Conditions);
|
||||
Assert.True(trustedCondition.Matched);
|
||||
Assert.Equal("(still active)", AsString(AsDict(trustedCondition.Evidence!)["phaseEndEventId"]));
|
||||
|
||||
var fallback = new List<EnrollmentEvent> { PhaseEvent("DeviceSetup", DateTime.UtcNow.AddMinutes(-5), 10, Fallback) };
|
||||
var (dryFallback, _, _) = await DryRunAsync(PhaseRule("DeviceSetup"), fallback);
|
||||
var fallbackCondition = Assert.Single(dryFallback.Conditions);
|
||||
Assert.False(fallbackCondition.Matched);
|
||||
Assert.Equal("start", AsString(AsDict(fallbackCondition.Evidence!)["provenanceEndpoint"]));
|
||||
}
|
||||
|
||||
// ===== app_install_duration =====
|
||||
|
||||
[Fact]
|
||||
public async Task AppInstallDuration_StartWithFallbackProvenance_IsNotMeasurable()
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
AppEvent("app_install_started", "app-a", T0, 10, Fallback),
|
||||
AppEvent("app_install_completed", "app-a", T0.AddHours(1), 20, LineAnchored),
|
||||
};
|
||||
|
||||
var (dry, _, _) = await DryRunAsync(AppDurationRule(minSeconds: 600), events);
|
||||
|
||||
Assert.Equal(RuleDryRunVerdict.RequiredConditionNotMet, dry.Verdict);
|
||||
var condition = Assert.Single(dry.Conditions);
|
||||
Assert.False(condition.Matched);
|
||||
var evidence = AsDict(condition.Evidence!);
|
||||
Assert.Contains("app install duration not measurable: start timestamp derived from reader-zone fallback", AsString(evidence["reason"]));
|
||||
Assert.Equal(Fallback, AsString(evidence["timestampProvenance"]));
|
||||
Assert.Equal("start", AsString(evidence["provenanceEndpoint"]));
|
||||
Assert.Equal(events[0].EventId, AsString(evidence["provenanceEventId"]));
|
||||
Assert.Equal(events[1].EventId, AsString(evidence["eventId"])); // completion stays the anchor
|
||||
Assert.Equal(20L, Convert.ToInt64(evidence["sequence"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AppInstallDuration_EndWithFallbackProvenance_IsNotMeasurable()
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
AppEvent("app_install_started", "app-a", T0, 10, LineAnchored),
|
||||
AppEvent("app_install_completed", "app-a", T0.AddHours(1), 20, Fallback),
|
||||
};
|
||||
|
||||
var (dry, _, _) = await DryRunAsync(AppDurationRule(minSeconds: 600), events);
|
||||
|
||||
var condition = Assert.Single(dry.Conditions);
|
||||
Assert.False(condition.Matched);
|
||||
var evidence = AsDict(condition.Evidence!);
|
||||
Assert.Equal("end", AsString(evidence["provenanceEndpoint"]));
|
||||
Assert.Equal(Fallback, AsString(evidence["timestampProvenance"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AppInstallDuration_TrustedProvenance_IsComputed()
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
AppEvent("app_install_started", "app-a", T0, 10, LineAnchored),
|
||||
AppEvent("app_install_completed", "app-a", T0.AddHours(1), 20, LineAnchored),
|
||||
};
|
||||
|
||||
var (dry, _, _) = await DryRunAsync(AppDurationRule(minSeconds: 600), events);
|
||||
|
||||
var condition = Assert.Single(dry.Conditions);
|
||||
Assert.True(condition.Matched);
|
||||
Assert.Equal(3600d, Convert.ToDouble(AsDict(condition.Evidence!)["durationSeconds"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AppInstallDuration_NoProvenance_IsComputed()
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
AppEvent("app_install_started", "app-a", T0, 10, origin: null),
|
||||
AppEvent("app_install_completed", "app-a", T0.AddHours(1), 20, origin: null),
|
||||
};
|
||||
|
||||
var (dry, _, _) = await DryRunAsync(AppDurationRule(minSeconds: 600), events);
|
||||
|
||||
Assert.True(Assert.Single(dry.Conditions).Matched);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AppInstallDuration_UnmeasurablePairDoesNotHideAMeasurableOne()
|
||||
{
|
||||
// The fallback pair is skipped, not fatal: another app with trusted endpoints still matches.
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
AppEvent("app_install_started", "app-a", T0, 10, Fallback),
|
||||
AppEvent("app_install_completed", "app-a", T0.AddHours(1), 20, LineAnchored),
|
||||
AppEvent("app_install_started", "app-b", T0.AddHours(1), 30, LineAnchored),
|
||||
AppEvent("app_install_completed", "app-b", T0.AddHours(2), 40, LineAnchored),
|
||||
};
|
||||
|
||||
var (dry, _, _) = await DryRunAsync(AppDurationRule(minSeconds: 600), events);
|
||||
|
||||
var condition = Assert.Single(dry.Conditions);
|
||||
Assert.True(condition.Matched);
|
||||
Assert.Equal("app-b", AsString(AsDict(condition.Evidence!)["appId"]));
|
||||
}
|
||||
|
||||
// ===== Rule level: ANALYZE-ESP-001 from rules/dist =====
|
||||
|
||||
[Fact]
|
||||
public async Task ANALYZE_ESP_001_does_not_fire_on_a_reader_zone_fallback_DeviceSetup()
|
||||
{
|
||||
// The field case: DeviceSetup start read under the wrong writer zone sits 3 h before the
|
||||
// next (correctly anchored) phase event although the real phase lasted ~20 minutes.
|
||||
var rule = BuiltInAnalyzeRules.GetAll().First(r => r.RuleId == "ANALYZE-ESP-001");
|
||||
Assert.True(rule.Enabled);
|
||||
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
PhaseEvent("DeviceSetup", T0, 10, Fallback),
|
||||
PhaseEvent("AccountSetup", T0.AddHours(3), 20, LineAnchored),
|
||||
};
|
||||
|
||||
var outcome = await RunBuiltInAsync(rule, events);
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ANALYZE_ESP_001_fires_on_the_same_span_when_line_anchored()
|
||||
{
|
||||
var rule = BuiltInAnalyzeRules.GetAll().First(r => r.RuleId == "ANALYZE-ESP-001");
|
||||
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
PhaseEvent("DeviceSetup", T0, 10, LineAnchored),
|
||||
PhaseEvent("AccountSetup", T0.AddHours(3), 20, LineAnchored),
|
||||
};
|
||||
|
||||
var outcome = await RunBuiltInAsync(rule, events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
Assert.Equal("ANALYZE-ESP-001", result.RuleId);
|
||||
Assert.True(result.ConfidenceScore >= rule.ConfidenceThreshold);
|
||||
var matched = AsDict(result.MatchedConditions["esp_stalled"]);
|
||||
Assert.Equal(3 * 3600d, Convert.ToDouble(matched["durationSeconds"]));
|
||||
}
|
||||
|
||||
// ===== Event builders — mirror the ImeLogTrackerAdapter emit shape =====
|
||||
|
||||
private static EnrollmentEvent PhaseEvent(string phase, DateTime timestamp, long sequence, string? origin)
|
||||
=> ImeEvent("esp_phase_changed", timestamp, sequence, origin, new Dictionary<string, object> { ["espPhase"] = phase });
|
||||
|
||||
private static EnrollmentEvent AppEvent(string eventType, string appId, DateTime timestamp, long sequence, string? origin)
|
||||
=> ImeEvent(eventType, timestamp, sequence, origin, new Dictionary<string, object> { ["appId"] = appId, ["appName"] = appId });
|
||||
|
||||
private static EnrollmentEvent ImeEvent(string eventType, DateTime timestamp, long sequence, string? origin, Dictionary<string, object> data)
|
||||
{
|
||||
if (origin != null)
|
||||
{
|
||||
data["sourceLocalTs"] = timestamp.ToString("yyyy-MM-ddTHH:mm:ss.fffffff");
|
||||
data["sourceOffsetOrigin"] = origin;
|
||||
data["sourceOffsetMinutes"] = "-240";
|
||||
}
|
||||
return new EnrollmentEvent
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
EventType = eventType,
|
||||
Timestamp = timestamp,
|
||||
Sequence = sequence,
|
||||
Source = origin != null ? "ImeLogTracker" : "Agent",
|
||||
Data = data,
|
||||
};
|
||||
}
|
||||
|
||||
// ===== Rules =====
|
||||
|
||||
private static AnalyzeRule PhaseRule(string phase) => new()
|
||||
{
|
||||
RuleId = "ANALYZE-TEST-PHASE",
|
||||
Title = "Phase duration draft",
|
||||
Severity = "warning",
|
||||
Category = "esp",
|
||||
IsBuiltIn = false,
|
||||
BaseConfidence = 50,
|
||||
ConfidenceThreshold = 40,
|
||||
Conditions = new List<RuleCondition>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Signal = "esp_stalled", Source = "phase_duration", EventType = "esp_phase_changed",
|
||||
DataField = "espPhase", Operator = "equals", Value = phase, Required = true,
|
||||
},
|
||||
},
|
||||
Explanation = "Phase {{phase}} lasted {{durationFormatted}}.",
|
||||
};
|
||||
|
||||
private static AnalyzeRule AppDurationRule(int minSeconds) => new()
|
||||
{
|
||||
RuleId = "ANALYZE-TEST-APPDUR",
|
||||
Title = "App install duration draft",
|
||||
Severity = "warning",
|
||||
Category = "apps",
|
||||
IsBuiltIn = false,
|
||||
BaseConfidence = 50,
|
||||
ConfidenceThreshold = 40,
|
||||
Conditions = new List<RuleCondition>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Signal = "slow_install", Source = "app_install_duration",
|
||||
Operator = "gt", Value = minSeconds.ToString(), Required = true,
|
||||
},
|
||||
},
|
||||
Explanation = "App {{appName}} took {{durationFormatted}}.",
|
||||
};
|
||||
|
||||
// ===== Harness =====
|
||||
|
||||
private static Dictionary<string, object> AsDict(object o)
|
||||
{
|
||||
if (o is Dictionary<string, object> d) return d;
|
||||
throw new InvalidOperationException($"Expected Dictionary<string,object>, got {o?.GetType().Name ?? "null"}");
|
||||
}
|
||||
|
||||
private static string AsString(object o) => o?.ToString() ?? string.Empty;
|
||||
|
||||
private static async Task<(RuleDryRun dry, Mock<ISessionRepository> sessionRepo, Mock<IRuleRepository> ruleRepo)> DryRunAsync(
|
||||
AnalyzeRule rule, List<EnrollmentEvent> events)
|
||||
{
|
||||
var ruleRepo = new Mock<IRuleRepository>();
|
||||
var sessionRepo = new Mock<ISessionRepository>();
|
||||
sessionRepo.Setup(s => s.GetSessionEventsStrictAsync(TenantId, SessionId, It.IsAny<int>())).ReturnsAsync(events);
|
||||
var ruleService = new AnalyzeRuleService(ruleRepo.Object, NullLogger<AnalyzeRuleService>.Instance);
|
||||
var engine = new RuleEngine(ruleService, ruleRepo.Object, sessionRepo.Object, NullLogger<RuleEngineDurationProvenanceTests>.Instance);
|
||||
var dry = await engine.DryRunRuleAsync(TenantId, SessionId, rule);
|
||||
return (dry, sessionRepo, ruleRepo);
|
||||
}
|
||||
|
||||
private static async Task<AnalysisOutcome> RunBuiltInAsync(AnalyzeRule rule, List<EnrollmentEvent> events)
|
||||
{
|
||||
var ruleRepo = new Mock<IRuleRepository>();
|
||||
ruleRepo.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(new List<AnalyzeRule> { rule });
|
||||
ruleRepo.Setup(r => r.GetAnalyzeRulesAsync(TenantId)).ReturnsAsync(new List<AnalyzeRule>());
|
||||
ruleRepo.Setup(r => r.GetRuleStatesAsync(It.IsAny<string>())).ReturnsAsync(new Dictionary<string, RuleState>());
|
||||
ruleRepo.Setup(r => r.GetRuleResultsAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(new List<RuleResult>());
|
||||
|
||||
var sessionRepo = new Mock<ISessionRepository>();
|
||||
sessionRepo.Setup(s => s.GetSessionEventsStrictAsync(TenantId, SessionId, It.IsAny<int>())).ReturnsAsync(events);
|
||||
|
||||
var ruleService = new AnalyzeRuleService(ruleRepo.Object, NullLogger<AnalyzeRuleService>.Instance);
|
||||
var engine = new RuleEngine(ruleService, ruleRepo.Object, sessionRepo.Object, NullLogger<RuleEngineDurationProvenanceTests>.Instance);
|
||||
|
||||
return await engine.AnalyzeSessionAsync(TenantId, SessionId);
|
||||
}
|
||||
}
|
||||
@@ -320,8 +320,10 @@ public class RuleEngineEvaluateOnTests
|
||||
// Pins the JSON → model deserialization of evaluateOn end-to-end through the
|
||||
// embedded catalog (rules/dist/analyze-rules.json).
|
||||
var rule = BuiltInAnalyzeRules.GetAll().First(r => r.RuleId == "ANALYZE-ID-004");
|
||||
Assert.Equal(new List<string> { "enrollment_end", "on_event:hybrid_login_pending" }, rule.EvaluateOn);
|
||||
// Interim safety: the rule must not fire on a single overdue-login signal — the
|
||||
// v2.0.0: the interim trigger is the agent's user-affinity signal (real-user desktop seen,
|
||||
// IME acquired no Entra user token), no longer hybrid_login_pending (desktop absence).
|
||||
Assert.Equal(new List<string> { "enrollment_end", "on_event:entra_user_affinity_pending" }, rule.EvaluateOn);
|
||||
// Interim safety: the rule must not fire on a single pending-affinity signal — the
|
||||
// threshold has to require the repetition factors (base 60 + count>=2 → 80).
|
||||
Assert.True(rule.ConfidenceThreshold > rule.BaseConfidence,
|
||||
"ANALYZE-ID-004 must be repetition-gated to stay interim-safe");
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the same-event value filter (FilterField/FilterOperator/FilterValue) on the
|
||||
/// <c>event_data</c> and <c>event_data_array</c> condition sources (backlog q8n). Every
|
||||
/// condition scans all events of its type independently, so two conditions cannot express
|
||||
/// "field A AND field B on the SAME event" — the filter can. Mirrors the event_count filter
|
||||
/// semantics (<see cref="RuleEngineEventCountFilterTests"/>): no filter = unchanged behaviour,
|
||||
/// a missing filter field stringifies to empty.
|
||||
/// </summary>
|
||||
public class RuleEngineEventDataFilterTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "c3d4e5f6-a7b8-9012-cdef-123456789012";
|
||||
|
||||
[Fact]
|
||||
public async Task EventData_FilterAndMainTest_MustHoldOnTheSameEvent()
|
||||
{
|
||||
// Event 1 passes the main test but fails the filter; event 2 passes the filter but
|
||||
// fails the main test. Independent evaluation would fire — the same-event filter must not.
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
Episode(sequence: 1, durationSeconds: 5000, backfilled: true),
|
||||
Episode(sequence: 2, durationSeconds: 90, backfilled: false),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(MakeEventDataRule(), events);
|
||||
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EventData_MatchesTheEventThatSatisfiesBoth_AndReportsItAsEvidence()
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
Episode(sequence: 1, durationSeconds: 5000, backfilled: true),
|
||||
Episode(sequence: 2, durationSeconds: 900, backfilled: false),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(MakeEventDataRule(), events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
var evidence = Assert.IsAssignableFrom<IDictionary<string, object>>(result.MatchedConditions["long_live_episode"]);
|
||||
Assert.Equal(2, Convert.ToInt32(evidence["sequence"]));
|
||||
Assert.Equal("900", evidence["value"]?.ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EventData_NoFilterConfigured_KeepsIndependentBehaviour()
|
||||
{
|
||||
var rule = MakeEventDataRule();
|
||||
rule.Conditions[0].FilterField = null!;
|
||||
rule.Conditions[0].FilterOperator = null!;
|
||||
rule.Conditions[0].FilterValue = null!;
|
||||
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
Episode(sequence: 1, durationSeconds: 5000, backfilled: true),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(rule, events);
|
||||
|
||||
Assert.Single(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EventData_MissingFilterField_IsExcludedByEquals_AndKeptByNotEquals()
|
||||
{
|
||||
var evt = Episode(sequence: 1, durationSeconds: 5000, backfilled: false);
|
||||
evt.Data!.Remove("backfilled");
|
||||
var events = new List<EnrollmentEvent> { evt };
|
||||
|
||||
// equals "false" on a missing field → empty string ≠ "false" → excluded.
|
||||
Assert.Empty((await RunAsync(MakeEventDataRule(), events)).Results);
|
||||
|
||||
// not_equals "true" on a missing field → kept.
|
||||
var lenient = MakeEventDataRule();
|
||||
lenient.Conditions[0].FilterOperator = "not_equals";
|
||||
lenient.Conditions[0].FilterValue = "true";
|
||||
Assert.Single((await RunAsync(lenient, events)).Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EventDataArray_FilterSelectsWhichEventsArraysAreIterated()
|
||||
{
|
||||
// The array element would match in both events; only the event passing the filter counts.
|
||||
var rule = new AnalyzeRule
|
||||
{
|
||||
RuleId = "ANALYZE-TST-011",
|
||||
Title = "Array with same-event filter",
|
||||
Severity = "warning",
|
||||
Category = "security",
|
||||
Enabled = true,
|
||||
IsBuiltIn = false,
|
||||
BaseConfidence = 80,
|
||||
ConfidenceThreshold = 40,
|
||||
Conditions = new List<RuleCondition>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Signal = "unexpected_artifact",
|
||||
Source = "event_data_array",
|
||||
EventType = "provisioning_package_scan",
|
||||
DataField = "artifacts",
|
||||
ItemField = "identity",
|
||||
Operator = "regex",
|
||||
Value = "^Evil",
|
||||
FilterField = "source",
|
||||
FilterOperator = "equals",
|
||||
FilterValue = "registry",
|
||||
Required = true
|
||||
}
|
||||
},
|
||||
Explanation = "test"
|
||||
};
|
||||
|
||||
var fileScan = ScanEvent(sequence: 1, source: "file", "Evil.ppkg");
|
||||
Assert.Empty((await RunAsync(rule, new List<EnrollmentEvent> { fileScan })).Results);
|
||||
|
||||
var registryScan = ScanEvent(sequence: 2, source: "registry", "Evil.ppkg");
|
||||
var outcome = await RunAsync(rule, new List<EnrollmentEvent> { fileScan, registryScan });
|
||||
var result = Assert.Single(outcome.Results);
|
||||
var evidence = Assert.IsAssignableFrom<IDictionary<string, object>>(result.MatchedConditions["unexpected_artifact"]);
|
||||
Assert.Equal(2, Convert.ToInt32(evidence["sequence"]));
|
||||
}
|
||||
|
||||
// ===== Builders =====
|
||||
|
||||
private static AnalyzeRule MakeEventDataRule() => new()
|
||||
{
|
||||
RuleId = "ANALYZE-TST-010",
|
||||
Title = "Long live sleep episode",
|
||||
Severity = "info",
|
||||
Category = "device",
|
||||
Enabled = true,
|
||||
// Synthetic rule ID outside the embedded catalog — see RuleEngineEventCountFilterTests.
|
||||
IsBuiltIn = false,
|
||||
BaseConfidence = 90,
|
||||
ConfidenceThreshold = 40,
|
||||
Conditions = new List<RuleCondition>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Signal = "long_live_episode",
|
||||
Source = "event_data",
|
||||
EventType = "system_sleep_episode",
|
||||
DataField = "durationSeconds",
|
||||
Operator = "gte",
|
||||
Value = "300",
|
||||
FilterField = "backfilled",
|
||||
FilterOperator = "equals",
|
||||
FilterValue = "false",
|
||||
Required = true
|
||||
}
|
||||
},
|
||||
Explanation = "test"
|
||||
};
|
||||
|
||||
private static EnrollmentEvent Episode(int sequence, long durationSeconds, bool backfilled) => new()
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
EventType = "system_sleep_episode",
|
||||
Timestamp = DateTime.UtcNow.AddMinutes(sequence),
|
||||
Sequence = sequence,
|
||||
Data = new Dictionary<string, object>
|
||||
{
|
||||
["kind"] = "modern_standby",
|
||||
["durationSeconds"] = durationSeconds,
|
||||
["backfilled"] = backfilled,
|
||||
}
|
||||
};
|
||||
|
||||
private static EnrollmentEvent ScanEvent(int sequence, string source, params string[] identities) => new()
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
EventType = "provisioning_package_scan",
|
||||
Timestamp = DateTime.UtcNow.AddMinutes(sequence),
|
||||
Sequence = sequence,
|
||||
Data = new Dictionary<string, object>
|
||||
{
|
||||
["source"] = source,
|
||||
["artifacts"] = identities
|
||||
.Select(id => (object)new Dictionary<string, object> { ["identity"] = id })
|
||||
.ToList(),
|
||||
}
|
||||
};
|
||||
|
||||
private static async Task<AnalysisOutcome> RunAsync(AnalyzeRule rule, List<EnrollmentEvent> events)
|
||||
{
|
||||
var ruleRepo = new Mock<IRuleRepository>();
|
||||
ruleRepo.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(new List<AnalyzeRule> { rule });
|
||||
ruleRepo.Setup(r => r.GetAnalyzeRulesAsync(TenantId)).ReturnsAsync(new List<AnalyzeRule>());
|
||||
ruleRepo.Setup(r => r.GetRuleStatesAsync(It.IsAny<string>())).ReturnsAsync(new Dictionary<string, RuleState>());
|
||||
ruleRepo.Setup(r => r.GetRuleResultsAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(new List<RuleResult>());
|
||||
|
||||
var sessionRepo = new Mock<ISessionRepository>();
|
||||
sessionRepo.Setup(s => s.GetSessionEventsStrictAsync(TenantId, SessionId, It.IsAny<int>())).ReturnsAsync(events);
|
||||
|
||||
var ruleService = new AnalyzeRuleService(ruleRepo.Object, NullLogger<AnalyzeRuleService>.Instance);
|
||||
var engine = new RuleEngine(ruleService, ruleRepo.Object, sessionRepo.Object, NullLogger<RuleEngineEventDataFilterTests>.Instance);
|
||||
|
||||
return await engine.AnalyzeSessionAsync(TenantId, SessionId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the absence gate on <c>event_type</c> conditions: <c>not_exists</c> without a
|
||||
/// <c>dataField</c> matches when no event of that type occurs in the session and is disproved by
|
||||
/// a single such event. Before this branch an absent type always evaluated false, so a required
|
||||
/// "must not have happened" condition could never be expressed (ANALYZE-ID-004 v2 relies on it).
|
||||
/// The dataField variant keeps its historical meaning (some event of the type has an empty field)
|
||||
/// and is not touched here.
|
||||
/// </summary>
|
||||
public class RuleEngineEventTypeNotExistsTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "12121212-3434-5656-7878-909090909090";
|
||||
|
||||
[Fact]
|
||||
public async Task Not_exists_matches_when_the_event_type_is_absent()
|
||||
{
|
||||
var events = new List<EnrollmentEvent> { Event("marker_seen", 1) };
|
||||
|
||||
var outcome = await RunAsync(Rule(), events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
var evidence = Assert.IsType<Dictionary<string, object>>(result.MatchedConditions["disproof_absent"]);
|
||||
Assert.Equal("disproof", evidence["eventType"]);
|
||||
Assert.Equal(0, evidence["count"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_single_event_of_the_type_vetoes_a_required_not_exists()
|
||||
{
|
||||
var events = new List<EnrollmentEvent> { Event("marker_seen", 1), Event("disproof", 2) };
|
||||
|
||||
var outcome = await RunAsync(Rule(), events);
|
||||
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
private static AnalyzeRule Rule() => new()
|
||||
{
|
||||
// Custom-namespace rule: a built-in ID outside the live catalog is hidden by the
|
||||
// sunset filter in AnalyzeRuleService (IsBuiltIn defaults to true).
|
||||
RuleId = "ANALYZE-CUSTOM-001",
|
||||
IsBuiltIn = false,
|
||||
Title = "not_exists absence gate",
|
||||
Severity = "info",
|
||||
Category = "device",
|
||||
Enabled = true,
|
||||
Trigger = "correlation",
|
||||
BaseConfidence = 80,
|
||||
ConfidenceThreshold = 50,
|
||||
Conditions = new List<RuleCondition>
|
||||
{
|
||||
new() { Signal = "marker", Source = "event_type", EventType = "marker_seen", Operator = "exists", Value = "", Required = true },
|
||||
new() { Signal = "disproof_absent", Source = "event_type", EventType = "disproof", Operator = "not_exists", Value = "", Required = true },
|
||||
},
|
||||
};
|
||||
|
||||
private static EnrollmentEvent Event(string eventType, int sequence) => new()
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
EventType = eventType,
|
||||
Timestamp = DateTime.UtcNow.AddMinutes(sequence),
|
||||
Sequence = sequence,
|
||||
Data = new Dictionary<string, object>(),
|
||||
};
|
||||
|
||||
private static async Task<AnalysisOutcome> RunAsync(AnalyzeRule rule, List<EnrollmentEvent> events)
|
||||
{
|
||||
var ruleRepo = new Mock<IRuleRepository>();
|
||||
ruleRepo.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(new List<AnalyzeRule> { rule });
|
||||
ruleRepo.Setup(r => r.GetAnalyzeRulesAsync(TenantId)).ReturnsAsync(new List<AnalyzeRule>());
|
||||
ruleRepo.Setup(r => r.GetRuleStatesAsync(It.IsAny<string>())).ReturnsAsync(new Dictionary<string, RuleState>());
|
||||
ruleRepo.Setup(r => r.GetRuleResultsAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(new List<RuleResult>());
|
||||
|
||||
var sessionRepo = new Mock<ISessionRepository>();
|
||||
sessionRepo.Setup(s => s.GetSessionEventsStrictAsync(TenantId, SessionId, It.IsAny<int>())).ReturnsAsync(events);
|
||||
|
||||
var ruleService = new AnalyzeRuleService(ruleRepo.Object, NullLogger<AnalyzeRuleService>.Instance);
|
||||
var engine = new RuleEngine(ruleService, ruleRepo.Object, sessionRepo.Object, NullLogger<RuleEngineEventTypeNotExistsTests>.Instance);
|
||||
|
||||
return await engine.AnalyzeSessionAsync(TenantId, SessionId);
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,8 @@ public sealed class SharedManifestParityTests
|
||||
["opsEventSeverities"] = ConstStrings(typeof(OpsEventSeverity)),
|
||||
// Declaration order (grouped by category) — the MCP renders this catalog verbatim.
|
||||
["opsEventTypes"] = OpsEventTypes.All,
|
||||
// Telemetry stores behind the operator KQL proxy (query_backend_logs `source`).
|
||||
["logSources"] = LogQuerySources.All,
|
||||
["tenantRoles"] = ConstStrings(typeof(Constants.TenantRoles)),
|
||||
["globalRoles"] = ConstStrings(typeof(Constants.GlobalRoles)),
|
||||
["delegatedRoles"] = ConstStrings(typeof(Constants.DelegatedRoles)),
|
||||
|
||||
@@ -90,9 +90,62 @@ public class SleepEpisodeRuleTests
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ANALYZE_DEV_012_does_not_fire_on_a_backfilled_pre_session_episode()
|
||||
{
|
||||
// Backlog q8n: the watcher backfills pre-agent episodes for timeline context. A 91 h
|
||||
// hibernate that ended before the enrollment started (session a2256107) satisfied the
|
||||
// duration test and fired the rule although the device never slept while enrolling.
|
||||
var rule = BuiltInAnalyzeRules.GetAll().First(r => r.RuleId == "ANALYZE-DEV-012");
|
||||
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
SleepEpisode(durationSeconds: 329_140, kind: "hibernate", backfilled: true),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(rule, events);
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ANALYZE_DEV_012_pins_duration_and_backfilled_to_the_same_episode()
|
||||
{
|
||||
// The adversarial mix from a2256107: a long backfilled episode plus a short live one.
|
||||
// Two independent conditions (duration >= 300, backfilled = false) would each find a
|
||||
// match on a different event and fire; the same-event filter must not.
|
||||
var rule = BuiltInAnalyzeRules.GetAll().First(r => r.RuleId == "ANALYZE-DEV-012");
|
||||
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
SleepEpisode(durationSeconds: 329_140, kind: "hibernate", backfilled: true),
|
||||
SleepEpisode(durationSeconds: 89, kind: "modern_standby", backfilled: false),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(rule, events);
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ANALYZE_DEV_012_fires_on_a_live_episode_next_to_a_backfilled_one()
|
||||
{
|
||||
var rule = BuiltInAnalyzeRules.GetAll().First(r => r.RuleId == "ANALYZE-DEV-012");
|
||||
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
SleepEpisode(durationSeconds: 329_140, kind: "hibernate", backfilled: true),
|
||||
SleepEpisode(durationSeconds: 600, kind: "modern_standby", backfilled: false),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(rule, events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
var matched = AsDict(result.MatchedConditions["slept_during_enrollment"]);
|
||||
Assert.Equal("600", AsString(matched["value"])); // the live episode, not the backfilled one
|
||||
}
|
||||
|
||||
// ===== Event builder — mirrors the SystemTimelineTracker emit shape =====
|
||||
|
||||
private static EnrollmentEvent SleepEpisode(long durationSeconds, string kind) => new()
|
||||
private static EnrollmentEvent SleepEpisode(long durationSeconds, string kind, bool backfilled = false) => new()
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
@@ -106,7 +159,7 @@ public class SleepEpisodeRuleTests
|
||||
["enteredAt"] = DateTime.UtcNow.AddSeconds(-durationSeconds).ToString("o"),
|
||||
["exitedAt"] = DateTime.UtcNow.ToString("o"),
|
||||
["durationSeconds"] = durationSeconds,
|
||||
["backfilled"] = false,
|
||||
["backfilled"] = backfilled,
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -11,30 +11,39 @@ namespace AutopilotMonitor.Functions.Tests;
|
||||
/// </summary>
|
||||
internal sealed class StubTenantEntitlementService : TenantEntitlementService
|
||||
{
|
||||
private readonly Func<string?, TenantEdition> _resolver;
|
||||
private readonly Func<string?, EditionResolution> _resolver;
|
||||
private readonly Func<string?, string?> _planOverrideResolver;
|
||||
|
||||
public StubTenantEntitlementService(TenantEdition edition) : this(_ => edition)
|
||||
{
|
||||
}
|
||||
|
||||
/// <param name="resolver">Edition per tenant id.</param>
|
||||
/// <param name="resolver">Edition per tenant id — Pro means Pro in the tenant's OWN right (plan).</param>
|
||||
/// <param name="planOverrideResolver">
|
||||
/// The tenant-wide MCP usage-plan override (TenantConfiguration.McpUsagePlanOverride) per tenant id;
|
||||
/// null = no override (the edition's plan name applies). Defaults to "no override anywhere".
|
||||
/// </param>
|
||||
public StubTenantEntitlementService(Func<string?, TenantEdition> resolver, Func<string?, string?>? planOverrideResolver = null)
|
||||
: this(tenantId => AsOwnResolution(resolver(tenantId)), planOverrideResolver)
|
||||
{
|
||||
}
|
||||
|
||||
/// <param name="resolver">Full resolution per tenant id (edition, source, own standing) — for conferred-Pro cases.</param>
|
||||
/// <param name="planOverrideResolver">See the edition-based constructor.</param>
|
||||
public StubTenantEntitlementService(Func<string?, EditionResolution> resolver, Func<string?, string?>? planOverrideResolver)
|
||||
: base(configService: null!, logger: NullLogger<TenantEntitlementService>.Instance)
|
||||
{
|
||||
_resolver = resolver;
|
||||
_planOverrideResolver = planOverrideResolver ?? (_ => null);
|
||||
}
|
||||
|
||||
public override Task<TenantEdition> GetEditionAsync(string? tenantId)
|
||||
=> Task.FromResult(_resolver(tenantId));
|
||||
private static EditionResolution AsOwnResolution(TenantEdition edition) => edition == TenantEdition.Pro
|
||||
? new EditionResolution(TenantEdition.Pro, EditionSource.Plan, OwnPro: true)
|
||||
: new EditionResolution(TenantEdition.Community, EditionSource.Community, OwnPro: false);
|
||||
|
||||
public override Task<EditionEntitlements> GetEntitlementsAsync(string? tenantId)
|
||||
=> Task.FromResult(FeatureEntitlementCatalog.Get(_resolver(tenantId)));
|
||||
// GetEditionAsync / GetEntitlementsAsync derive from this in the base class.
|
||||
public override Task<EditionResolution> GetResolutionAsync(string? tenantId)
|
||||
=> Task.FromResult(_resolver(tenantId));
|
||||
|
||||
public override Task<string> GetMcpUsagePlanNameAsync(string? tenantId)
|
||||
=> Task.FromResult(
|
||||
|
||||
@@ -28,7 +28,7 @@ public class TenantConfigProjectionTests
|
||||
private static readonly string[] AllSafeKeys =
|
||||
{
|
||||
"tenantId", "domainName", "planTier", "trialExpiresUtc", "trialConsumed", "maxDelegatedTenantsOverride",
|
||||
"mcpUsagePlanOverride",
|
||||
"mcpUsagePlanOverride", "payingCustomer", "managedByProTenantId",
|
||||
"disabled", "disabledReason",
|
||||
"onboardedAt", "onboardedBy", "lastUpdated", "dataRetentionDays",
|
||||
"homedAppClientId", "lastAuthClientId", "lastAuthClientIdSince",
|
||||
|
||||
@@ -226,6 +226,43 @@ public class TenantConfigTableSerializationTests
|
||||
Assert.Equal(overrideLimit, mapped.MaxDelegatedTenantsOverride);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void Roundtrip_PayingCustomer_SurvivesStoreAndMap(bool paying)
|
||||
{
|
||||
var config = new TenantConfiguration { TenantId = TenantId, DomainName = "contoso.com", UpdatedBy = "ga@operator.example", PayingCustomer = paying };
|
||||
|
||||
var mapped = TableConfigRepository.ConvertFromTenantTableEntity(TableConfigRepository.ConvertToTenantTableEntity(config));
|
||||
|
||||
Assert.Equal(paying, mapped.PayingCustomer);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_LegacyRow_WithoutPayingCustomerColumn_ReadsFalse()
|
||||
{
|
||||
var entity = new TableEntity(TenantId, "config") { { "DomainName", "fabrikam.com" } };
|
||||
|
||||
Assert.False(TableConfigRepository.ConvertFromTenantTableEntity(entity).PayingCustomer);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ManagedByProTenantId_IsNeverStored_AndNeverMapped()
|
||||
{
|
||||
// Read-time projection (conferred Pro): a value set on the model must not reach the table —
|
||||
// otherwise a stale column could keep a tenant Pro after its delegation ended.
|
||||
var config = new TenantConfiguration
|
||||
{
|
||||
TenantId = TenantId, DomainName = "contoso.com", UpdatedBy = "ga@operator.example",
|
||||
ManagedByProTenantId = "11111111-1111-1111-1111-111111111111",
|
||||
};
|
||||
|
||||
var entity = TableConfigRepository.ConvertToTenantTableEntity(config);
|
||||
|
||||
Assert.False(entity.ContainsKey("ManagedByProTenantId"));
|
||||
Assert.Null(TableConfigRepository.ConvertFromTenantTableEntity(entity).ManagedByProTenantId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("msp")]
|
||||
|
||||
+85
@@ -31,6 +31,91 @@ public sealed class TenantConfigurationServiceReadSemanticsTests
|
||||
return (service, repo);
|
||||
}
|
||||
|
||||
// ── Conferred-Pro projection (ManagedByProTenantId) ──────────────────────
|
||||
|
||||
private const string Owner = "99999999-9999-9999-9999-999999999999";
|
||||
|
||||
private static (TenantConfigurationService service, Mock<IConfigRepository> repo, StubManagedTenantProIndex index) BuildProjecting(string? owner)
|
||||
{
|
||||
var repo = new Mock<IConfigRepository>();
|
||||
var index = new StubManagedTenantProIndex(id => string.Equals(id, TenantId, StringComparison.OrdinalIgnoreCase) ? owner : null);
|
||||
var service = new TenantConfigurationService(
|
||||
repo.Object, Mock.Of<ILogger<TenantConfigurationService>>(), new MemoryCache(new MemoryCacheOptions()), index);
|
||||
return (service, repo, index);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Projection_IsAppliedOnMissAndOnCacheHit()
|
||||
{
|
||||
var (service, repo, _) = BuildProjecting(Owner);
|
||||
repo.Setup(r => r.GetTenantConfigurationAsync(TenantId)).ReturnsAsync(new TenantConfiguration { TenantId = TenantId });
|
||||
|
||||
var first = await service.GetConfigurationIfExistsAsync(TenantId);
|
||||
var second = await service.GetConfigurationIfExistsAsync(TenantId); // cache hit
|
||||
|
||||
Assert.Equal(Owner, first!.ManagedByProTenantId);
|
||||
Assert.Equal(Owner, second!.ManagedByProTenantId);
|
||||
repo.Verify(r => r.GetTenantConfigurationAsync(TenantId), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Projection_FollowsTheIndex_NotTheCachedRow()
|
||||
{
|
||||
// The index answer changes (delegation ended) while the config row stays cached: the next
|
||||
// read must reflect the index, i.e. staleness is bounded by the INDEX, not by this cache.
|
||||
var repo = new Mock<IConfigRepository>();
|
||||
string? owner = Owner;
|
||||
var index = new StubManagedTenantProIndex(_ => owner);
|
||||
var service = new TenantConfigurationService(
|
||||
repo.Object, Mock.Of<ILogger<TenantConfigurationService>>(), new MemoryCache(new MemoryCacheOptions()), index);
|
||||
repo.Setup(r => r.GetTenantConfigurationAsync(TenantId)).ReturnsAsync(new TenantConfiguration { TenantId = TenantId });
|
||||
|
||||
Assert.Equal(Owner, (await service.GetConfigurationAsync(TenantId)).ManagedByProTenantId);
|
||||
owner = null;
|
||||
Assert.Null((await service.GetConfigurationAsync(TenantId)).ManagedByProTenantId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Projection_CoversFreshAllAndPageReads()
|
||||
{
|
||||
var (service, repo, _) = BuildProjecting(Owner);
|
||||
TenantConfiguration Row() => new() { TenantId = TenantId };
|
||||
repo.Setup(r => r.GetTenantConfigurationAsync(TenantId)).ReturnsAsync(Row());
|
||||
repo.Setup(r => r.GetAllTenantConfigurationsAsync()).ReturnsAsync(new List<TenantConfiguration> { Row(), new() { TenantId = "other" } });
|
||||
repo.Setup(r => r.GetTenantConfigurationsPageAsync(It.IsAny<int>(), It.IsAny<string?>()))
|
||||
.ReturnsAsync(new AutopilotMonitor.Shared.Pagination.RawPage<TenantConfiguration>(new List<TenantConfiguration> { Row() }, null));
|
||||
|
||||
Assert.Equal(Owner, (await service.GetConfigurationFreshAsync(TenantId))!.ManagedByProTenantId);
|
||||
var all = await service.GetAllConfigurationsAsync();
|
||||
Assert.Equal(Owner, all.Single(c => c.TenantId == TenantId).ManagedByProTenantId);
|
||||
Assert.Null(all.Single(c => c.TenantId == "other").ManagedByProTenantId);
|
||||
var page = await service.GetConfigurationsPageAsync(10, null);
|
||||
Assert.Equal(Owner, page.Items.Single().ManagedByProTenantId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Projection_NeverAppliesToASynthesizedDefault()
|
||||
{
|
||||
// No row ⇒ the auto-created default is returned unprojected: a tenant without a configuration
|
||||
// row can never be Pro, whatever the index says (fail-closed).
|
||||
var (service, repo, _) = BuildProjecting(Owner);
|
||||
repo.Setup(r => r.GetTenantConfigurationAsync(TenantId)).ReturnsAsync((TenantConfiguration?)null);
|
||||
repo.Setup(r => r.SaveTenantConfigurationAsync(It.IsAny<TenantConfiguration>())).ReturnsAsync(true);
|
||||
|
||||
var config = await service.GetConfigurationAsync(TenantId);
|
||||
|
||||
Assert.Null(config.ManagedByProTenantId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ThreeArgumentConstructor_ProjectsNobody()
|
||||
{
|
||||
var (service, repo) = Build();
|
||||
repo.Setup(r => r.GetTenantConfigurationAsync(TenantId)).ReturnsAsync(new TenantConfiguration { TenantId = TenantId });
|
||||
|
||||
Assert.Null((await service.GetConfigurationIfExistsAsync(TenantId))!.ManagedByProTenantId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConfigurationIfExistsAsync_StorageError_Propagates()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
using System.Collections.Generic;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Recording stand-in for <see cref="IPrivilegedDenialReporter"/> so middleware tests can build a
|
||||
/// <c>PolicyEnforcementMiddleware</c> without the ops-event/notification stack and still assert
|
||||
/// what the deny path would have reported.
|
||||
/// </summary>
|
||||
internal sealed class RecordingDenialReporter : IPrivilegedDenialReporter
|
||||
{
|
||||
public List<PrivilegedDenial> Reported { get; } = new();
|
||||
|
||||
public void Report(PrivilegedDenial denial)
|
||||
{
|
||||
lock (Reported) Reported.Add(denial);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Conferred-Pro test doubles: an inert <see cref="ProConferralService"/> for subjects that merely
|
||||
/// depend on it, and a storage-free <see cref="ManagedTenantProIndex"/> that answers from a lambda.
|
||||
/// </summary>
|
||||
internal static class TestProConferral
|
||||
{
|
||||
/// <summary>A service over empty storage: every record call is a no-op that returns "nothing stamped".</summary>
|
||||
public static ProConferralService Inert()
|
||||
{
|
||||
var adminRepo = new Mock<IAdminRepository>();
|
||||
adminRepo.Setup(r => r.GetGroupTenantsAsync(It.IsAny<string>())).ReturnsAsync(new List<string>());
|
||||
var configs = new TenantConfigurationService(
|
||||
Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
|
||||
return new ProConferralService(adminRepo.Object, configs, ManagedTenantProIndex.None, NullLogger<ProConferralService>.Instance);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Index stub: the conferring owner per tenant id comes from the lambda; no storage, no cache.</summary>
|
||||
internal sealed class StubManagedTenantProIndex : ManagedTenantProIndex
|
||||
{
|
||||
private readonly Func<string?, string?> _owner;
|
||||
public int Invalidations { get; private set; }
|
||||
|
||||
public StubManagedTenantProIndex(Func<string?, string?> owner) => _owner = owner;
|
||||
|
||||
public override Task<string?> GetConferringOwnerAsync(string? tenantId) => Task.FromResult(_owner(tenantId));
|
||||
public override void Invalidate() => Invalidations++;
|
||||
}
|
||||
@@ -54,11 +54,42 @@ public class TrialExpirySweepFunctionTests
|
||||
var opsService = new OpsEventService(opsRepo.Object, NullLogger<OpsEventService>.Instance, alertDispatch);
|
||||
|
||||
var sut = new TrialExpirySweepFunction(
|
||||
configRepo.Object, opsService, NullLogger<TrialExpirySweepFunction>.Instance,
|
||||
Configs(configRepo.Object), opsService, NullLogger<TrialExpirySweepFunction>.Instance,
|
||||
new TestTimeProvider(Now));
|
||||
return (sut, events);
|
||||
}
|
||||
|
||||
private static TenantConfigurationService Configs(IConfigRepository repo, ManagedTenantProIndex? index = null)
|
||||
=> new(repo, NullLogger<TenantConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()), index ?? ManagedTenantProIndex.None);
|
||||
|
||||
[Fact]
|
||||
public async Task ExpiredTrial_OfManagedTenant_EmitsNothing_StillProViaMsp()
|
||||
{
|
||||
// The tenant's own trial ran out yesterday, but a permanent-Pro tenant manages it — the
|
||||
// projection keeps it Pro, so no "trial expired" alert may reach sales/support.
|
||||
var managed = Tenant("t-managed", Now.AddHours(-2), retentionDays: 365);
|
||||
var configRepo = new Mock<IConfigRepository>();
|
||||
configRepo.Setup(r => r.GetAllTenantConfigurationsAsync()).ReturnsAsync(new List<TenantConfiguration> { managed });
|
||||
var events = new List<OpsEventEntry>();
|
||||
var opsRepo = new Mock<IOpsEventRepository>();
|
||||
opsRepo.Setup(r => r.SaveOpsEventAsync(It.IsAny<OpsEventEntry>())).Callback<OpsEventEntry>(events.Add).Returns(Task.CompletedTask);
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
var adminConfig = new Mock<AdminConfigurationService>(
|
||||
Mock.Of<IConfigRepository>(), NullLogger<AdminConfigurationService>.Instance, cache)
|
||||
{ CallBase = false };
|
||||
adminConfig.Setup(a => a.GetConfigurationAsync()).ReturnsAsync(new AdminConfiguration { UpdatedBy = "test" });
|
||||
var opsService = new OpsEventService(opsRepo.Object, NullLogger<OpsEventService>.Instance, TestNotifications.InertOpsAlertDispatch(adminConfig.Object));
|
||||
var index = new StubManagedTenantProIndex(id => id == "t-managed" ? "11111111-1111-1111-1111-111111111111" : null);
|
||||
|
||||
var sut = new TrialExpirySweepFunction(Configs(configRepo.Object, index), opsService,
|
||||
NullLogger<TrialExpirySweepFunction>.Instance, new TestTimeProvider(Now));
|
||||
var result = await sut.RunCoreAsync(CancellationToken.None);
|
||||
|
||||
Assert.Equal(0, result.TrialsSeen);
|
||||
Assert.Equal(0, result.ExpiredEmitted);
|
||||
Assert.Empty(events);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExpiredWithinLookBack_EmitsTenantTrialExpired()
|
||||
{
|
||||
@@ -247,7 +278,7 @@ public class TrialExpirySweepFunctionTests
|
||||
var alertDispatch = TestNotifications.InertOpsAlertDispatch(adminConfig.Object);
|
||||
|
||||
var sut = new TrialExpirySweepFunction(
|
||||
configRepo.Object,
|
||||
Configs(configRepo.Object),
|
||||
new OpsEventService(opsRepo.Object, NullLogger<OpsEventService>.Instance, alertDispatch),
|
||||
NullLogger<TrialExpirySweepFunction>.Instance,
|
||||
new TestTimeProvider(Now));
|
||||
|
||||
@@ -376,6 +376,7 @@ public class TypedContractCompletionWireParityTests
|
||||
enableIntegrityBypassAnalyzer = true,
|
||||
unrestrictedMode = false,
|
||||
edition = "community",
|
||||
editionSource = "community",
|
||||
isTrial = false,
|
||||
trialExpiresUtc = (DateTime?)null, // not on trial → key vanishes
|
||||
trialAvailable = true,
|
||||
@@ -401,6 +402,7 @@ public class TypedContractCompletionWireParityTests
|
||||
EnableIntegrityBypassAnalyzer = true,
|
||||
UnrestrictedMode = false,
|
||||
Edition = "community",
|
||||
EditionSource = "community",
|
||||
IsTrial = false,
|
||||
TrialExpiresUtc = null,
|
||||
TrialAvailable = true,
|
||||
|
||||
@@ -71,14 +71,11 @@ public class TypedResponseGuardTests
|
||||
private static readonly Dictionary<string, int> IdentifierBaseline = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// JsonSerializer.Serialize(new { ... }) sites that are NOT responses. The single entry is
|
||||
/// an outgoing HTTP CLIENT request body (App Insights query POST) — not response debt.
|
||||
/// Everything else must be a typed DTO (error shapes are tolerated by the shape check).
|
||||
/// JsonSerializer.Serialize(new { ... }) sites that are NOT responses. EMPTY: the last entry (the
|
||||
/// App Insights query POST body) became a typed request record when the proxy learned sources.
|
||||
/// Everything must be a typed DTO (error shapes are tolerated by the shape check).
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, int> SerializeBaseline = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["Functions/Raw/AppInsightsQueryFunction.cs"] = 1,
|
||||
};
|
||||
private static readonly Dictionary<string, int> SerializeBaseline = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// A Build*/Compute*/*Payload/*Response method declared object hides its wire shape from
|
||||
|
||||
+3
@@ -746,6 +746,8 @@ namespace AutopilotMonitor.Functions.DataAccess.TableStorage
|
||||
{ "ProDowngradedUtc", config.ProDowngradedUtc },
|
||||
{ "MaxDelegatedTenantsOverride", config.MaxDelegatedTenantsOverride },
|
||||
{ "McpUsagePlanOverride", config.McpUsagePlanOverride },
|
||||
{ "PayingCustomer", config.PayingCustomer },
|
||||
// ManagedByProTenantId is a load-time projection (see TenantConfiguration) — deliberately no column.
|
||||
// SLA targets
|
||||
{ "SlaTargetSuccessRate", config.SlaTargetSuccessRate.HasValue ? (double)config.SlaTargetSuccessRate.Value : (double?)null },
|
||||
{ "SlaTargetMaxDurationMinutes", config.SlaTargetMaxDurationMinutes },
|
||||
@@ -863,6 +865,7 @@ namespace AutopilotMonitor.Functions.DataAccess.TableStorage
|
||||
ProDowngradedUtc = entity.GetDateTime("ProDowngradedUtc"),
|
||||
MaxDelegatedTenantsOverride = entity.GetInt32("MaxDelegatedTenantsOverride"),
|
||||
McpUsagePlanOverride = entity.GetString("McpUsagePlanOverride"),
|
||||
PayingCustomer = entity.GetBoolean("PayingCustomer") ?? false,
|
||||
// SLA targets
|
||||
SlaTargetSuccessRate = entity.GetDouble("SlaTargetSuccessRate") != null ? (decimal)entity.GetDouble("SlaTargetSuccessRate")! : null,
|
||||
SlaTargetMaxDurationMinutes = entity.GetInt32("SlaTargetMaxDurationMinutes"),
|
||||
|
||||
@@ -41,20 +41,47 @@ public static class ClaimsPrincipalExtensions
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user's UPN (User Principal Name) from token claims
|
||||
/// Falls back to preferred_username if upn is not available
|
||||
/// Supports both v1.0 and v2.0 token formats.
|
||||
/// The caller's principal key — the value every role table is keyed on (see
|
||||
/// <see cref="AutopilotMonitor.Shared.Constants.PrincipalKeys"/>). For a person it is the UPN
|
||||
/// (<c>upn</c>, falling back to <c>preferred_username</c>; v1.0 and v2.0 shapes); for an application
|
||||
/// principal (an app-only token, see <see cref="IsApplicationPrincipal"/>) it is
|
||||
/// <c>app:<client-id></c>, so a service flows through membership, whitelist, delegation, audit and
|
||||
/// throttling exactly like a person without any consumer having to know the difference.
|
||||
/// <para>
|
||||
/// Display / audit / row-key use only. Both claims are mutable and reusable across tenants, so no
|
||||
/// Display / audit / row-key use only. The UPN claims are mutable and reusable across tenants, so no
|
||||
/// cross-tenant authorization is keyed on this value alone — role resolution takes the full
|
||||
/// <see cref="Security.AdminIdentity"/> (upn + tid + oid) and verifies it against the identity binding.
|
||||
/// <see cref="Security.AdminIdentity"/> (key + tid + oid) and verifies it against the identity binding.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static string? GetUserPrincipalName(this ClaimsPrincipal principal)
|
||||
{
|
||||
return principal.FindFirst("upn")?.Value
|
||||
var upn = principal.FindFirst("upn")?.Value
|
||||
?? principal.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn")?.Value
|
||||
?? principal.FindFirst("preferred_username")?.Value;
|
||||
if (upn != null)
|
||||
return upn;
|
||||
|
||||
var applicationId = principal.IsApplicationPrincipal() ? principal.GetApplicationId() : null;
|
||||
return applicationId == null ? null : AutopilotMonitor.Shared.Constants.PrincipalKeys.ForApplication(applicationId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True for an app-only token (client-credentials, e.g. a workload with a federated credential): Entra
|
||||
/// stamps <c>idtyp = app</c> on access tokens for this API (optional claim on the app registration).
|
||||
/// A token without the claim is a user token by definition — the classification fails closed to
|
||||
/// "person", who then needs a UPN like everyone else.
|
||||
/// </summary>
|
||||
public static bool IsApplicationPrincipal(this ClaimsPrincipal principal)
|
||||
=> string.Equals(principal.FindFirst("idtyp")?.Value, "app", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// The calling application's Entra application (client) id: <c>appid</c> on v1.0 tokens, <c>azp</c> on
|
||||
/// v2.0 tokens. Null when the token names no client (never the case for a token Entra issued).
|
||||
/// </summary>
|
||||
public static string? GetApplicationId(this ClaimsPrincipal principal)
|
||||
{
|
||||
var id = principal.FindFirst("appid")?.Value ?? principal.FindFirst("azp")?.Value;
|
||||
return string.IsNullOrWhiteSpace(id) ? null : id.Trim().ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+2
@@ -195,6 +195,8 @@ public class DelegationSelfServiceFunction
|
||||
if (body == null || string.IsNullOrWhiteSpace(body.Upn))
|
||||
return await BadAsync(req, "upn is required");
|
||||
|
||||
// The member key as listed under Access Management — a UPN or a service principal's app:<client-id>
|
||||
// key; the service verifies it is a member of the caller's tenant, which is the only grant path.
|
||||
var result = await _svc.AssignAsync(ctx.TenantId, body.Upn, ctx.UserPrincipalName);
|
||||
if (!result.Ok)
|
||||
return await FailAsync(req, result.Failure!);
|
||||
|
||||
+47
-10
@@ -85,18 +85,32 @@ public class TenantAdminManagementFunction
|
||||
var requestCtx = context.GetRequestContext();
|
||||
var upn = requestCtx.UserPrincipalName;
|
||||
|
||||
// Parse request body
|
||||
// Parse request body. A member is either a person (upn) or an application (applicationId — the
|
||||
// Entra client id of a service principal in THIS tenant, stored under the app:<client-id> key).
|
||||
var body = await req.ReadFromJsonAsync<AddTenantAdminRequest>();
|
||||
if (body == null || string.IsNullOrWhiteSpace(body.Upn))
|
||||
var isApplication = !string.IsNullOrWhiteSpace(body?.ApplicationId);
|
||||
if (body == null || (string.IsNullOrWhiteSpace(body.Upn) && !isApplication))
|
||||
{
|
||||
var badRequestResponse = req.CreateResponse(HttpStatusCode.BadRequest);
|
||||
await badRequestResponse.WriteAsJsonAsync(new { error = "UPN is required" });
|
||||
await badRequestResponse.WriteAsJsonAsync(new { error = "UPN or applicationId is required" });
|
||||
return badRequestResponse;
|
||||
}
|
||||
if (isApplication && !Guid.TryParse(body.ApplicationId, out _))
|
||||
{
|
||||
var badAppResponse = req.CreateResponse(HttpStatusCode.BadRequest);
|
||||
await badAppResponse.WriteAsJsonAsync(new { error = "applicationId must be the application's (client) id GUID" });
|
||||
return badAppResponse;
|
||||
}
|
||||
var memberKey = isApplication
|
||||
? AutopilotMonitor.Shared.Constants.PrincipalKeys.ForApplication(body.ApplicationId!)
|
||||
: body.Upn;
|
||||
|
||||
// Determine role (default to Admin for backward compat), then validate against the
|
||||
// allow-list so arbitrary strings never reach storage.
|
||||
var requestedRole = !string.IsNullOrWhiteSpace(body.Role) ? body.Role : AutopilotMonitor.Shared.Constants.TenantRoles.Admin;
|
||||
// Determine role (default to Admin for backward compat, Viewer for an application), then validate
|
||||
// against the allow-list so arbitrary strings never reach storage. An application is read-only:
|
||||
// Viewer is the only role it may hold (the resolver caps it there regardless of the row).
|
||||
var requestedRole = !string.IsNullOrWhiteSpace(body.Role)
|
||||
? body.Role
|
||||
: isApplication ? AutopilotMonitor.Shared.Constants.TenantRoles.Viewer : AutopilotMonitor.Shared.Constants.TenantRoles.Admin;
|
||||
var role = TryCanonicalizeRole(requestedRole);
|
||||
if (role == null)
|
||||
{
|
||||
@@ -104,23 +118,31 @@ public class TenantAdminManagementFunction
|
||||
await badRoleResponse.WriteAsJsonAsync(new { error = $"Invalid role '{body.Role}'. Valid roles: Admin, Operator, Viewer." });
|
||||
return badRoleResponse;
|
||||
}
|
||||
if (isApplication && role != AutopilotMonitor.Shared.Constants.TenantRoles.Viewer)
|
||||
{
|
||||
var badRoleResponse = req.CreateResponse(HttpStatusCode.BadRequest);
|
||||
await badRoleResponse.WriteAsJsonAsync(new { error = ApplicationRoleError });
|
||||
return badRoleResponse;
|
||||
}
|
||||
var canManageBootstrapTokens = !isApplication && body.CanManageBootstrapTokens;
|
||||
|
||||
var newAdmin = await _tenantAdminsService.AddTenantMemberAsync(requestCtx.TargetTenantId, body.Upn, upn!, role, body.CanManageBootstrapTokens);
|
||||
var newAdmin = await _tenantAdminsService.AddTenantMemberAsync(requestCtx.TargetTenantId, memberKey, upn!, role, canManageBootstrapTokens);
|
||||
|
||||
await _maintenanceRepo.LogAuditEntryAsync(
|
||||
requestCtx.TargetTenantId,
|
||||
"CREATE",
|
||||
"TenantAdmin",
|
||||
body.Upn,
|
||||
memberKey,
|
||||
upn!,
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
{ "Role", role },
|
||||
{ "CanManageBootstrapTokens", body.CanManageBootstrapTokens.ToString() }
|
||||
{ "CanManageBootstrapTokens", canManageBootstrapTokens.ToString() },
|
||||
{ "PrincipalType", isApplication ? "Application" : "User" }
|
||||
}
|
||||
);
|
||||
|
||||
_logger.LogInformation($"Tenant member added: {body.Upn} with role {role} to tenant {requestCtx.TargetTenantId} by {upn}");
|
||||
_logger.LogInformation($"Tenant member added: {memberKey} with role {role} to tenant {requestCtx.TargetTenantId} by {upn}");
|
||||
|
||||
var response = req.CreateResponse(HttpStatusCode.Created);
|
||||
await response.WriteAsJsonAsync(new TenantAdminCreatedResponse { Admin = newAdmin });
|
||||
@@ -288,6 +310,12 @@ public class TenantAdminManagementFunction
|
||||
await badRoleResponse.WriteAsJsonAsync(new { error = $"Invalid role '{body.Role}'. Valid roles: Admin, Operator, Viewer." });
|
||||
return badRoleResponse;
|
||||
}
|
||||
if (AutopilotMonitor.Shared.Constants.PrincipalKeys.IsApplication(adminUpn) && role != AutopilotMonitor.Shared.Constants.TenantRoles.Viewer)
|
||||
{
|
||||
var badRoleResponse = req.CreateResponse(HttpStatusCode.BadRequest);
|
||||
await badRoleResponse.WriteAsJsonAsync(new { error = ApplicationRoleError });
|
||||
return badRoleResponse;
|
||||
}
|
||||
|
||||
// Prevent demoting yourself if you're the last Admin
|
||||
if (adminUpn.Equals(upn, StringComparison.OrdinalIgnoreCase) && role != AutopilotMonitor.Shared.Constants.TenantRoles.Admin)
|
||||
@@ -343,6 +371,9 @@ public class TenantAdminManagementFunction
|
||||
/// matching case-insensitively and canonicalizing to the exact constant casing so only
|
||||
/// canonical values are ever persisted. Returns null for anything not in the allow-list.
|
||||
/// </summary>
|
||||
internal const string ApplicationRoleError =
|
||||
"A service principal can only hold the Viewer role (read-only). Grant Operator or Admin to a person instead.";
|
||||
|
||||
internal static string? TryCanonicalizeRole(string role)
|
||||
{
|
||||
string[] validRoles =
|
||||
@@ -357,7 +388,13 @@ public class TenantAdminManagementFunction
|
||||
|
||||
public class AddTenantAdminRequest
|
||||
{
|
||||
/// <summary>The person's UPN. Leave empty when adding an application (<see cref="ApplicationId"/>).</summary>
|
||||
public string Upn { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// The Entra application (client) id of a service principal in this tenant. Stored under the
|
||||
/// <c>app:<client-id></c> member key; the role is fixed to Viewer.
|
||||
/// </summary>
|
||||
public string? ApplicationId { get; set; }
|
||||
public string? Role { get; set; }
|
||||
public bool CanManageBootstrapTokens { get; set; }
|
||||
}
|
||||
|
||||
+19
-1
@@ -34,6 +34,7 @@ public class TenantGroupManagementFunction
|
||||
private readonly IMaintenanceRepository _maintenanceRepo;
|
||||
private readonly ISignalRNotificationService _signalRService;
|
||||
private readonly DelegatedSlotService _slots;
|
||||
private readonly ProConferralService _proConferral;
|
||||
|
||||
private const string AuditEntity = "DelegatedGroupAccess";
|
||||
|
||||
@@ -43,7 +44,8 @@ public class TenantGroupManagementFunction
|
||||
AdminIdentityResolver identityResolver,
|
||||
IMaintenanceRepository maintenanceRepo,
|
||||
ISignalRNotificationService signalRService,
|
||||
DelegatedSlotService slots)
|
||||
DelegatedSlotService slots,
|
||||
ProConferralService proConferral)
|
||||
{
|
||||
_logger = logger;
|
||||
_delegatedAdminService = delegatedAdminService;
|
||||
@@ -51,6 +53,14 @@ public class TenantGroupManagementFunction
|
||||
_maintenanceRepo = maintenanceRepo;
|
||||
_signalRService = signalRService;
|
||||
_slots = slots;
|
||||
_proConferral = proConferral;
|
||||
}
|
||||
|
||||
/// <summary>The managing tenant that owns <paramref name="groupId"/> (self-service group), or null for operator groups / unknown groups.</summary>
|
||||
private async Task<string?> OwnerOfAsync(string groupId)
|
||||
{
|
||||
var group = await _delegatedAdminService.GetGroupAsync(groupId);
|
||||
return string.IsNullOrWhiteSpace(group?.OwnerTenantId) ? null : group!.OwnerTenantId;
|
||||
}
|
||||
|
||||
/// <summary>GET /api/global/tenant-groups — list every group with tenants + assignee count. GlobalReadOrAdmin.</summary>
|
||||
@@ -223,6 +233,9 @@ public class TenantGroupManagementFunction
|
||||
|
||||
foreach (var home in await _slots.ResolveHomeTenantsAsync(assignees.Select(a => a.Upn)))
|
||||
_slots.Invalidate(home);
|
||||
// An OWNED (self-service) group confers Pro on its members — drop the projection caches now.
|
||||
if (await OwnerOfAsync(groupId) != null)
|
||||
await _proConferral.NotifyDelegationChangedAsync(tenantId);
|
||||
|
||||
// Every current assignee just gained access to this tenant — audit under that tenant per assignee.
|
||||
foreach (var assignee in assignees)
|
||||
@@ -251,12 +264,17 @@ public class TenantGroupManagementFunction
|
||||
|
||||
// Snapshot assignees BEFORE the removal so we can audit each one's lost access under this tenant.
|
||||
var assignees = await _delegatedAdminService.GetGroupAssigneesAsync(groupId);
|
||||
var owner = await OwnerOfAsync(groupId);
|
||||
// The service returns false when the group doesn't exist or the tenant isn't a member — so a typo
|
||||
// can't 200 and write false "access removed" audit rows. Only audit after a real removal.
|
||||
var removed = await _delegatedAdminService.RemoveTenantFromGroupAsync(groupId, normalizedTenantId);
|
||||
if (!removed)
|
||||
return await NotFound(req);
|
||||
|
||||
// Leaving an OWNED (self-service) group ends conferred Pro — stamp the tenant's retention grace anchor.
|
||||
if (owner != null)
|
||||
await _proConferral.RecordLossAsync(normalizedTenantId, owner, "tenant-removed-from-group");
|
||||
|
||||
foreach (var assignee in assignees)
|
||||
{
|
||||
await _maintenanceRepo.LogAuditEntryAsync(
|
||||
|
||||
+8
-6
@@ -72,10 +72,11 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
/// </summary>
|
||||
internal static TenantFeatureFlagsResponse BuildPayload(TenantConfiguration config, DateTime nowUtc, bool appHomingFunnelActive = false)
|
||||
{
|
||||
var edition = FeatureEntitlementCatalog.ResolveEdition(config.PlanTier, config.TrialExpiresUtc, nowUtc);
|
||||
var entitlements = FeatureEntitlementCatalog.Get(edition);
|
||||
var isTrial = edition == TenantEdition.Pro &&
|
||||
!FeatureEntitlementCatalog.IsPermanentProTier(config.PlanTier);
|
||||
// Edition + source in one resolution: Pro from the plan, from a trial, or conferred by the
|
||||
// managing tenant ("msp" — shown as "Pro (MSP)", entitlements without the delegation right).
|
||||
var resolution = FeatureEntitlementCatalog.Resolve(config, nowUtc);
|
||||
var entitlements = FeatureEntitlementCatalog.Get(resolution);
|
||||
var isTrial = resolution.IsTrial;
|
||||
|
||||
return new TenantFeatureFlagsResponse
|
||||
{
|
||||
@@ -106,10 +107,11 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
UnrestrictedMode = TenantEntitlementService.IsUnrestrictedModeActive(config, nowUtc),
|
||||
// Edition/entitlement surface (read-time resolution — non-sensitive by design):
|
||||
// drives the EditionBadge, trial CTA and retention hint in the web UI.
|
||||
Edition = edition.ToString().ToLowerInvariant(),
|
||||
Edition = resolution.EditionName,
|
||||
EditionSource = resolution.SourceName,
|
||||
IsTrial = isTrial,
|
||||
TrialExpiresUtc = isTrial ? config.TrialExpiresUtc : null,
|
||||
TrialAvailable = !config.TrialConsumed && edition == TenantEdition.Community,
|
||||
TrialAvailable = !config.TrialConsumed && !resolution.IsPro,
|
||||
// Pro-requires-contact surface: drives the trial CTA gate and the dashboard
|
||||
// "set a contact address" banner for Pro tenants. Boolean only — the address
|
||||
// itself stays in the admin-gated full config response.
|
||||
|
||||
@@ -28,6 +28,7 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
private readonly AdminConfigurationService _adminConfigService;
|
||||
private readonly IMaintenanceRepository _maintenanceRepo;
|
||||
private readonly OpsEventService _opsEvents;
|
||||
private readonly ProConferralService _proConferral;
|
||||
private readonly TimeProvider _time;
|
||||
|
||||
public PlanManagementFunction(
|
||||
@@ -35,8 +36,9 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
TenantConfigurationService configService,
|
||||
AdminConfigurationService adminConfigService,
|
||||
IMaintenanceRepository maintenanceRepo,
|
||||
OpsEventService opsEvents)
|
||||
: this(logger, configService, adminConfigService, maintenanceRepo, opsEvents, TimeProvider.System)
|
||||
OpsEventService opsEvents,
|
||||
ProConferralService proConferral)
|
||||
: this(logger, configService, adminConfigService, maintenanceRepo, opsEvents, proConferral, TimeProvider.System)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -47,6 +49,7 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
AdminConfigurationService adminConfigService,
|
||||
IMaintenanceRepository maintenanceRepo,
|
||||
OpsEventService opsEvents,
|
||||
ProConferralService proConferral,
|
||||
TimeProvider time)
|
||||
{
|
||||
_logger = logger;
|
||||
@@ -54,13 +57,17 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
_adminConfigService = adminConfigService;
|
||||
_maintenanceRepo = maintenanceRepo;
|
||||
_opsEvents = opsEvents;
|
||||
_proConferral = proConferral;
|
||||
_time = time;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PATCH /api/config/{tenantId}/plan — GlobalAdminOnly (catalog-enforced).
|
||||
/// Body: { "planTier"?: "community"|"pro", "trialExpiresUtc"?: ISO-8601 | null, "maxDelegatedTenants"?: int | null,
|
||||
/// "mcpUsagePlan"?: string | null }.
|
||||
/// "mcpUsagePlan"?: string | null, "payingCustomer"?: bool }.
|
||||
/// payingCustomer is sales bookkeeping only (no entitlement effect). A permanent-Pro tenant that drops to
|
||||
/// Community here takes conferred Pro away from every tenant it manages — their retention grace anchor
|
||||
/// is stamped in the same request (ProConferralService).
|
||||
/// maxDelegatedTenants sets the delegated (MSP) slot override (null clears it — the plan entitlement applies).
|
||||
/// mcpUsagePlan sets the tenant-wide MCP usage-plan override — the name of a SectionUsagePlans plan, validated
|
||||
/// against the current definitions (400 for an unknown name, so a typo can never silently drop the tenant
|
||||
@@ -99,6 +106,8 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
int? newMaxDelegatedTenants = null;
|
||||
bool mcpPlanProvided = false;
|
||||
string? newMcpUsagePlan = null;
|
||||
bool payingProvided = false;
|
||||
bool newPayingCustomer = false;
|
||||
|
||||
using (doc)
|
||||
{
|
||||
@@ -171,10 +180,18 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
return await BadRequestAsync(req, "mcpUsagePlan must be a plan name or null");
|
||||
}
|
||||
}
|
||||
|
||||
if (doc.RootElement.TryGetProperty("payingCustomer", out var payingProp))
|
||||
{
|
||||
if (payingProp.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
|
||||
return await BadRequestAsync(req, "payingCustomer must be a boolean");
|
||||
payingProvided = true;
|
||||
newPayingCustomer = payingProp.GetBoolean();
|
||||
}
|
||||
}
|
||||
|
||||
if (newPlanTier == null && !trialProvided && !slotsProvided && !mcpPlanProvided)
|
||||
return await BadRequestAsync(req, "Provide planTier, trialExpiresUtc, maxDelegatedTenants and/or mcpUsagePlan");
|
||||
if (newPlanTier == null && !trialProvided && !slotsProvided && !mcpPlanProvided && !payingProvided)
|
||||
return await BadRequestAsync(req, "Provide planTier, trialExpiresUtc, maxDelegatedTenants, mcpUsagePlan and/or payingCustomer");
|
||||
|
||||
if (newMcpUsagePlan != null)
|
||||
{
|
||||
@@ -200,10 +217,15 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
var nowUtc = _time.GetUtcNow().UtcDateTime;
|
||||
var changes = new Dictionary<string, string>();
|
||||
|
||||
// Conferred Pro follows the PERMANENT tier of the managing tenant (a trial confers nothing):
|
||||
// remember the standing before the mutation so a permanent-Pro → non-permanent drop can
|
||||
// stamp the managed tenants' grace anchors below.
|
||||
var wasPermanentPro = FeatureEntitlementCatalog.IsPermanentProTier(config.PlanTier);
|
||||
var (editionBefore, editionAfter) =
|
||||
ApplyPlanChanges(config, newPlanTier, trialProvided, newTrialExpiresUtc, caller, nowUtc, changes);
|
||||
ApplyDelegatedSlotChange(config, slotsProvided, newMaxDelegatedTenants, changes);
|
||||
ApplyMcpUsagePlanChange(config, mcpPlanProvided, newMcpUsagePlan, changes);
|
||||
ApplyPayingCustomerChange(config, payingProvided, newPayingCustomer, changes);
|
||||
|
||||
if (changes.Count > 0)
|
||||
{
|
||||
@@ -231,6 +253,15 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
config.DataRetentionDays);
|
||||
}
|
||||
|
||||
if (wasPermanentPro && !FeatureEntitlementCatalog.IsPermanentProTier(config.PlanTier))
|
||||
{
|
||||
// After the save, so the managed tenants' index rebuild already sees the new tier.
|
||||
var stamped = await _proConferral.RecordLossForOwnedGroupAsync(
|
||||
requestCtx.TargetTenantId, "manager-lost-permanent-pro");
|
||||
if (stamped > 0)
|
||||
changes["ConferredProEndedForManagedTenants"] = stamped.ToString();
|
||||
}
|
||||
|
||||
// The mirror image of the downgrade event: a GA granting or extending a trial
|
||||
// is the same conversion moment as the self-service start, and sales/support
|
||||
// channels bind to one event type, not two. Keyed off the recorded change so
|
||||
@@ -250,6 +281,7 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
}
|
||||
}
|
||||
|
||||
var resolution = FeatureEntitlementCatalog.Resolve(config, nowUtc);
|
||||
var response = req.CreateResponse(HttpStatusCode.OK);
|
||||
await response.WriteAsJsonAsync(new SetTenantPlanTierResponse
|
||||
{
|
||||
@@ -257,12 +289,14 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
PlanTier = config.PlanTier,
|
||||
TrialExpiresUtc = config.TrialExpiresUtc,
|
||||
TrialConsumed = config.TrialConsumed,
|
||||
EffectiveEdition = editionAfter.ToString().ToLowerInvariant(),
|
||||
EffectiveEdition = resolution.EditionName,
|
||||
EditionSource = resolution.SourceName,
|
||||
RetentionGraceEndsUtc = TenantEntitlementService.GetRetentionGraceEndUtc(config, nowUtc),
|
||||
MaxDelegatedTenants = TenantEntitlementService.GetMaxDelegatedTenants(config, nowUtc),
|
||||
MaxDelegatedTenantsOverride = config.MaxDelegatedTenantsOverride,
|
||||
McpUsagePlan = TenantEntitlementService.GetMcpUsagePlanName(config, nowUtc),
|
||||
McpUsagePlanOverride = config.McpUsagePlanOverride,
|
||||
PayingCustomer = config.PayingCustomer,
|
||||
});
|
||||
return response;
|
||||
}
|
||||
@@ -295,7 +329,7 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
DateTime nowUtc,
|
||||
Dictionary<string, string> changes)
|
||||
{
|
||||
var before = FeatureEntitlementCatalog.ResolveEdition(config.PlanTier, config.TrialExpiresUtc, nowUtc);
|
||||
var before = FeatureEntitlementCatalog.ResolveEdition(config, nowUtc);
|
||||
|
||||
if (newPlanTier != null && !string.Equals(config.PlanTier, newPlanTier, StringComparison.Ordinal))
|
||||
{
|
||||
@@ -314,7 +348,7 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
}
|
||||
}
|
||||
|
||||
var after = FeatureEntitlementCatalog.ResolveEdition(config.PlanTier, config.TrialExpiresUtc, nowUtc);
|
||||
var after = FeatureEntitlementCatalog.ResolveEdition(config, nowUtc);
|
||||
|
||||
if (before == TenantEdition.Pro && after == TenantEdition.Community)
|
||||
{
|
||||
@@ -361,6 +395,19 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
config.McpUsagePlanOverride = normalized;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pure mutation core for the sales bookkeeping flag: records and applies the change only when a value
|
||||
/// was provided AND differs. No entitlement effect — see <see cref="TenantConfiguration.PayingCustomer"/>.
|
||||
/// </summary>
|
||||
internal static void ApplyPayingCustomerChange(
|
||||
TenantConfiguration config, bool provided, bool payingCustomer, Dictionary<string, string> changes)
|
||||
{
|
||||
if (!provided || config.PayingCustomer == payingCustomer)
|
||||
return;
|
||||
changes["PayingCustomer"] = $"{config.PayingCustomer} -> {payingCustomer}";
|
||||
config.PayingCustomer = payingCustomer;
|
||||
}
|
||||
|
||||
/// <summary>Pure: whether <paramref name="planName"/> (normalized) names a SectionUsagePlans definition.</summary>
|
||||
internal static bool IsKnownUsagePlan(string planName, IEnumerable<PlanTierDefinition> definitions)
|
||||
=> definitions.Any(d => string.Equals(TenantEntitlementService.NormalizePlanName(d.Name), planName, StringComparison.OrdinalIgnoreCase));
|
||||
@@ -391,7 +438,8 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
"This tenant has already used its one self-service Pro trial. Contact support to extend.");
|
||||
}
|
||||
|
||||
if (FeatureEntitlementCatalog.ResolveEdition(config.PlanTier, config.TrialExpiresUtc, nowUtc) == TenantEdition.Pro)
|
||||
// Effective edition, conferred Pro included: a tenant managed by a Pro tenant needs no trial.
|
||||
if (FeatureEntitlementCatalog.ResolveEdition(config, nowUtc) == TenantEdition.Pro)
|
||||
{
|
||||
return ("AlreadyPro", "This tenant is already on the Pro plan.");
|
||||
}
|
||||
|
||||
+7
-41
@@ -1,6 +1,5 @@
|
||||
using System.Net;
|
||||
using System.Web;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Functions.Services.Diagnostics;
|
||||
using AutopilotMonitor.Shared.Diagnostics;
|
||||
@@ -20,16 +19,11 @@ namespace AutopilotMonitor.Functions.Functions.Diagnostics
|
||||
/// <para>
|
||||
/// Replay is bounded by the 10-min ticket TTL, the admin size cap, and the fact that the ticket
|
||||
/// only ever points at the minting caller's own authorized blob; HMAC forgery is infeasible. On top
|
||||
/// of that the route carries a per-client-IP limit as defense in depth — it is unauthenticated and
|
||||
/// streams whole blobs, so a valid ticket replayed in a loop would otherwise be unbounded egress.
|
||||
/// of that the route carries a per-client-IP limit as defense in depth (<see cref="TicketDownloadPrelude"/>).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public class DiagnosticsTicketDownloadFunction
|
||||
{
|
||||
// Bounds replay of a still-valid ticket. A real client downloads a package once; the ceiling
|
||||
// only has to stay clear of a legitimate retry-after-timeout.
|
||||
private const int MaxRequestsPerMinutePerIp = 30;
|
||||
|
||||
private readonly ILogger<DiagnosticsTicketDownloadFunction> _logger;
|
||||
private readonly DiagnosticsBlobStreamer _streamer;
|
||||
private readonly RateLimitService _rateLimitService;
|
||||
@@ -50,41 +44,13 @@ namespace AutopilotMonitor.Functions.Functions.Diagnostics
|
||||
{
|
||||
try
|
||||
{
|
||||
// Rightmost X-Forwarded-For hop only — leftmost entries are caller-controlled.
|
||||
var clientIp = ClientIpExtractor.GetTrustedClientIp(req);
|
||||
var rateLimitResult = _rateLimitService.CheckRateLimit(
|
||||
$"diag_ticket_download_{clientIp}", MaxRequestsPerMinutePerIp);
|
||||
|
||||
if (!rateLimitResult.IsAllowed)
|
||||
{
|
||||
_logger.LogWarning("DiagnosticsTicketDownload rate limit exceeded for IP {ClientIp} ({Count} requests)",
|
||||
clientIp, rateLimitResult.RequestsInWindow);
|
||||
|
||||
var tooMany = req.CreateResponse(HttpStatusCode.TooManyRequests);
|
||||
if (rateLimitResult.RetryAfter.HasValue)
|
||||
tooMany.Headers.Add("Retry-After", ((int)rateLimitResult.RetryAfter.Value.TotalSeconds).ToString());
|
||||
await tooMany.WriteAsJsonAsync(new { success = false, message = "Rate limit exceeded." });
|
||||
return tooMany;
|
||||
}
|
||||
|
||||
var ticket = HttpUtility.ParseQueryString(req.Url.Query)["t"];
|
||||
if (string.IsNullOrEmpty(ticket))
|
||||
{
|
||||
var bad = req.CreateResponse(HttpStatusCode.BadRequest);
|
||||
await bad.WriteAsJsonAsync(new { success = false, message = "Missing download ticket." });
|
||||
return bad;
|
||||
}
|
||||
|
||||
if (!DiagnosticsDownloadTicket.TryDecode(ticket, out var tenantId, out var blobName, out _, out var reason))
|
||||
{
|
||||
_logger.LogWarning("DiagnosticsTicketDownload: rejecting ticket ({Reason})", reason);
|
||||
var unauth = req.CreateResponse(HttpStatusCode.Unauthorized);
|
||||
await unauth.WriteAsJsonAsync(new { success = false, message = "Invalid or expired download ticket." });
|
||||
return unauth;
|
||||
}
|
||||
var (reject, ticket) = await TicketDownloadPrelude.RunAsync(
|
||||
req, _rateLimitService, _logger, "diag_ticket_download", DiagnosticsDownloadTicket.DiagnosticsPurpose);
|
||||
if (reject != null)
|
||||
return reject;
|
||||
|
||||
return await _streamer.ProxyDownloadAsync(
|
||||
req, tenantId, blobName,
|
||||
req, ticket.TenantId, ticket.BlobName,
|
||||
new Dictionary<string, string> { ["Source"] = "mcp-ticket" });
|
||||
}
|
||||
catch (ArgumentException)
|
||||
|
||||
@@ -614,7 +614,7 @@ public class AuthFunction
|
||||
// included in Pro, Unrestricted Mode requires Pro + the GA on-request gate.
|
||||
BootstrapTokenEnabled = TenantEntitlementService.IsBootstrapEnabled(tenantConfig, DateTime.UtcNow),
|
||||
UnrestrictedModeEnabled =
|
||||
FeatureEntitlementCatalog.Get(TenantEntitlementService.ResolveEdition(tenantConfig, DateTime.UtcNow)).UnrestrictedModeAvailable
|
||||
FeatureEntitlementCatalog.Get(TenantEntitlementService.Resolve(tenantConfig, DateTime.UtcNow)).UnrestrictedModeAvailable
|
||||
&& tenantConfig.UnrestrictedModeEnabled
|
||||
}, needsAutoAdmin);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using AutopilotMonitor.Functions.Extensions;
|
||||
using AutopilotMonitor.Functions.Functions.Admin;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Infrastructure;
|
||||
@@ -20,15 +23,24 @@ public class McpUserFunction
|
||||
private readonly ILogger<McpUserFunction> _logger;
|
||||
private readonly McpUserService _mcpUserService;
|
||||
private readonly AdminIdentityResolver _identityResolver;
|
||||
private readonly IMetricsRepository _metricsRepo;
|
||||
private readonly OpsEventService _opsEvents;
|
||||
private readonly IMemoryCache _cache;
|
||||
|
||||
public McpUserFunction(
|
||||
ILogger<McpUserFunction> logger,
|
||||
McpUserService mcpUserService,
|
||||
AdminIdentityResolver identityResolver)
|
||||
AdminIdentityResolver identityResolver,
|
||||
IMetricsRepository metricsRepo,
|
||||
OpsEventService opsEvents,
|
||||
IMemoryCache cache)
|
||||
{
|
||||
_logger = logger;
|
||||
_mcpUserService = mcpUserService;
|
||||
_identityResolver = identityResolver;
|
||||
_metricsRepo = metricsRepo;
|
||||
_opsEvents = opsEvents;
|
||||
_cache = cache;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -67,20 +79,33 @@ public class McpUserFunction
|
||||
var currentUpn = principal?.GetUserPrincipalName();
|
||||
|
||||
var body = await req.ReadFromJsonAsync<AddMcpUserRequest>();
|
||||
if (body == null || string.IsNullOrWhiteSpace(body.Upn))
|
||||
var isApplication = !string.IsNullOrWhiteSpace(body?.ApplicationId);
|
||||
if (body == null || (string.IsNullOrWhiteSpace(body.Upn) && !isApplication))
|
||||
{
|
||||
var badResponse = req.CreateResponse(HttpStatusCode.BadRequest);
|
||||
await badResponse.WriteAsJsonAsync(new { error = "UPN is required" });
|
||||
await badResponse.WriteAsJsonAsync(new { error = "UPN or applicationId is required" });
|
||||
return badResponse;
|
||||
}
|
||||
var bindingError = IdentityBindingRequest.ValidateOptional(body.HomeTenantId, body.ObjectId);
|
||||
if (isApplication && !Guid.TryParse(body.ApplicationId, out _))
|
||||
{
|
||||
var badResponse = req.CreateResponse(HttpStatusCode.BadRequest);
|
||||
await badResponse.WriteAsJsonAsync(new { error = "applicationId must be the application's (client) id GUID" });
|
||||
return badResponse;
|
||||
}
|
||||
// An application has no sign-in history and no UPN domain to resolve a home tenant from: the tenant
|
||||
// its service principal lives in must be named. The object id (that tenant's SP object id) is pinned
|
||||
// on the first call, exactly like a person's.
|
||||
var bindingError = isApplication
|
||||
? IdentityBindingRequest.Validate(body.HomeTenantId, body.ObjectId)
|
||||
: IdentityBindingRequest.ValidateOptional(body.HomeTenantId, body.ObjectId);
|
||||
if (bindingError != null)
|
||||
{
|
||||
var badResponse = req.CreateResponse(HttpStatusCode.BadRequest);
|
||||
await badResponse.WriteAsJsonAsync(new { error = bindingError });
|
||||
return badResponse;
|
||||
}
|
||||
var identity = await IdentityBindingRequest.ResolveForGrantAsync(_identityResolver, body.Upn, body.HomeTenantId, body.ObjectId);
|
||||
var principalKey = isApplication ? Constants.PrincipalKeys.ForApplication(body.ApplicationId!) : body.Upn;
|
||||
var identity = await IdentityBindingRequest.ResolveForGrantAsync(_identityResolver, principalKey, body.HomeTenantId, body.ObjectId);
|
||||
if (identity == null)
|
||||
{
|
||||
var unresolved = req.CreateResponse(HttpStatusCode.UnprocessableEntity);
|
||||
@@ -91,7 +116,7 @@ public class McpUserFunction
|
||||
McpUserEntry user;
|
||||
try
|
||||
{
|
||||
user = await _mcpUserService.AddMcpUserAsync(body.Upn, currentUpn!, identity.Value.TenantId, identity.Value.ObjectId);
|
||||
user = await _mcpUserService.AddMcpUserAsync(principalKey, currentUpn!, identity.Value.TenantId, identity.Value.ObjectId);
|
||||
}
|
||||
catch (IdentityBindingConflictException ex)
|
||||
{
|
||||
@@ -105,6 +130,43 @@ public class McpUserFunction
|
||||
return response;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A service principal never signs in to the portal, so the MCP front door is where its presence is
|
||||
/// recorded: the sign-in history row (its "last seen", and what the per-user usage view keys the
|
||||
/// display on) plus, when the key has no history yet, the once-only
|
||||
/// <see cref="OpsEventTypes.McpServicePrincipalFirstSeen"/> so new automation is noticed the moment it
|
||||
/// starts. Fire-and-forget: observation must never delay or fail the access check.
|
||||
/// </summary>
|
||||
private void ObserveApplicationSession(ClaimsPrincipal principal, McpAccessCheckResult result)
|
||||
{
|
||||
var tenantId = principal.GetTenantId() ?? string.Empty;
|
||||
var objectId = principal.GetObjectId() ?? string.Empty;
|
||||
var applicationId = principal.GetApplicationId() ?? string.Empty;
|
||||
var principalKey = result.Upn;
|
||||
// The history read is a filtered scan meant for grant time; one per application per instance is
|
||||
// enough — after that the memory cache says "seen" and only the cheap login upsert remains.
|
||||
var seenKey = $"mcp-app-seen:{principalKey}";
|
||||
var alreadySeen = _cache.TryGetValue(seenKey, out _);
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!alreadySeen)
|
||||
{
|
||||
var history = await _metricsRepo.GetSignInIdentitiesByUpnAsync(principalKey);
|
||||
if (history.Count == 0)
|
||||
await _opsEvents.RecordMcpServicePrincipalFirstSeenAsync(tenantId, principalKey, applicationId, objectId, result.AccessGrant);
|
||||
_cache.Set(seenKey, true, TimeSpan.FromHours(24));
|
||||
}
|
||||
await _metricsRepo.RecordUserLoginAsync(tenantId, principalKey, displayName: $"Service principal {applicationId}", objectId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "[McpAccess] Failed to record the application session for {PrincipalKey}", principalKey);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DELETE /api/admin/mcp-users/{upn}
|
||||
/// Removes a user from the MCP whitelist. GlobalAdminOnly.
|
||||
@@ -204,6 +266,9 @@ public class McpUserFunction
|
||||
var result = await _mcpUserService.IsAllowedAsync(
|
||||
upn, principal?.GetTenantId(), principal?.GetObjectId(), principal?.GetAppRoles());
|
||||
|
||||
if (result.IsAllowed && principal != null && principal.IsApplicationPrincipal())
|
||||
ObserveApplicationSession(principal, result);
|
||||
|
||||
var response = req.CreateResponse(result.IsAllowed ? HttpStatusCode.OK : HttpStatusCode.Forbidden);
|
||||
// Only surface platform-role flags when the caller actually has one (null ⇒ key omitted).
|
||||
// A normal tenant user gets neither field: the MCP access-guard reads `globalRole` to decide
|
||||
@@ -228,7 +293,13 @@ public class McpUserFunction
|
||||
|
||||
public class AddMcpUserRequest
|
||||
{
|
||||
/// <summary>The person's UPN. Leave empty when adding an application (<see cref="ApplicationId"/>).</summary>
|
||||
public string Upn { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// The Entra application (client) id of a service principal; stored under the <c>app:<client-id></c>
|
||||
/// key. <see cref="HomeTenantId"/> is then required (no sign-in history to resolve it from).
|
||||
/// </summary>
|
||||
public string? ApplicationId { get; set; }
|
||||
/// <summary>The grantee's HOME Entra tenant id (optional override) — resolved from sign-in history / UPN domain when omitted.</summary>
|
||||
public string? HomeTenantId { get; set; }
|
||||
/// <summary>The grantee's Entra object id (optional) — taken from sign-in history, else pinned on their first sign-in.</summary>
|
||||
|
||||
+12
-8
@@ -42,27 +42,29 @@ public class TrialExpirySweepFunction
|
||||
/// <summary>03:30 UTC daily — off the busy maintenance window, after ScriptNameCacheCleanup (03:00).</summary>
|
||||
private const string Cron = "0 30 3 * * *";
|
||||
|
||||
private readonly IConfigRepository _configRepo;
|
||||
// The configuration SERVICE, not the repository: the sweep judges effective editions, and only the
|
||||
// service projects ManagedByProTenantId (a managed tenant's expired trial changes nothing).
|
||||
private readonly TenantConfigurationService _configs;
|
||||
private readonly OpsEventService _opsEvents;
|
||||
private readonly ILogger<TrialExpirySweepFunction> _logger;
|
||||
private readonly TimeProvider _time;
|
||||
|
||||
public TrialExpirySweepFunction(
|
||||
IConfigRepository configRepo,
|
||||
TenantConfigurationService configs,
|
||||
OpsEventService opsEvents,
|
||||
ILogger<TrialExpirySweepFunction> logger)
|
||||
: this(configRepo, opsEvents, logger, TimeProvider.System)
|
||||
: this(configs, opsEvents, logger, TimeProvider.System)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Test seam — inject a fake <see cref="TimeProvider"/> for deterministic window math.</summary>
|
||||
internal TrialExpirySweepFunction(
|
||||
IConfigRepository configRepo,
|
||||
TenantConfigurationService configs,
|
||||
OpsEventService opsEvents,
|
||||
ILogger<TrialExpirySweepFunction> logger,
|
||||
TimeProvider time)
|
||||
{
|
||||
_configRepo = configRepo;
|
||||
_configs = configs;
|
||||
_opsEvents = opsEvents;
|
||||
_logger = logger;
|
||||
_time = time;
|
||||
@@ -83,7 +85,7 @@ public class TrialExpirySweepFunction
|
||||
System.Collections.Generic.List<AutopilotMonitor.Shared.Models.TenantConfiguration> configs;
|
||||
try
|
||||
{
|
||||
configs = await _configRepo.GetAllTenantConfigurationsAsync().ConfigureAwait(false);
|
||||
configs = await _configs.GetAllConfigurationsAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -114,8 +116,10 @@ public class TrialExpirySweepFunction
|
||||
if (config.TrialExpiresUtc is not DateTime expiry)
|
||||
return;
|
||||
|
||||
// Permanent Pro: the trial timestamps are inert leftovers — expiry changes nothing.
|
||||
if (FeatureEntitlementCatalog.IsPermanentProTier(config.PlanTier))
|
||||
// Permanent Pro, or Pro conferred by the managing tenant: the trial timestamps are inert
|
||||
// leftovers — expiry changes nothing.
|
||||
if (FeatureEntitlementCatalog.IsPermanentProTier(config.PlanTier) ||
|
||||
FeatureEntitlementCatalog.Resolve(config, now).IsViaMsp)
|
||||
return;
|
||||
|
||||
result.TrialsSeen++;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Net;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Raw
|
||||
{
|
||||
/// <summary>
|
||||
/// GET /api/global/raw/access-probe — a GlobalAdminOnly route that does nothing.
|
||||
/// <para>
|
||||
/// It exists for the deny path, not the allow path. When a caller without the GlobalAdmin role
|
||||
/// asks the MCP for a GA-only tool, the tool is not registered for them and the SDK answers
|
||||
/// "not found" before any backend call — so the backend, which owns the identity binding and the
|
||||
/// <c>PrivilegedRouteDenied</c> ops event, would never learn about the probe. The MCP therefore
|
||||
/// fires this route (fire-and-forget, <c>X-MCP-Tool-Name</c> = the attempted tool) and the policy
|
||||
/// middleware refuses it exactly like any other GlobalAdminOnly route: same catalog, same identity
|
||||
/// check, same throttled Critical event, no second writer and no caller-supplied event payload.
|
||||
/// A genuine Global Admin reaching it simply gets a typed OK.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public class AccessProbeFunction
|
||||
{
|
||||
[Function("GlobalAccessProbe")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "global/raw/access-probe")] HttpRequestData req,
|
||||
FunctionContext context)
|
||||
{
|
||||
if (await RawGlobalAdminGate.DenyUnlessGlobalAdminAsync(req, context) is { } denied)
|
||||
return denied;
|
||||
|
||||
var response = req.CreateResponse(HttpStatusCode.OK);
|
||||
await response.WriteAsJsonAsync(new AccessProbeResponse { Success = true, Role = Constants.GlobalRoles.GlobalAdmin });
|
||||
return response;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user