mirror of
https://github.com/okieselbach/AutopilotMonitor.git
synced 2026-10-25 21:19:38 +00:00
Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f607e21c13 | |||
| 5940e9fc6a | |||
| 98cfd76232 | |||
| 09e68a614f | |||
| 88290caadc | |||
| f442dce9a4 | |||
| 4f03f39e9a | |||
| 38b667799c | |||
| a5f74d6abc | |||
| d0e09301a1 | |||
| 177915ea6b |
+1
-1
Submodule .claude/commands updated: 92d8689b1e...6b39d14ed0
@@ -348,16 +348,6 @@ jobs:
|
||||
RELEASE_ZIP: ${{ steps.artifact.outputs.versioned_zip_release }}
|
||||
RELEASE_NOTES: ${{ inputs.release_notes }}
|
||||
RELEASE_BODY_TAIL: |
|
||||
### 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
|
||||
|
||||
### Version Info
|
||||
- **Version:** ${{ steps.version.outputs.version }}
|
||||
- **Build Number:** ${{ steps.version.outputs.build_number }}
|
||||
@@ -392,7 +382,7 @@ jobs:
|
||||
$compare = "`n`n**Full changelog:** https://github.com/$env:GITHUB_REPOSITORY/compare/$prevTag...$env:RELEASE_TAG`n"
|
||||
}
|
||||
|
||||
$body = "## $env:RELEASE_NAME`n`n### What's new`n$notes`n`n" + "$env:RELEASE_BODY_TAIL".TrimEnd() + $compare
|
||||
$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 $body -Encoding utf8 -NoNewline
|
||||
|
||||
|
||||
@@ -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 internal updated: 2316e7c0f3...9f75da246a
@@ -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."
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
+16
-21
@@ -2940,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,
|
||||
@@ -2958,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
|
||||
@@ -2979,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": {
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
+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})");
|
||||
}
|
||||
}
|
||||
}
|
||||
+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);
|
||||
|
||||
@@ -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:
|
||||
@@ -439,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 { }
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -38,6 +38,30 @@ public class AppInsightsQueryFunctionTests
|
||||
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()
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -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,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
|
||||
}
|
||||
}
|
||||
+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()
|
||||
{
|
||||
|
||||
@@ -242,6 +242,26 @@ public class PolicyEnforcementMiddlewareTests
|
||||
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,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);
|
||||
}
|
||||
}
|
||||
@@ -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,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);
|
||||
}
|
||||
}
|
||||
@@ -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,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,
|
||||
|
||||
+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.");
|
||||
}
|
||||
|
||||
@@ -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++;
|
||||
|
||||
@@ -123,18 +123,20 @@ namespace AutopilotMonitor.Functions.Functions.Raw
|
||||
source.Name, upstreamResponse.StatusCode, LogSanitizer.Clean(Cap(responseText, 2048)));
|
||||
|
||||
var (errorMessage, errorCode) = ExtractError(responseText);
|
||||
var errorResp = req.CreateResponse(HttpStatusCode.BadGateway);
|
||||
// A query the store rejected is the CALLER's error (400): the MCP renders 4xx bodies in
|
||||
// full (message, hint, upstream) but sanitizes every 5xx down to the error code — and a
|
||||
// KQL syntax error hidden behind "retry later" is exactly the parity loss this proxy
|
||||
// exists to avoid. Store-side failures (5xx) and a missing read grant (401/403 — the
|
||||
// managed identity, not the caller) stay 502.
|
||||
var status = MapUpstreamFailure(upstreamResponse.StatusCode);
|
||||
var errorResp = req.CreateResponse(status);
|
||||
await errorResp.WriteAsJsonAsync(new
|
||||
{
|
||||
error = errorMessage,
|
||||
errorCode,
|
||||
statusCode = (int)upstreamResponse.StatusCode,
|
||||
source = source.Name,
|
||||
hint = errorCode == "SyntaxError"
|
||||
? "The KQL query has a syntax error. Check operators, pipe stages, and string quoting. Example: traces | where message contains 'error' | take 50"
|
||||
: errorCode == "SemanticError"
|
||||
? $"The KQL query references an unknown table or column for source '{source.Name}'. Run '<table> | getschema' to list columns."
|
||||
: (string?)null,
|
||||
hint = UpstreamHint(upstreamResponse.StatusCode, errorCode, source.Name),
|
||||
// Everything the store said, so nothing the CLI would print is lost.
|
||||
upstream = Cap(responseText, UpstreamErrorCap),
|
||||
});
|
||||
@@ -180,6 +182,29 @@ namespace AutopilotMonitor.Functions.Functions.Raw
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Upstream 4xx other than 401/403 = the caller's query (400 to the caller, rendered in full by the
|
||||
/// MCP); 401/403 = the managed identity lacks the read grant, and 5xx = the store — both 502.
|
||||
/// </summary>
|
||||
internal static HttpStatusCode MapUpstreamFailure(HttpStatusCode upstream)
|
||||
{
|
||||
var code = (int)upstream;
|
||||
if (code == 401 || code == 403) return HttpStatusCode.BadGateway;
|
||||
return code >= 400 && code < 500 ? HttpStatusCode.BadRequest : HttpStatusCode.BadGateway;
|
||||
}
|
||||
|
||||
internal static string? UpstreamHint(HttpStatusCode upstream, string? errorCode, string sourceName)
|
||||
{
|
||||
if ((int)upstream is 401 or 403)
|
||||
return $"The backend's managed identity has no read access to the '{sourceName}' store (Monitoring Reader on the App Insights component / Log Analytics Reader on the workspace). Role propagation can take minutes after a grant.";
|
||||
return errorCode switch
|
||||
{
|
||||
"SyntaxError" => "The KQL query has a syntax error. Check operators, pipe stages, and string quoting. Example: traces | where message contains 'error' | take 50",
|
||||
"SemanticError" => $"The KQL query references an unknown table or column for source '{sourceName}'. Run '<table> | getschema' to list columns.",
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Null or out-of-range budgets collapse to the default / the nearest bound.</summary>
|
||||
internal static int ClampBudget(int? requested)
|
||||
{
|
||||
|
||||
@@ -28,6 +28,10 @@ namespace AutopilotMonitor.Functions.Helpers
|
||||
("maxDelegatedTenantsOverride", c => c.MaxDelegatedTenantsOverride),
|
||||
// MCP usage-plan override — a plan name, not a secret; the GA tenant list renders it.
|
||||
("mcpUsagePlanOverride", c => c.McpUsagePlanOverride),
|
||||
// Sales bookkeeping flag — operator-only, never a customer surface.
|
||||
("payingCustomer", c => c.PayingCustomer),
|
||||
// Load-time projection: the permanent-Pro tenant conferring Pro on this one (null = none).
|
||||
("managedByProTenantId", c => c.ManagedByProTenantId),
|
||||
("disabled", c => c.Disabled),
|
||||
("disabledReason", c => c.DisabledReason),
|
||||
("onboardedAt", c => c.OnboardedAt),
|
||||
|
||||
@@ -218,7 +218,7 @@ namespace AutopilotMonitor.Functions.Helpers
|
||||
if (!isGlobalAdmin && candidate.DataRetentionDays != existing.DataRetentionDays)
|
||||
{
|
||||
var cap = FeatureEntitlementCatalog
|
||||
.Get(TenantEntitlementService.ResolveEdition(existing, DateTime.UtcNow))
|
||||
.Get(TenantEntitlementService.Resolve(existing, DateTime.UtcNow))
|
||||
.RetentionCapDays;
|
||||
if (candidate.DataRetentionDays < 7 || candidate.DataRetentionDays > cap)
|
||||
return $"Data retention must be between 7 and {cap} days for your plan. Upgrade to Pro for up to 365 days.";
|
||||
|
||||
@@ -12,6 +12,7 @@ using System.IdentityModel.Tokens.Jwt;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using AutopilotMonitor.Functions.Extensions;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
|
||||
@@ -182,6 +183,20 @@ public class AuthenticationMiddleware : IFunctionsWorkerMiddleware
|
||||
|
||||
var principal = _tokenHandler.ValidateToken(token, validationParameters, out var validatedToken);
|
||||
|
||||
// APPLICATION-PRINCIPAL GATE. An app-only token (idtyp=app: a service principal, typically
|
||||
// behind a federated credential) is a valid Entra token for this API in EVERY tenant where our
|
||||
// service principal exists, with or without any permission assigned. It is accepted here only
|
||||
// when the caller's tenant admin actually granted the application permission
|
||||
// (roles ∋ access_as_application) — that consent is the Entra-side half of the grant; the role
|
||||
// rows keyed on app:<client-id> are ours. Rejected tokens never reach the catalog.
|
||||
var applicationGateError = ValidateApplicationPrincipal(principal);
|
||||
if (applicationGateError != null)
|
||||
{
|
||||
_logger.LogWarning("[Auth Middleware] Rejected app-only token for {Path}: {Reason} (appid={AppId}, tid={Tid})",
|
||||
logPath, applicationGateError, principal.GetApplicationId() ?? "(none)", tenantId);
|
||||
throw new SecurityTokenValidationException(applicationGateError);
|
||||
}
|
||||
|
||||
// Get user identifier for logging (same logic as TenantHelper.GetUserIdentifier)
|
||||
var userIdentifier = principal.FindFirst("upn")?.Value ??
|
||||
principal.FindFirst(ClaimTypes.Upn)?.Value ??
|
||||
@@ -242,6 +257,25 @@ public class AuthenticationMiddleware : IFunctionsWorkerMiddleware
|
||||
/// <c>diagnostics/download</c> route). Unregistered routes (FindPolicy == null) are fail-closed:
|
||||
/// JWT required. Method-aware so e.g. an unexpected verb on a public path is not waved through.
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// The application-principal gate: null for a user token (or any token without <c>idtyp=app</c>),
|
||||
/// otherwise the rejection reason for an app-only token that is not admissible — no application
|
||||
/// (client) id, no object id, or the <c>access_as_application</c> permission missing from <c>roles</c>.
|
||||
/// Pure so the three rejections and the pass are unit-testable on hand-built principals.
|
||||
/// </summary>
|
||||
internal static string? ValidateApplicationPrincipal(ClaimsPrincipal principal)
|
||||
{
|
||||
if (!principal.IsApplicationPrincipal())
|
||||
return null;
|
||||
if (principal.GetApplicationId() == null)
|
||||
return "app-only token carries no application id (appid/azp)";
|
||||
if (string.IsNullOrWhiteSpace(principal.GetObjectId()))
|
||||
return "app-only token carries no object id (oid)";
|
||||
if (!principal.GetAppRoles().Contains(Constants.ApplicationPermissions.AccessAsApplication, StringComparer.OrdinalIgnoreCase))
|
||||
return $"app-only token lacks the '{Constants.ApplicationPermissions.AccessAsApplication}' application permission (admin consent in the caller's tenant)";
|
||||
return null;
|
||||
}
|
||||
|
||||
internal static bool SkipsJwtValidation(string httpMethod, string path)
|
||||
{
|
||||
var entry = EndpointAccessPolicyCatalog.FindPolicy(httpMethod, path);
|
||||
|
||||
@@ -132,11 +132,11 @@ public class PolicyEnforcementMiddleware : IFunctionsWorkerMiddleware
|
||||
private static string? DenialHeader(HttpContext httpContext, string name)
|
||||
{
|
||||
var raw = LogSanitizer.Clean(httpContext.Request.Headers[name].FirstOrDefault());
|
||||
if (string.IsNullOrEmpty(raw))
|
||||
return null;
|
||||
return raw.Length <= MaxDenialHeaderLength ? raw : raw[..MaxDenialHeaderLength];
|
||||
return string.IsNullOrEmpty(raw) ? null : Truncate(raw, MaxDenialHeaderLength);
|
||||
}
|
||||
|
||||
private static string Truncate(string value, int max) => value.Length <= max ? value : value[..max];
|
||||
|
||||
/// <summary>
|
||||
/// ASSUME-BREACH layer for the Global-Admin-only surface. A 403 on a <c>GlobalAdminOnly</c> route by
|
||||
/// an authenticated caller is the one denial that must never pass silently: it is either an operator
|
||||
@@ -171,13 +171,21 @@ public class PolicyEnforcementMiddleware : IFunctionsWorkerMiddleware
|
||||
&& result.Policy == EndpointPolicy.GlobalAdminOnly
|
||||
&& result.StatusCode == (int)HttpStatusCode.Forbidden;
|
||||
|
||||
/// <summary>Pure projection of a denial into the record the reporter writes; separated so tests can pin it without an HttpContext.</summary>
|
||||
/// <summary>Longest request path kept in a denial record; the route catalog has nothing longer.</summary>
|
||||
private const int MaxDenialPathLength = 256;
|
||||
|
||||
/// <summary>
|
||||
/// Pure projection of a denial into the record the reporter writes; separated so tests can pin it
|
||||
/// without an HttpContext. Method and path are caller-controlled too (the path is percent-DECODED,
|
||||
/// so %0A arrives as a newline) and the record's text reaches log lines, the ops-events table and
|
||||
/// the alert channels — sanitized and capped here, once, before any of that.
|
||||
/// </summary>
|
||||
internal static PrivilegedDenial BuildPrivilegedDenial(
|
||||
PolicyResult result, string httpMethod, string requestPath, ClaimsPrincipal principal, string? globalRole,
|
||||
string? clientSource, string? mcpToolName, string? correlationId)
|
||||
=> new(
|
||||
Method: httpMethod,
|
||||
Path: requestPath,
|
||||
Method: LogSanitizer.Clean(httpMethod) ?? string.Empty,
|
||||
Path: Truncate(LogSanitizer.Clean(requestPath) ?? string.Empty, MaxDenialPathLength),
|
||||
StatusCode: result.StatusCode,
|
||||
Reason: result.LogReason,
|
||||
Policy: result.Policy?.ToString() ?? string.Empty,
|
||||
@@ -444,6 +452,13 @@ public class PolicyEnforcementMiddleware : IFunctionsWorkerMiddleware
|
||||
var upn = principal?.GetUserPrincipalName();
|
||||
var userIdentifier = upn ?? "anonymous";
|
||||
|
||||
// An application principal (app-only token) is a member, a delegated reader or nothing — never
|
||||
// "some authenticated person". The roleless tiers admit any valid token, so they are closed to
|
||||
// applications unless the catalog entry opted in (auth/mcp). Every role-gated tier below already
|
||||
// resolves the app:<client-id> key through the same tables as a person, with its caps applied.
|
||||
if (principal != null && principal.IsApplicationPrincipal() && entry.IsRolelessTier && !entry.ApplicationAllowed)
|
||||
return CatalogDecisionResult.Deny(userIdentifier, "Application", "ApplicationPrincipalNotAllowed");
|
||||
|
||||
switch (entry.Policy)
|
||||
{
|
||||
case EndpointPolicy.PublicAnonymous:
|
||||
|
||||
@@ -4,6 +4,7 @@ using Microsoft.ApplicationInsights.Channel;
|
||||
using Microsoft.ApplicationInsights.DataContracts;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Middleware;
|
||||
using AutopilotMonitor.Functions.Extensions;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
|
||||
@@ -112,6 +113,16 @@ public class RequestTelemetryMiddleware : IFunctionsWorkerMiddleware
|
||||
if (!string.IsNullOrEmpty(mcpToolName))
|
||||
requestTelemetry.Properties["McpToolName"] = mcpToolName;
|
||||
|
||||
// APPLICATION PRINCIPALS — the request-row dimension that lets KQL separate automation
|
||||
// (app-only tokens) from people: "app" plus the calling client id, nothing for a person.
|
||||
if (context.GetUser() is { } principal && principal.IsApplicationPrincipal())
|
||||
{
|
||||
requestTelemetry.Properties["PrincipalKind"] = "app";
|
||||
var applicationId = principal.GetApplicationId();
|
||||
if (applicationId != null)
|
||||
requestTelemetry.Properties["ApplicationId"] = applicationId;
|
||||
}
|
||||
|
||||
if (context.Items.TryGetValue("CorrelationId", out var corrId) && corrId is string correlationId)
|
||||
requestTelemetry.Properties["CorrelationId"] = correlationId;
|
||||
|
||||
|
||||
@@ -234,7 +234,11 @@ builder.Services.AddHostedService<StartupTelemetryService>(); // BackendStartup
|
||||
// To switch to Cosmos DB: replace AddTableStorageDataAccess() with AddCosmosDataAccess().
|
||||
// To add event streaming: chain .AddEventStreaming<EventHubPublisher>() after this call.
|
||||
builder.Services.AddTableStorageDataAccess();
|
||||
// Conferred Pro ("Pro (MSP)"): the read-time index the configuration loader projects from, and the
|
||||
// write side that stamps the retention grace anchor when a conferring delegation ends.
|
||||
builder.Services.AddSingleton<ManagedTenantProIndex>();
|
||||
builder.Services.AddSingleton<TenantConfigurationService>();
|
||||
builder.Services.AddSingleton<ProConferralService>();
|
||||
builder.Services.AddSingleton<TenantConfigPatchService>();
|
||||
builder.Services.AddSingleton<AdminConfigurationService>();
|
||||
builder.Services.AddSingleton<AppHomingService>();
|
||||
|
||||
@@ -16,11 +16,20 @@ namespace AutopilotMonitor.Functions.Security;
|
||||
/// every consumer treats as "no cross-tenant role" (fail-closed).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="Upn">The UPN (lowercase) — the row key of the role tables.</param>
|
||||
/// <param name="Upn">The principal key (lowercase) — the row key of the role tables: a person's UPN, or
|
||||
/// <c>app:<client-id></c> for an application principal (<see cref="Shared.Constants.PrincipalKeys"/>).</param>
|
||||
/// <param name="TenantId">The JWT <c>tid</c> (lowercase) — the caller's home tenant.</param>
|
||||
/// <param name="ObjectId">The JWT <c>oid</c> (lowercase) — the caller's object id in that tenant.</param>
|
||||
/// <param name="ObjectId">The JWT <c>oid</c> (lowercase) — the caller's object id in that tenant (for an
|
||||
/// application the service principal's object id, which differs per tenant).</param>
|
||||
public sealed record AdminIdentity(string Upn, string TenantId, string ObjectId)
|
||||
{
|
||||
/// <summary>
|
||||
/// True when the key names an application (app-only token). Applications are capped everywhere: never
|
||||
/// a platform role, never more than Viewer in a tenant, never more than DelegatedReader on a managed
|
||||
/// tenant — the caps live in the respective role services, this flag is what they switch on.
|
||||
/// </summary>
|
||||
public bool IsApplication => Shared.Constants.PrincipalKeys.IsApplication(Upn);
|
||||
|
||||
/// <summary>Builds the identity from a validated principal, or null when upn, tid or oid is missing.</summary>
|
||||
public static AdminIdentity? FromPrincipal(ClaimsPrincipal? principal)
|
||||
=> principal == null
|
||||
|
||||
@@ -123,20 +123,35 @@ public sealed class EndpointPolicyEntry
|
||||
/// </summary>
|
||||
public bool ExcludeDelegated { get; }
|
||||
|
||||
/// <summary>
|
||||
/// When true, an application principal (app-only token, <c>app:<client-id></c> key) is admitted to
|
||||
/// an <see cref="EndpointPolicy.AuthenticatedUser"/> / <see cref="EndpointPolicy.AuthenticatedUserWithRole"/>
|
||||
/// route. Those two tiers mean "some person in some tenant" (Progress Portal, feedback, SignalR
|
||||
/// negotiate) and admit a valid token without any role, so a service reaching them would bypass every
|
||||
/// membership gate; applications are therefore denied there unless the entry opts in — today only the
|
||||
/// MCP front door (<c>GET auth/mcp</c>), which does its own membership check. Role-gated tiers need no
|
||||
/// flag: an application passes them only through its (Viewer-capped) membership or delegated scope.
|
||||
/// </summary>
|
||||
public bool ApplicationAllowed { get; }
|
||||
|
||||
// Pre-compiled regex for matching actual request paths against the route template
|
||||
internal Regex RouteRegex { get; }
|
||||
|
||||
public EndpointPolicyEntry(string httpMethod, string routeTemplate, EndpointPolicy policy,
|
||||
TenantScoping tenantScoping = TenantScoping.None, bool excludeDelegated = false)
|
||||
TenantScoping tenantScoping = TenantScoping.None, bool excludeDelegated = false, bool applicationAllowed = false)
|
||||
{
|
||||
HttpMethod = httpMethod.ToUpperInvariant();
|
||||
RouteTemplate = routeTemplate;
|
||||
Policy = policy;
|
||||
TenantScoping = tenantScoping;
|
||||
ExcludeDelegated = excludeDelegated;
|
||||
ApplicationAllowed = applicationAllowed;
|
||||
RouteRegex = BuildRouteRegex(routeTemplate);
|
||||
}
|
||||
|
||||
/// <summary>True when this entry's tier admits any valid token regardless of role.</summary>
|
||||
public bool IsRolelessTier => Policy is EndpointPolicy.AuthenticatedUser or EndpointPolicy.AuthenticatedUserWithRole;
|
||||
|
||||
/// <summary>
|
||||
/// Converts a route template like "sessions/{sessionId}/events" into a regex
|
||||
/// that matches actual paths like "sessions/abc-123/events".
|
||||
@@ -377,7 +392,9 @@ public static class EndpointAccessPolicyCatalog
|
||||
new("DELETE", "bootstrap/sessions/{code}", EndpointPolicy.BootstrapManagerOrGA, TenantScoping.QueryParam),
|
||||
|
||||
// ── MCP Access Check (any authenticated user can check their own access) ──
|
||||
new("GET", "auth/mcp", EndpointPolicy.AuthenticatedUser),
|
||||
// The MCP front door: the only roleless-tier route an application principal may reach — the
|
||||
// handler resolves membership / delegation itself (McpUserService.IsAllowedAsync).
|
||||
new("GET", "auth/mcp", EndpointPolicy.AuthenticatedUser, applicationAllowed: true),
|
||||
|
||||
// ── MCP Usage (self-service) ──────────────────────────────────
|
||||
new("GET", "metrics/mcp-usage/me", EndpointPolicy.AuthenticatedUser),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Security
|
||||
{
|
||||
@@ -12,6 +13,40 @@ namespace AutopilotMonitor.Functions.Security
|
||||
Pro
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// WHY a tenant is on its effective edition. <see cref="Msp"/> wins over the tenant's own plan
|
||||
/// and trial for display purposes ("Pro (MSP)" is shown even to a paying Pro tenant while it is
|
||||
/// managed) — the entitlement set is the UNION, see <see cref="EditionResolution.OwnPro"/>.
|
||||
/// </summary>
|
||||
public enum EditionSource
|
||||
{
|
||||
/// <summary>No Pro from any source.</summary>
|
||||
Community,
|
||||
/// <summary>Permanent Pro tier stored on the tenant (paid or support-assigned).</summary>
|
||||
Plan,
|
||||
/// <summary>Active trial (TrialExpiresUtc in the future) on a non-Pro tier.</summary>
|
||||
Trial,
|
||||
/// <summary>Pro conferred by the permanent-Pro tenant that manages this tenant (self-service delegation).</summary>
|
||||
Msp
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read-time edition resolution: the effective edition, its source, and whether the tenant is Pro
|
||||
/// in its OWN right (plan or trial) independent of any managing tenant. Delegation entitlements
|
||||
/// (DelegatedAdminAllowed, MaxDelegatedTenants) follow <see cref="OwnPro"/> only — conferred Pro
|
||||
/// never lets a managed tenant delegate onward.
|
||||
/// </summary>
|
||||
public readonly record struct EditionResolution(TenantEdition Edition, EditionSource Source, bool OwnPro)
|
||||
{
|
||||
public bool IsPro => Edition == TenantEdition.Pro;
|
||||
public bool IsTrial => Source == EditionSource.Trial;
|
||||
public bool IsViaMsp => Source == EditionSource.Msp;
|
||||
/// <summary>Wire spelling of <see cref="Source"/> ("community" | "plan" | "trial" | "msp").</summary>
|
||||
public string SourceName => Source.ToString().ToLowerInvariant();
|
||||
/// <summary>Wire spelling of <see cref="Edition"/> ("community" | "pro").</summary>
|
||||
public string EditionName => Edition.ToString().ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The static per-edition entitlement values. Immutable code catalog — analogous to
|
||||
/// <see cref="EndpointAccessPolicyCatalog"/>: entitlements are defined here, not in storage,
|
||||
@@ -43,7 +78,9 @@ namespace AutopilotMonitor.Functions.Security
|
||||
/// <summary>
|
||||
/// Whether users HOMED in this tenant may hold delegated ("MSP") admin scopes over other
|
||||
/// tenants. The gate applies to the delegated admin's home tenant (JWT tid) — the managed
|
||||
/// TARGET tenants may be any edition (a Pro MSP may manage Community customers).
|
||||
/// TARGET tenants may be any edition (a Pro MSP may manage Community customers; a
|
||||
/// permanent-Pro MSP additionally confers Pro on them, see <see cref="EditionSource.Msp"/>).
|
||||
/// Conferred Pro never includes this right (no transitive delegation).
|
||||
/// Enforced at resolve time in DelegatedAdminService.GetScopeAsync.
|
||||
/// </summary>
|
||||
public bool DelegatedAdminAllowed { get; init; }
|
||||
@@ -97,9 +134,11 @@ namespace AutopilotMonitor.Functions.Security
|
||||
///
|
||||
/// Resolution is computed at READ time: Pro ⇔ PlanTier == "pro" (or the legacy stored value
|
||||
/// "enterprise", kept readable so existing rows need no migration) OR an active trial
|
||||
/// (TrialExpiresUtc strictly in the future). Trial expiry therefore degrades the tenant
|
||||
/// automatically without any timer or sweep. Everything else — null, empty, "free",
|
||||
/// unknown — is Community (fail-closed, no data migration required).
|
||||
/// (TrialExpiresUtc strictly in the future) OR the tenant is managed by a permanent-Pro tenant
|
||||
/// (<see cref="TenantConfiguration.ManagedByProTenantId"/>, a load-time projection that is never
|
||||
/// stored). Trial expiry and the end of a delegation therefore degrade the tenant automatically
|
||||
/// without any timer or sweep. Everything else — null, empty, "free", unknown — is Community
|
||||
/// (fail-closed, no data migration required).
|
||||
/// </summary>
|
||||
public static class FeatureEntitlementCatalog
|
||||
{
|
||||
@@ -157,6 +196,28 @@ namespace AutopilotMonitor.Functions.Security
|
||||
McpTenantMonthlyRequestLimit = 60000
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Pro conferred by a managing tenant: every Pro value EXCEPT the delegation right. A managed
|
||||
/// tenant that is not Pro in its own right cannot invite or manage tenants itself — the
|
||||
/// delegation right is what the managing tenant paid for, and conferral must not chain.
|
||||
/// </summary>
|
||||
private static readonly EditionEntitlements ProViaMsp = new()
|
||||
{
|
||||
Edition = TenantEdition.Pro,
|
||||
RetentionCapDays = Pro.RetentionCapDays,
|
||||
UserRateLimitPerMinute = Pro.UserRateLimitPerMinute,
|
||||
DeviceRateLimitPerMinute = Pro.DeviceRateLimitPerMinute,
|
||||
DelegatedAdminAllowed = false,
|
||||
MaxDelegatedTenants = 0,
|
||||
BootstrapIncluded = Pro.BootstrapIncluded,
|
||||
UnrestrictedModeAvailable = Pro.UnrestrictedModeAvailable,
|
||||
McpUsagePlanName = Pro.McpUsagePlanName,
|
||||
McpDailyRequestLimit = Pro.McpDailyRequestLimit,
|
||||
McpMonthlyRequestLimit = Pro.McpMonthlyRequestLimit,
|
||||
McpTenantDailyRequestLimit = Pro.McpTenantDailyRequestLimit,
|
||||
McpTenantMonthlyRequestLimit = Pro.McpTenantMonthlyRequestLimit
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// True when the stored tier is a PERMANENT Pro tier ("pro", or the legacy stored value
|
||||
/// "enterprise"), independent of any trial. Used to separate paid tenants from trial
|
||||
@@ -170,22 +231,53 @@ namespace AutopilotMonitor.Functions.Security
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the effective edition from the stored plan tier and trial expiry.
|
||||
/// Pro ⇔ tier "pro"/legacy "enterprise" (case-insensitive) OR trialExpiresUtc > nowUtc.
|
||||
/// A trial expiring exactly at <paramref name="nowUtc"/> is already over (strict >).
|
||||
/// Resolves the effective edition and its source from the stored plan tier, the trial expiry
|
||||
/// and the load-time "managed by a permanent-Pro tenant" projection.
|
||||
/// Own Pro ⇔ tier "pro"/legacy "enterprise" (case-insensitive) OR trialExpiresUtc > nowUtc
|
||||
/// (a trial expiring exactly at <paramref name="nowUtc"/> is already over — strict >).
|
||||
/// Source precedence for DISPLAY: Msp > Plan > Trial; <see cref="EditionResolution.OwnPro"/>
|
||||
/// keeps the tenant's own standing so the entitlement union is exact.
|
||||
/// </summary>
|
||||
public static TenantEdition ResolveEdition(string? planTier, DateTime? trialExpiresUtc, DateTime nowUtc)
|
||||
public static EditionResolution Resolve(string? planTier, DateTime? trialExpiresUtc, string? managedByProTenantId, DateTime nowUtc)
|
||||
{
|
||||
if (IsPermanentProTier(planTier))
|
||||
return TenantEdition.Pro;
|
||||
var permanentPro = IsPermanentProTier(planTier);
|
||||
var trialActive = trialExpiresUtc.HasValue && trialExpiresUtc.Value > nowUtc;
|
||||
var ownPro = permanentPro || trialActive;
|
||||
|
||||
if (trialExpiresUtc.HasValue && trialExpiresUtc.Value > nowUtc)
|
||||
return TenantEdition.Pro;
|
||||
|
||||
return TenantEdition.Community;
|
||||
if (!string.IsNullOrWhiteSpace(managedByProTenantId))
|
||||
return new EditionResolution(TenantEdition.Pro, EditionSource.Msp, ownPro);
|
||||
if (permanentPro)
|
||||
return new EditionResolution(TenantEdition.Pro, EditionSource.Plan, true);
|
||||
if (trialActive)
|
||||
return new EditionResolution(TenantEdition.Pro, EditionSource.Trial, true);
|
||||
return new EditionResolution(TenantEdition.Community, EditionSource.Community, false);
|
||||
}
|
||||
|
||||
/// <summary>Returns the entitlement set for an edition. Unknown enum values → Community (fail-closed).</summary>
|
||||
/// <summary>Config-based overload of <see cref="Resolve(string?, DateTime?, string?, DateTime)"/> — the one every config-holding caller uses.</summary>
|
||||
public static EditionResolution Resolve(TenantConfiguration config, DateTime nowUtc)
|
||||
=> Resolve(config.PlanTier, config.TrialExpiresUtc, config.ManagedByProTenantId, nowUtc);
|
||||
|
||||
/// <summary>The effective edition only — see <see cref="Resolve(TenantConfiguration, DateTime)"/>.</summary>
|
||||
public static TenantEdition ResolveEdition(TenantConfiguration config, DateTime nowUtc)
|
||||
=> Resolve(config, nowUtc).Edition;
|
||||
|
||||
/// <summary>
|
||||
/// Returns the entitlement set for a resolution: Community values unless Pro; the full Pro set when the
|
||||
/// tenant is Pro in its own right (plan or trial); the conferred set (no delegation right) when Pro comes
|
||||
/// only from the managing tenant. Unknown enum values → Community (fail-closed).
|
||||
/// </summary>
|
||||
public static EditionEntitlements Get(EditionResolution resolution)
|
||||
{
|
||||
if (resolution.Edition != TenantEdition.Pro)
|
||||
return Community;
|
||||
return resolution.OwnPro ? Pro : ProViaMsp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the entitlement set for a bare edition (catalog lookups such as a cap value). Callers that
|
||||
/// hold a config must use <see cref="Get(EditionResolution)"/> so conferred Pro is resolved correctly.
|
||||
/// Unknown enum values → Community (fail-closed).
|
||||
/// </summary>
|
||||
public static EditionEntitlements Get(TenantEdition edition) =>
|
||||
edition == TenantEdition.Pro ? Pro : Community;
|
||||
}
|
||||
|
||||
@@ -116,7 +116,7 @@ namespace AutopilotMonitor.Functions.Security
|
||||
// Edition resolves purely from the config already in hand — no extra I/O on the
|
||||
// agent hot path. Fail-closed by construction (unknown tier → Community → null floor).
|
||||
var entitlementFloor = FeatureEntitlementCatalog
|
||||
.Get(Services.TenantEntitlementService.ResolveEdition(config, DateTime.UtcNow))
|
||||
.Get(Services.TenantEntitlementService.Resolve(config, DateTime.UtcNow))
|
||||
.DeviceRateLimitPerMinute;
|
||||
return RateLimitResolver.ResolveDeviceLimit(
|
||||
config.CustomRateLimitRequestsPerMinute,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Security;
|
||||
|
||||
@@ -32,6 +33,15 @@ public class TenantMemberRoleResolver
|
||||
{
|
||||
var (state, tableRole) = await _tenantAdminsService.GetTableMembershipAsync(tenantId, upn);
|
||||
|
||||
// An application principal (app:<client-id> key) is a member only through its table row, and never
|
||||
// above Viewer: the cap is enforced here and not only at grant time, so a row edited to Admin or
|
||||
// Operator by any other path still yields a read-only member. Its `roles` claim carries
|
||||
// application permissions (access_as_application), never a member role — the claim path is skipped.
|
||||
if (Constants.PrincipalKeys.IsApplication(upn))
|
||||
return state == TableMemberState.Enabled && tableRole != null
|
||||
? new MemberRoleInfo { Role = Constants.TenantRoles.Viewer, CanManageBootstrapTokens = false }
|
||||
: null;
|
||||
|
||||
// Table-first: an enabled row wins, a disabled row is an explicit deny. Both skip the claim path
|
||||
// entirely — and avoid the tenant-config lookup. Only when no row exists do we consult the Entra
|
||||
// app-role claim (gated by the per-tenant opt-in flag); a token without roles needs no lookup at all.
|
||||
|
||||
@@ -80,7 +80,12 @@ public class DelegatedAdminService
|
||||
if (!await _bindings.IsBoundAsync(identity))
|
||||
return DelegatedScope.Empty;
|
||||
|
||||
return await ApplyHomeTenantGateAsync(scope, identity.Upn, identity.TenantId);
|
||||
var gated = await ApplyHomeTenantGateAsync(scope, identity.Upn, identity.TenantId);
|
||||
|
||||
// An application principal reads managed tenants, it never administers them: whatever role its rows
|
||||
// carry (a GA grant on global/delegated-admins could say DelegatedAdmin), the scope it presents is
|
||||
// capped to DelegatedReader. Enforced at resolution so no grant path has to remember the rule.
|
||||
return identity.IsApplication ? gated.AsReaderOnly() : gated;
|
||||
}
|
||||
|
||||
/// <summary>The scope the assignment ROWS (direct + group-derived) confer on a UPN, ignoring identity binding
|
||||
@@ -163,7 +168,9 @@ public class DelegatedAdminService
|
||||
/// </summary>
|
||||
private async Task<DelegatedScope> ApplyHomeTenantGateAsync(DelegatedScope scope, string upn, string callerHomeTenantId)
|
||||
{
|
||||
if (await _entitlementService.GetEditionAsync(callerHomeTenantId) == Security.TenantEdition.Pro)
|
||||
// The ENTITLEMENT, not the edition: a tenant whose Pro is conferred by its own managing tenant
|
||||
// is Pro without the delegation right (no transitive delegation).
|
||||
if ((await _entitlementService.GetEntitlementsAsync(callerHomeTenantId)).DelegatedAdminAllowed)
|
||||
return scope;
|
||||
|
||||
_logger.LogInformation(
|
||||
@@ -444,6 +451,15 @@ public sealed class DelegatedScope
|
||||
/// <summary>Tenant IDs (lowercase) this scope grants access to.</summary>
|
||||
public IReadOnlyCollection<string> TenantIds => (IReadOnlyCollection<string>)_tenantRoles.Keys;
|
||||
|
||||
/// <summary>The same tenants, every role lowered to DelegatedReader (the application-principal cap).</summary>
|
||||
public DelegatedScope AsReaderOnly()
|
||||
{
|
||||
if (_tenantRoles.Values.All(r => r == Constants.DelegatedRoles.DelegatedReader))
|
||||
return this;
|
||||
var readerRoles = _tenantRoles.Keys.ToDictionary(t => t, _ => Constants.DelegatedRoles.DelegatedReader, StringComparer.OrdinalIgnoreCase);
|
||||
return new DelegatedScope(readerRoles, _homeCharged);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The covered tenants reached through a Tenant Group flagged <see cref="TenantGroup.ChargeHomeTenantQuota"/>:
|
||||
/// MCP reads into them are charged to the caller's HOME tenant. Billing attribution only — never authz.
|
||||
|
||||
@@ -304,7 +304,9 @@ public class DelegatedSlotService
|
||||
var config = await _configRepo.GetTenantConfigurationAsync(homeTenantId);
|
||||
if (config == null)
|
||||
return (0, 0, null, null);
|
||||
var catalog = Security.FeatureEntitlementCatalog.Get(TenantEntitlementService.ResolveEdition(config, nowUtc)).MaxDelegatedTenants;
|
||||
// Raw repository row: no ManagedByProTenantId projection, so this is the home tenant's OWN standing —
|
||||
// exactly right for slots (conferred Pro carries none).
|
||||
var catalog = Security.FeatureEntitlementCatalog.Get(TenantEntitlementService.Resolve(config, nowUtc)).MaxDelegatedTenants;
|
||||
return (TenantEntitlementService.GetMaxDelegatedTenants(config, nowUtc), catalog, config.MaxDelegatedTenantsOverride,
|
||||
string.IsNullOrWhiteSpace(config.DomainName) ? null : config.DomainName);
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ public class DelegationSelfService
|
||||
private readonly IConfigRepository _configRepo;
|
||||
private readonly IMaintenanceRepository _audit;
|
||||
private readonly ISignalRNotificationService _signalR;
|
||||
private readonly ProConferralService _proConferral;
|
||||
private readonly ILogger<DelegationSelfService> _logger;
|
||||
private readonly TimeProvider _time;
|
||||
|
||||
@@ -71,8 +72,9 @@ public class DelegationSelfService
|
||||
IConfigRepository configRepo,
|
||||
IMaintenanceRepository audit,
|
||||
ISignalRNotificationService signalR,
|
||||
ProConferralService proConferral,
|
||||
ILogger<DelegationSelfService> logger)
|
||||
: this(adminRepo, invitations, delegatedAdmins, slots, entitlements, configRepo, audit, signalR, logger, TimeProvider.System)
|
||||
: this(adminRepo, invitations, delegatedAdmins, slots, entitlements, configRepo, audit, signalR, proConferral, logger, TimeProvider.System)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -86,6 +88,7 @@ public class DelegationSelfService
|
||||
IConfigRepository configRepo,
|
||||
IMaintenanceRepository audit,
|
||||
ISignalRNotificationService signalR,
|
||||
ProConferralService proConferral,
|
||||
ILogger<DelegationSelfService> logger,
|
||||
TimeProvider time)
|
||||
{
|
||||
@@ -97,6 +100,7 @@ public class DelegationSelfService
|
||||
_configRepo = configRepo;
|
||||
_audit = audit;
|
||||
_signalR = signalR;
|
||||
_proConferral = proConferral;
|
||||
_logger = logger;
|
||||
_time = time;
|
||||
}
|
||||
@@ -217,6 +221,8 @@ public class DelegationSelfService
|
||||
|
||||
await EnsureOwnedGroupAsync(home);
|
||||
await _delegatedAdmins.AddTenantToGroupAsync(groupId, target);
|
||||
// Conferred Pro is projected from this membership — drop the caches so the customer sees "Pro (MSP)" now.
|
||||
await _proConferral.NotifyDelegationChangedAsync(target);
|
||||
|
||||
var actor = callerUpn.ToLowerInvariant();
|
||||
var assignees = await _delegatedAdmins.GetGroupAssigneesAsync(groupId);
|
||||
@@ -280,6 +286,8 @@ public class DelegationSelfService
|
||||
if (!await _delegatedAdmins.RemoveTenantFromGroupAsync(groupId, target))
|
||||
return DelegationResult<bool>.Fail(404, Constants.DelegationCodes.NotManagedBySelfService, "That tenant is not managed through a self-service delegation.");
|
||||
|
||||
// The customer's conferred Pro ends with the membership: stamp its retention grace anchor.
|
||||
await _proConferral.RecordLossAsync(target, home, reason);
|
||||
var hold = await _slots.RecordReleaseAsync(home, target, actor);
|
||||
var by = actor.ToLowerInvariant();
|
||||
foreach (var assignee in assignees)
|
||||
|
||||
@@ -73,6 +73,12 @@ public class GlobalAdminService
|
||||
return null;
|
||||
}
|
||||
|
||||
// An application principal never holds a platform role (D-133): a GlobalAdmins row keyed
|
||||
// app:<client-id> is inert even if one were written. Tenant membership and delegation are the only
|
||||
// grant paths for a service.
|
||||
if (identity.IsApplication)
|
||||
return null;
|
||||
|
||||
var role = await GetRowRoleAsync(identity.Upn);
|
||||
if (role == null)
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// The reverse index behind <c>TenantConfiguration.ManagedByProTenantId</c>: managed tenant → the
|
||||
/// permanent-Pro tenant whose owned self-service group (<c>msp-{tid}</c>) it belongs to. Built from ONE
|
||||
/// scan of the admin-scale Tenant Groups table plus a raw config read per owning tenant, cached
|
||||
/// process-wide for <see cref="Ttl"/>, so projecting the pointer onto a configuration costs a dictionary
|
||||
/// lookup — never a per-tenant table query on the agent or portal hot path.
|
||||
///
|
||||
/// Invariants:
|
||||
/// <list type="bullet">
|
||||
/// <item>Only OWNED groups (meta row with OwnerTenantId — the self-service delegation model) confer; operator-created groups never do.</item>
|
||||
/// <item>Only a PERMANENT Pro owner confers (<see cref="FeatureEntitlementCatalog.IsPermanentProTier"/>): a trial MSP may delegate but does not upgrade its customers.</item>
|
||||
/// <item>The owner's tier is read RAW from the repository, never through <see cref="TenantConfigurationService"/> — that service consults this index, and two tenants managing each other would otherwise recurse.</item>
|
||||
/// <item>Fail-soft ⇒ fail-closed: any storage error yields an empty map (nobody is projected as managed, i.e. Community values) with a Warning, cached briefly so a hiccup does not hammer storage.</item>
|
||||
/// <item>Owners are visited in group-id order so a tenant managed by two Pro tenants resolves deterministically.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public class ManagedTenantProIndex
|
||||
{
|
||||
private const string CacheKey = "managed-tenant-pro-index";
|
||||
/// <summary>Matches the tenant-config cache TTL — the staleness budget plan changes already accept.</summary>
|
||||
internal static readonly TimeSpan Ttl = TimeSpan.FromMinutes(5);
|
||||
/// <summary>A failed build is cached briefly: fail-closed without a storage storm.</summary>
|
||||
internal static readonly TimeSpan FailureTtl = TimeSpan.FromSeconds(30);
|
||||
|
||||
private static readonly IReadOnlyDictionary<string, string> Empty =
|
||||
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private readonly IAdminRepository _adminRepo;
|
||||
private readonly IConfigRepository _configRepo;
|
||||
private readonly IMemoryCache _cache;
|
||||
private readonly ILogger<ManagedTenantProIndex> _logger;
|
||||
|
||||
public ManagedTenantProIndex(
|
||||
IAdminRepository adminRepo,
|
||||
IConfigRepository configRepo,
|
||||
IMemoryCache cache,
|
||||
ILogger<ManagedTenantProIndex> logger)
|
||||
{
|
||||
_adminRepo = adminRepo;
|
||||
_configRepo = configRepo;
|
||||
_cache = cache;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>Test seam for subclasses that never touch storage (see <see cref="None"/>).</summary>
|
||||
protected ManagedTenantProIndex()
|
||||
{
|
||||
_adminRepo = null!;
|
||||
_configRepo = null!;
|
||||
_cache = null!;
|
||||
_logger = null!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An index that projects NO tenant as managed. For tests whose subject is not delegation and for
|
||||
/// the configuration service's storage-free test constructor — never registered in production DI.
|
||||
/// </summary>
|
||||
public static ManagedTenantProIndex None { get; } = new NoneIndex();
|
||||
|
||||
/// <summary>The permanent-Pro tenant currently conferring Pro on <paramref name="tenantId"/>, or null.</summary>
|
||||
public virtual async Task<string?> GetConferringOwnerAsync(string? tenantId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(tenantId))
|
||||
return null;
|
||||
var map = await GetMapAsync();
|
||||
return map.TryGetValue(tenantId, out var owner) ? owner : null;
|
||||
}
|
||||
|
||||
/// <summary>Drops the cached map on THIS instance; other instances refresh within <see cref="Ttl"/>.</summary>
|
||||
public virtual void Invalidate() => _cache.Remove(CacheKey);
|
||||
|
||||
private async Task<IReadOnlyDictionary<string, string>> GetMapAsync()
|
||||
{
|
||||
if (_cache.TryGetValue(CacheKey, out IReadOnlyDictionary<string, string>? cached) && cached != null)
|
||||
return cached;
|
||||
|
||||
var (map, ok) = await BuildAsync();
|
||||
_cache.Set(CacheKey, map, ok ? Ttl : FailureTtl);
|
||||
return map;
|
||||
}
|
||||
|
||||
private async Task<(IReadOnlyDictionary<string, string> Map, bool Ok)> BuildAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var groups = await _adminRepo.GetAllTenantGroupsAsync();
|
||||
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
var ownerTierCache = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (var group in groups
|
||||
.Where(g => !string.IsNullOrWhiteSpace(g.OwnerTenantId) && g.TenantIds.Count > 0)
|
||||
.OrderBy(g => g.GroupId, StringComparer.Ordinal))
|
||||
{
|
||||
var owner = group.OwnerTenantId!.Trim().ToLowerInvariant();
|
||||
if (!ownerTierCache.TryGetValue(owner, out var ownerIsPermanentPro))
|
||||
{
|
||||
// RAW read on purpose — see the class remarks (recursion through the config service).
|
||||
var ownerConfig = await _configRepo.GetTenantConfigurationAsync(owner);
|
||||
ownerIsPermanentPro = ownerConfig != null && FeatureEntitlementCatalog.IsPermanentProTier(ownerConfig.PlanTier);
|
||||
ownerTierCache[owner] = ownerIsPermanentPro;
|
||||
}
|
||||
if (!ownerIsPermanentPro)
|
||||
continue;
|
||||
|
||||
foreach (var tenantId in group.TenantIds)
|
||||
{
|
||||
var managed = tenantId.Trim().ToLowerInvariant();
|
||||
if (managed.Length == 0 || string.Equals(managed, owner, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
result.TryAdd(managed, owner);
|
||||
}
|
||||
}
|
||||
|
||||
return (result, true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"[ProConferral] Managed-tenant index build failed — no tenant is projected as managed until the next rebuild (fail-closed)");
|
||||
return (Empty, false);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class NoneIndex : ManagedTenantProIndex
|
||||
{
|
||||
public override Task<string?> GetConferringOwnerAsync(string? tenantId) => Task.FromResult<string?>(null);
|
||||
public override void Invalidate() { }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,8 +79,10 @@ public class McpUserService
|
||||
public virtual async Task<McpAccessCheckResult> IsAllowedAsync(
|
||||
string? upn, string? homeTenantId, string? objectId, IReadOnlyList<string>? appRoles = null)
|
||||
{
|
||||
// The principal key: a person's UPN, or app:<client-id> for an application principal. A token
|
||||
// that yields neither carries no identity we could grant anything to.
|
||||
if (string.IsNullOrWhiteSpace(upn))
|
||||
return McpAccessCheckResult.Denied("Missing UPN");
|
||||
return McpAccessCheckResult.Denied("Missing principal identity (no upn / preferred_username, and not an app-only token)");
|
||||
|
||||
upn = upn.ToLowerInvariant();
|
||||
var identity = AdminIdentity.Create(upn, homeTenantId, objectId);
|
||||
@@ -159,9 +161,11 @@ public class McpUserService
|
||||
var memberRole = string.IsNullOrWhiteSpace(homeTenantId)
|
||||
? null
|
||||
: await _memberRoleResolver.ResolveAsync(homeTenantId, upn, appRoles);
|
||||
return memberRole != null
|
||||
? McpAccessCheckResult.Allowed(upn, "AllMembers", false, null, delegatedTenantIds, delegatedRole)
|
||||
: McpAccessCheckResult.Denied("User not enabled for MCP usage (account has no role in its organization's tenant — ask a Tenant Admin to add you)");
|
||||
if (memberRole != null)
|
||||
return McpAccessCheckResult.Allowed(upn, "AllMembers", false, null, delegatedTenantIds, delegatedRole);
|
||||
return McpAccessCheckResult.Denied(Constants.PrincipalKeys.IsApplication(upn)
|
||||
? "Service principal not enabled for MCP usage (the application is not a member of its tenant — ask a Tenant Admin to add it under Members as a service principal)"
|
||||
: "User not enabled for MCP usage (account has no role in its organization's tenant — ask a Tenant Admin to add you)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+12
@@ -203,6 +203,7 @@ namespace AutopilotMonitor.Functions.Services.Offboarding
|
||||
private readonly ITenantCustomsArchiveRepository _customsArchive;
|
||||
private readonly IConfigRepository _configRepo;
|
||||
private readonly IOffboardFarewellEmailSender _farewellEmail;
|
||||
private readonly ProConferralService _proConferral;
|
||||
private readonly ILogger<TenantOffboardingHandler> _logger;
|
||||
|
||||
public TenantOffboardingHandler(
|
||||
@@ -219,6 +220,7 @@ namespace AutopilotMonitor.Functions.Services.Offboarding
|
||||
ITenantCustomsArchiveRepository customsArchive,
|
||||
IConfigRepository configRepo,
|
||||
IOffboardFarewellEmailSender farewellEmail,
|
||||
ProConferralService proConferral,
|
||||
ILogger<TenantOffboardingHandler> logger)
|
||||
{
|
||||
_auditRepo = auditRepo;
|
||||
@@ -234,6 +236,7 @@ namespace AutopilotMonitor.Functions.Services.Offboarding
|
||||
_customsArchive = customsArchive;
|
||||
_configRepo = configRepo;
|
||||
_farewellEmail = farewellEmail;
|
||||
_proConferral = proConferral;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@@ -654,6 +657,15 @@ namespace AutopilotMonitor.Functions.Services.Offboarding
|
||||
throw; // worker dequeues + eventually poisons
|
||||
}
|
||||
|
||||
// Conferred Pro: a permanent-Pro managing tenant leaves its customers behind. Their grace anchor
|
||||
// must be stamped BEFORE the owned group (the only record of who was managed) is wiped below.
|
||||
if (currentConfig != null && Security.FeatureEntitlementCatalog.IsPermanentProTier(currentConfig.PlanTier))
|
||||
{
|
||||
var stamped = await _proConferral.RecordLossForOwnedGroupAsync(tenantId, "manager-offboarded");
|
||||
if (stamped > 0)
|
||||
_logger.LogInformation("Offboarding tenant={Tenant}: conferred Pro ended for {Count} managed tenant(s)", tenantId, stamped);
|
||||
}
|
||||
|
||||
// 2.D-pass-1 — SafeWipe all tenant-scoped tables, including AuditLogs.
|
||||
var deletedCounts = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
await SafeWipeAllTenantTablesAsync(deletedCounts, tenantId, ct);
|
||||
|
||||
@@ -349,6 +349,17 @@ namespace AutopilotMonitor.Functions.Services
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An application principal opened its first MCP session (no sign-in history for its key yet).
|
||||
/// Recorded against the application's HOME tenant (JWT tid) once; afterwards its calls show up in the
|
||||
/// per-user usage view like anyone else's.
|
||||
/// </summary>
|
||||
public Task RecordMcpServicePrincipalFirstSeenAsync(string tenantId, string principalKey, string applicationId, string objectId, string accessGrant)
|
||||
=> WriteAsync(OpsEventCategory.Security, OpsEventTypes.McpServicePrincipalFirstSeen, OpsEventSeverity.Info,
|
||||
$"Service principal {applicationId} opened its first MCP session (grant: {accessGrant})",
|
||||
tenantId, principalKey,
|
||||
new { applicationId, oid = objectId, tid = tenantId, accessGrant });
|
||||
|
||||
/// <summary>
|
||||
/// The reporter's per-instance budget is spent: one Critical marker (same event type, so the same
|
||||
/// alert rule pushes it) that says further denials this window are trace-only. A storm is a
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// The WRITE side of conferred Pro ("Pro (MSP)"). The edition itself is never written — it is projected at
|
||||
/// read time from group membership (<see cref="ManagedTenantProIndex"/>). What must be written is the
|
||||
/// retention downgrade grace anchor: a managed tenant that raised its retention under conferred Pro would
|
||||
/// otherwise be clamped to the Community cap (hard deletes) the moment the relationship ends. Every path
|
||||
/// that ends a Pro-conferring relationship calls one of the record methods:
|
||||
/// <list type="bullet">
|
||||
/// <item>self-service removal / customer revoke and the Global Admin removing a tenant from an owned group → <see cref="RecordLossAsync"/></item>
|
||||
/// <item>the managing tenant losing its permanent Pro tier (plan endpoint) and its offboarding → <see cref="RecordLossForOwnedGroupAsync"/></item>
|
||||
/// </list>
|
||||
/// Accepting an invitation only needs the caches dropped (<see cref="NotifyDelegationChangedAsync"/>).
|
||||
/// </summary>
|
||||
public class ProConferralService
|
||||
{
|
||||
private const string BackupSource = "delegation";
|
||||
|
||||
private readonly IAdminRepository _adminRepo;
|
||||
private readonly TenantConfigurationService _configs;
|
||||
private readonly ManagedTenantProIndex _index;
|
||||
private readonly ILogger<ProConferralService> _logger;
|
||||
private readonly TimeProvider _time;
|
||||
|
||||
public ProConferralService(
|
||||
IAdminRepository adminRepo,
|
||||
TenantConfigurationService configs,
|
||||
ManagedTenantProIndex index,
|
||||
ILogger<ProConferralService> logger)
|
||||
: this(adminRepo, configs, index, logger, TimeProvider.System)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Test seam — inject a fake <see cref="TimeProvider"/>.</summary>
|
||||
public ProConferralService(
|
||||
IAdminRepository adminRepo,
|
||||
TenantConfigurationService configs,
|
||||
ManagedTenantProIndex index,
|
||||
ILogger<ProConferralService> logger,
|
||||
TimeProvider time)
|
||||
{
|
||||
_adminRepo = adminRepo;
|
||||
_configs = configs;
|
||||
_index = index;
|
||||
_logger = logger;
|
||||
_time = time;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A managed tenant joined or left a group on THIS instance: drop the index and the tenant's cached
|
||||
/// configuration so the next read reflects the new standing immediately here (other instances follow
|
||||
/// within the cache TTL).
|
||||
/// </summary>
|
||||
public virtual Task NotifyDelegationChangedAsync(string managedTenantId)
|
||||
{
|
||||
_index.Invalidate();
|
||||
_configs.InvalidateCache(managedTenantId.ToLowerInvariant());
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A single managed tenant left <paramref name="homeTenantId"/>'s owned group. Stamps the grace anchor when
|
||||
/// the home tenant is a permanent-Pro tenant (a trial MSP conferred nothing, so nothing is lost).
|
||||
/// Returns whether an anchor was written.
|
||||
/// </summary>
|
||||
public virtual async Task<bool> RecordLossAsync(string managedTenantId, string homeTenantId, string reason)
|
||||
{
|
||||
var home = homeTenantId.ToLowerInvariant();
|
||||
var managed = managedTenantId.ToLowerInvariant();
|
||||
try
|
||||
{
|
||||
var homeConfig = await _configs.GetConfigurationIfExistsAsync(home);
|
||||
var conferred = homeConfig != null && FeatureEntitlementCatalog.IsPermanentProTier(homeConfig.PlanTier);
|
||||
if (!conferred)
|
||||
return false;
|
||||
return await StampAsync(managed, home, reason);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await NotifyDelegationChangedAsync(managed);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every tenant in <paramref name="homeTenantId"/>'s owned group loses conferred Pro at once (the home
|
||||
/// tenant lost its permanent Pro tier or is being offboarded). The caller has established that the home
|
||||
/// tenant WAS a permanent-Pro tenant before the change. Returns the number of anchors written.
|
||||
/// </summary>
|
||||
public virtual async Task<int> RecordLossForOwnedGroupAsync(string homeTenantId, string reason)
|
||||
{
|
||||
var home = homeTenantId.ToLowerInvariant();
|
||||
var groupId = Constants.TenantGroupIds.ForHomeTenant(home);
|
||||
var members = await _adminRepo.GetGroupTenantsAsync(groupId);
|
||||
var stamped = 0;
|
||||
foreach (var member in members)
|
||||
{
|
||||
var managed = member.ToLowerInvariant();
|
||||
if (string.Equals(managed, home, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
if (await StampAsync(managed, home, reason))
|
||||
stamped++;
|
||||
_configs.InvalidateCache(managed);
|
||||
}
|
||||
_index.Invalidate();
|
||||
return stamped;
|
||||
}
|
||||
|
||||
private async Task<bool> StampAsync(string managedTenantId, string homeTenantId, string reason)
|
||||
{
|
||||
// Fresh read: the anchor is a read-modify-write on the whole row; a stale cached instance would
|
||||
// rewind fields another writer just changed (the app-homing failure mode).
|
||||
var config = await _configs.GetConfigurationFreshAsync(managedTenantId);
|
||||
if (config == null)
|
||||
return false;
|
||||
|
||||
var nowUtc = _time.GetUtcNow().UtcDateTime;
|
||||
config.ProDowngradedUtc = nowUtc;
|
||||
config.UpdatedBy = $"delegation:{homeTenantId}";
|
||||
await _configs.SaveConfigurationAsync(config, BackupSource, reason);
|
||||
_logger.LogInformation(
|
||||
"[ProConferral] {Managed} lost Pro conferred by {Home} ({Reason}); retention grace anchor set to {Anchor:O}",
|
||||
managedTenantId, homeTenantId, reason, nowUtc);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,6 +110,23 @@ namespace AutopilotMonitor.Functions.Services
|
||||
{
|
||||
var matchingEvents = events.Where(e => MatchesEventType(e, condition.EventType)).ToList();
|
||||
|
||||
// Absence gate: not_exists without a dataField matches when NO event of that type occurs
|
||||
// in the session (the same presence semantics as the precondition gate). A single event
|
||||
// of that type disproves the condition — as a required condition it vetoes the rule
|
||||
// (e.g. ime_user_token_acquired disproving ANALYZE-ID-004).
|
||||
if (string.IsNullOrEmpty(condition.DataField)
|
||||
&& string.Equals(condition.Operator, "not_exists", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (matchingEvents.Any())
|
||||
return (false, "event type present");
|
||||
|
||||
return (true, new Dictionary<string, object>
|
||||
{
|
||||
["eventType"] = condition.EventType,
|
||||
["count"] = 0
|
||||
});
|
||||
}
|
||||
|
||||
if (!matchingEvents.Any())
|
||||
return (false, "no matching events");
|
||||
|
||||
@@ -474,16 +491,26 @@ namespace AutopilotMonitor.Functions.Services
|
||||
// Calculate how long this phase lasted
|
||||
DateTime phaseEnd;
|
||||
string? phaseEndEventId = null;
|
||||
EnrollmentEvent? phaseEndEvent = null;
|
||||
if (i + 1 < phaseEvents.Count)
|
||||
{
|
||||
phaseEnd = phaseEvents[i + 1].Timestamp;
|
||||
phaseEndEventId = phaseEvents[i + 1].EventId;
|
||||
phaseEndEvent = phaseEvents[i + 1];
|
||||
phaseEnd = phaseEndEvent.Timestamp;
|
||||
phaseEndEventId = phaseEndEvent.EventId;
|
||||
}
|
||||
else
|
||||
{
|
||||
phaseEnd = DateTime.UtcNow; // Phase is still active
|
||||
phaseEnd = DateTime.UtcNow; // Phase is still active — the end carries no provenance
|
||||
}
|
||||
|
||||
// A duration is only as good as the weaker of its two endpoints: a reader-zone
|
||||
// fallback timestamp can be hours off, which turned a 20-minute DeviceSetup into a
|
||||
// 3 h "ESP Blocking App Timeout" (ANALYZE-ESP-001).
|
||||
if (HasReaderZoneFallbackTimestamp(evt))
|
||||
return (false, UnmeasurableDurationEvidence("phase duration", "start", evt, evt));
|
||||
if (phaseEndEvent != null && HasReaderZoneFallbackTimestamp(phaseEndEvent))
|
||||
return (false, UnmeasurableDurationEvidence("phase duration", "end", evt, phaseEndEvent));
|
||||
|
||||
var durationSeconds = (phaseEnd - evt.Timestamp).TotalSeconds;
|
||||
|
||||
return (true, new Dictionary<string, object>
|
||||
@@ -511,6 +538,38 @@ namespace AutopilotMonitor.Functions.Services
|
||||
return $"{ts.Seconds}s";
|
||||
}
|
||||
|
||||
// ===== Timestamp provenance of CMTrace-derived events =====
|
||||
// IME-log-derived events (esp_phase_changed, app_install_*, …) carry data.sourceOffsetOrigin:
|
||||
// "bias" | "calibrated" | "line-anchored" | "reader-zone-fallback". The last one means the
|
||||
// agent could not determine the log writer's timezone and assumed its own, so the
|
||||
// Timestamp may be off by whole hours. Agent-native events carry no tag and are trusted.
|
||||
|
||||
/// <summary>Data key written by the agent's IME log adapter for CMTrace-derived events.</summary>
|
||||
internal const string SourceOffsetOriginField = "sourceOffsetOrigin";
|
||||
/// <summary>Origin value that makes a timestamp unusable for an elapsed-duration measurement.</summary>
|
||||
internal const string ReaderZoneFallbackOrigin = "reader-zone-fallback";
|
||||
|
||||
private static bool HasReaderZoneFallbackTimestamp(EnrollmentEvent evt)
|
||||
=> string.Equals(GetDataFieldValue(evt, SourceOffsetOriginField), ReaderZoneFallbackOrigin, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Non-match evidence for a duration whose <paramref name="endpoint"/> ("start" | "end")
|
||||
/// timestamp is a reader-zone fallback. <paramref name="anchor"/> is the event the evaluator
|
||||
/// normally reports as its match (eventId/sequence), <paramref name="offender"/> the endpoint
|
||||
/// event carrying the fallback tag.
|
||||
/// </summary>
|
||||
private static Dictionary<string, object> UnmeasurableDurationEvidence(
|
||||
string what, string endpoint, EnrollmentEvent anchor, EnrollmentEvent offender)
|
||||
=> new()
|
||||
{
|
||||
["reason"] = $"{what} not measurable: {endpoint} timestamp derived from reader-zone fallback",
|
||||
["timestampProvenance"] = ReaderZoneFallbackOrigin,
|
||||
["provenanceEndpoint"] = endpoint,
|
||||
["provenanceEventId"] = offender.EventId ?? string.Empty,
|
||||
["eventId"] = anchor.EventId ?? string.Empty,
|
||||
["sequence"] = anchor.Sequence,
|
||||
};
|
||||
|
||||
private bool EvaluateConfidenceFactor(ConfidenceFactor factor, List<EnrollmentEvent> events, Dictionary<string, object> matchedConditions)
|
||||
{
|
||||
if (string.IsNullOrEmpty(factor.Condition))
|
||||
@@ -574,7 +633,7 @@ namespace AutopilotMonitor.Functions.Services
|
||||
return string.Equals(evt.EventType, eventType, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private string? GetDataFieldValue(EnrollmentEvent evt, string dataField)
|
||||
private static string? GetDataFieldValue(EnrollmentEvent evt, string dataField)
|
||||
{
|
||||
if (evt.Data == null || string.IsNullOrEmpty(dataField))
|
||||
return null;
|
||||
@@ -785,6 +844,11 @@ namespace AutopilotMonitor.Functions.Services
|
||||
.Where(e => completionEventTypes.Contains(e.EventType ?? string.Empty))
|
||||
.ToList();
|
||||
|
||||
// First pair skipped because one endpoint is a reader-zone fallback timestamp (see
|
||||
// HasReaderZoneFallbackTimestamp). Other apps stay measurable; the skip only becomes
|
||||
// the reported reason when nothing else matched.
|
||||
Dictionary<string, object>? unmeasurable = null;
|
||||
|
||||
foreach (var completionEvent in completionEvents)
|
||||
{
|
||||
var appId = GetDataFieldValue(completionEvent, "appId");
|
||||
@@ -803,6 +867,17 @@ namespace AutopilotMonitor.Functions.Services
|
||||
if (startEvent == null)
|
||||
continue;
|
||||
|
||||
if (HasReaderZoneFallbackTimestamp(startEvent))
|
||||
{
|
||||
unmeasurable ??= UnmeasurableDurationEvidence("app install duration", "start", completionEvent, startEvent);
|
||||
continue;
|
||||
}
|
||||
if (HasReaderZoneFallbackTimestamp(completionEvent))
|
||||
{
|
||||
unmeasurable ??= UnmeasurableDurationEvidence("app install duration", "end", completionEvent, completionEvent);
|
||||
continue;
|
||||
}
|
||||
|
||||
var durationSeconds = Math.Max(0, (completionEvent.Timestamp - startEvent.Timestamp).TotalSeconds);
|
||||
|
||||
if (!MatchesOperator(durationSeconds.ToString(), condition.Operator, condition.Value))
|
||||
@@ -823,6 +898,9 @@ namespace AutopilotMonitor.Functions.Services
|
||||
});
|
||||
}
|
||||
|
||||
if (unmeasurable != null)
|
||||
return (false, unmeasurable);
|
||||
|
||||
return (false, "no app install duration matched");
|
||||
}
|
||||
|
||||
|
||||
@@ -112,7 +112,8 @@ namespace AutopilotMonitor.Functions.Services
|
||||
"LastUpdated", "UpdatedBy", "OnboardedAt", "OnboardedBy",
|
||||
"HomedAppClientId", "LastAuthClientId", "LastAuthClientIdSince",
|
||||
"PlanTier", "TrialExpiresUtc", "TrialStartedUtc", "TrialConsumed", "TrialGrantedBy",
|
||||
"ProDowngradedUtc", "MaxDelegatedTenantsOverride", "McpUsagePlanOverride",
|
||||
"ProDowngradedUtc", "MaxDelegatedTenantsOverride", "McpUsagePlanOverride", "PayingCustomer",
|
||||
"ManagedByProTenantId",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
@@ -159,7 +160,7 @@ namespace AutopilotMonitor.Functions.Services
|
||||
"HomedAppClientId", "LastAuthClientId", "LastAuthClientIdSince",
|
||||
"OnboardedBy", "OnboardedAt",
|
||||
"PlanTier", "TrialExpiresUtc", "TrialStartedUtc", "TrialConsumed", "TrialGrantedBy",
|
||||
"ProDowngradedUtc", "MaxDelegatedTenantsOverride", "McpUsagePlanOverride",
|
||||
"ProDowngradedUtc", "MaxDelegatedTenantsOverride", "McpUsagePlanOverride", "PayingCustomer",
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, PropertyInfo> ModelProperties =
|
||||
@@ -507,8 +508,9 @@ namespace AutopilotMonitor.Functions.Services
|
||||
"HomedAppClientId" => "system-owned — written only by the app-homing flow",
|
||||
"LastAuthClientId" or "LastAuthClientIdSince" => "system-owned auth provenance",
|
||||
"PlanTier" or "TrialExpiresUtc" or "TrialStartedUtc" or "TrialConsumed" or "TrialGrantedBy"
|
||||
or "MaxDelegatedTenantsOverride" or "McpUsagePlanOverride"
|
||||
or "MaxDelegatedTenantsOverride" or "McpUsagePlanOverride" or "PayingCustomer"
|
||||
=> "mutable only via the dedicated plan/trial endpoints",
|
||||
"ManagedByProTenantId" => "read-time projection of the delegation state — never stored",
|
||||
_ => "not writable via the field patch",
|
||||
};
|
||||
|
||||
|
||||
@@ -12,20 +12,49 @@ namespace AutopilotMonitor.Functions.Services
|
||||
/// <summary>
|
||||
/// Service for managing tenant-specific configuration.
|
||||
/// Caching and business logic layer — delegates storage to IConfigRepository.
|
||||
///
|
||||
/// Every configuration that leaves this service through a READ path carries the load-time projection
|
||||
/// <see cref="TenantConfiguration.ManagedByProTenantId"/> (see <see cref="ManagedTenantProIndex"/>): it is
|
||||
/// applied on cache hits and misses alike, so its staleness is bounded by the index TTL alone, and it is
|
||||
/// never applied to a synthesized default (a tenant without a row can never be projected as Pro).
|
||||
/// </summary>
|
||||
public class TenantConfigurationService
|
||||
{
|
||||
private readonly IConfigRepository _configRepo;
|
||||
private readonly ILogger<TenantConfigurationService> _logger;
|
||||
private readonly IMemoryCache _cache;
|
||||
private readonly ManagedTenantProIndex _proIndex;
|
||||
|
||||
private static readonly TimeSpan CacheDuration = TimeSpan.FromMinutes(5);
|
||||
|
||||
public TenantConfigurationService(IConfigRepository configRepo, ILogger<TenantConfigurationService> logger, IMemoryCache cache)
|
||||
public TenantConfigurationService(
|
||||
IConfigRepository configRepo,
|
||||
ILogger<TenantConfigurationService> logger,
|
||||
IMemoryCache cache,
|
||||
ManagedTenantProIndex proIndex)
|
||||
{
|
||||
_configRepo = configRepo;
|
||||
_logger = logger;
|
||||
_cache = cache;
|
||||
_proIndex = proIndex;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test seam — no delegation index: no tenant is ever projected as managed. Production DI always
|
||||
/// resolves the four-argument constructor (the longest satisfiable one).
|
||||
/// </summary>
|
||||
public TenantConfigurationService(IConfigRepository configRepo, ILogger<TenantConfigurationService> logger, IMemoryCache cache)
|
||||
: this(configRepo, logger, cache, ManagedTenantProIndex.None)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Applies the read-time projection (see the class remarks). Idempotent; null passes through.</summary>
|
||||
private async Task<TenantConfiguration?> ProjectAsync(TenantConfiguration? config)
|
||||
{
|
||||
if (config == null)
|
||||
return null;
|
||||
config.ManagedByProTenantId = await _proIndex.GetConferringOwnerAsync(config.TenantId);
|
||||
return config;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -43,7 +72,7 @@ namespace AutopilotMonitor.Functions.Services
|
||||
|
||||
if (_cache.TryGetValue(cacheKey, out TenantConfiguration? cachedConfig) && cachedConfig != null)
|
||||
{
|
||||
return cachedConfig;
|
||||
return (await ProjectAsync(cachedConfig))!;
|
||||
}
|
||||
|
||||
try
|
||||
@@ -54,7 +83,7 @@ namespace AutopilotMonitor.Functions.Services
|
||||
if (config != null)
|
||||
{
|
||||
_cache.Set(cacheKey, config, CacheDuration);
|
||||
return config;
|
||||
return (await ProjectAsync(config))!;
|
||||
}
|
||||
|
||||
// Configuration not found - create and save default immediately
|
||||
@@ -197,13 +226,13 @@ namespace AutopilotMonitor.Functions.Services
|
||||
var cacheKey = $"tenant-config:{tenantId}";
|
||||
|
||||
if (_cache.TryGetValue(cacheKey, out TenantConfiguration? cachedConfig) && cachedConfig != null)
|
||||
return cachedConfig;
|
||||
return await ProjectAsync(cachedConfig);
|
||||
|
||||
var config = await _configRepo.GetTenantConfigurationAsync(tenantId);
|
||||
if (config != null)
|
||||
_cache.Set(cacheKey, config, CacheDuration);
|
||||
|
||||
return config;
|
||||
return await ProjectAsync(config);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -224,7 +253,7 @@ namespace AutopilotMonitor.Functions.Services
|
||||
if (config != null)
|
||||
_cache.Set($"tenant-config:{tenantId}", config, CacheDuration);
|
||||
|
||||
return config;
|
||||
return await ProjectAsync(config);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -261,7 +290,10 @@ namespace AutopilotMonitor.Functions.Services
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _configRepo.GetAllTenantConfigurationsAsync();
|
||||
var configs = await _configRepo.GetAllTenantConfigurationsAsync();
|
||||
foreach (var config in configs)
|
||||
await ProjectAsync(config);
|
||||
return configs;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -279,7 +311,10 @@ namespace AutopilotMonitor.Functions.Services
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _configRepo.GetTenantConfigurationsPageAsync(pageSize, continuation);
|
||||
var page = await _configRepo.GetTenantConfigurationsPageAsync(pageSize, continuation);
|
||||
foreach (var config in page.Items)
|
||||
await ProjectAsync(config);
|
||||
return page;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -38,41 +38,55 @@ namespace AutopilotMonitor.Functions.Services
|
||||
_time = time;
|
||||
}
|
||||
|
||||
private static readonly EditionResolution CommunityResolution =
|
||||
new(TenantEdition.Community, EditionSource.Community, OwnPro: false);
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the tenant's effective edition. Uses the strict point-read
|
||||
/// (<see cref="TenantConfigurationService.GetConfigurationIfExistsAsync"/>) so an
|
||||
/// Resolves the tenant's effective edition, its source and its own standing. Uses the strict
|
||||
/// point-read (<see cref="TenantConfigurationService.GetConfigurationIfExistsAsync"/>) so an
|
||||
/// entitlement check can never materialize a tenant-config row. No row / any error →
|
||||
/// Community (fail-closed).
|
||||
/// </summary>
|
||||
public virtual async Task<TenantEdition> GetEditionAsync(string? tenantId)
|
||||
public virtual async Task<EditionResolution> GetResolutionAsync(string? tenantId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(tenantId))
|
||||
return TenantEdition.Community;
|
||||
return CommunityResolution;
|
||||
|
||||
try
|
||||
{
|
||||
var config = await _configService.GetConfigurationIfExistsAsync(tenantId);
|
||||
if (config == null)
|
||||
return TenantEdition.Community;
|
||||
return CommunityResolution;
|
||||
|
||||
return ResolveEdition(config, _time.GetUtcNow().UtcDateTime);
|
||||
return Resolve(config, _time.GetUtcNow().UtcDateTime);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"[Entitlement] Edition resolution failed for tenant {TenantId} — treating as Community (fail-closed)",
|
||||
tenantId);
|
||||
return TenantEdition.Community;
|
||||
return CommunityResolution;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Resolves the tenant's effective entitlement set (fail-closed → Community values).</summary>
|
||||
/// <summary>The effective edition only — see <see cref="GetResolutionAsync"/>.</summary>
|
||||
public virtual async Task<TenantEdition> GetEditionAsync(string? tenantId)
|
||||
=> (await GetResolutionAsync(tenantId)).Edition;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the tenant's effective entitlement set (fail-closed → Community values). Conferred Pro
|
||||
/// yields the Pro set WITHOUT the delegation right (see <see cref="FeatureEntitlementCatalog.Get(EditionResolution)"/>).
|
||||
/// </summary>
|
||||
public virtual async Task<EditionEntitlements> GetEntitlementsAsync(string? tenantId)
|
||||
=> FeatureEntitlementCatalog.Get(await GetEditionAsync(tenantId));
|
||||
=> FeatureEntitlementCatalog.Get(await GetResolutionAsync(tenantId));
|
||||
|
||||
/// <summary>Pure resolution (edition + source + own standing) for callers that already hold the config.</summary>
|
||||
public static EditionResolution Resolve(TenantConfiguration config, DateTime nowUtc)
|
||||
=> FeatureEntitlementCatalog.Resolve(config, nowUtc);
|
||||
|
||||
/// <summary>Pure edition resolution for callers that already hold the config.</summary>
|
||||
public static TenantEdition ResolveEdition(TenantConfiguration config, DateTime nowUtc)
|
||||
=> FeatureEntitlementCatalog.ResolveEdition(config.PlanTier, config.TrialExpiresUtc, nowUtc);
|
||||
=> FeatureEntitlementCatalog.ResolveEdition(config, nowUtc);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the OOBE bootstrap feature is effectively enabled for this config: included in
|
||||
@@ -82,17 +96,18 @@ namespace AutopilotMonitor.Functions.Services
|
||||
/// the feature off automatically.
|
||||
/// </summary>
|
||||
public static bool IsBootstrapEnabled(TenantConfiguration config, DateTime nowUtc)
|
||||
=> FeatureEntitlementCatalog.Get(ResolveEdition(config, nowUtc)).BootstrapIncluded
|
||||
=> FeatureEntitlementCatalog.Get(Resolve(config, nowUtc)).BootstrapIncluded
|
||||
|| config.BootstrapTokenEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// The effective delegated ("MSP") tenant slot limit: the Global Admin override when set (it applies
|
||||
/// regardless of edition — a package can be provisioned ahead of the plan flip; USING delegation still
|
||||
/// needs Pro via DelegatedAdminAllowed), else the edition's catalog value (Community 0, Pro 2).
|
||||
/// needs Pro via DelegatedAdminAllowed), else the catalog value of the tenant's OWN standing
|
||||
/// (Community 0, Pro 2; conferred Pro 0 — a managed tenant gets no slots from its manager).
|
||||
/// </summary>
|
||||
public static int GetMaxDelegatedTenants(TenantConfiguration config, DateTime nowUtc)
|
||||
=> config.MaxDelegatedTenantsOverride
|
||||
?? FeatureEntitlementCatalog.Get(ResolveEdition(config, nowUtc)).MaxDelegatedTenants;
|
||||
?? FeatureEntitlementCatalog.Get(Resolve(config, nowUtc)).MaxDelegatedTenants;
|
||||
|
||||
/// <summary>Cached read-time variant of <see cref="GetMaxDelegatedTenants"/>. No row / any error ⇒ 0 (fail-closed).</summary>
|
||||
public virtual async Task<int> GetMaxDelegatedTenantsAsync(string? homeTenantId)
|
||||
@@ -122,7 +137,7 @@ namespace AutopilotMonitor.Functions.Services
|
||||
public static string GetMcpUsagePlanName(TenantConfiguration config, DateTime nowUtc)
|
||||
{
|
||||
var overridePlan = NormalizePlanName(config.McpUsagePlanOverride);
|
||||
return overridePlan ?? FeatureEntitlementCatalog.Get(ResolveEdition(config, nowUtc)).McpUsagePlanName;
|
||||
return overridePlan ?? FeatureEntitlementCatalog.Get(Resolve(config, nowUtc)).McpUsagePlanName;
|
||||
}
|
||||
|
||||
/// <summary>Trimmed lower-case plan name, or null for blank input.</summary>
|
||||
@@ -159,7 +174,7 @@ namespace AutopilotMonitor.Functions.Services
|
||||
/// opt-in toggle (<see cref="TenantConfiguration.UnrestrictedMode"/>).
|
||||
/// </summary>
|
||||
public static bool IsUnrestrictedModeActive(TenantConfiguration config, DateTime nowUtc)
|
||||
=> FeatureEntitlementCatalog.Get(ResolveEdition(config, nowUtc)).UnrestrictedModeAvailable
|
||||
=> FeatureEntitlementCatalog.Get(Resolve(config, nowUtc)).UnrestrictedModeAvailable
|
||||
&& config.UnrestrictedModeEnabled
|
||||
&& config.UnrestrictedMode;
|
||||
|
||||
|
||||
@@ -364,3 +364,45 @@ describe('accessGuard — 429 (rate limit) and caching', () => {
|
||||
expect(fetchFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('accessGuard — application principals (app-only tokens)', () => {
|
||||
// A service principal calls with a client-credentials token it obtained from Entra directly: no upn,
|
||||
// idtyp=app, the client id in appid (v1) / azp (v2). The guard keys it as app:<client-id> and lets the
|
||||
// backend decide membership — exactly like a person's UPN.
|
||||
let appSeed = 0;
|
||||
const uniqueAppId = () => `0000000${++appSeed}-0000-4000-8000-000000000000`.slice(-36);
|
||||
const appToken = (appId: string, claim: 'appid' | 'azp' = 'appid') =>
|
||||
makeToken({ idtyp: 'app', [claim]: appId, oid: 'sp-object-id', tid: 'tenant-1', roles: ['access_as_application'], exp: futureExp() });
|
||||
|
||||
it('admits an app-only token the backend allows and keys the caller on app:<client-id>', async () => {
|
||||
const appId = uniqueAppId();
|
||||
const fetchFn = stubBackend({ body: { allowed: true, accessGrant: 'AllMembers', upn: `app:${appId}` } });
|
||||
|
||||
const out = await runGuard(mockReq(`Bearer ${appToken(appId, 'azp')}`));
|
||||
|
||||
expect(out.nextCalled).toBe(true);
|
||||
expect(fetchFn).toHaveBeenCalledTimes(1);
|
||||
expect(out.ctx?.ga).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects an app-only token without idtyp (a token without any principal)', async () => {
|
||||
const fetchFn = stubBackend({ body: { allowed: true } });
|
||||
const out = await runGuard(mockReq(`Bearer ${makeToken({ appid: uniqueAppId(), oid: 'x', exp: futureExp() })}`));
|
||||
expect(out.status).toBe(401);
|
||||
expect(fetchFn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('names the service principal and the Members fix in a denial', async () => {
|
||||
const appId = uniqueAppId();
|
||||
stubBackend({ body: { allowed: false, reason: 'Service principal not enabled for MCP usage' } });
|
||||
|
||||
const out = await runGuard(mockReq(`Bearer ${appToken(appId)}`));
|
||||
|
||||
expect(out.status).toBe(403);
|
||||
const body = out.body as { error: string; message: string };
|
||||
expect(body.error).toBe('Service principal not enabled for MCP usage');
|
||||
expect(body.message).toContain(appId);
|
||||
expect(body.message).toMatch(/Members/);
|
||||
expect(body.message).not.toMatch(/whitelist/i);
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user