mirror of
https://github.com/okieselbach/AutopilotMonitor.git
synced 2026-10-25 13:10:13 +00:00
Compare commits
88 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c26eca2f01 | |||
| 9f1879a9f3 | |||
| c24c7bf7ef | |||
| 5fac3d6004 | |||
| 7605d2e9f5 | |||
| 7bf5412d63 | |||
| b53ceb1a7c | |||
| 647581b4ff | |||
| db9b1995bc | |||
| 7563435837 | |||
| e39f2abb61 | |||
| 47dad7143f | |||
| d81f41dc72 | |||
| cc6be10532 | |||
| 0ac548bfce | |||
| 9c1d0586ef | |||
| 21ec5e4773 | |||
| e4a5a6654d | |||
| 01bc35aa97 | |||
| e33d85c01d | |||
| 4e73ba8900 | |||
| 4df52b3da9 | |||
| 844d86410c | |||
| 9514e1033d | |||
| b2236bf65f | |||
| 31535b07e0 | |||
| 066b6e6f04 | |||
| a1e2b76a9f | |||
| 29e5b8251d | |||
| 02168a5c55 | |||
| a6b6661320 | |||
| 0c72666a7a | |||
| 9023321db9 | |||
| 7ef097529c | |||
| e7df69efe4 | |||
| 2c7efa2733 | |||
| 2742549827 | |||
| 3c45f5cb09 | |||
| d5d1d7bfbd | |||
| f4e2088b69 | |||
| 55425058a8 | |||
| eec0d17607 | |||
| 43f5304ba4 | |||
| b21472dd8c | |||
| e3991d55be | |||
| 864d1ed31e | |||
| 76ef1e53ca | |||
| 7dd298f04e | |||
| 66452621c6 | |||
| 0b23d93957 | |||
| 4281a6d81b | |||
| fe919a51aa | |||
| 0dcf0eb503 | |||
| e2fb99d5d8 | |||
| a3ee613b60 | |||
| d2197c6a57 | |||
| e5997bc50e | |||
| 75138016ce | |||
| fc4772efb0 | |||
| 0bde428fa0 | |||
| 16ca3a059c | |||
| 1bfc80e6db | |||
| fa705a2ef6 | |||
| 81f807e124 | |||
| a4f7c88785 | |||
| 54259f070f | |||
| 26cef3ab06 | |||
| 00ad230ffe | |||
| 3d920a8113 | |||
| f6eac1964a | |||
| e1b5b9d163 | |||
| 094833f831 | |||
| 3579ce0add | |||
| 0188860d1c | |||
| 871a1ac059 | |||
| 298a182fbb | |||
| e71223507c | |||
| 02187f0f3c | |||
| 3e2f62daeb | |||
| c8b8a8dbb4 | |||
| 9e4c5f11c5 | |||
| b16e72c10e | |||
| 5cb9b0b30b | |||
| c925001a8a | |||
| e494334720 | |||
| 1554540431 | |||
| fef09690d2 | |||
| 3a975fa74f |
+1
-1
Submodule .claude/commands updated: e8b8c08c1b...d004f83c8a
@@ -0,0 +1,51 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Returns the request headers that authorize an Azure Storage REST call with Microsoft Entra.
|
||||
|
||||
.DESCRIPTION
|
||||
One place for the storage OAuth contract shared by every publisher in this repo -- the
|
||||
agent ZIP and MSI, the customer bootstrap scripts, the version manifests and the build
|
||||
counters. Resource id, the az invocation, the service version and the failure message
|
||||
live here so they cannot drift between call sites.
|
||||
|
||||
Identity comes from whatever `az login` established: the federated GitHub OIDC principal
|
||||
in CI (azure/login, subject repo:okieselbach/AutopilotMonitor:ref:refs/heads/main), the
|
||||
operator's own account for the local build. No secret is read, stored or passed around.
|
||||
|
||||
x-ms-version is MANDATORY here, not decoration: Entra-authorized requests are rejected
|
||||
below 2017-11-09, and Table requests without a SAS must carry the header at all. 2021-08-06
|
||||
is old enough to be deployed in every region and new enough for everything we send.
|
||||
|
||||
Callers merge the result into their own headers -- `$auth + @{ ... }` yields a new
|
||||
hashtable per request, so nothing is shared across uploads:
|
||||
|
||||
$auth = & "$PSScriptRoot/Get-StorageAuthHeaders.ps1"
|
||||
Invoke-RestMethod -Uri $url -Method Put -Headers ($auth + @{ 'x-ms-blob-type' = 'BlockBlob' }) -Body $bytes
|
||||
|
||||
Acquire once per step and reuse: every call shells out to az (~1s) and the token is valid
|
||||
for the lifetime of a job.
|
||||
|
||||
.OUTPUTS
|
||||
[hashtable] Authorization + x-ms-version.
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param()
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# The data-plane resource, not management.azure.com -- a management token is accepted by
|
||||
# neither the blob nor the table endpoint.
|
||||
$token = az account get-access-token --resource https://storage.azure.com --query accessToken -o tsv 2>$null
|
||||
|
||||
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($token)) {
|
||||
throw ('Could not acquire an Azure Storage token. In CI this means the azure/login step ' +
|
||||
'is missing or its federated credential does not cover this ref; locally, run ' +
|
||||
'`az login`. A token alone is not enough: the principal also needs Storage Blob ' +
|
||||
'Data Contributor on the container it writes, and Storage Table Data Contributor ' +
|
||||
'on the table -- a missing role shows up later as HTTP 403 AuthorizationPermissionMismatch.')
|
||||
}
|
||||
|
||||
return @{
|
||||
'Authorization' = "Bearer $token"
|
||||
'x-ms-version' = '2021-08-06'
|
||||
}
|
||||
@@ -12,52 +12,78 @@
|
||||
lands a consistent set (ZIP + manifest + scripts).
|
||||
|
||||
Both callers run the same code. The scripts on the download alias are the live
|
||||
copy the WDP bootstrap MSI (Invoke-BootstrapDownload.ps1) downloads on every
|
||||
enrolling device, so "current" is a correctness property, not cosmetics.
|
||||
copy the stage-1 loader downloads on every enrolling device, whether it came from
|
||||
Intune or from the bootstrap MSI, so "current" is a correctness property, not
|
||||
cosmetics.
|
||||
|
||||
Steps, in order:
|
||||
1. Parse $ScriptVersion from the bootstrap source.
|
||||
2. Render the -Dev variant by literal substitution of the two URL/manifest
|
||||
1. Parse $ScriptVersion from the loader and the bootstrap source.
|
||||
2. Render the -Dev variants by literal substitution of the URL/manifest
|
||||
defaults. A missing anchor is a hard failure -- a silently un-substituted
|
||||
dev script would point the dev fleet at the stable agent.
|
||||
3. Version-bump guard: if the published bootstrap differs from the source
|
||||
but carries the same $ScriptVersion, abort. Otherwise the docs badge,
|
||||
3. Version-bump guard: if a published script differs from its source but
|
||||
carries the same $ScriptVersion, abort. Otherwise the docs badge,
|
||||
version.json.bootstrapVersion and the portal's "your script is outdated"
|
||||
hint would all keep asserting a version that is no longer what ships.
|
||||
4. Upload every script blob with Cache-Control: no-cache (they rotate in
|
||||
4. Build the publish set (loader, bootstrap, both dev renders, the extras).
|
||||
5. Authenticode-sign every script (see -SigningToken). Signing is the LAST
|
||||
transformation: it covers the exact CRLF/UTF-8 bytes that get uploaded,
|
||||
and nothing may touch them afterwards or the signature breaks.
|
||||
6. Upload every script blob with Cache-Control: no-cache (they rotate in
|
||||
place), mirrored fail-soft to the legacy account.
|
||||
5. Reconcile the two version oracles: version.json.bootstrapVersion
|
||||
(read-modify-write under If-Match, so a concurrent agent release cannot
|
||||
lose its agent fields) and AdminConfiguration.LatestBootstrapV2ScriptVersion.
|
||||
6. Verify through the alias -- re-download each blob and compare SHA-256.
|
||||
7. Reconcile the version oracles: version.json.bootstrapVersion and
|
||||
.loaderVersion (read-modify-write under If-Match, so a concurrent agent
|
||||
release cannot lose its agent fields) and
|
||||
AdminConfiguration.LatestBootstrapV2ScriptVersion.
|
||||
8. Verify through the alias -- re-download each blob and compare SHA-256.
|
||||
|
||||
.PARAMETER SasToken
|
||||
Container SAS for the eu storage account with write permission. Leading '?' tolerated.
|
||||
Comparisons against a published script always strip its signature block first
|
||||
(Get-ComparableText). A signature carries a timestamp, so signed bytes differ on
|
||||
every run; without stripping, the bump guard and the drift check would report a
|
||||
change for every unchanged script.
|
||||
|
||||
.PARAMETER LegacySasToken
|
||||
Container SAS for the legacy account. Optional -- a mirror failure warns, never fails.
|
||||
|
||||
.PARAMETER TableSasToken
|
||||
Table SAS for AdminConfiguration. Optional -- omitted or 'XXX' skips the oracle update.
|
||||
The legacy account lives in a different tenant, so the ambient Entra identity cannot
|
||||
reach it; this is the only credential the publisher still takes.
|
||||
|
||||
.PARAMETER RepoRoot
|
||||
Repository root. Defaults to the parent of .github/scripts.
|
||||
|
||||
.PARAMETER DryRun
|
||||
Run every check and render, upload nothing.
|
||||
Run every check and render, upload nothing. A dry run signs when a token is supplied
|
||||
and skips signing when it is not: the PR gate runs this without any Azure login.
|
||||
|
||||
.PARAMETER SigningToken
|
||||
Azure Key Vault access token for AzureSignTool. MANDATORY for a real publish -- an
|
||||
unsigned customer script is not something this repo publishes. Together with
|
||||
-KeyVaultUrl and -CertificateName.
|
||||
|
||||
.PARAMETER ExpectedPublisher
|
||||
Optional -like pattern the signer subject must match after signing. Pins the publisher
|
||||
instead of accepting any trusted signature; the loader on the device pins the same way.
|
||||
|
||||
.PARAMETER SignedOutputDir
|
||||
Optional directory that receives a copy of every published file exactly as uploaded.
|
||||
Used by CI to offer the signed scripts as a build artifact for local inspection.
|
||||
|
||||
.EXAMPLE
|
||||
./Publish-BootstrapScripts.ps1 -DryRun
|
||||
|
||||
.EXAMPLE
|
||||
./Publish-BootstrapScripts.ps1 -SasToken $env:SAS -TableSasToken $env:TABLE_SAS
|
||||
./Publish-BootstrapScripts.ps1 -LegacySasToken $env:LEGACY_SAS -SigningToken $env:AKV_TOKEN `
|
||||
-KeyVaultUrl $env:KV_URL -CertificateName $env:CERT
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$SasToken,
|
||||
[string]$LegacySasToken,
|
||||
[string]$TableSasToken,
|
||||
[string]$RepoRoot,
|
||||
[string]$SigningToken,
|
||||
[string]$KeyVaultUrl,
|
||||
[string]$CertificateName,
|
||||
[string]$TimestampUrl = 'http://timestamp.acs.microsoft.com',
|
||||
[string]$ExpectedPublisher,
|
||||
[string]$SignedOutputDir,
|
||||
[switch]$DryRun
|
||||
)
|
||||
|
||||
@@ -66,9 +92,6 @@ $ErrorActionPreference = 'Stop'
|
||||
if (-not $RepoRoot) {
|
||||
$RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path
|
||||
}
|
||||
if (-not $DryRun -and [string]::IsNullOrWhiteSpace($SasToken)) {
|
||||
throw 'SasToken is required unless -DryRun is used.'
|
||||
}
|
||||
|
||||
$ContainerUrl = 'https://autopilotmonitoreu.blob.core.windows.net/agent'
|
||||
$LegacyContainerUrl = 'https://autopilotmonitor.blob.core.windows.net/agent'
|
||||
@@ -78,8 +101,23 @@ $TableUrl = "https://autopilotmonitoreu.table.core.windows.net/AdminCo
|
||||
$BootstrapSource = Join-Path $RepoRoot 'scripts/Bootstrap/Install-AutopilotMonitor.ps1'
|
||||
$BootstrapBlob = 'Install-AutopilotMonitor.ps1'
|
||||
$DevBlob = 'Install-AutopilotMonitor-Dev.ps1'
|
||||
# Stage 1. Assigned in Intune once, and embedded in the bootstrap MSI; it downloads the
|
||||
# bootstrap above on every device and verifies its publisher before running it.
|
||||
$LoaderSource = Join-Path $RepoRoot 'scripts/Bootstrap/Start-AutopilotMonitor.ps1'
|
||||
$LoaderBlob = 'Start-AutopilotMonitor.ps1'
|
||||
$LoaderDevBlob = 'Start-AutopilotMonitor-Dev.ps1'
|
||||
$ScriptContentType = 'text/plain; charset=utf-8'
|
||||
|
||||
$SigningEnabled = -not [string]::IsNullOrWhiteSpace($SigningToken)
|
||||
if (-not $DryRun -and -not $SigningEnabled) {
|
||||
throw ('Publishing requires -SigningToken (plus -KeyVaultUrl and -CertificateName): the ' +
|
||||
'loader on every device verifies the publisher of what it downloads, so an unsigned ' +
|
||||
'script would be rejected in the field. Only -DryRun may run without signing.')
|
||||
}
|
||||
if ($SigningEnabled -and ([string]::IsNullOrWhiteSpace($KeyVaultUrl) -or [string]::IsNullOrWhiteSpace($CertificateName))) {
|
||||
throw '-SigningToken needs -KeyVaultUrl and -CertificateName.'
|
||||
}
|
||||
|
||||
function Get-HttpStatus {
|
||||
param($ErrorRecord)
|
||||
if ($ErrorRecord.Exception.PSObject.Properties['Response'] -and $ErrorRecord.Exception.Response) {
|
||||
@@ -125,6 +163,132 @@ function Get-PublishBytes {
|
||||
return ,(New-Object System.Text.UTF8Encoding $false).GetBytes($normalised)
|
||||
}
|
||||
|
||||
# A PowerShell signature is appended as a comment block at the end of the file, so the
|
||||
# published bytes are "source + signature". Everything that compares a published script to
|
||||
# its source has to cut that block off first -- the signature carries a timestamp and is
|
||||
# therefore different on every publish, while the script above it is unchanged.
|
||||
function Remove-SignatureBlock {
|
||||
param([string]$Text)
|
||||
$marker = '# SIG # Begin signature block'
|
||||
$index = $Text.IndexOf($marker)
|
||||
if ($index -lt 0) { return $Text }
|
||||
return $Text.Substring(0, $index)
|
||||
}
|
||||
|
||||
# Comparison form: no signature, LF, no trailing blank lines. Used for "is the published
|
||||
# copy still this source" -- never for what gets uploaded.
|
||||
function Get-ComparableText {
|
||||
param([string]$Text)
|
||||
return (Remove-SignatureBlock $Text).Replace("`r`n", "`n").TrimEnd("`n")
|
||||
}
|
||||
|
||||
# Signs the publish set in place: each item's bytes are written to a work directory, signed
|
||||
# there, verified, and read back as the bytes that will be uploaded. Signing has to be the
|
||||
# last transformation -- the signature covers exactly these bytes, so nothing may normalise
|
||||
# or re-encode them afterwards.
|
||||
function Set-PublishSetSignature {
|
||||
param([object[]]$Items, [string]$WorkDir)
|
||||
|
||||
if (-not (Get-Command azuresigntool -ErrorAction SilentlyContinue)) {
|
||||
throw "azuresigntool is not on PATH. Install it with: dotnet tool install --global AzureSignTool --version 7.0.1"
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $WorkDir | Out-Null
|
||||
|
||||
$paths = @()
|
||||
foreach ($item in $Items) {
|
||||
$path = Join-Path $WorkDir $item.BlobName
|
||||
[System.IO.File]::WriteAllBytes($path, [byte[]]$item.Bytes)
|
||||
$paths += $path
|
||||
}
|
||||
|
||||
Write-Host "Signing $($paths.Count) script(s) with certificate '$CertificateName'..."
|
||||
& azuresigntool.exe sign --verbose `
|
||||
--azure-key-vault-url $KeyVaultUrl `
|
||||
--azure-key-vault-accesstoken $SigningToken `
|
||||
--azure-key-vault-certificate $CertificateName `
|
||||
--timestamp-rfc3161 $TimestampUrl `
|
||||
--file-digest sha256 `
|
||||
--description 'Autopilot Monitor bootstrap' `
|
||||
--description-url 'https://www.autopilotmonitor.com' `
|
||||
$paths
|
||||
|
||||
# Native tool: PowerShell does not throw on a non-zero exit, and an unnoticed signing
|
||||
# failure would publish unsigned scripts that every loader in the field then rejects.
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "azuresigntool failed with exit code $LASTEXITCODE -- nothing was uploaded."
|
||||
}
|
||||
|
||||
foreach ($item in $Items) {
|
||||
$path = Join-Path $WorkDir $item.BlobName
|
||||
$sig = Get-AuthenticodeSignature -FilePath $path
|
||||
if ($sig.Status -ne 'Valid') {
|
||||
throw "Signature on $($item.BlobName) is '$($sig.Status)', expected 'Valid'."
|
||||
}
|
||||
# Without a timestamp the signature dies with the certificate, and these scripts sit
|
||||
# on customer devices far longer than a certificate lifetime.
|
||||
if (-not $sig.TimeStamperCertificate) {
|
||||
throw "Signature on $($item.BlobName) carries no timestamp."
|
||||
}
|
||||
if ($ExpectedPublisher -and $sig.SignerCertificate.Subject -notlike $ExpectedPublisher) {
|
||||
throw "$($item.BlobName) was signed by '$($sig.SignerCertificate.Subject)', expected '$ExpectedPublisher'."
|
||||
}
|
||||
# Plain assignment, NO comma operator: the ',' elsewhere in this file exists because
|
||||
# PowerShell unrolls an array RETURNED from a function, which is not what a property
|
||||
# assignment does -- here it would wrap the byte[] in an Object[] of length 1 and the
|
||||
# upload would fail converting it back.
|
||||
$signedBytes = [System.IO.File]::ReadAllBytes($path)
|
||||
if ($signedBytes.Length -le $item.Bytes.Length) {
|
||||
throw ("Signed $($item.BlobName) is $($signedBytes.Length) bytes but the unsigned form " +
|
||||
"was $($item.Bytes.Length) -- a signature only ever adds bytes, so this is a " +
|
||||
'read-back bug, not a signing result.')
|
||||
}
|
||||
$item.Bytes = $signedBytes
|
||||
Write-Host " signed $($item.BlobName) ($($signedBytes.Length) bytes, signer $($sig.SignerCertificate.Subject.Split(',')[0]))"
|
||||
}
|
||||
}
|
||||
|
||||
# Aborts when a published script changed behaviour without a version bump. Consumers act on
|
||||
# the version (docs badge, version.json, the portal's outdated-script hint), so an unchanged
|
||||
# version has to mean unchanged behaviour.
|
||||
function Assert-VersionBump {
|
||||
param(
|
||||
[string]$BlobName,
|
||||
[string]$SourceContent,
|
||||
[string]$SourceOrigin,
|
||||
[string]$SourceVersion
|
||||
)
|
||||
|
||||
$publishedBytes = Get-PublishedBytes "$AliasUrl/$BlobName"
|
||||
if ($null -eq $publishedBytes) {
|
||||
Write-Host "No published $BlobName yet -- version-bump guard skipped (first publish)"
|
||||
return
|
||||
}
|
||||
|
||||
$publishedText = [System.Text.Encoding]::UTF8.GetString($publishedBytes)
|
||||
if ((Get-ComparableText $publishedText) -eq (Get-ComparableText $SourceContent)) {
|
||||
Write-Host "Published $BlobName is already this source (signature block aside)"
|
||||
return
|
||||
}
|
||||
|
||||
$publishedVersion = Get-BootstrapScriptVersion -Content $publishedText -Origin "$AliasUrl/$BlobName" -Optional
|
||||
|
||||
if ($null -eq $publishedVersion) {
|
||||
Write-Host "::warning::The published $BlobName is not a readable script (no ScriptVersion found). Republishing over it."
|
||||
} elseif ($publishedVersion -ne $SourceVersion) {
|
||||
Write-Host "Version bump: $publishedVersion -> $SourceVersion ($BlobName)"
|
||||
} elseif ((Get-CodeFingerprint -Text (Remove-SignatureBlock $publishedText) -Origin "$AliasUrl/$BlobName") -eq
|
||||
(Get-CodeFingerprint -Text $SourceContent -Origin $SourceOrigin)) {
|
||||
# Comments, typos in comments, reflow -- nothing a consumer of the version can act on.
|
||||
Write-Host "::warning::$BlobName changed in comments or formatting only; publishing under the unchanged version $SourceVersion."
|
||||
} else {
|
||||
throw ("Version-bump guard: $BlobName changed behaviour but ScriptVersion is still $SourceVersion. " +
|
||||
"Bump it in $SourceOrigin -- the docs badge, version.json and the " +
|
||||
'portal outdated-script hint all read that value, and customers decide from it whether ' +
|
||||
'to re-upload their Intune copy. Comment-only and formatting changes do not need a bump.')
|
||||
}
|
||||
}
|
||||
|
||||
function Get-BootstrapScriptVersion {
|
||||
param([string]$Content, [string]$Origin, [switch]$Optional)
|
||||
if ($Content -match '\$ScriptVersion\s*=\s*"([\d\.\-a-zA-Z]+)"') { return $Matches[1] }
|
||||
@@ -152,12 +316,16 @@ function Get-CodeFingerprint {
|
||||
return (($tokens | Where-Object { $ignored -notcontains $_.Kind.ToString() } | ForEach-Object { $_.Text }) -join "`n")
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ 1. source
|
||||
# ------------------------------------------------------------------ 1. sources
|
||||
$sourceContent = Get-Content $BootstrapSource -Raw
|
||||
$sourceBytes = Get-PublishBytes $sourceContent
|
||||
$scriptVersion = Get-BootstrapScriptVersion -Content $sourceContent -Origin $BootstrapSource
|
||||
Write-Host "Bootstrap script version: $scriptVersion"
|
||||
|
||||
$loaderContent = Get-Content $LoaderSource -Raw
|
||||
$loaderVersion = Get-BootstrapScriptVersion -Content $loaderContent -Origin $LoaderSource
|
||||
Write-Host "Loader script version: $loaderVersion"
|
||||
|
||||
# ------------------------------------------------------------------ 2. dev render
|
||||
$stableUrlLiteral = '$AgentDownloadUrl = "https://download.autopilotmonitor.com/agent/AutopilotMonitor-Agent.zip"'
|
||||
$devUrlLiteral = '$AgentDownloadUrl = "https://download.autopilotmonitor.com/agent/AutopilotMonitor-Agent-dev.zip"'
|
||||
@@ -170,33 +338,21 @@ if ($sourceContent.IndexOf($stableUrlLiteral) -lt 0 -or $sourceContent.IndexOf($
|
||||
$devContent = $sourceContent.Replace($stableUrlLiteral, $devUrlLiteral).Replace($stableManLiteral, $devManLiteral)
|
||||
Write-Host "Rendered $DevBlob (dev agent URL + version-dev.json)"
|
||||
|
||||
# ------------------------------------------------------------------ 3. bump guard
|
||||
$publishedBytes = Get-PublishedBytes "$AliasUrl/$BootstrapBlob"
|
||||
if ($null -eq $publishedBytes) {
|
||||
Write-Host 'No published bootstrap yet -- version-bump guard skipped (first publish)'
|
||||
} elseif ((Get-Sha256 $publishedBytes) -eq (Get-Sha256 $sourceBytes)) {
|
||||
Write-Host 'Published bootstrap is already byte-identical to the source'
|
||||
} else {
|
||||
$publishedText = [System.Text.Encoding]::UTF8.GetString($publishedBytes)
|
||||
$publishedVersion = Get-BootstrapScriptVersion -Content $publishedText -Origin "$AliasUrl/$BootstrapBlob" -Optional
|
||||
# The dev loader must fetch the dev bootstrap, or a dev device would run the stable chain.
|
||||
$stableLoaderLiteral = '$BootstrapUrl = "https://download.autopilotmonitor.com/agent/Install-AutopilotMonitor.ps1"'
|
||||
$devLoaderLiteral = '$BootstrapUrl = "https://download.autopilotmonitor.com/agent/Install-AutopilotMonitor-Dev.ps1"'
|
||||
|
||||
if ($null -eq $publishedVersion) {
|
||||
Write-Host "::warning::The published $BootstrapBlob is not a readable bootstrap script (no ScriptVersion found). Republishing over it."
|
||||
} elseif ($publishedVersion -ne $scriptVersion) {
|
||||
Write-Host "Version bump: $publishedVersion -> $scriptVersion"
|
||||
} elseif ((Get-CodeFingerprint -Text $publishedText -Origin "$AliasUrl/$BootstrapBlob") -eq
|
||||
(Get-CodeFingerprint -Text $sourceContent -Origin $BootstrapSource)) {
|
||||
# Comments, typos in comments, reflow -- nothing a consumer of the version can act on.
|
||||
Write-Host "::warning::$BootstrapBlob changed in comments or formatting only; publishing under the unchanged version $scriptVersion."
|
||||
} else {
|
||||
throw ("Version-bump guard: $BootstrapBlob changed behaviour but ScriptVersion is still $scriptVersion. " +
|
||||
"Bump it in $BootstrapSource -- the docs badge, version.json.bootstrapVersion and the " +
|
||||
'portal outdated-script hint all read that value, and customers decide from it whether ' +
|
||||
'to re-upload their Intune copy. Comment-only and formatting changes do not need a bump.')
|
||||
}
|
||||
if ($loaderContent.IndexOf($stableLoaderLiteral) -lt 0) {
|
||||
throw "Loader dev-render: anchor literal missing in $LoaderSource"
|
||||
}
|
||||
$devLoaderContent = $loaderContent.Replace($stableLoaderLiteral, $devLoaderLiteral)
|
||||
Write-Host "Rendered $LoaderDevBlob (points at $DevBlob)"
|
||||
|
||||
# ------------------------------------------------------------------ 4. upload
|
||||
# ------------------------------------------------------------------ 3. bump guards
|
||||
Assert-VersionBump -BlobName $BootstrapBlob -SourceContent $sourceContent -SourceOrigin $BootstrapSource -SourceVersion $scriptVersion
|
||||
Assert-VersionBump -BlobName $LoaderBlob -SourceContent $loaderContent -SourceOrigin $LoaderSource -SourceVersion $loaderVersion
|
||||
|
||||
# ------------------------------------------------------------------ 4. publish set
|
||||
# Sources beyond the bootstrap pair, read straight from the repo.
|
||||
$extraSources = @(
|
||||
@{ Path = 'scripts/Bootstrap/Test-ShouldBootstrapAgent.ps1'; BlobName = 'Test-ShouldBootstrapAgent.ps1' }
|
||||
@@ -206,20 +362,38 @@ $extraSources = @(
|
||||
# Uninstall-AutopilotMonitor.ps1 is deliberately NOT published: nothing links it, and
|
||||
# an unauthenticated uninstall script on the public download host is not a feature.
|
||||
|
||||
# Text is the unsigned publish form and stays the reference for every comparison against a
|
||||
# published copy; Bytes is what goes on the wire and carries the signature after step 4.
|
||||
$publishSet = [System.Collections.Generic.List[object]]::new()
|
||||
$publishSet.Add([pscustomobject]@{ BlobName = $BootstrapBlob; Bytes = $sourceBytes })
|
||||
$publishSet.Add([pscustomobject]@{ BlobName = $DevBlob; Bytes = (Get-PublishBytes $devContent) })
|
||||
$publishSet.Add([pscustomobject]@{ BlobName = $LoaderBlob; Text = $loaderContent; Bytes = (Get-PublishBytes $loaderContent) })
|
||||
$publishSet.Add([pscustomobject]@{ BlobName = $LoaderDevBlob; Text = $devLoaderContent; Bytes = (Get-PublishBytes $devLoaderContent) })
|
||||
$publishSet.Add([pscustomobject]@{ BlobName = $BootstrapBlob; Text = $sourceContent; Bytes = $sourceBytes })
|
||||
$publishSet.Add([pscustomobject]@{ BlobName = $DevBlob; Text = $devContent; Bytes = (Get-PublishBytes $devContent) })
|
||||
foreach ($extra in $extraSources) {
|
||||
$extraPath = Join-Path $RepoRoot $extra.Path
|
||||
if (-not (Test-Path $extraPath)) {
|
||||
throw "Publish source missing: $extraPath"
|
||||
}
|
||||
$publishSet.Add([pscustomobject]@{ BlobName = $extra.BlobName; Bytes = (Get-PublishBytes (Get-Content $extraPath -Raw)) })
|
||||
$extraText = Get-Content $extraPath -Raw
|
||||
$publishSet.Add([pscustomobject]@{ BlobName = $extra.BlobName; Text = $extraText; Bytes = (Get-PublishBytes $extraText) })
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ 5. sign
|
||||
# After this point the bytes are final. Normalising, re-encoding or rewriting a line ending
|
||||
# would invalidate the signature, and the device-side loader would refuse the script.
|
||||
if ($SigningEnabled) {
|
||||
Set-PublishSetSignature -Items $publishSet -WorkDir (Join-Path ([System.IO.Path]::GetTempPath()) "apm-publish-$PID")
|
||||
} else {
|
||||
Write-Host '::warning::No signing token supplied -- dry run continues with unsigned scripts.'
|
||||
}
|
||||
|
||||
$legacySas = if ($LegacySasToken) { $LegacySasToken.TrimStart('?') } else { '' }
|
||||
$writeSas = if ($SasToken) { $SasToken.TrimStart('?') } else { '' }
|
||||
|
||||
# Acquired lazily: a dry run must stay runnable without any Azure login -- the PR gate
|
||||
# (bootstrap-script-gates.yml) executes this script with -DryRun and never logs in.
|
||||
$authHeaders = if ($DryRun) { $null } else { & (Join-Path $PSScriptRoot 'Get-StorageAuthHeaders.ps1') }
|
||||
|
||||
# ------------------------------------------------------------------ 6. upload
|
||||
foreach ($item in $publishSet) {
|
||||
# Explicit type, not a convenience: an Object[] body is uploaded as space-separated
|
||||
# decimals rather than raw bytes, and every hash check still passes because [byte[]]
|
||||
@@ -227,11 +401,21 @@ foreach ($item in $publishSet) {
|
||||
[byte[]]$bytes = $item.Bytes
|
||||
$item | Add-Member -NotePropertyName Sha256 -NotePropertyValue (Get-Sha256 $bytes) -Force
|
||||
|
||||
# Exactly the bytes that go on the wire, for the CI artifact. Written in a dry run too:
|
||||
# that is the run an operator uses to inspect a signed script before it is published.
|
||||
if ($SignedOutputDir) {
|
||||
New-Item -ItemType Directory -Force -Path $SignedOutputDir | Out-Null
|
||||
[System.IO.File]::WriteAllBytes((Join-Path $SignedOutputDir $item.BlobName), $bytes)
|
||||
}
|
||||
|
||||
if ($DryRun) {
|
||||
# Doubles as a drift check: says per blob whether the alias already serves this source.
|
||||
# Doubles as a drift check: says per blob whether the alias already serves this
|
||||
# source. Compared as text without the signature block -- signed bytes differ on
|
||||
# every run, so a byte comparison would report drift for every unchanged script.
|
||||
$served = Get-PublishedBytes "$AliasUrl/$($item.BlobName)"
|
||||
$state = if ($null -eq $served) { 'MISSING on the alias' }
|
||||
elseif ((Get-Sha256 $served) -eq $item.Sha256) { 'already current' }
|
||||
elseif ((Get-ComparableText ([System.Text.Encoding]::UTF8.GetString($served))) -eq
|
||||
(Get-ComparableText $item.Text)) { 'already current' }
|
||||
else { 'STALE on the alias' }
|
||||
Write-Host " [dry-run] $($item.BlobName) ($($bytes.Length) bytes, sha256 $($item.Sha256)) -- $state"
|
||||
continue
|
||||
@@ -241,8 +425,18 @@ foreach ($item in $publishSet) {
|
||||
# with Front Door. Route caching is disabled there, but a stale script paired with a
|
||||
# fresh manifest would fail the bootstrap SHA check -- this keeps that class of bug
|
||||
# impossible even if caching is ever re-enabled.
|
||||
$headers = @{ 'x-ms-blob-type' = 'BlockBlob'; 'Content-Type' = $ScriptContentType; 'x-ms-blob-cache-control' = 'no-cache' }
|
||||
Invoke-RestMethod -Uri "$ContainerUrl/$($item.BlobName)?$writeSas" -Method Put -Headers $headers -Body $bytes | Out-Null
|
||||
#
|
||||
# Content-Disposition: without it a text/plain blob opens as a web page in every
|
||||
# browser, and the documented "download the script" step silently becomes "copy this
|
||||
# text". The header makes the link a download everywhere, and command-line clients
|
||||
# (the loader, the MSI, curl) ignore it.
|
||||
$headers = @{
|
||||
'x-ms-blob-type' = 'BlockBlob'
|
||||
'Content-Type' = $ScriptContentType
|
||||
'x-ms-blob-cache-control' = 'no-cache'
|
||||
'x-ms-blob-content-disposition' = ('attachment; filename="{0}"' -f $item.BlobName)
|
||||
}
|
||||
Invoke-RestMethod -Uri "$ContainerUrl/$($item.BlobName)" -Method Put -Headers ($authHeaders + $headers) -Body $bytes | Out-Null
|
||||
|
||||
# Read straight back from the blob (authoritative, no CDN in the way) before touching the
|
||||
# mirror or the next file. The alias verification at the end would catch a bad body too,
|
||||
@@ -266,7 +460,7 @@ foreach ($item in $publishSet) {
|
||||
}
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ 5. version oracles
|
||||
# ------------------------------------------------------------------ 7. version oracles
|
||||
# version.json is the agent manifest; only bootstrapVersion belongs to us. Read from the
|
||||
# blob (not the alias) for an authoritative ETag, write back under If-Match so a concurrent
|
||||
# agent release cannot lose its version/sha256 fields.
|
||||
@@ -278,11 +472,15 @@ if (-not $DryRun) {
|
||||
} else { [string]$manifestResp.Content }
|
||||
$manifest = $manifestRaw | ConvertFrom-Json
|
||||
|
||||
if ($manifest.bootstrapVersion -eq $scriptVersion) {
|
||||
Write-Host "version.json already reports bootstrapVersion $scriptVersion"
|
||||
if ($manifest.bootstrapVersion -eq $scriptVersion -and $manifest.loaderVersion -eq $loaderVersion) {
|
||||
Write-Host "version.json already reports bootstrapVersion $scriptVersion and loaderVersion $loaderVersion"
|
||||
} else {
|
||||
$etag = '"' + ([string]($manifestResp.Headers['ETag'] | Select-Object -First 1)).Trim('"') + '"'
|
||||
$manifest | Add-Member -NotePropertyName 'bootstrapVersion' -NotePropertyValue $scriptVersion -Force
|
||||
# Additive: no consumer reads loaderVersion yet. It exists so support can tell
|
||||
# which stage-1 file a device was assigned -- stage 2 is always current by
|
||||
# construction, so its version says nothing about the customer's Intune copy.
|
||||
$manifest | Add-Member -NotePropertyName 'loaderVersion' -NotePropertyValue $loaderVersion -Force
|
||||
$body = [System.Text.Encoding]::UTF8.GetBytes(($manifest | ConvertTo-Json -Compress))
|
||||
$manifestHeaders = @{
|
||||
'x-ms-blob-type' = 'BlockBlob'
|
||||
@@ -290,8 +488,8 @@ if (-not $DryRun) {
|
||||
'x-ms-blob-cache-control' = 'no-cache'
|
||||
'If-Match' = $etag
|
||||
}
|
||||
Invoke-RestMethod -Uri "$ContainerUrl/version.json?$writeSas" -Method Put -Headers $manifestHeaders -Body $body | Out-Null
|
||||
Write-Host "version.json bootstrapVersion -> $scriptVersion (agent fields untouched)"
|
||||
Invoke-RestMethod -Uri "$ContainerUrl/version.json" -Method Put -Headers ($authHeaders + $manifestHeaders) -Body $body | Out-Null
|
||||
Write-Host "version.json bootstrapVersion -> $scriptVersion, loaderVersion -> $loaderVersion (agent fields untouched)"
|
||||
|
||||
if ($legacySas) {
|
||||
try {
|
||||
@@ -310,11 +508,8 @@ if (-not $DryRun) {
|
||||
}
|
||||
}
|
||||
|
||||
$tableSas = if ($TableSasToken) { $TableSasToken.TrimStart('?') } else { '' }
|
||||
if ($DryRun) {
|
||||
Write-Host " [dry-run] would set AdminConfiguration.LatestBootstrapV2ScriptVersion = $scriptVersion"
|
||||
} elseif ([string]::IsNullOrEmpty($tableSas) -or $tableSas -eq 'XXX') {
|
||||
Write-Host 'SKIPPED: AdminConfiguration update -- set AZURE_TABLE_ADMIN_SAS_TOKEN to enable the portal version oracle'
|
||||
} else {
|
||||
$tableHeaders = @{
|
||||
'Content-Type' = 'application/json'
|
||||
@@ -322,11 +517,11 @@ if ($DryRun) {
|
||||
'If-Match' = '*'
|
||||
}
|
||||
$tableBody = @{ LatestBootstrapV2ScriptVersion = $scriptVersion } | ConvertTo-Json
|
||||
Invoke-RestMethod -Uri "$TableUrl`?$tableSas" -Method Merge -Headers $tableHeaders -Body $tableBody | Out-Null
|
||||
Invoke-RestMethod -Uri $TableUrl -Method Merge -Headers ($authHeaders + $tableHeaders) -Body $tableBody | Out-Null
|
||||
Write-Host "AdminConfiguration.LatestBootstrapV2ScriptVersion = $scriptVersion"
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------ 6. verify via alias
|
||||
# ------------------------------------------------------------------ 8. verify via alias
|
||||
if (-not $DryRun) {
|
||||
$pending = [System.Collections.ArrayList]::new()
|
||||
$publishSet | ForEach-Object { [void]$pending.Add($_) }
|
||||
@@ -358,7 +553,8 @@ if ($env:GITHUB_STEP_SUMMARY) {
|
||||
$summary = @(
|
||||
"### Bootstrap scripts: $mode",
|
||||
'',
|
||||
"Bootstrap script version: **$scriptVersion**",
|
||||
"Loader script version: **$loaderVersion** | Bootstrap script version: **$scriptVersion**",
|
||||
"Signed: **$(if ($SigningEnabled) { "yes, certificate '$CertificateName'" } else { 'NO (unsigned dry run)' })**",
|
||||
''
|
||||
) + ($publishSet | ForEach-Object { "- $($_.BlobName) -- sha256 $($_.Sha256)" })
|
||||
($summary -join [Environment]::NewLine) | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
A failed build burns a number, which is harmless -- uniqueness matters,
|
||||
density does not.
|
||||
|
||||
The blob is public-read; only the write needs the container SAS.
|
||||
The blob is public-read; only the write needs authorization, and that comes from the
|
||||
ambient Entra identity (see Get-StorageAuthHeaders.ps1) -- no secret is passed in.
|
||||
|
||||
Why a counter and not the published version manifest: manifests are written
|
||||
on publish, not on build (the agent writes version.json only for stable
|
||||
@@ -20,10 +21,7 @@
|
||||
overwrite each other's versioned artifact.
|
||||
|
||||
.PARAMETER CounterUrl
|
||||
Full URL of the counter blob, without SAS.
|
||||
|
||||
.PARAMETER SasToken
|
||||
Container SAS with create+write permission. A leading '?' is tolerated.
|
||||
Full URL of the counter blob.
|
||||
|
||||
.PARAMETER Override
|
||||
Explicit build number instead of counter+1. If it is not greater than the
|
||||
@@ -37,20 +35,19 @@
|
||||
[int] the reserved build number. Progress goes to the host, not the pipeline.
|
||||
|
||||
.EXAMPLE
|
||||
$n = ./Request-BuildNumber.ps1 -CounterUrl $url -SasToken $sas
|
||||
$n = ./Request-BuildNumber.ps1 -CounterUrl $url
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$CounterUrl,
|
||||
[Parameter(Mandatory = $true)][string]$SasToken,
|
||||
[int]$Override = 0,
|
||||
[int]$MaxAttempts = 5
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# Tolerate both secret formats ("sp=cw&..." and "?sp=cw&...").
|
||||
$writeUrl = $CounterUrl + '?' + $SasToken.TrimStart('?')
|
||||
# The write is Entra-authorized; the read below stays anonymous (public container).
|
||||
$authHeaders = & (Join-Path $PSScriptRoot 'Get-StorageAuthHeaders.ps1')
|
||||
|
||||
function Get-HttpStatus {
|
||||
param($ErrorRecord)
|
||||
@@ -85,8 +82,8 @@ for ($attempt = 1; $attempt -le $MaxAttempts; $attempt++) {
|
||||
$target = if ($Override -gt 0) { $Override } else { $counter.Value + 1 }
|
||||
|
||||
try {
|
||||
$headers = @{ 'x-ms-blob-type' = 'BlockBlob'; 'If-Match' = $counter.ETag }
|
||||
Invoke-RestMethod -Uri $writeUrl -Method Put -Headers $headers -Body "$target" -ContentType 'text/plain' | Out-Null
|
||||
$headers = $authHeaders + @{ 'x-ms-blob-type' = 'BlockBlob'; 'If-Match' = $counter.ETag }
|
||||
Invoke-RestMethod -Uri $CounterUrl -Method Put -Headers $headers -Body "$target" -ContentType 'text/plain' | Out-Null
|
||||
Write-Host " Reserved build number $target (CAS write ok, attempt $attempt)"
|
||||
return $target
|
||||
} catch {
|
||||
|
||||
@@ -57,6 +57,13 @@ env:
|
||||
VERSIONED_ZIP: AutopilotMonitor-Agent-v2.zip
|
||||
STABLE_ZIP: AutopilotMonitor-Agent.zip
|
||||
STABLE_MANIFEST: version.json
|
||||
# Authenticode via Azure Key Vault; identity and vault come from repository variables.
|
||||
# CODE_SIGN_EXPECTED_SUBJECT is optional and pins the publisher in the verify step.
|
||||
CODE_SIGN_CLIENT_ID: ${{ vars.CODE_SIGN_CLIENT_ID }}
|
||||
CODE_SIGN_CERTIFICATE_NAME: ${{ vars.CODE_SIGN_CERTIFICATE_NAME }}
|
||||
CODE_SIGN_KEY_VAULT_URL: ${{ vars.CODE_SIGN_KEY_VAULT_URL }}
|
||||
CODE_SIGN_EXPECTED_SUBJECT: ${{ vars.CODE_SIGN_EXPECTED_SUBJECT }}
|
||||
CODE_SIGN_TIMESTAMP_URL: http://timestamp.acs.microsoft.com
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -67,12 +74,64 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
# Every released build is signed; a missing variable stops the run before a build
|
||||
# number is burnt.
|
||||
- name: Check code-signing configuration
|
||||
shell: pwsh
|
||||
run: |
|
||||
foreach ($name in 'CODE_SIGN_CLIENT_ID', 'CODE_SIGN_CERTIFICATE_NAME', 'CODE_SIGN_KEY_VAULT_URL') {
|
||||
if ([string]::IsNullOrWhiteSpace([Environment]::GetEnvironmentVariable($name))) {
|
||||
throw "Repository variable $name is not set. Every released build must be Authenticode-signed."
|
||||
}
|
||||
}
|
||||
Write-Host "Code-signing configuration present (certificate '$env:CODE_SIGN_CERTIFICATE_NAME')"
|
||||
|
||||
# Logs in FIRST and only to fetch the Key Vault token: azure/login sets the default az
|
||||
# account, so the storage login below has to be the last one. Both federated credentials
|
||||
# are bound to the ref, so this job must never be given an `environment:` -- that would
|
||||
# change the OIDC subject claim and break both logins.
|
||||
- name: Login to Azure (code-signing identity)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
with:
|
||||
client-id: ${{ env.CODE_SIGN_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
allow-no-subscriptions: true
|
||||
|
||||
- name: Acquire Key Vault token for signing
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$token = az account get-access-token --scope https://vault.azure.net/.default --query accessToken --output tsv
|
||||
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($token)) {
|
||||
throw "Could not acquire a Key Vault token for the code-signing identity."
|
||||
}
|
||||
Write-Host "::add-mask::$token"
|
||||
"CODE_SIGN_AKV_ACCESS_TOKEN=$token" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
|
||||
|
||||
# Every storage write below (counter blob, agent ZIP, manifests, AdminConfiguration)
|
||||
# is authorized by this federated identity -- no SAS secret. One login covers the whole
|
||||
# job: the federated credential is bound to the ref, and a release run takes ~2 minutes,
|
||||
# well inside the token lifetime. Only the legacy mirror still needs a SAS: that account
|
||||
# lives in the pre-migration tenant, where this principal has no identity.
|
||||
- name: Login to Azure (OIDC)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||
|
||||
# SDK 10 = single build toolchain (parity with local build.ps1 / global.json).
|
||||
- name: Setup .NET
|
||||
uses: actions/setup-dotnet@v6
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
# Version pinned; roll-forward because the tool targets an older runtime than the SDK above.
|
||||
- name: Install AzureSignTool
|
||||
env:
|
||||
DOTNET_ROLL_FORWARD: LatestMajor
|
||||
run: dotnet tool install --no-cache --global AzureSignTool --version 7.0.1
|
||||
|
||||
# Build numbers come from the shared counter blob -- one counter and one
|
||||
# implementation for CI and the local build (.github/scripts/Request-BuildNumber.ps1).
|
||||
# Reserve-before-build with ETag-CAS: concurrent builds can never mint the same
|
||||
@@ -85,7 +144,6 @@ jobs:
|
||||
# build_number could otherwise break out of the quotes and run arbitrary code.
|
||||
env:
|
||||
BUILD_NUMBER_OVERRIDE: ${{ inputs.build_number }}
|
||||
AGENT_SAS_TOKEN: ${{ secrets.AZURE_BLOB_AGENT_SAS_TOKEN }}
|
||||
run: |
|
||||
$override = 0
|
||||
if ($env:BUILD_NUMBER_OVERRIDE -ne '') {
|
||||
@@ -96,7 +154,7 @@ jobs:
|
||||
}
|
||||
|
||||
$counterUrl = "https://autopilotmonitoreu.blob.core.windows.net/agent/buildcounter-v$($env:LINE_MAJOR).txt"
|
||||
$buildNumber = & ./.github/scripts/Request-BuildNumber.ps1 -CounterUrl $counterUrl -SasToken $env:AGENT_SAS_TOKEN -Override $override
|
||||
$buildNumber = & ./.github/scripts/Request-BuildNumber.ps1 -CounterUrl $counterUrl -Override $override
|
||||
|
||||
$csproj = Get-Content $env:CSPROJ_PATH -Raw
|
||||
if ($csproj -match '<VersionPrefix>(\d+\.\d+)</VersionPrefix>') {
|
||||
@@ -129,6 +187,47 @@ jobs:
|
||||
- name: Run Agent unit tests
|
||||
run: dotnet test ${{ env.TEST_PROJECT }} --configuration Release --no-restore --verbosity quiet
|
||||
|
||||
# Authenticode over everything we author; third-party assemblies keep their own signature.
|
||||
#
|
||||
# THE POSITION IS LOAD-BEARING: signing rewrites the PE file, so it must run before the
|
||||
# ZIP and every SHA-256 in the next step -- those hashes are the bootstrap's integrity
|
||||
# oracle, and hashes taken before signing match no downloaded file.
|
||||
#
|
||||
# $LASTEXITCODE is checked explicitly: PowerShell does not throw on a native non-zero exit.
|
||||
- name: Sign agent binaries (Authenticode)
|
||||
shell: pwsh
|
||||
env:
|
||||
DOTNET_ROLL_FORWARD: LatestMajor
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$targets = @()
|
||||
$targets += Get-ChildItem -Path "$env:AGENT_OUTPUT/*" -Include 'AutopilotMonitor.*.exe', 'AutopilotMonitor.*.dll' -File
|
||||
$targets += Get-ChildItem -Path "$env:DIALOG_OUTPUT/AutopilotMonitor.SummaryDialog.exe" -File
|
||||
|
||||
if (-not ($targets | Where-Object Name -eq 'AutopilotMonitor.Agent.exe')) {
|
||||
throw "AutopilotMonitor.Agent.exe not found in $env:AGENT_OUTPUT -- nothing to sign."
|
||||
}
|
||||
if (-not ($targets | Where-Object Name -eq 'AutopilotMonitor.SummaryDialog.exe')) {
|
||||
throw "AutopilotMonitor.SummaryDialog.exe not found in $env:DIALOG_OUTPUT -- nothing to sign."
|
||||
}
|
||||
|
||||
$targets | ForEach-Object { Write-Host "Signing $($_.Name)" }
|
||||
|
||||
& azuresigntool.exe sign --verbose `
|
||||
--azure-key-vault-url "$env:CODE_SIGN_KEY_VAULT_URL" `
|
||||
--azure-key-vault-accesstoken "$env:CODE_SIGN_AKV_ACCESS_TOKEN" `
|
||||
--azure-key-vault-certificate "$env:CODE_SIGN_CERTIFICATE_NAME" `
|
||||
--timestamp-rfc3161 "$env:CODE_SIGN_TIMESTAMP_URL" `
|
||||
--file-digest sha256 `
|
||||
--description "Autopilot Monitor Agent" `
|
||||
--description-url "https://www.autopilotmonitor.com" `
|
||||
($targets | ForEach-Object { $_.FullName })
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "azuresigntool failed with exit code $LASTEXITCODE -- aborting before anything is published."
|
||||
}
|
||||
|
||||
- name: Create release artifact
|
||||
id: artifact
|
||||
shell: pwsh
|
||||
@@ -219,12 +318,57 @@ jobs:
|
||||
"sha256=$sha256Hash" >> $env:GITHUB_OUTPUT
|
||||
"exe_sha256=$exeSha256Hash" >> $env:GITHUB_OUTPUT
|
||||
|
||||
# Verified against the STAGING copy -- the exact bytes that ship. The invariant is "every
|
||||
# AutopilotMonitor PE in the ZIP is signed", so a project added later cannot ride along
|
||||
# unsigned. A missing timestamp fails too: without it the signature dies with the cert.
|
||||
- name: Verify Authenticode signatures
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$files = Get-ChildItem -Path "staging/agent/*" -Include 'AutopilotMonitor.*.exe', 'AutopilotMonitor.*.dll' -File
|
||||
if ($files.Count -lt 2) {
|
||||
throw "Expected signed binaries in staging/agent, found $($files.Count)."
|
||||
}
|
||||
|
||||
$failed = $false
|
||||
$thumbprints = @{}
|
||||
foreach ($file in $files) {
|
||||
$sig = Get-AuthenticodeSignature -FilePath $file.FullName
|
||||
if ($sig.Status -ne 'Valid') {
|
||||
Write-Host "::error file=$($file.Name)::Signature status is '$($sig.Status)' -- expected 'Valid'."
|
||||
$failed = $true
|
||||
continue
|
||||
}
|
||||
if (-not $sig.TimeStamperCertificate) {
|
||||
Write-Host "::error file=$($file.Name)::Signature carries no RFC-3161 timestamp -- it would expire with the certificate."
|
||||
$failed = $true
|
||||
continue
|
||||
}
|
||||
if (-not [string]::IsNullOrWhiteSpace($env:CODE_SIGN_EXPECTED_SUBJECT) -and
|
||||
$sig.SignerCertificate.Subject -notlike $env:CODE_SIGN_EXPECTED_SUBJECT) {
|
||||
Write-Host "::error file=$($file.Name)::Signed by '$($sig.SignerCertificate.Subject)', expected '$env:CODE_SIGN_EXPECTED_SUBJECT'."
|
||||
$failed = $true
|
||||
continue
|
||||
}
|
||||
$thumbprints[$sig.SignerCertificate.Thumbprint] = $true
|
||||
Write-Host "$($file.Name): Valid, timestamped $($sig.TimeStamperCertificate.Subject.Split(',')[0]), signer $($sig.SignerCertificate.Subject)"
|
||||
}
|
||||
|
||||
if ($thumbprints.Count -gt 1) {
|
||||
Write-Host "::error::Staged binaries carry $($thumbprints.Count) different signing certificates -- expected exactly one."
|
||||
$failed = $true
|
||||
}
|
||||
if ($failed) {
|
||||
throw "Signature verification failed. Nothing was published."
|
||||
}
|
||||
Write-Host "All $($files.Count) binaries signed with certificate $($thumbprints.Keys -join ', ')"
|
||||
|
||||
- name: Upload to Azure Blob Storage
|
||||
if: inputs.upload_blob
|
||||
shell: pwsh
|
||||
run: |
|
||||
$containerUrl = "https://autopilotmonitoreu.blob.core.windows.net/agent"
|
||||
$sasToken = "${{ secrets.AZURE_BLOB_AGENT_SAS_TOKEN }}".TrimStart('?')
|
||||
$authHeaders = & ./.github/scripts/Get-StorageAuthHeaders.ps1
|
||||
# Legacy mirror (transition until customers moved to the download.-alias):
|
||||
# blobs are ALSO pushed to the old account so the bootstrap URL baked into
|
||||
# customers' Intune scripts keeps serving current bits. Fail-soft -- a
|
||||
@@ -234,7 +378,6 @@ jobs:
|
||||
|
||||
function Send-Blob {
|
||||
param([string]$Local, [string]$BlobName, [string]$ContentType)
|
||||
$url = "$containerUrl/$BlobName`?$sasToken"
|
||||
$bytes = [System.IO.File]::ReadAllBytes($Local)
|
||||
# no-cache on EVERY blob: they all rotate in place (even the per-line ZIP is
|
||||
# overwritten each build), and the download alias fronts them with Front Door.
|
||||
@@ -248,7 +391,7 @@ jobs:
|
||||
$md5.Dispose()
|
||||
}
|
||||
Write-Host "Uploading $BlobName ($([math]::Round($bytes.Length / 1MB, 2)) MB)..."
|
||||
Invoke-RestMethod -Uri $url -Method Put -Headers $headers -Body $bytes
|
||||
Invoke-RestMethod -Uri "$containerUrl/$BlobName" -Method Put -Headers ($authHeaders + $headers) -Body $bytes
|
||||
Write-Host " uploaded $BlobName"
|
||||
if (-not [string]::IsNullOrEmpty($legacySasToken)) {
|
||||
try {
|
||||
@@ -274,47 +417,57 @@ jobs:
|
||||
# to main, so a release lands a set that is consistent with what is already live
|
||||
# (dev render, version-bump guard, bootstrapVersion oracles, alias verification).
|
||||
# Runs AFTER version.json so its bootstrapVersion read sees this build's manifest.
|
||||
# Signed with the same identity: the device-side loader verifies the publisher
|
||||
# of what it downloads, and the publisher refuses to upload unsigned scripts.
|
||||
./.github/scripts/Publish-BootstrapScripts.ps1 `
|
||||
-SasToken '${{ secrets.AZURE_BLOB_AGENT_SAS_TOKEN }}' `
|
||||
-LegacySasToken '${{ secrets.AZURE_BLOB_AGENT_LEGACY_SAS_TOKEN }}' `
|
||||
-TableSasToken '${{ secrets.AZURE_TABLE_ADMIN_SAS_TOKEN }}'
|
||||
-SigningToken $env:CODE_SIGN_AKV_ACCESS_TOKEN `
|
||||
-KeyVaultUrl $env:CODE_SIGN_KEY_VAULT_URL `
|
||||
-CertificateName $env:CODE_SIGN_CERTIFICATE_NAME `
|
||||
-TimestampUrl $env:CODE_SIGN_TIMESTAMP_URL `
|
||||
-ExpectedPublisher $env:CODE_SIGN_EXPECTED_SUBJECT
|
||||
}
|
||||
|
||||
# Update AdminConfiguration LatestAgentV2* -- ONLY on stable cutover. The hash-oracle
|
||||
# must never point at a build that is not actually in the stable namespace.
|
||||
# LatestBootstrapV2ScriptVersion is NOT set here: it belongs to the script publisher
|
||||
# above, which also owns it on script-only pushes. One writer per field.
|
||||
$tableSasToken = "${{ secrets.AZURE_TABLE_ADMIN_SAS_TOKEN }}".TrimStart('?')
|
||||
if ('${{ inputs.publish_as_stable }}' -ne 'true') {
|
||||
Write-Host "SKIPPED: AdminConfiguration update (versioned-only run -- stable namespace unchanged)"
|
||||
} elseif ([string]::IsNullOrEmpty($tableSasToken) -or $tableSasToken -eq "XXX") {
|
||||
Write-Host "SKIPPED: Table SAS token not configured -- set AZURE_TABLE_ADMIN_SAS_TOKEN secret to enable backend hash-oracle"
|
||||
} else {
|
||||
$sha256 = "${{ steps.artifact.outputs.sha256 }}"
|
||||
$exeSha256 = "${{ steps.artifact.outputs.exe_sha256 }}"
|
||||
$agentVersion = "${{ steps.version.outputs.version }}"
|
||||
$tableUrl = "https://autopilotmonitoreu.table.core.windows.net/AdminConfiguration(PartitionKey='GlobalConfig',RowKey='config')?$tableSasToken"
|
||||
$tableUrl = "https://autopilotmonitoreu.table.core.windows.net/AdminConfiguration(PartitionKey='GlobalConfig',RowKey='config')"
|
||||
$tableBody = @{
|
||||
LatestAgentV2Version = $agentVersion
|
||||
LatestAgentV2Sha256 = $sha256
|
||||
LatestAgentV2ExeSha256 = $exeSha256
|
||||
}
|
||||
Invoke-RestMethod -Uri $tableUrl -Method Merge -Headers @{
|
||||
Invoke-RestMethod -Uri $tableUrl -Method Merge -Headers ($authHeaders + @{
|
||||
"Content-Type" = "application/json"
|
||||
"Accept" = "application/json;odata=nometadata"
|
||||
"If-Match" = "*"
|
||||
} -Body ($tableBody | ConvertTo-Json)
|
||||
}) -Body ($tableBody | ConvertTo-Json)
|
||||
Write-Host "AdminConfiguration updated: V2 version=$agentVersion, sha256=$sha256, exeSha256=$exeSha256"
|
||||
}
|
||||
|
||||
# Sigstore keyless provenance: binds the ZIP digest to this workflow run (repo, ref,
|
||||
# commit, workflow file) in a public transparency log. The digest covers the identical
|
||||
# Sigstore keyless provenance: binds the artifact digests to this workflow run (repo, ref,
|
||||
# commit, workflow file) in a public transparency log. The digests cover the identical
|
||||
# bytes uploaded to blob (versioned AND stable), so one attestation covers all copies.
|
||||
# Verify: gh attestation verify <zip> --repo okieselbach/AutopilotMonitor
|
||||
- name: Attest build provenance (ZIP)
|
||||
# Complements Authenticode rather than replacing it: the signature says who published a
|
||||
# binary, the attestation which build produced these exact bytes. Both EXEs are subjects
|
||||
# of their own so an extracted binary can be verified without the ZIP.
|
||||
# Verify: gh attestation verify <file> --repo okieselbach/AutopilotMonitor
|
||||
# Skipped on runs that publish nothing -- no log entry for bytes nobody receives.
|
||||
- name: Attest build provenance
|
||||
if: inputs.upload_blob || inputs.create_release
|
||||
uses: actions/attest-build-provenance@v4
|
||||
with:
|
||||
subject-path: ${{ steps.artifact.outputs.versioned_zip_release }}
|
||||
subject-path: |
|
||||
${{ steps.artifact.outputs.versioned_zip_release }}
|
||||
staging/agent/AutopilotMonitor.Agent.exe
|
||||
staging/agent/AutopilotMonitor.SummaryDialog.exe
|
||||
|
||||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
@@ -356,7 +509,7 @@ jobs:
|
||||
- **Published as stable:** ${{ inputs.publish_as_stable }}
|
||||
|
||||
### Provenance
|
||||
This ZIP carries a [GitHub Artifact Attestation](https://github.com/okieselbach/AutopilotMonitor/attestations) (Sigstore keyless). Verify:
|
||||
The executables are Authenticode-signed and timestamped. The ZIP and both executables carry a [GitHub Artifact Attestation](https://github.com/okieselbach/AutopilotMonitor/attestations) (Sigstore keyless). Verify:
|
||||
```
|
||||
gh attestation verify AutopilotMonitor-Agent-v${{ steps.version.outputs.version }}.zip --repo okieselbach/AutopilotMonitor
|
||||
```
|
||||
|
||||
+119
-12
@@ -1,11 +1,11 @@
|
||||
name: Build & Publish Bootstrap MSI
|
||||
|
||||
# Thin MDM LOB delivery vehicle for WDP (Autopilot v2) — see
|
||||
# src/Agent/AutopilotMonitor.BootstrapMsi/Package.wxs. The MSI carries no bootstrap
|
||||
# logic (only the runner script that downloads the CURRENT server-hosted
|
||||
# Install-AutopilotMonitor.ps1), so it is rebuilt rarely: only when the runner script
|
||||
# or the WiX package changes. Version lives in Package.wxs — bump it there before
|
||||
# dispatching so Intune LOB update detection sees a new ProductVersion.
|
||||
# src/Agent/AutopilotMonitor.BootstrapMsi/Package.wxs. The MSI is packaging only: it
|
||||
# carries the SAME stage-1 loader that is assigned directly in Intune, so it is rebuilt
|
||||
# rarely — only when that loader or the WiX package changes. Version lives in Package.wxs
|
||||
# — bump it there before dispatching so Intune LOB update detection sees a new
|
||||
# ProductVersion.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
@@ -23,8 +23,15 @@ permissions:
|
||||
|
||||
env:
|
||||
MSI_PROJECT_DIR: src/Agent/AutopilotMonitor.BootstrapMsi
|
||||
RUNNER_SCRIPT: src/Agent/AutopilotMonitor.BootstrapMsi/Invoke-BootstrapDownload.ps1
|
||||
RUNNER_SCRIPT: scripts/Bootstrap/Start-AutopilotMonitor.ps1
|
||||
STABLE_MSI: AutopilotMonitor-Bootstrap.msi
|
||||
# Authenticode via Azure Key Vault; identity and vault come from repository variables.
|
||||
# CODE_SIGN_EXPECTED_SUBJECT is optional and pins the publisher in the verify steps.
|
||||
CODE_SIGN_CLIENT_ID: ${{ vars.CODE_SIGN_CLIENT_ID }}
|
||||
CODE_SIGN_CERTIFICATE_NAME: ${{ vars.CODE_SIGN_CERTIFICATE_NAME }}
|
||||
CODE_SIGN_KEY_VAULT_URL: ${{ vars.CODE_SIGN_KEY_VAULT_URL }}
|
||||
CODE_SIGN_EXPECTED_SUBJECT: ${{ vars.CODE_SIGN_EXPECTED_SUBJECT }}
|
||||
CODE_SIGN_TIMESTAMP_URL: http://timestamp.acs.microsoft.com
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -35,8 +42,10 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
# The runner executes as SYSTEM on every enrolling device — a parse error or
|
||||
# The loader executes as SYSTEM on every enrolling device — a parse error or
|
||||
# non-ASCII mojibake (PS 5.1 codepage roulette) must fail the build, not the fleet.
|
||||
# bootstrap-script-gates.yml runs the same checks plus Pester on pushes; this job
|
||||
# stands on its own because it can be dispatched at any time.
|
||||
- name: Validate runner script (parse + ASCII-only)
|
||||
shell: pwsh
|
||||
run: |
|
||||
@@ -62,9 +71,75 @@ jobs:
|
||||
Write-Host "MSI version (from Package.wxs): $version"
|
||||
"version=$version" >> $env:GITHUB_OUTPUT
|
||||
|
||||
# Every published MSI is signed; a missing variable stops the run before the build.
|
||||
- name: Check code-signing configuration
|
||||
shell: pwsh
|
||||
run: |
|
||||
foreach ($name in 'CODE_SIGN_CLIENT_ID', 'CODE_SIGN_CERTIFICATE_NAME', 'CODE_SIGN_KEY_VAULT_URL') {
|
||||
if ([string]::IsNullOrWhiteSpace([Environment]::GetEnvironmentVariable($name))) {
|
||||
throw "Repository variable $name is not set. Every published MSI must be Authenticode-signed."
|
||||
}
|
||||
}
|
||||
|
||||
# Logs in FIRST and only to fetch the Key Vault token: azure/login sets the default az
|
||||
# account, so the storage login below has to be the last one. Both federated credentials
|
||||
# are bound to the ref, so this job must never be given an `environment:` -- that would
|
||||
# change the OIDC subject claim and break both logins.
|
||||
- name: Login to Azure (code-signing identity)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
with:
|
||||
client-id: ${{ env.CODE_SIGN_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
allow-no-subscriptions: true
|
||||
|
||||
- name: Acquire Key Vault token for signing
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$token = az account get-access-token --scope https://vault.azure.net/.default --query accessToken --output tsv
|
||||
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($token)) {
|
||||
throw "Could not acquire a Key Vault token for the code-signing identity."
|
||||
}
|
||||
Write-Host "::add-mask::$token"
|
||||
"CODE_SIGN_AKV_ACCESS_TOKEN=$token" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
|
||||
|
||||
# The blob upload below is authorized by this federated identity, not by a SAS.
|
||||
- name: Login to Azure (OIDC)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||
|
||||
- name: Install WiX toolset
|
||||
run: dotnet tool install --global wix --version "5.*"
|
||||
|
||||
# Version pinned; roll-forward because the tool targets an older runtime than the SDK.
|
||||
- name: Install AzureSignTool
|
||||
env:
|
||||
DOTNET_ROLL_FORWARD: LatestMajor
|
||||
run: dotnet tool install --no-cache --global AzureSignTool --version 7.0.1
|
||||
|
||||
# BEFORE the build: wix embeds the file as it finds it, so a loader signed afterwards
|
||||
# would leave the copy inside the MSI unsigned. Devices under an AllSigned policy need
|
||||
# the embedded loader to carry a signature of its own.
|
||||
- name: Sign bootstrap loader (Authenticode)
|
||||
shell: pwsh
|
||||
env:
|
||||
DOTNET_ROLL_FORWARD: LatestMajor
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
& azuresigntool.exe sign --verbose `
|
||||
--azure-key-vault-url "$env:CODE_SIGN_KEY_VAULT_URL" `
|
||||
--azure-key-vault-accesstoken "$env:CODE_SIGN_AKV_ACCESS_TOKEN" `
|
||||
--azure-key-vault-certificate "$env:CODE_SIGN_CERTIFICATE_NAME" `
|
||||
--timestamp-rfc3161 "$env:CODE_SIGN_TIMESTAMP_URL" `
|
||||
--file-digest sha256 `
|
||||
--description 'Autopilot Monitor bootstrap runner' `
|
||||
--description-url 'https://www.autopilotmonitor.com' `
|
||||
$env:RUNNER_SCRIPT
|
||||
if ($LASTEXITCODE -ne 0) { throw "azuresigntool failed with exit code $LASTEXITCODE" }
|
||||
|
||||
- name: Build MSI
|
||||
shell: pwsh
|
||||
run: |
|
||||
@@ -75,16 +150,46 @@ jobs:
|
||||
wix build Package.wxs -arch x64 -o $out
|
||||
Pop-Location
|
||||
if (-not (Test-Path $env:STABLE_MSI)) { Write-Error "wix build produced no MSI"; exit 1 }
|
||||
$sha256 = (Get-FileHash $env:STABLE_MSI -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
Write-Host "Built $env:STABLE_MSI ($([math]::Round((Get-Item $env:STABLE_MSI).Length / 1KB)) KB)"
|
||||
Write-Host "SHA-256: $sha256"
|
||||
|
||||
# Signing rewrites the MSI, so it runs before the hash and the upload. A missing
|
||||
# timestamp fails the run: without it the signature dies with the certificate.
|
||||
- name: Sign MSI (Authenticode)
|
||||
shell: pwsh
|
||||
env:
|
||||
DOTNET_ROLL_FORWARD: LatestMajor
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
& azuresigntool.exe sign --verbose `
|
||||
--azure-key-vault-url "$env:CODE_SIGN_KEY_VAULT_URL" `
|
||||
--azure-key-vault-accesstoken "$env:CODE_SIGN_AKV_ACCESS_TOKEN" `
|
||||
--azure-key-vault-certificate "$env:CODE_SIGN_CERTIFICATE_NAME" `
|
||||
--timestamp-rfc3161 "$env:CODE_SIGN_TIMESTAMP_URL" `
|
||||
--file-digest sha256 `
|
||||
--description 'Autopilot Monitor Bootstrap' `
|
||||
--description-url 'https://www.autopilotmonitor.com' `
|
||||
$env:STABLE_MSI
|
||||
if ($LASTEXITCODE -ne 0) { throw "azuresigntool failed with exit code $LASTEXITCODE" }
|
||||
|
||||
# The MSI and the loader it carries -- verified here, before anything is published.
|
||||
foreach ($file in @($env:STABLE_MSI, $env:RUNNER_SCRIPT)) {
|
||||
$sig = Get-AuthenticodeSignature -FilePath $file
|
||||
if ($sig.Status -ne 'Valid') { throw "Signature on $file is '$($sig.Status)', expected 'Valid'." }
|
||||
if (-not $sig.TimeStamperCertificate) { throw "Signature on $file carries no timestamp." }
|
||||
if ($env:CODE_SIGN_EXPECTED_SUBJECT -and $sig.SignerCertificate.Subject -notlike $env:CODE_SIGN_EXPECTED_SUBJECT) {
|
||||
throw "$file was signed by '$($sig.SignerCertificate.Subject)', expected '$env:CODE_SIGN_EXPECTED_SUBJECT'."
|
||||
}
|
||||
Write-Host "$file : Valid, timestamped, signer $($sig.SignerCertificate.Subject.Split(',')[0])"
|
||||
}
|
||||
|
||||
Write-Host "SHA-256: $((Get-FileHash $env:STABLE_MSI -Algorithm SHA256).Hash.ToLowerInvariant())"
|
||||
|
||||
- name: Upload to Azure Blob Storage
|
||||
if: inputs.upload_blob
|
||||
shell: pwsh
|
||||
run: |
|
||||
$containerUrl = "https://autopilotmonitoreu.blob.core.windows.net/agent"
|
||||
$sasToken = "${{ secrets.AZURE_BLOB_AGENT_SAS_TOKEN }}".TrimStart('?')
|
||||
$authHeaders = & ./.github/scripts/Get-StorageAuthHeaders.ps1
|
||||
$version = "${{ steps.version.outputs.version }}"
|
||||
|
||||
# Same Send-Blob contract as build-agent.yml: no-cache on every blob because the
|
||||
@@ -102,7 +207,7 @@ jobs:
|
||||
$headers["Content-MD5"] = [Convert]::ToBase64String($md5.ComputeHash($bytes))
|
||||
$md5.Dispose()
|
||||
Write-Host "Uploading $BlobName ($([math]::Round($bytes.Length / 1KB)) KB)..."
|
||||
Invoke-RestMethod -Uri "$containerUrl/$BlobName`?$sasToken" -Method Put -Headers $headers -Body $bytes
|
||||
Invoke-RestMethod -Uri "$containerUrl/$BlobName" -Method Put -Headers ($authHeaders + $headers) -Body $bytes
|
||||
Write-Host " uploaded $BlobName"
|
||||
}
|
||||
|
||||
@@ -125,9 +230,11 @@ jobs:
|
||||
}
|
||||
Write-Host "Alias verified: https://download.autopilotmonitor.com/agent/$env:STABLE_MSI ($remoteSize bytes)"
|
||||
|
||||
# Sigstore keyless provenance, same as the agent ZIP. Verify:
|
||||
# Sigstore keyless provenance, same as the agent ZIP; covers the signed bytes. Skipped
|
||||
# on runs that publish nothing -- no log entry for bytes nobody receives. Verify:
|
||||
# gh attestation verify AutopilotMonitor-Bootstrap.msi --repo okieselbach/AutopilotMonitor
|
||||
- name: Attest build provenance (MSI)
|
||||
if: inputs.upload_blob
|
||||
uses: actions/attest-build-provenance@v4
|
||||
with:
|
||||
subject-path: ${{ env.STABLE_MSI }}
|
||||
|
||||
@@ -41,7 +41,7 @@ jobs:
|
||||
id: version
|
||||
shell: pwsh
|
||||
run: |
|
||||
$buildNumber = & ./.github/scripts/Request-BuildNumber.ps1 -CounterUrl "${{ env.VERSIONS_CONTAINER }}/backend.txt" -SasToken '${{ secrets.AZURE_BLOB_VERSIONS_SAS_TOKEN }}'
|
||||
$buildNumber = & ./.github/scripts/Request-BuildNumber.ps1 -CounterUrl "${{ env.VERSIONS_CONTAINER }}/backend.txt"
|
||||
|
||||
$csproj = Get-Content ${{ env.CSPROJ_PATH }} -Raw
|
||||
if ($csproj -notmatch '<VersionPrefix>(\d+\.\d+)</VersionPrefix>') {
|
||||
@@ -115,9 +115,9 @@ jobs:
|
||||
runId = '${{ github.run_id }}'
|
||||
} | ConvertTo-Json
|
||||
|
||||
$sas = '${{ secrets.AZURE_BLOB_VERSIONS_SAS_TOKEN }}'.TrimStart('?')
|
||||
$url = "${{ env.VERSIONS_CONTAINER }}/backend.json?$sas"
|
||||
$authHeaders = & ./.github/scripts/Get-StorageAuthHeaders.ps1
|
||||
$url = "${{ env.VERSIONS_CONTAINER }}/backend.json"
|
||||
# no-cache: rotating pointer, must never be served stale by any fronting cache.
|
||||
Invoke-RestMethod -Uri $url -Method Put -Headers @{ 'x-ms-blob-type' = 'BlockBlob'; 'x-ms-blob-cache-control' = 'no-cache' } -Body $manifest -ContentType 'application/json' | Out-Null
|
||||
Invoke-RestMethod -Uri $url -Method Put -Headers ($authHeaders + @{ 'x-ms-blob-type' = 'BlockBlob'; 'x-ms-blob-cache-control' = 'no-cache' }) -Body $manifest -ContentType 'application/json' | Out-Null
|
||||
Write-Host "Published versions/backend.json"
|
||||
Write-Host $manifest
|
||||
|
||||
@@ -59,7 +59,7 @@ jobs:
|
||||
id: version
|
||||
shell: pwsh
|
||||
run: |
|
||||
$buildNumber = & ./.github/scripts/Request-BuildNumber.ps1 -CounterUrl "${{ env.VERSIONS_CONTAINER }}/mcp.txt" -SasToken '${{ secrets.AZURE_BLOB_VERSIONS_SAS_TOKEN }}'
|
||||
$buildNumber = & ./.github/scripts/Request-BuildNumber.ps1 -CounterUrl "${{ env.VERSIONS_CONTAINER }}/mcp.txt"
|
||||
|
||||
$pkgVersion = (Get-Content ${{ env.PACKAGE_JSON }} -Raw | ConvertFrom-Json).version
|
||||
$prefix = ($pkgVersion -split '\.')[0..1] -join '.'
|
||||
@@ -144,9 +144,9 @@ jobs:
|
||||
docsCommit = '${{ steps.docs.outputs.sha }}'.Substring(0, 7)
|
||||
} | ConvertTo-Json
|
||||
|
||||
$sas = '${{ secrets.AZURE_BLOB_VERSIONS_SAS_TOKEN }}'.TrimStart('?')
|
||||
$url = "${{ env.VERSIONS_CONTAINER }}/mcp.json?$sas"
|
||||
$authHeaders = & ./.github/scripts/Get-StorageAuthHeaders.ps1
|
||||
$url = "${{ env.VERSIONS_CONTAINER }}/mcp.json"
|
||||
# no-cache: rotating pointer, must never be served stale by any fronting cache.
|
||||
Invoke-RestMethod -Uri $url -Method Put -Headers @{ 'x-ms-blob-type' = 'BlockBlob'; 'x-ms-blob-cache-control' = 'no-cache' } -Body $manifest -ContentType 'application/json' | Out-Null
|
||||
Invoke-RestMethod -Uri $url -Method Put -Headers ($authHeaders + @{ 'x-ms-blob-type' = 'BlockBlob'; 'x-ms-blob-cache-control' = 'no-cache' }) -Body $manifest -ContentType 'application/json' | Out-Null
|
||||
Write-Host "Published versions/mcp.json"
|
||||
Write-Host $manifest
|
||||
|
||||
@@ -40,6 +40,32 @@ jobs:
|
||||
lfs: false
|
||||
fetch-depth: 0 # Full history needed for git-based sitemap lastmod dates
|
||||
|
||||
# Only the version manifest at the very end needs Azure; logging in here rather than
|
||||
# next to that step keeps a credential problem from surfacing after a live deploy.
|
||||
- name: Login to Azure (OIDC)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||
|
||||
# The customer docs repo is the single source of the "What's new" panel: the prebuild
|
||||
# step (scripts/whats-new/build-whats-new.js) turns changelog/*.md into
|
||||
# public/whats-new.json and dates every bullet via git blame — hence the full history.
|
||||
# Public repo, no token. Editing the docs does NOT update the live panel until this
|
||||
# workflow runs again (push under src/Web/** or a manual dispatch); versions/web.json
|
||||
# records which docs commit is live.
|
||||
- name: Check out documentation bundle
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
repository: autopilotmonitor/autopilotmonitor-docs
|
||||
path: whats-new-docs
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Resolve docs commit
|
||||
id: docs
|
||||
run: echo "sha=$(git -C whats-new-docs rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '22'
|
||||
@@ -51,7 +77,7 @@ jobs:
|
||||
run: npm ci
|
||||
|
||||
# next.config output:'export' -- `next build` writes the static site to out/
|
||||
# (prebuild: sync-error-codes, generate-lastmod, generate-version).
|
||||
# (prebuild: sync-error-codes, generate-lastmod, generate-version, whats-new).
|
||||
- name: Build
|
||||
working-directory: ${{ env.WEB_DIR }}
|
||||
env:
|
||||
@@ -68,9 +94,12 @@ jobs:
|
||||
# Build stamp for public/version.json (scripts/generate-version.js in prebuild);
|
||||
# the verify step below polls the deployed file for exactly this commit.
|
||||
GITHUB_SHA: ${{ github.sha }}
|
||||
# Docs checkout for public/whats-new.json; the prebuild fails in CI without it.
|
||||
WHATS_NEW_DOCS_DIR: ${{ github.workspace }}/whats-new-docs
|
||||
run: |
|
||||
npm run build
|
||||
test -f out/version.json || { echo "out/version.json missing - export did not run"; exit 1; }
|
||||
test -f out/whats-new.json || { echo "out/whats-new.json missing - whats-new prebuild did not run"; exit 1; }
|
||||
|
||||
# One archive of the exact bytes that get uploaded, so the attestation has a single subject.
|
||||
- name: Package export
|
||||
@@ -136,7 +165,8 @@ jobs:
|
||||
throw "Portal did not serve commit $expectedCommit within 5 minutes -- deployment not verified, version manifest NOT published"
|
||||
|
||||
# Cross-component deploy record, written last and only on a verified deploy --
|
||||
# same contract as versions/backend.json and versions/mcp.json.
|
||||
# same contract as versions/backend.json and versions/mcp.json. docsCommit says which
|
||||
# docs revision the live What's new panel was generated from (as for the MCP corpus).
|
||||
- name: Publish version manifest
|
||||
shell: pwsh
|
||||
run: |
|
||||
@@ -145,11 +175,12 @@ jobs:
|
||||
commit = '${{ github.sha }}'.Substring(0, 7)
|
||||
deployedUtc = [DateTime]::UtcNow.ToString('o')
|
||||
runId = '${{ github.run_id }}'
|
||||
docsCommit = '${{ steps.docs.outputs.sha }}'.Substring(0, 7)
|
||||
} | ConvertTo-Json
|
||||
|
||||
$sas = '${{ secrets.AZURE_BLOB_VERSIONS_SAS_TOKEN }}'.TrimStart('?')
|
||||
$url = "${{ env.VERSIONS_CONTAINER }}/web.json?$sas"
|
||||
$authHeaders = & ./.github/scripts/Get-StorageAuthHeaders.ps1
|
||||
$url = "${{ env.VERSIONS_CONTAINER }}/web.json"
|
||||
# no-cache: rotating pointer, must never be served stale by any fronting cache.
|
||||
Invoke-RestMethod -Uri $url -Method Put -Headers @{ 'x-ms-blob-type' = 'BlockBlob'; 'x-ms-blob-cache-control' = 'no-cache' } -Body $manifest -ContentType 'application/json' | Out-Null
|
||||
Invoke-RestMethod -Uri $url -Method Put -Headers ($authHeaders + @{ 'x-ms-blob-type' = 'BlockBlob'; 'x-ms-blob-cache-control' = 'no-cache' }) -Body $manifest -ContentType 'application/json' | Out-Null
|
||||
Write-Host "Published versions/web.json"
|
||||
Write-Host $manifest
|
||||
|
||||
@@ -26,6 +26,7 @@ on:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write # OIDC federated login for the storage writes (secret-less)
|
||||
|
||||
# Shared with build-agent.yml: a script publish and an agent release both touch
|
||||
# version.json, and the bootstrapVersion read-modify-write must not interleave with the
|
||||
@@ -34,6 +35,16 @@ concurrency:
|
||||
group: agent-blob-publish
|
||||
cancel-in-progress: false
|
||||
|
||||
# Authenticode for the customer scripts. Same identity and same repository variables as
|
||||
# build-agent.yml -- the loader on every device pins this publisher, so the two must not
|
||||
# drift apart.
|
||||
env:
|
||||
CODE_SIGN_CLIENT_ID: ${{ vars.CODE_SIGN_CLIENT_ID }}
|
||||
CODE_SIGN_CERTIFICATE_NAME: ${{ vars.CODE_SIGN_CERTIFICATE_NAME }}
|
||||
CODE_SIGN_KEY_VAULT_URL: ${{ vars.CODE_SIGN_KEY_VAULT_URL }}
|
||||
CODE_SIGN_EXPECTED_SUBJECT: ${{ vars.CODE_SIGN_EXPECTED_SUBJECT }}
|
||||
CODE_SIGN_TIMESTAMP_URL: http://timestamp.acs.microsoft.com
|
||||
|
||||
jobs:
|
||||
gates:
|
||||
uses: ./.github/workflows/bootstrap-script-gates.yml
|
||||
@@ -45,12 +56,79 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Check code-signing configuration
|
||||
shell: pwsh
|
||||
run: |
|
||||
foreach ($name in 'CODE_SIGN_CLIENT_ID', 'CODE_SIGN_CERTIFICATE_NAME', 'CODE_SIGN_KEY_VAULT_URL') {
|
||||
if ([string]::IsNullOrWhiteSpace([Environment]::GetEnvironmentVariable($name))) {
|
||||
throw "Repository variable $name is not set. Published customer scripts must be signed."
|
||||
}
|
||||
}
|
||||
|
||||
# First, and only to fetch the Key Vault token: azure/login sets the default az
|
||||
# account and the storage login below has to be the one that stays. See D-223 --
|
||||
# both federated credentials are bound to the ref, so this job must never carry a
|
||||
# GitHub `environment:`.
|
||||
- name: Login to Azure (code-signing identity)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
with:
|
||||
client-id: ${{ env.CODE_SIGN_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
allow-no-subscriptions: true
|
||||
|
||||
- name: Acquire Key Vault token for signing
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$token = az account get-access-token --scope https://vault.azure.net/.default --query accessToken --output tsv
|
||||
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($token)) {
|
||||
throw "Could not acquire a Key Vault token for the code-signing identity."
|
||||
}
|
||||
Write-Host "::add-mask::$token"
|
||||
"CODE_SIGN_AKV_ACCESS_TOKEN=$token" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
|
||||
|
||||
# Authorizes the eu blob writes and the AdminConfiguration merge. The gates job above
|
||||
# runs the same publisher with -DryRun and deliberately without a login -- a dry run
|
||||
# must never need Azure credentials.
|
||||
- name: Login to Azure (OIDC)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||
|
||||
# Version pinned so a new or compromised NuGet release cannot flow into signing
|
||||
# unreviewed; roll-forward because the tool targets an older runtime than the SDK
|
||||
# preinstalled on the runner.
|
||||
- name: Install AzureSignTool
|
||||
env:
|
||||
DOTNET_ROLL_FORWARD: LatestMajor
|
||||
run: dotnet tool install --no-cache --global AzureSignTool --version 7.0.1
|
||||
|
||||
- name: Publish bootstrap + customer scripts
|
||||
shell: pwsh
|
||||
env:
|
||||
DOTNET_ROLL_FORWARD: LatestMajor
|
||||
run: |
|
||||
$dryRun = '${{ inputs.dry_run }}' -eq 'true'
|
||||
./.github/scripts/Publish-BootstrapScripts.ps1 `
|
||||
-SasToken '${{ secrets.AZURE_BLOB_AGENT_SAS_TOKEN }}' `
|
||||
-LegacySasToken '${{ secrets.AZURE_BLOB_AGENT_LEGACY_SAS_TOKEN }}' `
|
||||
-TableSasToken '${{ secrets.AZURE_TABLE_ADMIN_SAS_TOKEN }}' `
|
||||
-SigningToken $env:CODE_SIGN_AKV_ACCESS_TOKEN `
|
||||
-KeyVaultUrl $env:CODE_SIGN_KEY_VAULT_URL `
|
||||
-CertificateName $env:CODE_SIGN_CERTIFICATE_NAME `
|
||||
-TimestampUrl $env:CODE_SIGN_TIMESTAMP_URL `
|
||||
-ExpectedPublisher $env:CODE_SIGN_EXPECTED_SUBJECT `
|
||||
-SignedOutputDir "$env:RUNNER_TEMP/signed-scripts" `
|
||||
-DryRun:$dryRun
|
||||
|
||||
# The exact bytes that were (or, on a dry run, would have been) uploaded. A dry-run
|
||||
# dispatch is therefore the way to inspect a signed script locally before it reaches
|
||||
# a single customer. Kept on failure too: a failed alias verification is precisely
|
||||
# when someone wants to look at the file.
|
||||
- name: Upload signed scripts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: signed-scripts
|
||||
path: ${{ runner.temp }}/signed-scripts
|
||||
if-no-files-found: ignore
|
||||
|
||||
@@ -145,6 +145,10 @@ internal/docs/~$Introduction-AutopilotMonitor.pptx
|
||||
# changes each run) and served at /version.json from the static export.
|
||||
src/Web/autopilot-monitor-web/public/version.json
|
||||
|
||||
# What's new payload: generated by scripts/whats-new/build-whats-new.js from the docs
|
||||
# checkout on every build and served at /whats-new.json from the static export.
|
||||
src/Web/autopilot-monitor-web/public/whats-new.json
|
||||
|
||||
|
||||
# Local IME installer scratch (MSI + extracted payload per version, for grepping
|
||||
# in binaries). Operator-only, never committed.
|
||||
|
||||
@@ -1,33 +1,63 @@
|
||||
# <img src=".github/assets/logo.svg" height="28" alt="" /> Autopilot Monitor
|
||||
# <img src=".github/assets/logo.svg" height="28" alt="Autopilot Monitor logo" /> Autopilot Monitor
|
||||
|
||||
[](https://www.autopilotmonitor.com)
|
||||
[](LICENSE)
|
||||
[](https://www.autopilotmonitor.com)
|
||||
|
||||
Advanced monitoring and troubleshooting solution for Windows Autopilot deployments. Gain full visibility into every enrollment session with a detailed event timeline, fleet health dashboards, and session reporting. Define custom analysis rules to automatically detect issues and gather rules to collect targeted evidence. Retrieve diagnostics packages on demand, configure agent settings like auto-reboot behavior and automatic timezone adjustment — all managed centrally from the web dashboard.
|
||||
Autopilot Monitor is an open-source, real-time monitoring and troubleshooting platform for **Windows Autopilot** and **Microsoft Intune** enrollment. It records enrollment events, application installations, policies, device state, and diagnostics while provisioning is still running, instead of collecting logs by hand after a failure. Administrators get live enrollment tracking, Enrollment Status Page (ESP) visibility, detailed session timelines, automated issue detection, on-demand diagnostics, fleet health analytics, and AI-assisted troubleshooting through a hosted Model Context Protocol (MCP) server.
|
||||
|
||||
The platform supports classic Windows Autopilot and modern Intune provisioning scenarios, including **Windows Autopilot Device Preparation**.
|
||||
|
||||
## Availability
|
||||
|
||||
Autopilot Monitor is **publicly available** — the Community plan is free. Sign in with your work account at **[autopilotmonitor.com](https://www.autopilotmonitor.com)**; new organizations complete a short activation step after first sign-in.
|
||||
|
||||
<p align="center">
|
||||
<img src=".github/assets/SessionList.png" width="45%" />
|
||||
<img src=".github/assets/FleetHealth.png" width="45%" />
|
||||
<img src=".github/assets/SessionList.png" width="45%" alt="Autopilot Monitor dashboard showing live Windows Autopilot and Intune enrollment sessions" />
|
||||
<img src=".github/assets/FleetHealth.png" width="45%" alt="Autopilot Monitor fleet health dashboard with Windows Autopilot enrollment analytics and success metrics" />
|
||||
</p>
|
||||
<p align="center">
|
||||
<img src=".github/assets/SessionDetails.png" width="45%" />
|
||||
<img src=".github/assets/SessionTimeline.png" width="45%" />
|
||||
<img src=".github/assets/SessionDetails.png" width="45%" alt="Autopilot Monitor session details showing device information, diagnostics, apps, policies, and enrollment status" />
|
||||
<img src=".github/assets/SessionTimeline.png" width="45%" alt="Windows Autopilot enrollment timeline showing ESP phases, application installs, policies, events, and errors" />
|
||||
</p>
|
||||
|
||||
## Overview
|
||||
## Key Features
|
||||
|
||||
Autopilot Monitor provides real-time tracking, intelligent diagnostics, and automated troubleshooting for Windows Autopilot enrollment processes. It consists of:
|
||||
- **Real-time Windows Autopilot monitoring** — follow device provisioning while enrollment is still running
|
||||
- **Detailed enrollment timelines** — correlate Autopilot, ESP, Intune Management Extension, apps, policies, device state, and system events
|
||||
- **Enrollment Status Page visibility** — see which phase, application, or policy is delaying provisioning
|
||||
- **Automated issue detection** — define custom analysis rules that identify known failure patterns
|
||||
- **Targeted evidence collection** — gather registry values, event log entries, files, log-parser matches, and allow-listed commands when specific conditions are detected
|
||||
- **On-demand diagnostics** — request diagnostics packages from enrolled devices remotely
|
||||
- **Fleet health analytics** — success rates, deployment duration, device models, applications, errors, and recurring issues
|
||||
- **Session reporting** — inspect and share detailed enrollment information for individual devices
|
||||
- **Windows Autopilot Device Preparation support** — monitor Device Preparation deployments alongside classic Autopilot scenarios
|
||||
- **Centralized agent configuration** — control diagnostic behavior, automatic reboots, timezone adjustment, and other monitoring settings from the web dashboard
|
||||
- **AI-assisted troubleshooting** — query enrollment data through the built-in Model Context Protocol server
|
||||
|
||||
- **Bootstrap Script** — PowerShell script deployed via Intune that starts monitoring early in the enrollment process
|
||||
- **Monitoring Agent** — Lightweight .NET application that collects telemetry and evidence during enrollment
|
||||
## How it works
|
||||
|
||||
Autopilot Monitor consists of several components working together throughout Windows enrollment:
|
||||
|
||||
- **Bootstrap Script** — PowerShell script deployed through Microsoft Intune that starts monitoring early in the provisioning process
|
||||
- **Monitoring Agent** — lightweight .NET application that collects telemetry and evidence during enrollment
|
||||
- **Backend API** — Azure Functions-based ingestion and processing pipeline
|
||||
- **Web Dashboard** — Next.js application for real-time monitoring and fleet analytics
|
||||
- **MCP Server** — Model Context Protocol server that lets AI assistants query and troubleshoot enrollments in natural language
|
||||
- **Web Dashboard** — Next.js application for real-time monitoring, troubleshooting, and fleet analytics
|
||||
- **MCP Server** — Model Context Protocol server that lets AI assistants query Autopilot Monitor data in natural language
|
||||
|
||||
## Windows Autopilot and Intune Troubleshooting
|
||||
|
||||
Autopilot Monitor helps investigate common Windows provisioning and enrollment problems such as:
|
||||
|
||||
- Windows Autopilot deployments that fail or appear stuck
|
||||
- Enrollment Status Page (ESP) delays and unusually long deployment phases
|
||||
- Win32 application installation failures and slow application downloads
|
||||
- Intune Management Extension problems
|
||||
- Microsoft Entra join, Hybrid Join, and device registration issues
|
||||
- policies that block or delay provisioning
|
||||
- inconsistent behavior across hardware models and recurring failures affecting multiple devices
|
||||
|
||||
Because telemetry is collected during enrollment, many problems can be investigated without reproducing the issue or manually collecting logs from the affected device.
|
||||
|
||||
## AI Integration (MCP)
|
||||
|
||||
@@ -35,13 +65,19 @@ Autopilot Monitor ships a hosted **[Model Context Protocol](https://modelcontext
|
||||
|
||||
- *"Show me all failed enrollments from the last 24 hours and group them by failure reason."*
|
||||
- *"Why did session X fail, and which app install caused the delay?"*
|
||||
- *"Which devices had unusually long ESP application phases this week?"*
|
||||
- *"Which device models have the highest Autopilot failure rate?"*
|
||||
- *"Which devices in my fleet are affected by CVE-2024-30078?"*
|
||||
|
||||
Server URL: `https://mcp.autopilotmonitor.com/mcp` — sign-in runs through your existing work account, access is scoped to your tenant exactly like in the portal, and no credentials are stored. Setup guide: **[AI Integration (MCP)](https://docs.autopilotmonitor.com/integrations/ai-integration-mcp)**.
|
||||
Server URL: `https://mcp.autopilotmonitor.com/mcp` — sign-in runs through your existing work account, access is scoped to your tenant exactly like in the portal, and the MCP server stores no credentials. Setup guide: **[AI Integration (MCP)](https://docs.autopilotmonitor.com/integrations/ai-integration-mcp)**.
|
||||
|
||||
## Documentation
|
||||
|
||||
Full admin documentation is available at **[docs.autopilotmonitor.com](https://docs.autopilotmonitor.com)**
|
||||
Full admin documentation is available at **[docs.autopilotmonitor.com](https://docs.autopilotmonitor.com)** — deployment, configuration, monitoring, diagnostics, troubleshooting, analysis and gather rules, integrations, and AI-assisted troubleshooting.
|
||||
|
||||
## Open Source
|
||||
|
||||
Autopilot Monitor is developed openly on GitHub. The source is published so that customers and security reviewers can see what runs on their devices and with their data: the repository contains the device agent, shared library, backend, web dashboard, and MCP server.
|
||||
|
||||
## Feedback
|
||||
|
||||
|
||||
+1
-1
Submodule infra updated: 2c2687b6ab...55a8eaf929
+1
-1
Submodule internal updated: 54efd666b0...8204fc68af
@@ -5,7 +5,7 @@
|
||||
"description": "Detects when the Enrollment Status Page failed on the Apps subcategory and the agent's AppX deployment log scan identified a suspected MSIX/Store package. Store/MSIX apps install outside the Win32 pipeline, so the regular per-app tracking sees nothing — this correlation names the likely culprit.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
@@ -93,7 +93,7 @@
|
||||
"steps": [
|
||||
"Open Event Viewer → Applications and Services Logs → Microsoft → Windows → AppXDeploymentServer → Operational on the device (or in the diagnostics archive if uploaded)",
|
||||
"Filter for Error-level events around the ESP failure time and confirm the package name and HRESULT match this finding",
|
||||
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = invalid/corrupt package, 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
|
||||
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = package could not be opened (unsigned, publisher mismatch, or not found), 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"$schema": "../schema/analyze-rule.schema.json",
|
||||
"ruleId": "ANALYZE-APP-018",
|
||||
"title": "App Return Code Requested a Reboot During Enrollment",
|
||||
"description": "Detects Win32 apps whose installer exit code maps to Soft reboot or Hard reboot in the app's Intune return-code table (the '[Win32App] lpExitCode is defined as ...' line). Hard reboot stops app processing and restarts the device in Device Setup - the mid-enrollment restart and second sign-in; Soft reboot leaves the app pending until the next restart while the ESP moves on. Confidence rises for Hard reboot and when a reboot was actually observed in the session.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
"whiteglove_sealed"
|
||||
],
|
||||
"trigger": "single",
|
||||
"baseConfidence": 60,
|
||||
"conditions": [
|
||||
{
|
||||
"signal": "reboot_return_code",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_completed",
|
||||
"dataField": "exitCodeClass",
|
||||
"operator": "in",
|
||||
"value": "SoftReboot,HardReboot",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "hard_reboot_return_code",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_completed",
|
||||
"dataField": "exitCodeClass",
|
||||
"operator": "equals",
|
||||
"value": "HardReboot",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"signal": "reboot_observed",
|
||||
"source": "event_count",
|
||||
"eventType": "system_reboot_detected",
|
||||
"operator": "count_gte",
|
||||
"value": "1",
|
||||
"required": false
|
||||
}
|
||||
],
|
||||
"confidenceFactors": [
|
||||
{
|
||||
"signal": "hard_reboot_return_code",
|
||||
"condition": "exists",
|
||||
"weight": 25
|
||||
},
|
||||
{
|
||||
"signal": "reboot_observed",
|
||||
"condition": "exists",
|
||||
"weight": 15
|
||||
}
|
||||
],
|
||||
"confidenceThreshold": 60,
|
||||
"explanation": "App **{{appName}}** returned exit code **{{exitCode}}**, which its Intune return-code table maps to **{{exitCodeClass}}** - the installer asked for a restart before its work is complete.\n\n- **SoftReboot**: the Intune Management Extension reports the app as *pending reboot*. The Enrollment Status Page treats it as completed and moves on, and Intune only marks the app installed after the next restart re-evaluates the detection rule. Until then the app may be unusable or half-configured, and the user sees a restart notification.\n- **HardReboot**: the Intune Management Extension stops processing further apps and, in Device Setup, restarts the device right away (the restart grace period does not apply during the ESP) - the same mid-enrollment restart and second sign-in that ANALYZE-ESP-005 attributes to reboot-required policies. In Account Setup the extension does not restart the device itself and the app stays pending.\n\nA restart requested by an installer is normal for many MSI packages (exit codes 3010 and 1641), but during Autopilot it lengthens the ESP, can surprise the user with a restart, and hides the app's real state until after the reboot. The return-code class is the app's own configuration in Intune, not a device fault.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Check the app's return-code mapping",
|
||||
"steps": [
|
||||
"Open the app in the Intune admin center > Properties > Program and review the return codes table: exit code {{exitCode}} is currently mapped to {{exitCodeClass}}",
|
||||
"If the installer only recommends a restart (MSI 3010 ERROR_SUCCESS_REBOOT_REQUIRED, 1641 ERROR_SUCCESS_REBOOT_INITIATED), map the code to Soft reboot instead of Hard reboot so the next app can install before the restart",
|
||||
"If the app works without an immediate restart, suppress the installer's own reboot (for MSI: REBOOT=ReallySuppress on the install command) so it returns 0 and the restart happens on your schedule",
|
||||
"Keep Hard reboot only when the following apps genuinely cannot install before the restart - and then expect the mid-ESP restart in every enrollment"
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "Take the app out of the ESP critical path",
|
||||
"steps": [
|
||||
"If the app is not needed for first use, remove it from the ESP blocking-app list so the restart happens after the user reaches the desktop",
|
||||
"If it must stay blocking, order it last in Device Setup (dependencies or install order) so a hard reboot does not interrupt the remaining apps",
|
||||
"For Soft reboot apps, plan a restart at the end of enrollment or accept that the app finishes on the user's first restart"
|
||||
]
|
||||
}
|
||||
],
|
||||
"relatedDocs": [
|
||||
{
|
||||
"title": "Microsoft Learn: Add a Win32 app - Program step (device restart behavior and return codes)",
|
||||
"url": "https://learn.microsoft.com/en-us/intune/app-management/deployment/add-win32#step-2-program"
|
||||
},
|
||||
{
|
||||
"title": "Microsoft Learn: Enrollment Status Page tracking",
|
||||
"url": "https://learn.microsoft.com/en-us/autopilot/enrollment-status"
|
||||
}
|
||||
],
|
||||
"markSessionAsFailedDefault": false,
|
||||
"tags": [
|
||||
"apps",
|
||||
"reboot",
|
||||
"return-code",
|
||||
"soft-reboot",
|
||||
"hard-reboot",
|
||||
"esp",
|
||||
"second-sign-in"
|
||||
]
|
||||
}
|
||||
+99
-2
@@ -615,7 +615,7 @@
|
||||
"description": "Detects when the Enrollment Status Page failed on the Apps subcategory and the agent's AppX deployment log scan identified a suspected MSIX/Store package. Store/MSIX apps install outside the Win32 pipeline, so the regular per-app tracking sees nothing — this correlation names the likely culprit.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.1",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
@@ -703,7 +703,7 @@
|
||||
"steps": [
|
||||
"Open Event Viewer → Applications and Services Logs → Microsoft → Windows → AppXDeploymentServer → Operational on the device (or in the diagnostics archive if uploaded)",
|
||||
"Filter for Error-level events around the ESP failure time and confirm the package name and HRESULT match this finding",
|
||||
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = invalid/corrupt package, 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
|
||||
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = package could not be opened (unsigned, publisher mismatch, or not found), 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -1034,6 +1034,103 @@
|
||||
"esp"
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "ANALYZE-APP-018",
|
||||
"title": "App Return Code Requested a Reboot During Enrollment",
|
||||
"description": "Detects Win32 apps whose installer exit code maps to Soft reboot or Hard reboot in the app's Intune return-code table (the '[Win32App] lpExitCode is defined as ...' line). Hard reboot stops app processing and restarts the device in Device Setup - the mid-enrollment restart and second sign-in; Soft reboot leaves the app pending until the next restart while the ESP moves on. Confidence rises for Hard reboot and when a reboot was actually observed in the session.",
|
||||
"severity": "warning",
|
||||
"category": "apps",
|
||||
"version": "1.0.0",
|
||||
"author": "Autopilot Monitor",
|
||||
"enabled": true,
|
||||
"evaluateOn": [
|
||||
"enrollment_end",
|
||||
"whiteglove_sealed"
|
||||
],
|
||||
"trigger": "single",
|
||||
"baseConfidence": 60,
|
||||
"conditions": [
|
||||
{
|
||||
"signal": "reboot_return_code",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_completed",
|
||||
"dataField": "exitCodeClass",
|
||||
"operator": "in",
|
||||
"value": "SoftReboot,HardReboot",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "hard_reboot_return_code",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_completed",
|
||||
"dataField": "exitCodeClass",
|
||||
"operator": "equals",
|
||||
"value": "HardReboot",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"signal": "reboot_observed",
|
||||
"source": "event_count",
|
||||
"eventType": "system_reboot_detected",
|
||||
"operator": "count_gte",
|
||||
"value": "1",
|
||||
"required": false
|
||||
}
|
||||
],
|
||||
"confidenceFactors": [
|
||||
{
|
||||
"signal": "hard_reboot_return_code",
|
||||
"condition": "exists",
|
||||
"weight": 25
|
||||
},
|
||||
{
|
||||
"signal": "reboot_observed",
|
||||
"condition": "exists",
|
||||
"weight": 15
|
||||
}
|
||||
],
|
||||
"confidenceThreshold": 60,
|
||||
"explanation": "App **{{appName}}** returned exit code **{{exitCode}}**, which its Intune return-code table maps to **{{exitCodeClass}}** - the installer asked for a restart before its work is complete.\n\n- **SoftReboot**: the Intune Management Extension reports the app as *pending reboot*. The Enrollment Status Page treats it as completed and moves on, and Intune only marks the app installed after the next restart re-evaluates the detection rule. Until then the app may be unusable or half-configured, and the user sees a restart notification.\n- **HardReboot**: the Intune Management Extension stops processing further apps and, in Device Setup, restarts the device right away (the restart grace period does not apply during the ESP) - the same mid-enrollment restart and second sign-in that ANALYZE-ESP-005 attributes to reboot-required policies. In Account Setup the extension does not restart the device itself and the app stays pending.\n\nA restart requested by an installer is normal for many MSI packages (exit codes 3010 and 1641), but during Autopilot it lengthens the ESP, can surprise the user with a restart, and hides the app's real state until after the reboot. The return-code class is the app's own configuration in Intune, not a device fault.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Check the app's return-code mapping",
|
||||
"steps": [
|
||||
"Open the app in the Intune admin center > Properties > Program and review the return codes table: exit code {{exitCode}} is currently mapped to {{exitCodeClass}}",
|
||||
"If the installer only recommends a restart (MSI 3010 ERROR_SUCCESS_REBOOT_REQUIRED, 1641 ERROR_SUCCESS_REBOOT_INITIATED), map the code to Soft reboot instead of Hard reboot so the next app can install before the restart",
|
||||
"If the app works without an immediate restart, suppress the installer's own reboot (for MSI: REBOOT=ReallySuppress on the install command) so it returns 0 and the restart happens on your schedule",
|
||||
"Keep Hard reboot only when the following apps genuinely cannot install before the restart - and then expect the mid-ESP restart in every enrollment"
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "Take the app out of the ESP critical path",
|
||||
"steps": [
|
||||
"If the app is not needed for first use, remove it from the ESP blocking-app list so the restart happens after the user reaches the desktop",
|
||||
"If it must stay blocking, order it last in Device Setup (dependencies or install order) so a hard reboot does not interrupt the remaining apps",
|
||||
"For Soft reboot apps, plan a restart at the end of enrollment or accept that the app finishes on the user's first restart"
|
||||
]
|
||||
}
|
||||
],
|
||||
"relatedDocs": [
|
||||
{
|
||||
"title": "Microsoft Learn: Add a Win32 app - Program step (device restart behavior and return codes)",
|
||||
"url": "https://learn.microsoft.com/en-us/intune/app-management/deployment/add-win32#step-2-program"
|
||||
},
|
||||
{
|
||||
"title": "Microsoft Learn: Enrollment Status Page tracking",
|
||||
"url": "https://learn.microsoft.com/en-us/autopilot/enrollment-status"
|
||||
}
|
||||
],
|
||||
"markSessionAsFailedDefault": false,
|
||||
"tags": [
|
||||
"apps",
|
||||
"reboot",
|
||||
"return-code",
|
||||
"soft-reboot",
|
||||
"hard-reboot",
|
||||
"esp",
|
||||
"second-sign-in"
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "ANALYZE-CORR-003",
|
||||
"title": "Proxy Configuration Causing Download Failure",
|
||||
|
||||
+11
@@ -339,6 +339,17 @@
|
||||
"description": "Captures the installer exit code (lpExitCode) for the current app.",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"patternId": "IME-EXITCODE-CLASS",
|
||||
"category": "currentPhase",
|
||||
"pattern": "^\\[Win32App\\] lpExitCode is defined as (?<exitCodeClass>Success|SoftReboot|HardReboot|Retry|Failed)$",
|
||||
"action": "captureExitCodeClass",
|
||||
"parameters": {
|
||||
"useCurrentApp": "true"
|
||||
},
|
||||
"description": "Captures the admin-defined return-code class of the installer exit code for the current app ('[Win32App] lpExitCode is defined as <Failed|Success|SoftReboot|HardReboot|Retry>', Win32AppInstaller.cs, enum AppReturnCodeType - literal identical from IME 1.50 through 1.105). Stored as exitCodeClass on the app and emitted on its terminal events; the last value wins, so a Retry loop that ends in Success reports Success. Anchored on both ends on purpose: the no-mapping warning ('... defined as <n>, fall into default now.') and an unparsable numeric type print a raw number and must not match. Companion of IME-EXITCODE (the number, logged just before) and IME-EXITCODE-MAPPED-FAILED (the Failed state transition), which still owns the error path.",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"patternId": "IME-EXITCODE-MAPPED-FAILED",
|
||||
"category": "currentPhase",
|
||||
|
||||
@@ -282,5 +282,25 @@
|
||||
"log_entry",
|
||||
"agent_trace",
|
||||
"stall_probe_check"
|
||||
],
|
||||
"imeLogDerivedEventTypes": [
|
||||
"app_install_started",
|
||||
"app_install_completed",
|
||||
"app_install_failed",
|
||||
"app_install_skipped",
|
||||
"app_download_started",
|
||||
"app_tracking_summary",
|
||||
"download_progress",
|
||||
"do_telemetry",
|
||||
"script_started",
|
||||
"script_completed",
|
||||
"script_failed",
|
||||
"script_timeout_suspected",
|
||||
"esp_phase_changed",
|
||||
"ime_agent_version",
|
||||
"ime_token_failure",
|
||||
"ime_user_session_completed",
|
||||
"ime_process_exited",
|
||||
"ime_user_token_acquired"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "../schema/ime-log-pattern.schema.json",
|
||||
"patternId": "IME-EXITCODE-CLASS",
|
||||
"category": "currentPhase",
|
||||
"pattern": "^\\[Win32App\\] lpExitCode is defined as (?<exitCodeClass>Success|SoftReboot|HardReboot|Retry|Failed)$",
|
||||
"action": "captureExitCodeClass",
|
||||
"parameters": { "useCurrentApp": "true" },
|
||||
"description": "Captures the admin-defined return-code class of the installer exit code for the current app ('[Win32App] lpExitCode is defined as <Failed|Success|SoftReboot|HardReboot|Retry>', Win32AppInstaller.cs, enum AppReturnCodeType - literal identical from IME 1.50 through 1.105). Stored as exitCodeClass on the app and emitted on its terminal events; the last value wins, so a Retry loop that ends in Success reports Success. Anchored on both ends on purpose: the no-mapping warning ('... defined as <n>, fall into default now.') and an unparsable numeric type print a raw number and must not match. Companion of IME-EXITCODE (the number, logged just before) and IME-EXITCODE-MAPPED-FAILED (the Failed state transition), which still owns the error path.",
|
||||
"enabled": true
|
||||
}
|
||||
@@ -114,6 +114,11 @@
|
||||
"description": "Emit behavior: \"always\" (default — emit on every collection) or \"on_change\" (poll on the trigger cadence but emit only when the collected result changes; the first in-scope result always emits).",
|
||||
"enum": ["always", "on_change"]
|
||||
},
|
||||
"enrichErrorCodes": {
|
||||
"type": "boolean",
|
||||
"description": "Opt-in: let the backend explain error-code fields in this rule's output (exitCode, errorCode, hresult, ...) with the Windows/MSI/Intune error-code catalog, attaching the same *Info siblings built-in events get. Default false because gather-rule codes usually come from third-party logs or commands (HP Image Assistant, Dell Command Update, custom scripts) with their own exit-code numbering, where the catalog meaning would be wrong. Enable only when the parsed source really uses Windows codes (e.g. an msiexec or IME log).",
|
||||
"default": false
|
||||
},
|
||||
"outputEventType": {
|
||||
"type": "string",
|
||||
"description": "EventType for the emitted event (e.g., \"gather_proxy_settings\")."
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"blockedFilePrefixes": { "$ref": "#/$defs/stringList" },
|
||||
"blockedCommandPatterns": { "$ref": "#/$defs/stringList" },
|
||||
"blockedInterimTriggerEventTypes": { "$ref": "#/$defs/stringList" },
|
||||
"imeLogDerivedEventTypes": { "$ref": "#/$defs/stringList" },
|
||||
"maxCommandLength": { "type": "integer", "minimum": 1, "maximum": 100000 }
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -79,7 +79,8 @@
|
||||
"captureAppTypeWinGet",
|
||||
"captureAppTypeMsi",
|
||||
"captureAttemptNumber",
|
||||
"captureDetectionResult"
|
||||
"captureDetectionResult",
|
||||
"captureExitCodeClass"
|
||||
]
|
||||
},
|
||||
"parameters": {
|
||||
|
||||
@@ -142,6 +142,7 @@ if (fs.existsSync(guardrailsPath)) {
|
||||
assertStringList(guardrails[key], key);
|
||||
}
|
||||
assertStringList(guardrails.blockedInterimTriggerEventTypes ?? [], 'blockedInterimTriggerEventTypes');
|
||||
assertStringList(guardrails.imeLogDerivedEventTypes ?? [], 'imeLogDerivedEventTypes');
|
||||
if (!Number.isInteger(guardrails.maxCommandLength) || guardrails.maxCommandLength < 1) {
|
||||
fail(`maxCommandLength: expected a positive integer, got ${JSON.stringify(guardrails.maxCommandLength)}`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
# Pester tests (Pester 5+) for the stage-1 loader Start-AutopilotMonitor.ps1.
|
||||
#
|
||||
# The script under test is dot-sourced; its entry guard prevents the loader from
|
||||
# executing, so loading it here is side-effect free. Network and signature checks
|
||||
# are mocked -- what is verified is the DECISION: what does the loader accept, what
|
||||
# does it refuse, and how often does it retry.
|
||||
#
|
||||
# Run under Windows PowerShell 5.1 to match the IME runtime:
|
||||
# powershell.exe -NoProfile -Command "& { $c = New-PesterConfiguration; $c.Run.Path = 'scripts\Bootstrap'; $c.Output.Verbosity = 'Detailed'; Invoke-Pester -Configuration $c }"
|
||||
#
|
||||
# This file MUST remain pure ASCII (PS 5.1 reads BOM-less files as ANSI).
|
||||
|
||||
BeforeAll {
|
||||
. (Join-Path $PSScriptRoot 'Start-AutopilotMonitor.ps1')
|
||||
|
||||
function New-FakeSignature {
|
||||
param([string]$Status, [string]$Subject)
|
||||
$cert = if ($Subject) {
|
||||
[pscustomobject]@{ Subject = $Subject; Thumbprint = '0123456789ABCDEF' }
|
||||
} else { $null }
|
||||
return [pscustomobject]@{ Status = $Status; SignerCertificate = $cert }
|
||||
}
|
||||
}
|
||||
|
||||
Describe 'Test-BootstrapSignature' {
|
||||
BeforeEach {
|
||||
Mock Write-Log { }
|
||||
}
|
||||
|
||||
It 'accepts a valid signature from the expected publisher' {
|
||||
Mock Get-AuthenticodeSignature { New-FakeSignature -Status 'Valid' -Subject 'CN=glueckkanja AG, O=glueckkanja AG, C=DE' }
|
||||
Test-BootstrapSignature -Path 'TestDrive:\x.ps1' | Should -BeTrue
|
||||
}
|
||||
|
||||
# An EV subject is a line of street address and registration numbers; the log gets the CN.
|
||||
It 'logs the signer CN, not the whole subject' {
|
||||
Mock Get-AuthenticodeSignature {
|
||||
New-FakeSignature -Status 'Valid' -Subject 'CN=glueckkanja AG, O=glueckkanja AG, L=Offenbach am Main, C=DE, SERIALNUMBER=HRB 12381'
|
||||
}
|
||||
Test-BootstrapSignature -Path 'TestDrive:\x.ps1' | Should -BeTrue
|
||||
Should -Invoke Write-Log -ParameterFilter { $Message -eq 'Signature status: Valid. Signer: glueckkanja AG' }
|
||||
}
|
||||
|
||||
It 'refuses an unsigned script' {
|
||||
Mock Get-AuthenticodeSignature { New-FakeSignature -Status 'NotSigned' -Subject $null }
|
||||
Test-BootstrapSignature -Path 'TestDrive:\x.ps1' | Should -BeFalse
|
||||
}
|
||||
|
||||
It 'refuses a tampered script (hash mismatch)' {
|
||||
Mock Get-AuthenticodeSignature { New-FakeSignature -Status 'HashMismatch' -Subject 'CN=glueckkanja AG, O=glueckkanja AG, C=DE' }
|
||||
Test-BootstrapSignature -Path 'TestDrive:\x.ps1' | Should -BeFalse
|
||||
}
|
||||
|
||||
It 'refuses a signature whose chain does not validate' {
|
||||
Mock Get-AuthenticodeSignature { New-FakeSignature -Status 'UnknownError' -Subject 'CN=glueckkanja AG, O=glueckkanja AG, C=DE' }
|
||||
Test-BootstrapSignature -Path 'TestDrive:\x.ps1' | Should -BeFalse
|
||||
}
|
||||
|
||||
# The whole point of the pinned publisher: a validly signed script from someone else
|
||||
# is exactly what an attacker with any code-signing certificate can produce.
|
||||
It 'refuses a valid signature from a different publisher' {
|
||||
Mock Get-AuthenticodeSignature { New-FakeSignature -Status 'Valid' -Subject 'CN=Somebody Else, O=Somebody Else Ltd, C=US' }
|
||||
Test-BootstrapSignature -Path 'TestDrive:\x.ps1' | Should -BeFalse
|
||||
}
|
||||
|
||||
It 'refuses when the signature check itself fails' {
|
||||
Mock Get-AuthenticodeSignature { throw 'file not found' }
|
||||
Test-BootstrapSignature -Path 'TestDrive:\x.ps1' | Should -BeFalse
|
||||
}
|
||||
}
|
||||
|
||||
Describe 'Get-VerifiedBootstrapScript' {
|
||||
BeforeEach {
|
||||
Mock Write-Log { }
|
||||
Mock Start-Sleep { }
|
||||
Mock Invoke-WebRequest { }
|
||||
}
|
||||
|
||||
It 'returns after the first attempt when the download verifies' {
|
||||
Mock Test-BootstrapSignature { $true }
|
||||
Get-VerifiedBootstrapScript -Url 'https://example.invalid/s.ps1' -Destination 'TestDrive:\s.ps1' | Should -BeTrue
|
||||
Should -Invoke Invoke-WebRequest -Times 1 -Exactly
|
||||
}
|
||||
|
||||
It 'gives up after three attempts when verification keeps failing' {
|
||||
Mock Test-BootstrapSignature { $false }
|
||||
Get-VerifiedBootstrapScript -Url 'https://example.invalid/s.ps1' -Destination 'TestDrive:\s.ps1' | Should -BeFalse
|
||||
Should -Invoke Invoke-WebRequest -Times 3 -Exactly
|
||||
}
|
||||
|
||||
# A truncated or proxy-mangled body fails verification, so the retry has to cover the
|
||||
# download AND the check, not just the transport.
|
||||
It 'retries a failed verification and accepts a later attempt' {
|
||||
$script:calls = 0
|
||||
Mock Test-BootstrapSignature { $script:calls++; return ($script:calls -ge 2) }
|
||||
Get-VerifiedBootstrapScript -Url 'https://example.invalid/s.ps1' -Destination 'TestDrive:\s.ps1' | Should -BeTrue
|
||||
Should -Invoke Invoke-WebRequest -Times 2 -Exactly
|
||||
}
|
||||
|
||||
It 'retries a transport failure' {
|
||||
$script:downloads = 0
|
||||
Mock Invoke-WebRequest { $script:downloads++; if ($script:downloads -eq 1) { throw 'connection reset' } }
|
||||
Mock Test-BootstrapSignature { $true }
|
||||
Get-VerifiedBootstrapScript -Url 'https://example.invalid/s.ps1' -Destination 'TestDrive:\s.ps1' | Should -BeTrue
|
||||
Should -Invoke Invoke-WebRequest -Times 2 -Exactly
|
||||
}
|
||||
|
||||
It 'never executes anything when no attempt verifies' {
|
||||
Mock Test-BootstrapSignature { $false }
|
||||
Get-VerifiedBootstrapScript -Url 'https://example.invalid/s.ps1' -Destination 'TestDrive:\s.ps1' | Should -BeFalse
|
||||
}
|
||||
}
|
||||
|
||||
Describe 'publish contract' {
|
||||
BeforeAll {
|
||||
$script:loaderText = Get-Content (Join-Path $PSScriptRoot 'Start-AutopilotMonitor.ps1') -Raw
|
||||
}
|
||||
|
||||
# Publish-BootstrapScripts.ps1 renders the -Dev loader by substituting this exact
|
||||
# literal and fails the publish when it is gone. Catching that here means the PR fails
|
||||
# instead of the publish.
|
||||
It 'carries the dev-render anchor the publisher substitutes' {
|
||||
$anchor = '$BootstrapUrl = "https://download.autopilotmonitor.com/agent/Install-AutopilotMonitor.ps1"'
|
||||
$script:loaderText.Contains($anchor) | Should -BeTrue
|
||||
}
|
||||
|
||||
# The publisher parses this to write version.json.loaderVersion and to run the
|
||||
# version-bump guard.
|
||||
It 'declares a parsable ScriptVersion' {
|
||||
$script:loaderText -match '\$ScriptVersion\s*=\s*"([\d\.\-a-zA-Z]+)"' | Should -BeTrue
|
||||
}
|
||||
|
||||
It 'pins the expected publisher by subject, not by thumbprint' {
|
||||
$script:loaderText -match '\$ExpectedPublisher\s*=\s*"\*O=' | Should -BeTrue
|
||||
}
|
||||
|
||||
# The bootstrap MSI installs this same file and runs it with -LogFileName so the delivery
|
||||
# channel stays visible in a diagnostics package. Renaming the parameter on either side
|
||||
# would leave the MSI channel silently logging under the wrong name.
|
||||
It 'keeps the -LogFileName contract the bootstrap MSI relies on' {
|
||||
$script:loaderText -match '\[string\]\$LogFileName' | Should -BeTrue
|
||||
|
||||
$wxs = Get-Content (Join-Path $PSScriptRoot '..\..\src\Agent\AutopilotMonitor.BootstrapMsi\Package.wxs') -Raw
|
||||
$wxs.Contains('[INSTALLFOLDER]Start-AutopilotMonitor.ps1') | Should -BeTrue
|
||||
$wxs.Contains('-LogFileName bootstrap-msi.log') | Should -BeTrue
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Stage 1 of the Autopilot Monitor bootstrap: fetches the current installer and runs it.
|
||||
|
||||
.DESCRIPTION
|
||||
This is the file an administrator assigns in Intune, and the same file the bootstrap MSI
|
||||
installs and runs -- one implementation for both delivery channels; the MSI is only the
|
||||
packaging. It carries no enrollment logic at all: it downloads the published
|
||||
Install-AutopilotMonitor.ps1, proves that it was signed by Autopilot Monitor, and runs it
|
||||
in this process.
|
||||
|
||||
Why two stages: the installer holds every guard, relax rule and download path, and those
|
||||
change. Whoever assigns the installer directly has to replace their Intune copy each
|
||||
time; whoever assigns this loader never does, because the part that changes lives on the
|
||||
server. Assigning the installer directly stays supported and unchanged.
|
||||
|
||||
This file is deliberately boring. It is the one piece that cannot be fixed remotely, so
|
||||
it does the least it can: download, verify, invoke, log.
|
||||
|
||||
Verification is by Authenticode publisher, not by hash. A hash oracle would have to be
|
||||
fetched from the same host as the script itself, so it could not survive a compromise of
|
||||
that host, while the expected publisher below travels with this file. It pins the
|
||||
certificate SUBJECT and not a thumbprint, so a certificate renewal does not brick a
|
||||
loader that is already deployed on devices.
|
||||
|
||||
Fail-soft: the loader always exits 0 and never throws into the caller. A device that
|
||||
cannot reach the download endpoint is a device without monitoring, never a failed
|
||||
enrollment step. Verification failures are the same: nothing runs, and the reason is in
|
||||
the log. Refusing to execute unverified code as SYSTEM is the point of this file.
|
||||
|
||||
This file MUST remain pure ASCII (PS 5.1 reads BOM-less files as ANSI).
|
||||
|
||||
.PARAMETER BootstrapUrl
|
||||
Installer URL. Defaults to the published stable installer; the -Dev variant of this
|
||||
loader is rendered from that default at publish time.
|
||||
|
||||
.PARAMETER LogFileName
|
||||
Log file inside the agent log directory. The MSI channel passes bootstrap-msi.log so the
|
||||
delivery channel stays visible in a diagnostics package; the diag tooling keys on these
|
||||
names, so do not rename them.
|
||||
|
||||
.PARAMETER BootstrapArguments
|
||||
Everything else is passed through to the installer unchanged, so any parameter the
|
||||
installer accepts can be set here without this file knowing about it.
|
||||
|
||||
.EXAMPLE
|
||||
.\Start-AutopilotMonitor.ps1
|
||||
|
||||
.EXAMPLE
|
||||
.\Start-AutopilotMonitor.ps1 -MaxBootstrapWindowHours 24
|
||||
|
||||
.NOTES
|
||||
Author : Oliver Kieselbach (autopilotmonitor.com)
|
||||
Runtime : Windows PowerShell 5.1, SYSTEM context, during Autopilot enrollment
|
||||
|
||||
.CHANGELOG
|
||||
2026-09-08 v1.2 Log the signer CN instead of the full EV subject; the full subject is
|
||||
logged only when the publisher is why a script was rejected.
|
||||
2026-09-08 v1.1 Also used by the bootstrap MSI, which replaced its own copy of this
|
||||
logic; -LogFileName keeps the channel visible in diagnostics.
|
||||
2026-09-08 v1.0 Initial version: two-stage bootstrap, publisher-pinned verification.
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$BootstrapUrl = "https://download.autopilotmonitor.com/agent/Install-AutopilotMonitor.ps1",
|
||||
|
||||
[Parameter(Mandatory = $false)]
|
||||
[ValidatePattern('^[A-Za-z0-9._-]+$')]
|
||||
[string]$LogFileName = "bootstrap-loader.log",
|
||||
|
||||
[Parameter(Mandatory = $false, ValueFromRemainingArguments = $true)]
|
||||
[string[]]$BootstrapArguments
|
||||
)
|
||||
|
||||
# Script version (bump on meaningful changes; see .CHANGELOG above)
|
||||
$ScriptVersion = "1.2"
|
||||
|
||||
# The publisher every downloaded stage-2 script must carry. A -like pattern on the subject,
|
||||
# NOT a thumbprint: certificates are renewed, deployed loaders are not.
|
||||
$ExpectedPublisher = "*O=glueckkanja AG*"
|
||||
|
||||
$LoaderBasePath = "$env:ProgramData\AutopilotMonitor"
|
||||
$LoaderLogPath = "$LoaderBasePath\Logs"
|
||||
$LogFile = "$LoaderLogPath\$LogFileName"
|
||||
$BootstrapPath = "$LoaderBasePath\Install-AutopilotMonitor.ps1"
|
||||
|
||||
$DownloadAttempts = 3
|
||||
$RetryDelaySeconds = 10
|
||||
|
||||
# Write-Host as well as the file: the Intune script output is what an administrator sees in
|
||||
# the portal, the file is what a support case reads.
|
||||
function Write-Log {
|
||||
param([string]$Message)
|
||||
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
|
||||
$logMessage = "[$timestamp] $Message"
|
||||
Write-Host $logMessage
|
||||
Add-Content -Path $LogFile -Value $logMessage -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
# True only when the file is signed, the signature validates against the machine's trust
|
||||
# chain, and the signer is us. Any error is a false -- an unreadable signature is an
|
||||
# unverified script.
|
||||
function Test-BootstrapSignature {
|
||||
param([string]$Path)
|
||||
|
||||
try {
|
||||
$sig = Get-AuthenticodeSignature -FilePath $Path -ErrorAction Stop
|
||||
}
|
||||
catch {
|
||||
Write-Log "Signature check failed to run: $($_.Exception.Message)"
|
||||
return $false
|
||||
}
|
||||
|
||||
if ($null -eq $sig) {
|
||||
Write-Log "Signature check returned nothing."
|
||||
return $false
|
||||
}
|
||||
|
||||
# The full subject of an EV certificate is a line of street address and registration
|
||||
# numbers. The CN answers the only question the log has to answer; the full subject is
|
||||
# logged when it is the reason for a rejection.
|
||||
$subject = if ($sig.SignerCertificate) { $sig.SignerCertificate.Subject } else { "<unsigned>" }
|
||||
$signer = if ($subject -match 'CN=([^,]+)') { $Matches[1] } else { $subject }
|
||||
Write-Log "Signature status: $($sig.Status). Signer: $signer"
|
||||
|
||||
if ($sig.Status -ne 'Valid') {
|
||||
Write-Log "REJECTED: expected signature status 'Valid'."
|
||||
return $false
|
||||
}
|
||||
if ($subject -notlike $ExpectedPublisher) {
|
||||
Write-Log "REJECTED: signer does not match the expected publisher. Full subject: $subject"
|
||||
return $false
|
||||
}
|
||||
|
||||
Write-Log "Signature accepted (thumbprint $($sig.SignerCertificate.Thumbprint))."
|
||||
return $true
|
||||
}
|
||||
|
||||
# Downloads the installer and returns $true once a downloaded copy passes verification.
|
||||
# Verification lives inside the retry loop on purpose: a truncated or proxy-mangled body
|
||||
# fails the signature check, and that is worth another attempt.
|
||||
function Get-VerifiedBootstrapScript {
|
||||
param([string]$Url, [string]$Destination)
|
||||
|
||||
for ($attempt = 1; $attempt -le $DownloadAttempts; $attempt++) {
|
||||
try {
|
||||
Write-Log "Download attempt $attempt/$DownloadAttempts from $Url"
|
||||
Invoke-WebRequest -Uri $Url -OutFile $Destination -UseBasicParsing -TimeoutSec 60 -ErrorAction Stop
|
||||
|
||||
if (Test-BootstrapSignature -Path $Destination) {
|
||||
return $true
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-Log "Download attempt $attempt failed: $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
if ($attempt -lt $DownloadAttempts) {
|
||||
Start-Sleep -Seconds $RetryDelaySeconds
|
||||
}
|
||||
}
|
||||
|
||||
return $false
|
||||
}
|
||||
|
||||
# Main flow. Only invoked when the script is run directly (see entry guard at the bottom),
|
||||
# so the Pester suite can dot-source this file without bootstrapping anything.
|
||||
function Start-BootstrapLoader {
|
||||
New-Item -ItemType Directory -Force -Path $LoaderLogPath -ErrorAction SilentlyContinue | Out-Null
|
||||
|
||||
Write-Log "=== Autopilot Monitor bootstrap loader v$ScriptVersion started (user=$env:USERNAME, pid=$PID) ==="
|
||||
|
||||
# PS 5.1 on an OOBE device still defaults to TLS 1.0 for this process.
|
||||
try {
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
|
||||
}
|
||||
catch {
|
||||
Write-Log "INFO: could not raise the TLS protocol: $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
if (-not (Get-VerifiedBootstrapScript -Url $BootstrapUrl -Destination $BootstrapPath)) {
|
||||
Write-Log "No verified installer available after $DownloadAttempts attempt(s). Nothing was executed."
|
||||
return
|
||||
}
|
||||
|
||||
Write-Log "Executing $BootstrapPath"
|
||||
|
||||
# Same process, so the execution policy this loader runs under applies to stage 2 as
|
||||
# well and no second policy decision can strand the installer. Splatting an array of
|
||||
# remaining arguments keeps this file free of any knowledge about the installer's
|
||||
# parameters.
|
||||
$arguments = @()
|
||||
if ($BootstrapArguments) { $arguments = $BootstrapArguments }
|
||||
|
||||
try {
|
||||
& $BootstrapPath @arguments
|
||||
Write-Log "Installer finished (exit code $LASTEXITCODE)."
|
||||
}
|
||||
catch {
|
||||
Write-Log "Installer threw: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
|
||||
# Entry guard: dot-sourcing (Pester) loads the functions without running the loader.
|
||||
if ($MyInvocation.InvocationName -ne '.') {
|
||||
try {
|
||||
Start-BootstrapLoader
|
||||
}
|
||||
catch {
|
||||
# Nothing above should throw; if it does, it must not become a failed Intune script.
|
||||
Write-Log "Loader failed: $($_.Exception.Message)"
|
||||
}
|
||||
exit 0
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
|
||||
{
|
||||
/// <summary>
|
||||
/// <see cref="GatherRule.EnrichErrorCodes"/> is an opt-in the backend honours at response time:
|
||||
/// the agent stamps <c>enrichErrorCodes: true</c> into the event data of a rule that set it and
|
||||
/// nothing at all otherwise (the default payload stays as it was).
|
||||
/// </summary>
|
||||
[Collection("SerialThreading")] // startup rules execute on the shared ThreadPool
|
||||
public sealed class GatherRuleExecutorEnrichErrorCodesTests : IDisposable
|
||||
{
|
||||
private readonly TempDirectory _tmp = new TempDirectory();
|
||||
private readonly List<EnrollmentEvent> _events = new List<EnrollmentEvent>();
|
||||
private readonly object _eventsGate = new object();
|
||||
private readonly GatherRuleExecutor _executor;
|
||||
|
||||
private const string AbsentPath =
|
||||
"HKLM\\SOFTWARE\\AutopilotMonitorTests\\DefinitelyAbsent_7e3a1f4b-0000-0000-0000-000000000000";
|
||||
|
||||
public GatherRuleExecutorEnrichErrorCodesTests()
|
||||
{
|
||||
var logger = new AgentLogger(_tmp.Path, AgentLogLevel.Info);
|
||||
_executor = new GatherRuleExecutor(
|
||||
"sess", "tenant",
|
||||
evt => { lock (_eventsGate) _events.Add(evt); },
|
||||
logger)
|
||||
{
|
||||
UnrestrictedMode = true
|
||||
};
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_executor.Dispose();
|
||||
_tmp.Dispose();
|
||||
}
|
||||
|
||||
private EnrollmentEvent SingleEvent()
|
||||
{
|
||||
lock (_eventsGate) return Assert.Single(_events);
|
||||
}
|
||||
|
||||
private bool WaitForEventCount(int count, int timeoutMs = 10000)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
while (sw.ElapsedMilliseconds < timeoutMs)
|
||||
{
|
||||
lock (_eventsGate) if (_events.Count >= count) return true;
|
||||
Thread.Sleep(25);
|
||||
}
|
||||
lock (_eventsGate) return _events.Count >= count;
|
||||
}
|
||||
|
||||
private static GatherRule StartupRule(bool enrichErrorCodes) => new GatherRule
|
||||
{
|
||||
RuleId = "GATHER-EEC-001",
|
||||
Title = "enrich test",
|
||||
CollectorType = "registry",
|
||||
Target = AbsentPath,
|
||||
Trigger = "startup",
|
||||
OutputEventType = "gather_test",
|
||||
Enabled = true,
|
||||
EnrichErrorCodes = enrichErrorCodes,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void StampRuleMarkers_AddsMarkerOnlyWhenOptedIn()
|
||||
{
|
||||
var optedIn = new Dictionary<string, object> { ["exitCode"] = "1603" };
|
||||
GatherRuleExecutor.StampRuleMarkers(StartupRule(enrichErrorCodes: true), optedIn);
|
||||
Assert.Equal(true, optedIn[Constants.GatherRuleDataKeys.EnrichErrorCodes]);
|
||||
|
||||
var defaultRule = new Dictionary<string, object> { ["exitCode"] = "1603" };
|
||||
GatherRuleExecutor.StampRuleMarkers(StartupRule(enrichErrorCodes: false), defaultRule);
|
||||
Assert.False(defaultRule.ContainsKey(Constants.GatherRuleDataKeys.EnrichErrorCodes));
|
||||
Assert.Single(defaultRule);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExecuteRule_StampsMarker_WhenRuleOptsIn()
|
||||
{
|
||||
_executor.UpdateRules(new List<GatherRule> { StartupRule(enrichErrorCodes: true) });
|
||||
|
||||
Assert.True(_executor.WaitForStartupRules(30));
|
||||
Assert.True(WaitForEventCount(1));
|
||||
var evt = SingleEvent();
|
||||
Assert.Equal(GatherRuleExecutor.SourceName, evt.Source);
|
||||
Assert.Equal(true, evt.Data[Constants.GatherRuleDataKeys.EnrichErrorCodes]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExecuteRule_LeavesPayloadUnchanged_ByDefault()
|
||||
{
|
||||
_executor.UpdateRules(new List<GatherRule> { StartupRule(enrichErrorCodes: false) });
|
||||
|
||||
Assert.True(_executor.WaitForStartupRules(30));
|
||||
Assert.True(WaitForEventCount(1));
|
||||
Assert.False(SingleEvent().Data.ContainsKey(Constants.GatherRuleDataKeys.EnrichErrorCodes));
|
||||
}
|
||||
}
|
||||
}
|
||||
+33
@@ -311,6 +311,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
"[Win32App] Admin did NOT set mapping for lpExitCode: 1603 of app: " + Guid1,
|
||||
new[] { "exitCode=1603", "id=" + Guid1 }
|
||||
};
|
||||
// Win32AppInstaller.cs "[Win32App] lpExitCode is defined as {0}", enum AppReturnCodeType
|
||||
// (identical 1.50–1.105).
|
||||
yield return new object[]
|
||||
{
|
||||
"IME-EXITCODE-CLASS",
|
||||
"[Win32App] lpExitCode is defined as SoftReboot",
|
||||
new[] { "exitCodeClass=SoftReboot" }
|
||||
};
|
||||
yield return new object[]
|
||||
{
|
||||
"IME-GRS-SKIP",
|
||||
@@ -361,6 +369,31 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Success")]
|
||||
[InlineData("SoftReboot")]
|
||||
[InlineData("HardReboot")]
|
||||
[InlineData("Retry")]
|
||||
[InlineData("Failed")]
|
||||
public void IME_EXITCODE_CLASS_captures_every_AppReturnCodeType_member(string member)
|
||||
{
|
||||
var m = Compile(Get("IME-EXITCODE-CLASS")).Match("[Win32App] lpExitCode is defined as " + member);
|
||||
Assert.True(m.Success);
|
||||
Assert.Equal(member, m.Groups["exitCodeClass"].Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IME_EXITCODE_CLASS_ignores_the_no_mapping_warning_and_raw_numeric_types()
|
||||
{
|
||||
// The default branch logs "... defined as {0}, fall into default now." and an admin
|
||||
// type outside the enum prints as a raw number; neither is a class the app carries.
|
||||
var regex = Compile(Get("IME-EXITCODE-CLASS"));
|
||||
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode is defined as 5, fall into default now.");
|
||||
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode is defined as SoftReboot, fall into default now.");
|
||||
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode is defined as 5");
|
||||
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode 3010");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PS_SCRIPT_CONTEXT_no_longer_fires_on_Win32App_detection_script_lines()
|
||||
{
|
||||
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
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 Newtonsoft.Json;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
|
||||
{
|
||||
/// <summary>
|
||||
/// Return-code class of the installer exit code (IME "[Win32App] lpExitCode is defined as
|
||||
/// {AppReturnCodeType}"): captured by the shipped IME-EXITCODE-CLASS pattern into
|
||||
/// <see cref="AppPackageState.ExitCodeClass"/>, last value wins across a Retry loop, the
|
||||
/// no-mapping/default-branch variants are ignored, and the value survives the agent
|
||||
/// restart that a SoftReboot/HardReboot app causes (persistence round trip).
|
||||
/// </summary>
|
||||
public sealed class ImeLogTrackerExitCodeClassTests
|
||||
{
|
||||
private const string AppId = "5c95bf94-1cf4-4629-88d1-3f616e7a405c";
|
||||
|
||||
// ---------------------------------------------------------------- AppPackageState
|
||||
|
||||
[Fact]
|
||||
public void UpdateExitCodeClass_last_value_wins_and_ignores_empty()
|
||||
{
|
||||
var pkg = new AppPackageState(AppId, 0);
|
||||
Assert.Null(pkg.ExitCodeClass);
|
||||
|
||||
Assert.True(pkg.UpdateExitCodeClass("Retry"));
|
||||
Assert.True(pkg.UpdateExitCodeClass(" Success "));
|
||||
Assert.Equal("Success", pkg.ExitCodeClass);
|
||||
Assert.False(pkg.UpdateExitCodeClass("Success"));
|
||||
Assert.False(pkg.UpdateExitCodeClass(""));
|
||||
Assert.False(pkg.UpdateExitCodeClass(null));
|
||||
Assert.Equal("Success", pkg.ExitCodeClass);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToEventData_carries_the_class_only_when_known()
|
||||
{
|
||||
var pkg = new AppPackageState(AppId, 0);
|
||||
Assert.False(pkg.ToEventData().ContainsKey("exitCodeClass"));
|
||||
|
||||
pkg.UpdateExitCode("3010");
|
||||
pkg.UpdateExitCodeClass("SoftReboot");
|
||||
var data = pkg.ToEventData();
|
||||
Assert.Equal("3010", data["exitCode"]);
|
||||
Assert.Equal("SoftReboot", data["exitCodeClass"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Restore_round_trips_the_class()
|
||||
{
|
||||
var pkg = AppPackageState.Restore(
|
||||
AppId, 0, "Contoso VPN",
|
||||
AppRunAs.System, AppIntent.Install, AppTargeted.Device,
|
||||
new HashSet<string>(),
|
||||
AppInstallationState.Installed, true, 100, 0, 0,
|
||||
exitCode: "3010", exitCodeClass: "SoftReboot");
|
||||
|
||||
Assert.Equal("SoftReboot", pkg.ExitCodeClass);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- shipped pack, end to end
|
||||
|
||||
private static string FindRulesPatternDir()
|
||||
{
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (dir != null)
|
||||
{
|
||||
var candidate = Path.Combine(dir.FullName, "rules", "ime-log-patterns");
|
||||
if (Directory.Exists(candidate)) return candidate;
|
||||
dir = dir.Parent;
|
||||
}
|
||||
throw new DirectoryNotFoundException($"Could not locate rules/ime-log-patterns walking up from {AppContext.BaseDirectory}");
|
||||
}
|
||||
|
||||
/// <summary>The shipped pack, exactly as combine.js embeds it (sorted by file name).</summary>
|
||||
private static List<ImeLogPattern> ShippedPack()
|
||||
=> Directory.GetFiles(FindRulesPatternDir(), "*.json")
|
||||
.OrderBy(f => f, StringComparer.Ordinal)
|
||||
.Select(f => JsonConvert.DeserializeObject<ImeLogPattern>(File.ReadAllText(f))!)
|
||||
.ToList();
|
||||
|
||||
private static string Entry(string message, DateTime utcInstant)
|
||||
{
|
||||
// CMTrace line with a zero writer offset: the tracker reads the local time and
|
||||
// resolves it against the reader zone; only freshness (< 24 h) matters here.
|
||||
return $"<![LOG[{message}]LOG]!><time=\"{utcInstant:HH:mm:ss.fffffff}\" date=\"{utcInstant:M-d-yyyy}\" " +
|
||||
"component=\"IntuneManagementExtension\" context=\"\" type=\"1\" thread=\"1\" file=\"\">";
|
||||
}
|
||||
|
||||
private sealed class Harness : IDisposable
|
||||
{
|
||||
private readonly TempDirectory _tmp = new TempDirectory();
|
||||
public ImeLogTracker Tracker { get; }
|
||||
public string StateDir { get; }
|
||||
public DateTime Now { get; } = new DateTime(2026, 9, 6, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
public Harness()
|
||||
{
|
||||
StateDir = Path.Combine(_tmp.Path, "State");
|
||||
Tracker = Build();
|
||||
}
|
||||
|
||||
public ImeLogTracker Build()
|
||||
{
|
||||
var tracker = new ImeLogTracker(
|
||||
logFolder: _tmp.Path,
|
||||
patterns: ShippedPack(),
|
||||
logger: new AgentLogger(_tmp.Path, AgentLogLevel.Info),
|
||||
stateDirectory: StateDir);
|
||||
// The historic-replay guard skips app-mutating actions for lines older than 24 h
|
||||
// relative to "now": pin both so the CMTrace entries below are always fresh.
|
||||
tracker.UtcNowProvider = () => Now;
|
||||
return tracker;
|
||||
}
|
||||
|
||||
public void Append(params string[] messages)
|
||||
{
|
||||
var lines = messages.Select((m, i) => Entry(m, Now.AddSeconds(-60 + i)));
|
||||
File.AppendAllText(Path.Combine(_tmp.Path, "IntuneManagementExtension.log"),
|
||||
string.Join(Environment.NewLine, lines) + Environment.NewLine);
|
||||
}
|
||||
|
||||
public Task Pass() => Tracker.CheckLogFilesAsync(CancellationToken.None);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Tracker.Dispose();
|
||||
_tmp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static string PhaseLine => "[Win32App] In EspPhase: DeviceSetup.";
|
||||
private static string CurrentAppLine => @"[Win32App] SetCurrentDirectory: C:\Windows\IMECache\" + AppId + "_1";
|
||||
|
||||
[Fact]
|
||||
public async Task Shipped_pattern_captures_the_class_for_the_current_app()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
|
||||
h.Append(
|
||||
PhaseLine, // activates the currentPhase pack (IME-EXITCODE, IME-EXITCODE-CLASS)
|
||||
CurrentAppLine, // IME-SET-CURRENT-4 → current app
|
||||
"[Win32App] lpExitCode 3010",
|
||||
"[Win32App] lpExitCode is defined as SoftReboot");
|
||||
|
||||
await h.Pass();
|
||||
|
||||
var pkg = h.Tracker.PackageStates.GetPackage(AppId);
|
||||
Assert.NotNull(pkg);
|
||||
Assert.Equal("3010", pkg!.ExitCode);
|
||||
Assert.Equal("SoftReboot", pkg.ExitCodeClass);
|
||||
Assert.NotEqual(AppInstallationState.Error, pkg.InstallationState);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Retry_loop_that_ends_in_success_reports_the_last_class()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
|
||||
h.Append(
|
||||
PhaseLine, CurrentAppLine,
|
||||
"[Win32App] lpExitCode 1618",
|
||||
"[Win32App] lpExitCode is defined as Retry",
|
||||
"[Win32App] lpExitCode 1618",
|
||||
"[Win32App] lpExitCode is defined as Retry",
|
||||
"[Win32App] lpExitCode 0",
|
||||
"[Win32App] lpExitCode is defined as Success");
|
||||
|
||||
await h.Pass();
|
||||
|
||||
var pkg = h.Tracker.PackageStates.GetPackage(AppId)!;
|
||||
Assert.Equal("0", pkg.ExitCode);
|
||||
Assert.Equal("Success", pkg.ExitCodeClass);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Failed_class_still_drives_the_error_transition_and_carries_the_class()
|
||||
{
|
||||
// IME-EXITCODE-CLASS and IME-EXITCODE-MAPPED-FAILED both match the Failed line: the
|
||||
// class is captured and the existing error path stays intact.
|
||||
using var h = new Harness();
|
||||
var pkg = new AppPackageState(AppId, 0);
|
||||
pkg.UpdateState(AppInstallationState.Installing);
|
||||
h.Tracker.PackageStates.Add(pkg);
|
||||
h.Append(
|
||||
PhaseLine, CurrentAppLine,
|
||||
"[Win32App] lpExitCode 1603",
|
||||
"[Win32App] lpExitCode is defined as Failed");
|
||||
|
||||
await h.Pass();
|
||||
|
||||
Assert.Equal(AppInstallationState.Error, pkg.InstallationState);
|
||||
Assert.Equal("Failed", pkg.ExitCodeClass);
|
||||
Assert.Equal("IME-EXITCODE-MAPPED-FAILED", pkg.ErrorPatternId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Default_branch_and_raw_numeric_types_leave_the_class_unset()
|
||||
{
|
||||
using var h = new Harness();
|
||||
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
|
||||
h.Append(
|
||||
PhaseLine, CurrentAppLine,
|
||||
"[Win32App] lpExitCode 5",
|
||||
"[Win32App] lpExitCode is defined as 5",
|
||||
"[Win32App] lpExitCode is defined as 5, fall into default now.",
|
||||
"[Win32App] Setting enforcementState as: Error with lpExitCode: 5 without mapping");
|
||||
|
||||
await h.Pass();
|
||||
|
||||
var pkg = h.Tracker.PackageStates.GetPackage(AppId)!;
|
||||
Assert.Equal("5", pkg.ExitCode);
|
||||
Assert.Null(pkg.ExitCodeClass);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Class_survives_the_state_round_trip_of_an_agent_restart()
|
||||
{
|
||||
// A SoftReboot/HardReboot app completes only after the reboot; the restarted agent
|
||||
// must still know the class when the post-reboot Success line arrives.
|
||||
using var h = new Harness();
|
||||
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
|
||||
h.Append(
|
||||
PhaseLine, CurrentAppLine,
|
||||
"[Win32App] lpExitCode 1641",
|
||||
"[Win32App] lpExitCode is defined as HardReboot");
|
||||
await h.Pass();
|
||||
h.Tracker.SaveStateForTest();
|
||||
|
||||
using var restarted = h.Build();
|
||||
restarted.LoadStateForTest();
|
||||
|
||||
var pkg = restarted.GetAllKnownPackageStates().Single(p => p.Id == AppId);
|
||||
Assert.Equal("1641", pkg.ExitCode);
|
||||
Assert.Equal("HardReboot", pkg.ExitCodeClass);
|
||||
}
|
||||
}
|
||||
}
|
||||
+82
@@ -903,5 +903,87 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Runtime
|
||||
NtfsLinks.RemoveLink(link);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================= packaging counters
|
||||
|
||||
[Fact]
|
||||
public void BuildArchiveBytes_records_packaging_counters_by_reason_and_kind_without_paths()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
File.WriteAllText(Path.Combine(rig.StateFolder, "small.json"), "{}");
|
||||
File.WriteAllText(Path.Combine(rig.StateFolder, "big-1.json"), new string('x', 64));
|
||||
File.WriteAllText(Path.Combine(rig.StateFolder, "big-2.json"), new string('y', 64));
|
||||
var blockedPath = @"C:\Windows\System32\config\SYSTEM";
|
||||
|
||||
var service = rig.Build(cfg => cfg.DiagnosticsLogPaths.Add(
|
||||
new AutopilotMonitor.Shared.Models.DiagnosticsLogPath { Path = blockedPath }));
|
||||
service.Budget = new DiagnosticsBudget { MaxSingleFileBytes = 16, MaxTotalUncompressedBytes = 1L << 30, MaxFileCount = 5000 };
|
||||
|
||||
Assert.Null(service.LastPackaging);
|
||||
var bytes = service.BuildArchiveBytes(enrollmentSucceeded: true);
|
||||
|
||||
var stats = service.LastPackaging;
|
||||
Assert.NotNull(stats);
|
||||
Assert.True(stats!.Truncated);
|
||||
Assert.Equal(2, stats.SkippedFiles);
|
||||
Assert.Equal(2, stats.SkippedByReason["size"]);
|
||||
Assert.Single(stats.SkippedByReason);
|
||||
Assert.Equal(1, stats.ProblemsByKind["path-guard"]);
|
||||
Assert.Single(stats.ProblemsByKind);
|
||||
Assert.True(stats.IncludedFiles >= 1, "the small file must have been included");
|
||||
Assert.True(stats.IncludedBytes >= 2);
|
||||
|
||||
// The ZIP still carries the per-file list; the counters never do.
|
||||
Assert.NotNull(ReadZipEntryText(bytes, "_TRUNCATED.txt"));
|
||||
foreach (var key in stats.SkippedByReason.Keys.Concat(stats.ProblemsByKind.Keys))
|
||||
{
|
||||
Assert.DoesNotContain("\\", key);
|
||||
Assert.DoesNotContain(":", key);
|
||||
Assert.DoesNotContain("/", key);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildArchiveBytes_reports_a_clean_build_as_not_truncated_with_empty_maps()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
File.WriteAllText(Path.Combine(rig.StateFolder, "snapshot.json"), "{}");
|
||||
|
||||
var service = rig.Build();
|
||||
service.BuildArchiveBytes(enrollmentSucceeded: true);
|
||||
|
||||
var stats = service.LastPackaging;
|
||||
Assert.NotNull(stats);
|
||||
Assert.False(stats!.Truncated);
|
||||
Assert.Equal(0, stats.SkippedFiles);
|
||||
Assert.Empty(stats.SkippedByReason);
|
||||
Assert.Empty(stats.ProblemsByKind);
|
||||
Assert.True(stats.IncludedFiles >= 1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildArchiveBytes_counts_a_rejected_source_folder_as_a_problem()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
using var outside = new TempDirectory();
|
||||
File.WriteAllText(Path.Combine(outside.Path, "snapshot.json"), "{}");
|
||||
var link = Path.Combine(rig.Tmp.Path, "StateLink");
|
||||
NtfsLinks.CreateJunction(link, outside.Path);
|
||||
|
||||
try
|
||||
{
|
||||
var service = rig.Build(sectionFolderOverrides: new Dictionary<string, string> { ["AgentState"] = link });
|
||||
service.BuildArchiveBytes(enrollmentSucceeded: true);
|
||||
|
||||
// The section is walked once per search pattern (11 patterns) but the folder
|
||||
// failed once — the counter says so.
|
||||
Assert.Equal(1, service.LastPackaging!.ProblemsByKind["folder-rejected"]);
|
||||
Assert.False(service.LastPackaging.Truncated);
|
||||
}
|
||||
finally
|
||||
{
|
||||
NtfsLinks.RemoveLink(link);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+16
-5
@@ -243,12 +243,23 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DecodeHResult_KnownAndUnknown()
|
||||
public void ResolveHResultSymbol_ReadsTheSharedCatalog()
|
||||
{
|
||||
Assert.Equal("WU_E_ALL_UPDATES_FAILED", WindowsUpdateTracker.DecodeHResult(0x80240022));
|
||||
Assert.Equal("CBS_E_INSTALLERS_FAILED", WindowsUpdateTracker.DecodeHResult(0x800F0922));
|
||||
Assert.Equal("S_OK", WindowsUpdateTracker.DecodeHResult(0x00000000));
|
||||
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.DecodeHResult(0x8888DEAD));
|
||||
Assert.Equal("WU_E_ALL_UPDATES_FAILED", WindowsUpdateTracker.ResolveHResultSymbol(0x80240022));
|
||||
Assert.Equal("CBS_E_INSTALLERS_FAILED", WindowsUpdateTracker.ResolveHResultSymbol(0x800F0922));
|
||||
Assert.Equal("ERROR_TIMEOUT", WindowsUpdateTracker.ResolveHResultSymbol(0x800705B4));
|
||||
Assert.Equal("S_OK", WindowsUpdateTracker.ResolveHResultSymbol(0x00000000));
|
||||
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.ResolveHResultSymbol(0x8888DEAD));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveHResultSymbol_FallsBackWhenTheCatalogHasNoSymbolOrThrows()
|
||||
{
|
||||
// An entry without a symbol (IME/Intune paraphrases) still yields the sentinel.
|
||||
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.ResolveHResultSymbol(0x87D1041C));
|
||||
// A catalog load failure is decoration lost, never an event lost.
|
||||
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.ResolveHResultSymbol(0x80240022, _ => throw new InvalidOperationException("catalog")));
|
||||
Assert.Equal("S_OK", WindowsUpdateTracker.ResolveHResultSymbol(0, _ => throw new InvalidOperationException("catalog")));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
+10
-1
@@ -282,8 +282,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
errorPatternId: null,
|
||||
errorDetail: null,
|
||||
errorCode: null,
|
||||
exitCode: null,
|
||||
exitCode: "0",
|
||||
hresultFromWin32: null,
|
||||
exitCodeClass: "Success",
|
||||
appVersion: "11.2.1787.0",
|
||||
appType: "WinGet",
|
||||
attemptNumber: 1,
|
||||
@@ -293,6 +294,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
|
||||
var info = Assert.Single(f.InfoEvents(SharedEventTypes.AppInstallComplete));
|
||||
Assert.Equal("app-xyz", info.Payload!["appId"]);
|
||||
// Installer outcome surfaces on the terminal event even when the app succeeded: the
|
||||
// return-code class is the only evidence of a SoftReboot/HardReboot mapping and the
|
||||
// number says which code was mapped (IME-EXITCODE-CLASS, ANALYZE-APP-018).
|
||||
Assert.Equal("Success", info.Payload["exitCodeClass"]);
|
||||
Assert.Equal("0", info.Payload["exitCode"]);
|
||||
Assert.Equal("Company Portal", info.Payload["appName"]);
|
||||
Assert.Equal("Installed", info.Payload["state"]);
|
||||
Assert.Equal("Install", info.Payload["intent"]);
|
||||
@@ -331,6 +337,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
errorCode: "60001",
|
||||
exitCode: "60001",
|
||||
hresultFromWin32: "-2146964895",
|
||||
exitCodeClass: "Failed",
|
||||
attemptNumber: 1,
|
||||
detectionResult: "NotDetected");
|
||||
|
||||
@@ -340,6 +347,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
|
||||
Assert.Equal("true", info.Payload!["isError"]);
|
||||
Assert.Equal("IME-ERROR-UNMAPPED-EXIT", info.Payload["errorPatternId"]);
|
||||
Assert.Equal("60001", info.Payload["errorCode"]);
|
||||
Assert.Equal("60001", info.Payload["exitCode"]);
|
||||
Assert.Equal("Failed", info.Payload["exitCodeClass"]);
|
||||
Assert.Equal("-2146964895", info.Payload["hresultFromWin32"]);
|
||||
Assert.Equal(EventSeverity.Error.ToString(), info.Payload[SignalPayloadKeys.Severity]);
|
||||
// Codex review follow-up (P1): an unrelated ErrorPatternId (here a regular
|
||||
|
||||
+81
@@ -1701,5 +1701,86 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Termination
|
||||
rig.PromotionCalls[0].failureType);
|
||||
Assert.Null(rig.PromotionCalls[0].errorCode);
|
||||
}
|
||||
|
||||
// ============================================================= packaging counters on the diag events
|
||||
|
||||
[Fact]
|
||||
public void Handle_diagnostics_uploaded_carries_packaging_counters_when_the_packager_reported_them()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Completed }.Build();
|
||||
rig.DiagnosticsResult = new DiagnosticsUploadResult
|
||||
{
|
||||
BlobName = "diag-blob.zip",
|
||||
Packaging = new DiagnosticsPackagingStats
|
||||
{
|
||||
IncludedFiles = 412,
|
||||
IncludedBytes = 123456,
|
||||
SkippedFiles = 3,
|
||||
SkippedByReason = new Dictionary<string, int> { ["size"] = 2, ["total"] = 1 },
|
||||
ProblemsByKind = new Dictionary<string, int> { ["copy"] = 1 },
|
||||
},
|
||||
};
|
||||
var cfg = rig.BuildConfig(diagEnabled: true, diagMode: "Always", selfDestruct: false);
|
||||
|
||||
rig.Build(cfg).Handle(sender: null!,
|
||||
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Succeeded, SessionStage.Completed));
|
||||
|
||||
var uploaded = rig.DataOf("diagnostics_uploaded");
|
||||
Assert.NotNull(uploaded);
|
||||
Assert.Equal(true, uploaded!["truncated"]);
|
||||
Assert.Equal(412, uploaded["includedFiles"]);
|
||||
Assert.Equal(123456L, uploaded["includedBytes"]);
|
||||
Assert.Equal(3, uploaded["skippedFiles"]);
|
||||
var byReason = Assert.IsType<Dictionary<string, int>>(uploaded["skippedByReason"]);
|
||||
Assert.Equal(2, byReason["size"]);
|
||||
Assert.Equal(1, byReason["total"]);
|
||||
var problems = Assert.IsType<Dictionary<string, int>>(uploaded["problemsByKind"]);
|
||||
Assert.Equal(1, problems["copy"]);
|
||||
// Counters only — no key or value carries a file path.
|
||||
foreach (var kv in uploaded)
|
||||
Assert.False(kv.Value is string s && (s.Contains("\\") || s.Contains("/")) && kv.Key != "sasUrlPrefix",
|
||||
$"payload key {kv.Key} looks like a path: {kv.Value}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handle_diagnostics_upload_failed_after_a_build_carries_the_counters_too()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Failed }.Build();
|
||||
rig.DiagnosticsResult = new DiagnosticsUploadResult
|
||||
{
|
||||
ErrorCode = "upload_5xx",
|
||||
Packaging = new DiagnosticsPackagingStats { IncludedFiles = 40, IncludedBytes = 1000 },
|
||||
};
|
||||
var cfg = rig.BuildConfig(diagEnabled: true, diagMode: "Always", selfDestruct: false);
|
||||
|
||||
rig.Build(cfg).Handle(sender: null!,
|
||||
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Failed, SessionStage.Failed));
|
||||
|
||||
var failed = rig.DataOf("diagnostics_upload_failed");
|
||||
Assert.NotNull(failed);
|
||||
Assert.Equal("upload_5xx", (string)failed!["errorCode"]);
|
||||
Assert.Equal(false, failed["truncated"]);
|
||||
Assert.Equal(40, failed["includedFiles"]);
|
||||
Assert.Empty(Assert.IsType<Dictionary<string, int>>(failed["skippedByReason"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Handle_diagnostics_events_omit_the_counters_when_no_package_was_built()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Completed }.Build();
|
||||
rig.DiagnosticsResult = new DiagnosticsUploadResult { BlobName = "diag-blob.zip" };
|
||||
var cfg = rig.BuildConfig(diagEnabled: true, diagMode: "Always", selfDestruct: false);
|
||||
|
||||
rig.Build(cfg).Handle(sender: null!,
|
||||
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Succeeded, SessionStage.Completed));
|
||||
|
||||
var uploaded = rig.DataOf("diagnostics_uploaded");
|
||||
Assert.NotNull(uploaded);
|
||||
Assert.False(uploaded!.ContainsKey("truncated"));
|
||||
Assert.False(uploaded.ContainsKey("skippedByReason"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +99,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// Installer result codes (captured from lpExitCode / hResultFromWin32 log lines)
|
||||
public string ExitCode { get; private set; }
|
||||
public string HResultFromWin32 { get; private set; }
|
||||
/// <summary>
|
||||
/// Admin-defined return-code class of the last installer exit code: Success, SoftReboot,
|
||||
/// HardReboot, Retry or Failed (IME's AppReturnCodeType, captured from the
|
||||
/// "lpExitCode is defined as X" line by IME-EXITCODE-CLASS). Last value wins, so a Retry
|
||||
/// loop that ends in Success reports Success.
|
||||
/// </summary>
|
||||
public string ExitCodeClass { get; private set; }
|
||||
|
||||
// App metadata (captured from IME log patterns — used by App Dashboard / reports)
|
||||
/// <summary>Product version detected after install (e.g. "11.2.1787.0"). From ReportingManager DetectedIdentityVersion.</summary>
|
||||
@@ -167,6 +174,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
int? progressPercent, long bytesDownloaded, long bytesTotal,
|
||||
string errorPatternId = null, string errorDetail = null, string errorCode = null,
|
||||
string exitCode = null, string hresultFromWin32 = null,
|
||||
string exitCodeClass = null,
|
||||
long doFileSize = 0, long doTotalBytesDownloaded = 0,
|
||||
long doBytesFromPeers = 0, int doPercentPeerCaching = 0,
|
||||
long doBytesFromLanPeers = 0, long doBytesFromGroupPeers = 0,
|
||||
@@ -195,6 +203,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
ErrorCode = errorCode,
|
||||
ExitCode = exitCode,
|
||||
HResultFromWin32 = hresultFromWin32,
|
||||
ExitCodeClass = exitCodeClass,
|
||||
InstallationStateLastChangedTicks = Stopwatch.GetTimestamp(),
|
||||
DoFileSize = doFileSize,
|
||||
DoTotalBytesDownloaded = doTotalBytesDownloaded,
|
||||
@@ -302,6 +311,19 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
HResultFromWin32 = code;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Captures the return-code class (Success/SoftReboot/HardReboot/Retry/Failed) IME assigned
|
||||
/// to the last exit code. Last value wins; empty values are ignored.
|
||||
/// </summary>
|
||||
public bool UpdateExitCodeClass(string exitCodeClass)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(exitCodeClass)) return false;
|
||||
var trimmed = exitCodeClass.Trim();
|
||||
if (ExitCodeClass == trimmed) return false;
|
||||
ExitCodeClass = trimmed;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the product version detected for this app (e.g. "11.2.1787.0").
|
||||
/// Only applies non-empty values so a later detection without version cannot wipe it.
|
||||
@@ -547,6 +569,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
data["exitCode"] = ExitCode;
|
||||
if (!string.IsNullOrEmpty(HResultFromWin32))
|
||||
data["hresultFromWin32"] = HResultFromWin32;
|
||||
if (!string.IsNullOrEmpty(ExitCodeClass))
|
||||
data["exitCodeClass"] = ExitCodeClass;
|
||||
|
||||
// App metadata fields (emitted whenever available so ingest can merge them).
|
||||
if (!string.IsNullOrEmpty(AppVersion))
|
||||
|
||||
+10
-1
@@ -491,7 +491,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
"imeshutdown", "espphasedetected", "setcurrentapp",
|
||||
"updatestateinstalled", "updatestatedownloading", "updatestateinstalling",
|
||||
"updatestateskipped", "updatestateerror", "updatestatepostponed",
|
||||
"captureexitcode", "capturehresult", "captureappversion",
|
||||
"captureexitcode", "capturehresult", "captureexitcodeclass", "captureappversion",
|
||||
"captureapptypewinget", "captureapptypemsi", "captureattemptnumber",
|
||||
"capturedetectionresult", "esptrackstatus", "policiesdiscovered",
|
||||
"ignorecompletedapp", "updatename", "updatewin32appstate",
|
||||
@@ -715,6 +715,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
_packageStates.GetPackage(_packageStates.CurrentPackageId)?.UpdateHResult(hresultVal);
|
||||
break;
|
||||
|
||||
case "captureexitcodeclass":
|
||||
// Return-code class of the exit code captured just before (IME logs the
|
||||
// number, then "lpExitCode is defined as <class>"). Same current-app
|
||||
// addressing as captureExitCode; last value wins across a Retry loop.
|
||||
var exitCodeClassVal = match.Groups["exitCodeClass"]?.Value;
|
||||
if (!string.IsNullOrEmpty(exitCodeClassVal) && !string.IsNullOrEmpty(_packageStates.CurrentPackageId))
|
||||
_packageStates.GetPackage(_packageStates.CurrentPackageId)?.UpdateExitCodeClass(exitCodeClassVal);
|
||||
break;
|
||||
|
||||
case "captureappversion":
|
||||
var appVersionVal = match.Groups["appVersion"]?.Value;
|
||||
if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(appVersionVal))
|
||||
|
||||
+12
-1
@@ -223,7 +223,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
return true;
|
||||
}
|
||||
|
||||
private const int MaxScriptOutputLength = 2048;
|
||||
// Script stdout kept per event. Measured over 1,486 script outputs in the fleet
|
||||
// (2026-08-25..09-08): median 39, p90 644, max 1,501 chars -- the maximum being our own
|
||||
// one-stage bootstrap, and nothing ever hit the previous 2,048 cap. The two-stage
|
||||
// bootstrap then added a ~460-char loader preamble to that maximum and started
|
||||
// truncating the one output an operator actually reads. 8,192 leaves room for the
|
||||
// realistic worst case (download retries plus relax logging, ~2,700) and stays 4x below
|
||||
// the 32K-char Table Storage property limit that bounds the event downstream. Growth
|
||||
// driver is the number of log lines the bootstrap chain writes, so re-measure before
|
||||
// adding a chatty step rather than raising this again.
|
||||
private const int MaxScriptOutputLength = 8192;
|
||||
private const int MaxMultiLineBufferLines = 100;
|
||||
// Size cap for ONE entry — a single physical line (enforced by BoundedLineReader before
|
||||
// the line is materialized) and an assembled multiline entry alike. Any process able to
|
||||
@@ -1241,6 +1250,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
ErrorCode = p.ErrorCode,
|
||||
ExitCode = p.ExitCode,
|
||||
HResultFromWin32 = p.HResultFromWin32,
|
||||
ExitCodeClass = p.ExitCodeClass,
|
||||
DoFileSize = p.DoFileSize,
|
||||
DoTotalBytesDownloaded = p.DoTotalBytesDownloaded,
|
||||
DoBytesFromPeers = p.DoBytesFromPeers,
|
||||
@@ -1270,6 +1280,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
p.ProgressPercent, p.BytesDownloaded, p.BytesTotal,
|
||||
errorPatternId: p.ErrorPatternId, errorDetail: p.ErrorDetail, errorCode: p.ErrorCode,
|
||||
exitCode: p.ExitCode, hresultFromWin32: p.HResultFromWin32,
|
||||
exitCodeClass: p.ExitCodeClass,
|
||||
doFileSize: p.DoFileSize, doTotalBytesDownloaded: p.DoTotalBytesDownloaded,
|
||||
doBytesFromPeers: p.DoBytesFromPeers, doPercentPeerCaching: p.DoPercentPeerCaching,
|
||||
doBytesFromLanPeers: p.DoBytesFromLanPeers, doBytesFromGroupPeers: p.DoBytesFromGroupPeers,
|
||||
|
||||
+3
@@ -190,6 +190,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
|
||||
// Installer result codes
|
||||
public string ExitCode { get; set; }
|
||||
public string HResultFromWin32 { get; set; }
|
||||
// Return-code class of the last exit code (null on state files written before the field
|
||||
// existed) - must survive the reboot a SoftReboot/HardReboot app asks for.
|
||||
public string ExitCodeClass { get; set; }
|
||||
|
||||
// Delivery Optimization telemetry
|
||||
public long DoFileSize { get; set; }
|
||||
|
||||
+18
-28
@@ -9,6 +9,7 @@ using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Orchestration;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Services;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
@@ -303,7 +304,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
if (TryNormalizeHResult(errorCode, out var hresultValue, out hresultHex))
|
||||
{
|
||||
data["hresult"] = hresultHex;
|
||||
data["hresultSymbol"] = DecodeHResult(hresultValue);
|
||||
data["hresultSymbol"] = ResolveHResultSymbol(hresultValue);
|
||||
}
|
||||
|
||||
var title = string.IsNullOrEmpty(updateTitle) ? "(unknown update)" : updateTitle;
|
||||
@@ -462,36 +463,25 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps common Windows Update HRESULTs to their symbolic name. Not exhaustive — the full
|
||||
/// catalog lives at
|
||||
/// https://learn.microsoft.com/windows/deployment/update/windows-update-error-reference.
|
||||
/// Unknown codes return "WU_E_UNKNOWN" so the raw <c>hresult</c> hex still carries the value.
|
||||
/// Symbolic name of a WU HRESULT from the shared error-code catalog (WU, CBS, Win32 and
|
||||
/// COM families). <c>S_OK</c> for zero, <c>WU_E_UNKNOWN</c> when the catalog has no symbol,
|
||||
/// so the raw <c>hresult</c> hex still carries the value. A catalog load failure is
|
||||
/// swallowed the same way: decoding is decoration and must never cost the event.
|
||||
/// </summary>
|
||||
internal static string DecodeHResult(uint hresult)
|
||||
internal static string ResolveHResultSymbol(uint hresult)
|
||||
=> ResolveHResultSymbol(hresult, code => ErrorCodeCatalog.TryLookup(code));
|
||||
|
||||
internal static string ResolveHResultSymbol(uint hresult, Func<string, ErrorCodeEntry> lookup)
|
||||
{
|
||||
switch (hresult)
|
||||
if (hresult == 0) return "S_OK";
|
||||
try
|
||||
{
|
||||
case 0x00000000: return "S_OK";
|
||||
// WU agent codes (0x8024xxxx)
|
||||
case 0x80240022: return "WU_E_ALL_UPDATES_FAILED";
|
||||
case 0x8024200B: return "WU_E_UH_INSTALLERFAILURE";
|
||||
case 0x80240020: return "WU_E_NO_INTERACTIVE_USER";
|
||||
case 0x80240016: return "WU_E_INSTALL_NOT_ALLOWED";
|
||||
case 0x8024000B: return "WU_E_CALL_CANCELLED";
|
||||
case 0x8024000C: return "WU_E_NOOP";
|
||||
case 0x80240FFF: return "WU_E_UNEXPECTED";
|
||||
case 0x80248007: return "WU_E_DS_NODATA";
|
||||
case 0x8024402C: return "WU_E_PT_WINHTTP_NAME_NOT_RESOLVED";
|
||||
// Generic Win32 / HRESULT
|
||||
case 0x80070005: return "E_ACCESSDENIED";
|
||||
case 0x80070002: return "ERROR_FILE_NOT_FOUND";
|
||||
case 0x80070003: return "ERROR_PATH_NOT_FOUND";
|
||||
case 0x800705B4: return "ERROR_TIMEOUT";
|
||||
// CBS / servicing (LCU install failures)
|
||||
case 0x800F0831: return "CBS_E_STORE_CORRUPTION";
|
||||
case 0x800F0922: return "CBS_E_INSTALLERS_FAILED";
|
||||
case 0x800F0991: return "PSFX_E_MISSING_PAYLOAD_FILE";
|
||||
default: return "WU_E_UNKNOWN";
|
||||
var symbol = lookup("0x" + hresult.ToString("x8", CultureInfo.InvariantCulture))?.Symbol;
|
||||
return string.IsNullOrEmpty(symbol) ? "WU_E_UNKNOWN" : symbol;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "WU_E_UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+88
-1
@@ -65,6 +65,44 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
|
||||
public static DiagnosticsUploadResult SkippedBy(string gate) =>
|
||||
new DiagnosticsUploadResult { Skipped = true, ErrorCode = gate };
|
||||
|
||||
/// <summary>
|
||||
/// Counters of the archive build that produced (or preceded) this result; null when no
|
||||
/// package was built (configuration gate, build exception). Surfaced into the
|
||||
/// <c>diagnostics_uploaded</c> / <c>diagnostics_upload_failed</c> events so a truncated or
|
||||
/// partially failed package is visible without opening the ZIP.
|
||||
/// </summary>
|
||||
public DiagnosticsPackagingStats Packaging { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the packager included, skipped and failed on — as bounded counters only. File paths
|
||||
/// stay inside the ZIP (<c>package-manifest.txt</c>, <c>_TRUNCATED.txt</c>): they can carry
|
||||
/// user names, and a skip list has no upper bound while this payload must stay small no
|
||||
/// matter how many files a cap rejected.
|
||||
/// </summary>
|
||||
public sealed class DiagnosticsPackagingStats
|
||||
{
|
||||
private static readonly IReadOnlyDictionary<string, int> Empty = new Dictionary<string, int>();
|
||||
|
||||
public int IncludedFiles { get; set; }
|
||||
public long IncludedBytes { get; set; }
|
||||
|
||||
/// <summary>Files rejected by a cap or a reparse-point check (the <c>_TRUNCATED.txt</c> list).</summary>
|
||||
public int SkippedFiles { get; set; }
|
||||
|
||||
/// <summary>True when at least one file was skipped — the same condition that writes <c>_TRUNCATED.txt</c>.</summary>
|
||||
public bool Truncated => SkippedFiles > 0;
|
||||
|
||||
/// <summary>Skip count per reason: <c>size</c>, <c>count</c>, <c>total</c>, <c>reparse</c>, <c>resolved-outside-folder</c>.</summary>
|
||||
public IReadOnlyDictionary<string, int> SkippedByReason { get; set; } = Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Packaging problems that are not cap skips, per kind: <c>path-guard</c> (configured path
|
||||
/// refused), <c>no-user-session</c> (user-profile token without a signed-in user),
|
||||
/// <c>folder-rejected</c>, <c>enumerate</c>, <c>open</c>, <c>copy</c>.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, int> ProblemsByKind { get; set; } = Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -134,6 +172,41 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
Skipped.Add(new SkipRecord(path, reason, size));
|
||||
|
||||
public bool HasSkips => Skipped.Count > 0;
|
||||
|
||||
// Non-cap problems (guard refusals, enumeration/open/copy failures) by kind — the
|
||||
// manifest names the files, the event carries only these counts.
|
||||
public Dictionary<string, int> Problems { get; } = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
private readonly HashSet<string> _problemKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Counts one problem of <paramref name="kind"/>. A section is walked once per search
|
||||
/// pattern, so a folder-level failure would otherwise be counted once per pattern —
|
||||
/// pass the folder as <paramref name="dedupeKey"/> to count it once.
|
||||
/// </summary>
|
||||
public void RecordProblem(string kind, string dedupeKey = null)
|
||||
{
|
||||
if (dedupeKey != null && !_problemKeys.Add(kind + "|" + dedupeKey)) return;
|
||||
Problems.TryGetValue(kind, out var n);
|
||||
Problems[kind] = n + 1;
|
||||
}
|
||||
|
||||
public DiagnosticsPackagingStats ToStats()
|
||||
{
|
||||
var byReason = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
foreach (var s in Skipped)
|
||||
{
|
||||
byReason.TryGetValue(s.Reason, out var n);
|
||||
byReason[s.Reason] = n + 1;
|
||||
}
|
||||
return new DiagnosticsPackagingStats
|
||||
{
|
||||
IncludedFiles = FileCount,
|
||||
IncludedBytes = TotalBytes,
|
||||
SkippedFiles = Skipped.Count,
|
||||
SkippedByReason = byReason,
|
||||
ProblemsByKind = new Dictionary<string, int>(Problems, StringComparer.Ordinal),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private readonly struct SkipRecord
|
||||
@@ -262,6 +335,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
var zipFileName = $"AgentDiagnostics-{_configuration.SessionId}-{timestamp}{suffix}.zip";
|
||||
|
||||
var zipBytes = BuildArchiveBytes(enrollmentSucceeded);
|
||||
var packaging = LastPackaging;
|
||||
|
||||
_logger.Info($"Diagnostics package created: {zipFileName} ({zipBytes.Length / 1024} KB)");
|
||||
|
||||
@@ -276,7 +350,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
var errorCode = uploadUrlResponse?.Message ?? "Failed to get diagnostics upload URL from backend";
|
||||
_logger.Warning($"Failed to get diagnostics upload URL from backend — skipping upload: {errorCode}");
|
||||
return new DiagnosticsUploadResult { ErrorCode = errorCode };
|
||||
return new DiagnosticsUploadResult { ErrorCode = errorCode, Packaging = packaging };
|
||||
}
|
||||
|
||||
var sasUrlPrefix = BuildSasUrlPrefix(uploadUrlResponse.UploadUrl);
|
||||
@@ -305,6 +379,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
BlobName = persistedBlobName,
|
||||
Destination = uploadUrlResponse.Destination,
|
||||
SasUrlPrefix = sasUrlPrefix,
|
||||
Packaging = packaging,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -313,6 +388,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
Destination = uploadUrlResponse.Destination,
|
||||
SasUrlPrefix = sasUrlPrefix,
|
||||
ErrorCode = uploadErrorCode,
|
||||
Packaging = packaging,
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -351,6 +427,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
// INSIDE the ZIP (field case: sessions a11102f4 / 3ae7528b, missing evtx undiagnosable).
|
||||
private StringBuilder _manifest;
|
||||
|
||||
/// <summary>Counters of the most recent <see cref="BuildArchiveBytes"/>; null before the first build.</summary>
|
||||
internal DiagnosticsPackagingStats LastPackaging { get; private set; }
|
||||
|
||||
private void ManifestLine(string text)
|
||||
{
|
||||
_manifest?.AppendLine($"[{DateTime.UtcNow:HH:mm:ss.fff}Z] {text}");
|
||||
@@ -391,6 +470,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Diagnostics path blocked by guard: {entry.Path}");
|
||||
ManifestLine($"BLOCKED (path guard): {entry.Path}");
|
||||
tracker.RecordProblem("path-guard");
|
||||
continue;
|
||||
}
|
||||
var expandedPath = UserProfileResolver.ExpandCustomTokens(entry.Path);
|
||||
@@ -398,6 +478,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Diagnostics path skipped (no user session for token): {entry.Path}");
|
||||
ManifestLine($"SKIPPED (no user session for token): {entry.Path}");
|
||||
tracker.RecordProblem("no-user-session");
|
||||
continue;
|
||||
}
|
||||
var folder = Path.GetDirectoryName(expandedPath);
|
||||
@@ -427,6 +508,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
WriteTruncatedMarker(archive, tracker);
|
||||
}
|
||||
|
||||
LastPackaging = tracker.ToStats();
|
||||
return ms.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -498,6 +580,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Built-in diagnostics section skipped (no user session for token): {section.Id}");
|
||||
ManifestLine($"BUILT-IN SKIPPED (no user session for token): {section.Id} '{section.SourceFolder}'");
|
||||
tracker.RecordProblem("no-user-session");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -584,6 +667,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Diagnostics source folder rejected ({folderRejection}): {sourceFolder}");
|
||||
ManifestLine($"FOLDER REJECTED ({folderRejection}): {sourceFolder} (pattern '{searchPattern}')");
|
||||
tracker.RecordProblem("folder-rejected", sourceFolder);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -597,6 +681,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Failed to enumerate log files in {sourceFolder}: {ex.Message}");
|
||||
ManifestLine($"ENUMERATION FAILED: {sourceFolder} (pattern '{searchPattern}'): {ex.Message}");
|
||||
tracker.RecordProblem("enumerate", sourceFolder);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -681,6 +766,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
{
|
||||
_logger.Warning($"Failed to add log file to diagnostics package: {file} - {ex.Message}");
|
||||
ManifestLine($"FAILED (copy): {file}: {ex.Message}");
|
||||
tracker.RecordProblem("copy");
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -720,6 +806,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
default:
|
||||
_logger.Warning($"Failed to open {file}: {rejection}");
|
||||
ManifestLine($"FAILED (open): {file}: {rejection}");
|
||||
tracker.RecordProblem("open");
|
||||
break;
|
||||
}
|
||||
return null;
|
||||
|
||||
+2
@@ -278,6 +278,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
|
||||
data["logFile"] = Path.GetFileName(filePath);
|
||||
data["ruleId"] = rule.RuleId;
|
||||
data["ruleTitle"] = rule.Title;
|
||||
GatherRuleExecutor.StampRuleMarkers(rule, data);
|
||||
|
||||
var eventType = !string.IsNullOrEmpty(rule.OutputEventType)
|
||||
? rule.OutputEventType
|
||||
@@ -347,6 +348,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
|
||||
data["logFile"] = Path.GetFileName(filePath);
|
||||
data["ruleId"] = rule.RuleId;
|
||||
data["ruleTitle"] = rule.Title;
|
||||
GatherRuleExecutor.StampRuleMarkers(rule, data);
|
||||
|
||||
var eventType = !string.IsNullOrEmpty(rule.OutputEventType)
|
||||
? rule.OutputEventType
|
||||
|
||||
+13
-1
@@ -26,7 +26,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
/// emits (executor, context guard events, collectors). The timeline feed uses it to keep
|
||||
/// gather output from re-triggering on_event rules.
|
||||
/// </summary>
|
||||
public const string SourceName = "GatherRuleExecutor";
|
||||
public const string SourceName = Constants.EventSources.GatherRuleExecutor;
|
||||
|
||||
/// <summary>
|
||||
/// Upper bound on on_event executions per rule and session. on_event has no natural
|
||||
@@ -496,6 +496,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
|
||||
result["ruleId"] = rule.RuleId;
|
||||
result["ruleTitle"] = rule.Title;
|
||||
StampRuleMarkers(rule, result);
|
||||
|
||||
var eventType = !string.IsNullOrEmpty(rule.OutputEventType) ? rule.OutputEventType : Constants.EventTypes.GatherResult;
|
||||
|
||||
@@ -537,6 +538,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
|
||||
// ===== Phase scope (ActivePhases / ActiveFromPhase) =====
|
||||
|
||||
/// <summary>
|
||||
/// Injects the per-rule opt-in markers the backend reads at response time. Called after
|
||||
/// the on_change hash is taken (the markers are rule config, not collected data) by the
|
||||
/// executor and by collectors that emit directly (logparser).
|
||||
/// </summary>
|
||||
internal static void StampRuleMarkers(GatherRule rule, Dictionary<string, object> data)
|
||||
{
|
||||
if (rule.EnrichErrorCodes)
|
||||
data[Constants.GatherRuleDataKeys.EnrichErrorCodes] = true;
|
||||
}
|
||||
|
||||
private static bool HasPhaseScope(GatherRule rule)
|
||||
{
|
||||
return (rule.ActivePhases != null && rule.ActivePhases.Count > 0)
|
||||
|
||||
@@ -1628,6 +1628,15 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
if (app.AttemptNumber > 0) data["attemptNumber"] = app.AttemptNumber.ToString(culture);
|
||||
if (!string.IsNullOrEmpty(app.DetectionResult)) data["detectionResult"] = app.DetectionResult!;
|
||||
|
||||
// Installer outcome of the last attempt (IME-EXITCODE + IME-EXITCODE-CLASS). The class
|
||||
// is the admin's return-code mapping (Success/SoftReboot/HardReboot/Retry/Failed) and
|
||||
// the only evidence that an app asked for a reboot; the number says which code was
|
||||
// mapped (3010 vs 1641 vs custom). Both are known from the terminal lpExitCode lines
|
||||
// only, so they surface on the terminal events - completed, postponed, skipped and
|
||||
// failed alike - never on progress events.
|
||||
if (!string.IsNullOrEmpty(app.ExitCodeClass)) data["exitCodeClass"] = app.ExitCodeClass!;
|
||||
if (IsCompletedState(newState) && !string.IsNullOrEmpty(app.ExitCode)) data["exitCode"] = app.ExitCode!;
|
||||
|
||||
// Plan §5 Fix 4c — per-app install-lifecycle timing. StartedAt appears on the
|
||||
// first Downloading/Installing/InProgress event; CompletedAt + DurationSeconds
|
||||
// light up on the terminal event. Values are omitted when not yet known so the
|
||||
@@ -1644,7 +1653,6 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
|
||||
if (!string.IsNullOrEmpty(app.ErrorPatternId)) data["errorPatternId"] = app.ErrorPatternId!;
|
||||
if (!string.IsNullOrEmpty(app.ErrorDetail)) data["errorDetail"] = app.ErrorDetail!;
|
||||
if (!string.IsNullOrEmpty(app.ErrorCode)) data["errorCode"] = app.ErrorCode!;
|
||||
if (!string.IsNullOrEmpty(app.ExitCode)) data["exitCode"] = app.ExitCode!;
|
||||
if (!string.IsNullOrEmpty(app.HResultFromWin32)) data["hresultFromWin32"] = app.HResultFromWin32!;
|
||||
|
||||
// Likely-stuck / detection-failure / install-failure classification: when the
|
||||
|
||||
+42
-17
@@ -1007,6 +1007,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
if (result != null && result.Success)
|
||||
{
|
||||
_logger.Info($"EnrollmentTerminationHandler: diagnostics uploaded (blob={result.BlobName}).");
|
||||
var data = new Dictionary<string, object>
|
||||
{
|
||||
{ "blobName", result.BlobName ?? string.Empty },
|
||||
// Tells the backend which storage the blob landed in so it can
|
||||
// stamp Session.DiagnosticsBlobDestination and route downloads
|
||||
// even after a future tenant destination switch. Empty when the
|
||||
// backend predates the field (agent falls through harmlessly).
|
||||
{ "destination", result.Destination ?? string.Empty },
|
||||
{ "sasUrlPrefix", result.SasUrlPrefix ?? string.Empty },
|
||||
};
|
||||
AppendPackagingStats(data, result.Packaging);
|
||||
EmitEventSafe(new EnrollmentEvent
|
||||
{
|
||||
SessionId = _configuration.SessionId,
|
||||
@@ -1015,17 +1026,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
Severity = EventSeverity.Info,
|
||||
Source = "EnrollmentTerminationHandler",
|
||||
Phase = EnrollmentPhase.Unknown,
|
||||
Message = $"Diagnostics package uploaded ({result.BlobName}).",
|
||||
Data = new Dictionary<string, object>
|
||||
{
|
||||
{ "blobName", result.BlobName ?? string.Empty },
|
||||
// Tells the backend which storage the blob landed in so it can
|
||||
// stamp Session.DiagnosticsBlobDestination and route downloads
|
||||
// even after a future tenant destination switch. Empty when the
|
||||
// backend predates the field (agent falls through harmlessly).
|
||||
{ "destination", result.Destination ?? string.Empty },
|
||||
{ "sasUrlPrefix", result.SasUrlPrefix ?? string.Empty },
|
||||
},
|
||||
Message = $"Diagnostics package uploaded ({result.BlobName})."
|
||||
+ (result.Packaging != null && result.Packaging.Truncated
|
||||
? $" Truncated: {result.Packaging.SkippedFiles} file(s) skipped by the packaging caps."
|
||||
: string.Empty),
|
||||
Data = data,
|
||||
ImmediateUpload = true,
|
||||
});
|
||||
}
|
||||
@@ -1033,6 +1038,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
{
|
||||
var errorCode = result?.ErrorCode ?? "null-result";
|
||||
_logger.Warning($"EnrollmentTerminationHandler: diagnostics upload failed: {errorCode}.");
|
||||
var data = new Dictionary<string, object>
|
||||
{
|
||||
{ "errorCode", errorCode },
|
||||
{ "blobName", result?.BlobName ?? string.Empty },
|
||||
{ "destination", result?.Destination ?? string.Empty },
|
||||
};
|
||||
AppendPackagingStats(data, result?.Packaging);
|
||||
EmitEventSafe(new EnrollmentEvent
|
||||
{
|
||||
SessionId = _configuration.SessionId,
|
||||
@@ -1042,17 +1054,30 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
|
||||
Source = "EnrollmentTerminationHandler",
|
||||
Phase = EnrollmentPhase.Unknown,
|
||||
Message = $"Diagnostics upload failed: {errorCode}.",
|
||||
Data = new Dictionary<string, object>
|
||||
{
|
||||
{ "errorCode", errorCode },
|
||||
{ "blobName", result?.BlobName ?? string.Empty },
|
||||
{ "destination", result?.Destination ?? string.Empty },
|
||||
},
|
||||
Data = data,
|
||||
ImmediateUpload = true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the packager's counters to a diagnostics event payload — counts only, never a
|
||||
/// file path (paths live in the ZIP's manifest and may carry user names). Absent when no
|
||||
/// package was built, so consumers treat the keys as optional.
|
||||
/// </summary>
|
||||
private static void AppendPackagingStats(Dictionary<string, object> data, DiagnosticsPackagingStats packaging)
|
||||
{
|
||||
if (packaging == null) return;
|
||||
data["truncated"] = packaging.Truncated;
|
||||
data["includedFiles"] = packaging.IncludedFiles;
|
||||
data["includedBytes"] = packaging.IncludedBytes;
|
||||
data["skippedFiles"] = packaging.SkippedFiles;
|
||||
data["skippedByReason"] = new Dictionary<string, int>(
|
||||
(IDictionary<string, int>)packaging.SkippedByReason ?? new Dictionary<string, int>(), StringComparer.Ordinal);
|
||||
data["problemsByKind"] = new Dictionary<string, int>(
|
||||
(IDictionary<string, int>)packaging.ProblemsByKind ?? new Dictionary<string, int>(), StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
private void WriteEnrollmentCompleteMarker(EnrollmentTerminatedEventArgs args)
|
||||
{
|
||||
// On WhiteGlove Part 1 exit we keep the session alive for Part 2 — DO NOT write the
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
# Invoke-BootstrapDownload.ps1 - thin runner embedded in the Bootstrap MSI.
|
||||
#
|
||||
# The MSI is only a delivery vehicle (MDM LOB channel installs earlier than the IME
|
||||
# script/app batches during Autopilot Device Preparation). This runner downloads the
|
||||
# CURRENT Install-AutopilotMonitor.ps1 from the download endpoint and executes it, so
|
||||
# every piece of real bootstrap logic (guards, relax rules, agent download) stays
|
||||
# server-updatable without re-shipping the MSI.
|
||||
#
|
||||
# Fail-soft by design: the runner always exits 0 so a transient network failure never
|
||||
# marks the LOB install as failed; diagnostics go to bootstrap-msi.log.
|
||||
# ASCII only - no special characters in this file.
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$baseDir = Join-Path $env:ProgramData 'AutopilotMonitor'
|
||||
$logDir = Join-Path $baseDir 'Logs'
|
||||
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
|
||||
$log = Join-Path $logDir 'bootstrap-msi.log'
|
||||
|
||||
function Write-Log([string]$message) {
|
||||
Add-Content -Path $log -Value ("[{0}] {1}" -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $message)
|
||||
}
|
||||
|
||||
try {
|
||||
Write-Log "MSI bootstrap runner started (user=$env:USERNAME, pid=$PID)."
|
||||
|
||||
if (Test-Path 'HKLM:\SOFTWARE\AutopilotMonitor\Deployed') {
|
||||
Write-Log 'Deployed marker present - skipping, another channel already installed the agent.'
|
||||
exit 0
|
||||
}
|
||||
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$url = 'https://download.autopilotmonitor.com/agent/Install-AutopilotMonitor.ps1'
|
||||
$dest = Join-Path $baseDir 'Install-AutopilotMonitor.ps1'
|
||||
|
||||
for ($attempt = 1; $attempt -le 3; $attempt++) {
|
||||
try {
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $dest
|
||||
break
|
||||
} catch {
|
||||
Write-Log "Download attempt $attempt failed: $_"
|
||||
if ($attempt -eq 3) { throw }
|
||||
Start-Sleep -Seconds 10
|
||||
}
|
||||
}
|
||||
|
||||
Write-Log "Bootstrap script downloaded to $dest - executing."
|
||||
# PS 5.1 file redirection (*>>) writes UTF-16LE, which garbles a log otherwise
|
||||
# written via Add-Content (ANSI). Route through Add-Content for one encoding.
|
||||
& $dest *>&1 | ForEach-Object { $_.ToString() } | Add-Content -Path $log
|
||||
Write-Log "Bootstrap script finished (exit code $LASTEXITCODE)."
|
||||
exit 0
|
||||
} catch {
|
||||
Write-Log ("MSI bootstrap runner failed: " + ($_ | Out-String))
|
||||
exit 0
|
||||
}
|
||||
@@ -4,16 +4,19 @@
|
||||
LOB MSIs are installed by the OMA-DM stack (EnterpriseDesktopAppManagement CSP) during
|
||||
the first MDM sync, i.e. BEFORE/parallel to the Device Preparation SLDM app batch -
|
||||
earlier than any IME-delivered script (Batch 2) or Win32 app can run. The MSI itself
|
||||
carries no bootstrap logic: it installs one runner script and executes it once. The
|
||||
runner downloads the CURRENT server-hosted Install-AutopilotMonitor.ps1, keeping all
|
||||
real logic updatable without re-shipping the MSI.
|
||||
carries no bootstrap logic and no downloader of its own: it installs the SAME stage-1
|
||||
loader that is assigned directly in Intune (scripts/Bootstrap/Start-AutopilotMonitor.ps1)
|
||||
and runs it once. The loader downloads the current server-hosted
|
||||
Install-AutopilotMonitor.ps1 and verifies its publisher before executing it, so all real
|
||||
logic stays updatable without re-shipping the MSI, and both delivery channels share one
|
||||
implementation.
|
||||
|
||||
Build: wix build Package.wxs -arch x64 -o bin\AutopilotMonitor-Bootstrap.msi
|
||||
-->
|
||||
<Wix xmlns="http://wixtoolset.org/schemas/v4/wxs">
|
||||
<Package Name="Autopilot Monitor Bootstrap"
|
||||
Manufacturer="Autopilot Monitor"
|
||||
Version="1.0.2"
|
||||
Version="1.1.0"
|
||||
UpgradeCode="1fbe5515-d346-445c-b8b8-14ee79f97522"
|
||||
Scope="perMachine"
|
||||
Compressed="yes">
|
||||
@@ -28,8 +31,13 @@
|
||||
</StandardDirectory>
|
||||
|
||||
<ComponentGroup Id="MainComponents" Directory="INSTALLFOLDER">
|
||||
<Component Id="RunnerScript" Guid="8c8e8962-719f-458b-b291-dd99d3f1dc30">
|
||||
<File Id="RunnerPs1" Source="Invoke-BootstrapDownload.ps1" KeyPath="yes" />
|
||||
<!-- Source is relative to the build working directory (the project dir), not to this
|
||||
file. New component GUID because the key path changed. -->
|
||||
<Component Id="RunnerScript" Guid="A972F561-01B5-400A-8C2A-47D12BA97DCA">
|
||||
<File Id="RunnerPs1"
|
||||
Source="..\..\..\scripts\Bootstrap\Start-AutopilotMonitor.ps1"
|
||||
Name="Start-AutopilotMonitor.ps1"
|
||||
KeyPath="yes" />
|
||||
</Component>
|
||||
</ComponentGroup>
|
||||
|
||||
@@ -38,11 +46,12 @@
|
||||
</Feature>
|
||||
|
||||
<!-- Deferred + no-impersonate: runs as SYSTEM after files land. Return=ignore keeps
|
||||
the LOB install green even if the runner hits a transient error (the runner is
|
||||
additionally fail-soft itself); diagnostics live in bootstrap-msi.log. -->
|
||||
the LOB install green even if the loader hits a transient error (the loader is
|
||||
additionally fail-soft itself). -LogFileName keeps this channel distinguishable in
|
||||
a diagnostics package; the diag tooling keys on that name. -->
|
||||
<CustomAction Id="RunBootstrap"
|
||||
Directory="INSTALLFOLDER"
|
||||
ExeCommand=""[System64Folder]WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File "[INSTALLFOLDER]Invoke-BootstrapDownload.ps1""
|
||||
ExeCommand=""[System64Folder]WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File "[INSTALLFOLDER]Start-AutopilotMonitor.ps1" -LogFileName bootstrap-msi.log"
|
||||
Execute="deferred"
|
||||
Impersonate="no"
|
||||
Return="ignore" />
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the derivation shared by the agent channel (GET agent/config) and the Global-Admin
|
||||
/// report route (GET config/{tenantId}/effective-agent-config): every rule the Tenant Config
|
||||
/// Report used to re-implement in the web now has exactly one implementation, and these
|
||||
/// facts are its contract.
|
||||
/// </summary>
|
||||
public class AgentConfigResolverTests
|
||||
{
|
||||
private const string TenantId = "11111111-2222-3333-4444-555555555555";
|
||||
private static readonly DateTime Now = new(2026, 9, 6, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private static TenantConfiguration Tenant(Action<TenantConfiguration>? mutate = null)
|
||||
{
|
||||
var c = new TenantConfiguration { TenantId = TenantId, DomainName = "contoso.example", UpdatedBy = "ga@operator.example" };
|
||||
mutate?.Invoke(c);
|
||||
return c;
|
||||
}
|
||||
|
||||
private static AdminConfiguration Admin(Action<AdminConfiguration>? mutate = null)
|
||||
{
|
||||
var a = new AdminConfiguration();
|
||||
mutate?.Invoke(a);
|
||||
return a;
|
||||
}
|
||||
|
||||
private static AgentConfigResponse Build(TenantConfiguration tenant, AdminConfiguration? admin = null, int agentMajor = AgentConfigResolver.CurrentAgentMajor)
|
||||
=> AgentConfigResolver.Build(tenant, admin ?? Admin(), new List<GatherRule>(), new List<ImeLogPattern>(), agentMajor, Now).Response;
|
||||
|
||||
[Fact]
|
||||
public void Fresh_tenant_gets_the_agent_defaults()
|
||||
{
|
||||
var r = Build(Tenant());
|
||||
|
||||
Assert.Equal(AgentConfigResolver.ConfigVersion, r.ConfigVersion);
|
||||
Assert.Equal(AutopilotMonitor.Shared.Constants.DefaultUploadIntervalSeconds, r.UploadIntervalSeconds);
|
||||
Assert.Equal(10, r.UploadIntervalSeconds); // the report showed 30 for a month — pinned
|
||||
Assert.True(r.SelfDestructOnComplete);
|
||||
Assert.False(r.KeepLogFile);
|
||||
Assert.True(r.EnableGeoLocation);
|
||||
Assert.Equal(5, r.MaxAuthFailures);
|
||||
Assert.Equal(0, r.AuthFailureTimeoutMinutes);
|
||||
Assert.Equal("Info", r.LogLevel);
|
||||
Assert.Equal(10, r.RebootDelaySeconds);
|
||||
Assert.Equal(60, r.EnrollmentSummaryTimeoutSeconds);
|
||||
Assert.Equal(120, r.EnrollmentSummaryLaunchRetrySeconds);
|
||||
Assert.Equal(100, r.MaxBatchSize);
|
||||
Assert.Equal("time.windows.com", r.NtpServer);
|
||||
Assert.Equal("Off", r.DiagnosticsUploadMode);
|
||||
Assert.False(r.DiagnosticsUploadEnabled);
|
||||
Assert.False(r.UnrestrictedMode);
|
||||
Assert.False(r.DeviceBlocked);
|
||||
Assert.False(r.DeviceKillSignal);
|
||||
Assert.Null(r.UnblockAt);
|
||||
Assert.Null(r.MigrateToApiBaseUrl);
|
||||
|
||||
Assert.Equal(360, r.Collectors.AgentMaxLifetimeMinutes);
|
||||
Assert.Equal(15, r.Collectors.CollectorIdleTimeoutMinutes);
|
||||
Assert.Equal(10, r.Collectors.DesktopDetectorNoCandidateTimeoutMinutes);
|
||||
Assert.Equal(new[] { 100, 1005, 1010 }, r.Collectors.ModernDeploymentHarmlessEventIds);
|
||||
|
||||
Assert.True(r.Analyzers.EnableLocalAdminAnalyzer);
|
||||
Assert.Empty(r.Analyzers.LocalAdminAllowedAccounts);
|
||||
Assert.False(r.Analyzers.EnableSoftwareInventoryAnalyzer);
|
||||
Assert.True(r.Analyzers.EnableIntegrityBypassAnalyzer);
|
||||
Assert.False(r.Analyzers.EnableRealmJoinWatcher);
|
||||
Assert.False(r.Analyzers.KeepAwakeDuringUserEsp);
|
||||
Assert.True(r.Analyzers.EnableConsoleBypassDetection);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, "CustomerSas", "Off", false)]
|
||||
[InlineData(null, "Hosted", "Off", true)] // hosted destination needs no SAS
|
||||
[InlineData("https://acct.blob.core.windows.net/c?sv=1", "CustomerSas", "Off", true)] // SAS enables regardless of mode
|
||||
public void Diagnostics_upload_enabled_follows_sas_or_hosted_not_the_mode(string? sas, string destination, string mode, bool expected)
|
||||
{
|
||||
var r = Build(Tenant(t =>
|
||||
{
|
||||
t.DiagnosticsBlobSasUrl = sas!;
|
||||
t.DiagnosticsUploadDestination = destination;
|
||||
t.DiagnosticsUploadMode = mode;
|
||||
}));
|
||||
Assert.Equal(expected, r.DiagnosticsUploadEnabled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("free", true, true, false)] // Community: entitlement missing
|
||||
[InlineData("pro", false, true, false)] // GA gate off
|
||||
[InlineData("pro", true, false, false)] // tenant toggle off
|
||||
[InlineData("pro", true, true, true)]
|
||||
public void Unrestricted_mode_needs_entitlement_and_gate_and_toggle(string planTier, bool gaGate, bool toggle, bool expected)
|
||||
{
|
||||
var r = Build(Tenant(t =>
|
||||
{
|
||||
t.PlanTier = planTier;
|
||||
t.UnrestrictedModeEnabled = gaGate;
|
||||
t.UnrestrictedMode = toggle;
|
||||
}));
|
||||
Assert.Equal(expected, r.UnrestrictedMode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Operator_knobs_come_from_the_admin_configuration()
|
||||
{
|
||||
var admin = Admin(a =>
|
||||
{
|
||||
a.CollectorIdleTimeoutMinutes = 25;
|
||||
a.DesktopDetectorNoCandidateTimeoutMinutes = 7;
|
||||
a.AllowAgentDowngrade = true;
|
||||
a.ModernDeploymentHarmlessEventIdsJson = "[100, 42]";
|
||||
a.LatestAgentV2Sha256 = "zip-v2";
|
||||
a.LatestAgentV2ExeSha256 = "exe-v2";
|
||||
});
|
||||
|
||||
var r = Build(Tenant(), admin);
|
||||
|
||||
Assert.Equal(25, r.Collectors.CollectorIdleTimeoutMinutes);
|
||||
Assert.Equal(7, r.Collectors.DesktopDetectorNoCandidateTimeoutMinutes);
|
||||
Assert.True(r.AllowAgentDowngrade);
|
||||
Assert.Equal(new[] { 100, 42 }, r.Collectors.ModernDeploymentHarmlessEventIds);
|
||||
Assert.Equal("zip-v2", r.LatestAgentSha256);
|
||||
Assert.Equal("exe-v2", r.LatestAgentExeSha256);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Legacy_major_gets_empty_hashes_the_current_major_gets_v2()
|
||||
{
|
||||
var admin = Admin(a => { a.LatestAgentV2Sha256 = "zip-v2"; a.LatestAgentV2ExeSha256 = "exe-v2"; });
|
||||
|
||||
var legacy = Build(Tenant(), admin, agentMajor: 1);
|
||||
Assert.Equal(string.Empty, legacy.LatestAgentSha256);
|
||||
|
||||
var current = Build(Tenant(), admin, agentMajor: AgentConfigResolver.CurrentAgentMajor);
|
||||
Assert.Equal("zip-v2", current.LatestAgentSha256);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Tenant_overrides_win_over_defaults()
|
||||
{
|
||||
var r = Build(Tenant(t =>
|
||||
{
|
||||
t.MaxBatchSize = 25;
|
||||
t.LogLevel = "Debug";
|
||||
t.NtpServer = "";
|
||||
t.LocalAdminAllowedAccountsJson = "[\"Admin\",\"Helpdesk\"]";
|
||||
t.AgentMaxLifetimeMinutes = 120;
|
||||
t.EnableConsoleBypassDetection = false;
|
||||
}));
|
||||
|
||||
Assert.Equal(25, r.MaxBatchSize);
|
||||
Assert.Equal("Debug", r.LogLevel);
|
||||
Assert.Equal("time.windows.com", r.NtpServer); // empty string falls back like null
|
||||
Assert.Equal(new[] { "Admin", "Helpdesk" }, r.Analyzers.LocalAdminAllowedAccounts);
|
||||
Assert.Equal(120, r.Collectors.AgentMaxLifetimeMinutes);
|
||||
Assert.False(r.Analyzers.EnableConsoleBypassDetection);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Migration_target_is_served_when_valid_and_reported_when_rejected()
|
||||
{
|
||||
const string Us = "https://autopilotmonitor-api-us.azurewebsites.net";
|
||||
var served = AgentConfigResolver.Build(Tenant(), Admin(a => a.AgentMigrateApiBaseUrl = Us),
|
||||
new List<GatherRule>(), new List<ImeLogPattern>(), AgentConfigResolver.CurrentAgentMajor, Now);
|
||||
Assert.Equal(Us, served.Response.MigrateToApiBaseUrl);
|
||||
Assert.Null(served.RejectedMigrateCandidate);
|
||||
|
||||
var rejected = AgentConfigResolver.Build(Tenant(), Admin(a => a.AgentMigrateApiBaseUrl = "https://evil.example"),
|
||||
new List<GatherRule>(), new List<ImeLogPattern>(), AgentConfigResolver.CurrentAgentMajor, Now);
|
||||
Assert.Null(rejected.Response.MigrateToApiBaseUrl);
|
||||
Assert.Equal("https://evil.example", rejected.RejectedMigrateCandidate);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Catalogs_pass_through_unchanged()
|
||||
{
|
||||
var rules = new List<GatherRule> { new() { RuleId = "GATHER-TEST-001" } };
|
||||
var patterns = new List<ImeLogPattern> { new() { PatternId = "IME-TEST-001" } };
|
||||
var r = AgentConfigResolver.Build(Tenant(), Admin(), rules, patterns, AgentConfigResolver.CurrentAgentMajor, Now).Response;
|
||||
Assert.Same(rules, r.GatherRules);
|
||||
Assert.Same(patterns, r.ImeLogPatterns);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using System.Threading;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
@@ -21,7 +22,7 @@ public class AgentEfficiencyMetricsServiceTests
|
||||
{
|
||||
var repo = new Mock<ISessionRepository>();
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(new List<SessionSummary>(), null));
|
||||
repo
|
||||
.Setup(r => r.GetSessionEventsByTypesAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IReadOnlyCollection<string>>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<int>()))
|
||||
@@ -67,7 +68,7 @@ public class AgentEfficiencyMetricsServiceTests
|
||||
private static void SetupSessions(Mock<ISessionRepository> repo, List<SessionSummary> sessions)
|
||||
{
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(sessions, null));
|
||||
}
|
||||
|
||||
@@ -201,8 +202,8 @@ public class AgentEfficiencyMetricsServiceTests
|
||||
string? capturedTenant = null;
|
||||
IEnumerable<string>? capturedSelect = null;
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?>((t, _, _, _, _, sel) => { capturedTenant = t; capturedSelect = sel; })
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?, CancellationToken>((t, _, _, _, _, sel, _) => { capturedTenant = t; capturedSelect = sel; })
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(new List<SessionSummary>(), null));
|
||||
|
||||
var result = await service.ComputeAsync(days: 45, limit: 100, tenantId: Tenant);
|
||||
@@ -220,7 +221,7 @@ public class AgentEfficiencyMetricsServiceTests
|
||||
var (service, repo) = CreateService();
|
||||
int callCount = 0;
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.Callback(() => callCount++)
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(new List<SessionSummary>(), null));
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using AutopilotMonitor.Functions.Functions.Config;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Services;
|
||||
using Xunit;
|
||||
@@ -8,7 +8,7 @@ namespace AutopilotMonitor.Functions.Tests;
|
||||
/// <summary>
|
||||
/// Pins the endpoint-migration serving contract: the shared allowlist rules
|
||||
/// (<see cref="AgentEndpointMigrationRules"/>, used verbatim by the agent too) and the
|
||||
/// backend-side per-tenant resolution (<see cref="GetAgentConfigFunction.ResolveMigrateTarget"/> —
|
||||
/// backend-side per-tenant resolution (<see cref="AgentConfigResolver.ResolveMigrateTarget"/> —
|
||||
/// tenant override wins, empty override pins, invalid values are never served).
|
||||
/// </summary>
|
||||
public class AgentEndpointMigrationTests
|
||||
@@ -75,7 +75,7 @@ public class AgentEndpointMigrationTests
|
||||
{
|
||||
var config = new AdminConfiguration();
|
||||
|
||||
Assert.Null(GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out var rejected));
|
||||
Assert.Null(AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out var rejected));
|
||||
Assert.Null(rejected);
|
||||
}
|
||||
|
||||
@@ -84,8 +84,8 @@ public class AgentEndpointMigrationTests
|
||||
{
|
||||
var config = new AdminConfiguration { AgentMigrateApiBaseUrl = UsUrl };
|
||||
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantB, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantB, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -97,8 +97,8 @@ public class AgentEndpointMigrationTests
|
||||
AgentMigrateTenantOverridesJson = $"{{\"{TenantA}\": \"{EuUrl}\"}}"
|
||||
};
|
||||
|
||||
Assert.Equal(EuUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantB, out _));
|
||||
Assert.Equal(EuUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantB, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -110,9 +110,9 @@ public class AgentEndpointMigrationTests
|
||||
AgentMigrateTenantOverridesJson = $"{{\"{TenantA}\": \"\"}}"
|
||||
};
|
||||
|
||||
Assert.Null(GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out var rejected));
|
||||
Assert.Null(AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out var rejected));
|
||||
Assert.Null(rejected); // pinned, not rejected
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantB, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantB, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -123,7 +123,7 @@ public class AgentEndpointMigrationTests
|
||||
AgentMigrateTenantOverridesJson = $"{{\"{TenantA.ToUpperInvariant()}\": \"{UsUrl}\"}}"
|
||||
};
|
||||
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -131,7 +131,7 @@ public class AgentEndpointMigrationTests
|
||||
{
|
||||
var config = new AdminConfiguration { AgentMigrateApiBaseUrl = "https://attacker.example.com" };
|
||||
|
||||
Assert.Null(GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out var rejected));
|
||||
Assert.Null(AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out var rejected));
|
||||
Assert.Equal("https://attacker.example.com", rejected);
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ public class AgentEndpointMigrationTests
|
||||
AgentMigrateTenantOverridesJson = "{not json"
|
||||
};
|
||||
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -155,6 +155,6 @@ public class AgentEndpointMigrationTests
|
||||
AgentMigrateApiBaseUrl = "https://AutopilotMonitor-API-US.azurewebsites.net/"
|
||||
};
|
||||
|
||||
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
|
||||
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,7 +356,8 @@ public class ApplicationPrincipalTests
|
||||
var members = new StubTenantMemberRoleResolver();
|
||||
var sut = new McpUserService(
|
||||
adminRepo.Object, bindings, cache, NullLogger<McpUserService>.Instance,
|
||||
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, members);
|
||||
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, members,
|
||||
new TenantConfigurationService(Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache));
|
||||
return (sut, members);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ public class AuthFunctionSideEffectTests
|
||||
var mcpUserMock = new Mock<McpUserService>(
|
||||
adminRepo, new StubAdminIdentityBindingService(bound: true), cache, Mock.Of<ILogger<McpUserService>>(),
|
||||
globalAdminMock.Object, delegatedAdminMock.Object, adminConfigService.Object,
|
||||
new TenantMemberRoleResolver(_tenantAdminsMock.Object, _tenantConfigMock.Object))
|
||||
new TenantMemberRoleResolver(_tenantAdminsMock.Object, _tenantConfigMock.Object), _tenantConfigMock.Object)
|
||||
{ CallBase = false };
|
||||
|
||||
_metricsRepoMock = new Mock<IMetricsRepository>();
|
||||
|
||||
@@ -55,6 +55,76 @@ public class AuthFunctionTests
|
||||
Assert.True((bool)body.hasMcpAccess);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HappyPath_SurfacesWhatsNewSeenMarks()
|
||||
{
|
||||
var platformSeen = new DateTime(2026, 9, 8, 10, 0, 0, DateTimeKind.Utc);
|
||||
var agentSeen = new DateTime(2026, 9, 8, 10, 5, 0, DateTimeKind.Utc);
|
||||
|
||||
var result = AuthFunction.BuildAuthResult(
|
||||
DefaultConfig(), isGlobalAdmin: false, isGlobalReader: false, isPreviewApproved: true,
|
||||
memberRole: AdminRole(), mcpCheck: McpAllowed(),
|
||||
hasTenantAdmins: true,
|
||||
TenantId, Upn, DisplayName, ObjectId,
|
||||
whatsNewSeenPlatformUtc: platformSeen,
|
||||
whatsNewSeenAgentUtc: agentSeen);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
var body = ToDynamic(result.Body);
|
||||
Assert.Equal(platformSeen, (DateTime)body.whatsNewSeenPlatformUtc);
|
||||
Assert.Equal(agentSeen, (DateTime)body.whatsNewSeenAgentUtc);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("platform", "platform")]
|
||||
[InlineData("Platform", "platform")]
|
||||
[InlineData("agent", "agent")]
|
||||
public void TryNormalizeWhatsNewSeen_AcceptsKnownChannels(string input, string expected)
|
||||
{
|
||||
var seen = new DateTime(2026, 9, 8, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
var ok = AuthFunction.TryNormalizeWhatsNewSeen(
|
||||
new WhatsNewSeenRequest { Channel = input, SeenUtc = seen },
|
||||
seen.AddMinutes(1),
|
||||
out var channel,
|
||||
out var seenUtc,
|
||||
out var error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(expected, channel);
|
||||
Assert.Equal(seen, seenUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryNormalizeWhatsNewSeen_RejectsUnknownChannel()
|
||||
{
|
||||
var ok = AuthFunction.TryNormalizeWhatsNewSeen(
|
||||
new WhatsNewSeenRequest { Channel = "other", SeenUtc = DateTime.UtcNow },
|
||||
DateTime.UtcNow,
|
||||
out _,
|
||||
out _,
|
||||
out var error);
|
||||
|
||||
Assert.False(ok);
|
||||
Assert.Equal("channel must be 'platform' or 'agent'", error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryNormalizeWhatsNewSeen_ClampsFarFutureTimestamp()
|
||||
{
|
||||
var now = new DateTime(2026, 9, 8, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
var ok = AuthFunction.TryNormalizeWhatsNewSeen(
|
||||
new WhatsNewSeenRequest { Channel = "agent", SeenUtc = now.AddMinutes(6) },
|
||||
now,
|
||||
out _,
|
||||
out var seenUtc,
|
||||
out var error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(now, seenUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HappyPath_OperatorUser_ReturnsCorrectRole()
|
||||
{
|
||||
|
||||
@@ -47,6 +47,12 @@ public class AutopilotDeviceValidatorTests
|
||||
new(status) { Content = new StringContent(body) };
|
||||
|
||||
private static (AutopilotDeviceValidator Sut, DelayingHandler Handler, MemoryCache Cache) BuildSut(params HttpResponseMessage?[] responses)
|
||||
{
|
||||
var built = BuildSutWithTokens(responses);
|
||||
return (built.Sut, built.Handler, built.Cache);
|
||||
}
|
||||
|
||||
private static (AutopilotDeviceValidator Sut, DelayingHandler Handler, MemoryCache Cache, Mock<GraphTokenService> Tokens) BuildSutWithTokens(params HttpResponseMessage?[] responses)
|
||||
{
|
||||
var handler = new DelayingHandler(responses);
|
||||
var factory = new Mock<IHttpClientFactory>();
|
||||
@@ -71,10 +77,52 @@ public class AutopilotDeviceValidatorTests
|
||||
|
||||
var sut = new AutopilotDeviceValidator(
|
||||
NullLogger<AutopilotDeviceValidator>.Instance, factory.Object, cache, tokenService.Object);
|
||||
return (sut, handler, cache);
|
||||
return (sut, handler, cache, tokenService);
|
||||
}
|
||||
|
||||
private const string FoundBody = "{\"value\":[{\"id\":\"ap-1\",\"serialNumber\":\"PF3XKQ7\"}]}";
|
||||
private const string ForbiddenBody = "{\"error\":{\"code\":\"Authorization_RequestDenied\",\"message\":\"Application is not authorized to perform this operation.\"}}";
|
||||
|
||||
[Fact]
|
||||
public async Task StaleTokenForbidden_ThenSuccess_InvalidatesOnce_AndValidatesWithTheFreshToken()
|
||||
{
|
||||
// Field case 2026-09-02: a second instance held a roleless app-only token minted before the
|
||||
// tenant's consent; Graph answered 403 for 45 minutes. Attempt 1 must drop that token and
|
||||
// attempt 2 must succeed with the re-minted one — no 503 loop, no cached negative.
|
||||
var (sut, handler, cache, tokens) = BuildSutWithTokens(
|
||||
Json(ForbiddenBody, HttpStatusCode.Forbidden),
|
||||
Json(FoundBody));
|
||||
|
||||
var result = await sut.ValidateAutopilotDeviceAsync(TenantId, Serial, null, CancellationToken.None);
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
Assert.Equal("ap-1", result.AutopilotDeviceId);
|
||||
Assert.Equal(2, handler.Requests.Count);
|
||||
tokens.Verify(t => t.InvalidateTenant(TenantId), Times.Once);
|
||||
tokens.Verify(t => t.GetAccessTokenAsync(TenantId, It.IsAny<CancellationToken>()), Times.Exactly(2));
|
||||
Assert.True(cache.TryGetValue($"autopilot-device-validation:{TenantId}:{Serial}", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ForbiddenWithFreshToken_StaysTransient_WithLongerRetryAfter_NotCached()
|
||||
{
|
||||
// Consent genuinely missing (or not yet propagated): the agent must keep getting 503 (a 403
|
||||
// would make it shut down as "device not registered"), but with the permission-gap
|
||||
// Retry-After and nothing cached so a granted consent takes effect on the next call.
|
||||
var (sut, handler, cache, tokens) = BuildSutWithTokens(
|
||||
Json(ForbiddenBody, HttpStatusCode.Forbidden),
|
||||
Json(ForbiddenBody, HttpStatusCode.Forbidden));
|
||||
|
||||
var result = await sut.ValidateAutopilotDeviceAsync(TenantId, Serial, null, CancellationToken.None);
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
Assert.True(result.IsTransient);
|
||||
Assert.Equal(GraphAuthFailure.PermissionMissingRetryAfterSeconds, result.RetryAfterSeconds);
|
||||
Assert.Contains("permission missing", result.ErrorMessage);
|
||||
Assert.Equal(2, handler.Requests.Count);
|
||||
tokens.Verify(t => t.InvalidateTenant(TenantId), Times.Once);
|
||||
Assert.False(cache.TryGetValue($"autopilot-device-validation:{TenantId}:{Serial}", out _));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Budget_defaults_sit_inside_the_agents_30s_client_timeout()
|
||||
|
||||
@@ -53,4 +53,94 @@ public class BuiltInRuleCatalogPolicyTests
|
||||
Assert.True(duplicates.Count == 0,
|
||||
$"Duplicate built-in gather rule IDs: {string.Join(", ", duplicates)}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Built-in rules that assert an ABSENCE (required not_exists) of an event the agent derives
|
||||
/// from the IME logs, and deliberately do NOT carry the ime_tracker_degraded coverage gate.
|
||||
/// Every entry is a decision with a reason; adding one here is the way to ship such a rule.
|
||||
/// </summary>
|
||||
private static readonly IReadOnlyDictionary<string, string> AbsenceWithoutCoverageGate =
|
||||
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["ANALYZE-ID-004"] =
|
||||
"A hybrid session whose user never obtained an Entra token must not lose its finding because " +
|
||||
"the tracker skipped the remaining patterns on one line; the tracker state is shown next to " +
|
||||
"the finding in get_session_summary (coverage) instead (plan session-coverage-and-absence-audit).",
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Required_not_exists_on_ime_derived_events_is_coverage_gated_or_documented()
|
||||
{
|
||||
// "Absence proves nothing": a required not_exists on an IME-log-derived event evaluates
|
||||
// to true both when the event never happened and when the IME log tracker skipped the
|
||||
// line that carried it (ime_tracker_degraded). A built-in rule that asserts such an
|
||||
// absence either suppresses itself on degraded sessions (precondition
|
||||
// ime_tracker_degraded not_exists) or is listed above with the reason it does not.
|
||||
// The IME-derived list is the guardrails.json mirror the MCP validate_rule lint reads,
|
||||
// so catalog and pre-flight judge by one list.
|
||||
var guardrailsPath = Path.Combine(FindRepoRoot(), "rules", "guardrails.json");
|
||||
var json = Newtonsoft.Json.Linq.JObject.Parse(File.ReadAllText(guardrailsPath));
|
||||
var imeDerived = new HashSet<string>(
|
||||
json["imeLogDerivedEventTypes"]!.ToObject<string[]>()!, StringComparer.OrdinalIgnoreCase);
|
||||
Assert.Contains("ime_user_token_acquired", imeDerived);
|
||||
|
||||
var offenders = new List<string>();
|
||||
foreach (var rule in BuiltInAnalyzeRules.GetAll())
|
||||
{
|
||||
var assertsImeAbsence = rule.Conditions.Any(c =>
|
||||
c.Required
|
||||
&& string.Equals(c.Operator, "not_exists", StringComparison.OrdinalIgnoreCase)
|
||||
&& string.IsNullOrEmpty(c.DataField)
|
||||
&& !string.IsNullOrEmpty(c.EventType)
|
||||
&& imeDerived.Contains(c.EventType));
|
||||
if (!assertsImeAbsence) continue;
|
||||
|
||||
var gated = rule.Preconditions.Any(p =>
|
||||
string.Equals(p.EventType, "ime_tracker_degraded", StringComparison.OrdinalIgnoreCase)
|
||||
&& string.Equals(p.Operator, "not_exists", StringComparison.OrdinalIgnoreCase)
|
||||
&& string.IsNullOrEmpty(p.DataField));
|
||||
if (gated || AbsenceWithoutCoverageGate.ContainsKey(rule.RuleId)) continue;
|
||||
offenders.Add(rule.RuleId);
|
||||
}
|
||||
|
||||
Assert.True(offenders.Count == 0,
|
||||
"Built-in rules assert the absence of an IME-log-derived event without the " +
|
||||
"ime_tracker_degraded coverage precondition and without a documented exception: " +
|
||||
string.Join(", ", offenders));
|
||||
|
||||
// The exception list must not outlive the rules it excuses.
|
||||
var catalogIds = new HashSet<string>(BuiltInAnalyzeRules.GetAll().Select(r => r.RuleId), StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var excused in AbsenceWithoutCoverageGate.Keys)
|
||||
Assert.True(catalogIds.Contains(excused), $"Exception list names a rule that is not in the catalog: {excused}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ime_derived_list_names_only_real_event_types_and_the_tracker_event_exists()
|
||||
{
|
||||
var guardrailsPath = Path.Combine(FindRepoRoot(), "rules", "guardrails.json");
|
||||
var json = Newtonsoft.Json.Linq.JObject.Parse(File.ReadAllText(guardrailsPath));
|
||||
var imeDerived = json["imeLogDerivedEventTypes"]!.ToObject<string[]>()!;
|
||||
|
||||
var known = new HashSet<string>(
|
||||
typeof(AutopilotMonitor.Shared.Constants.EventTypes)
|
||||
.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
|
||||
.Where(f => f.IsLiteral && f.FieldType == typeof(string))
|
||||
.Select(f => (string)f.GetRawConstantValue()!),
|
||||
StringComparer.Ordinal);
|
||||
|
||||
var phantom = imeDerived.Where(t => !known.Contains(t)).ToList();
|
||||
Assert.True(phantom.Count == 0, $"imeLogDerivedEventTypes lists unknown event types: {string.Join(", ", phantom)}");
|
||||
Assert.Contains(AutopilotMonitor.Shared.Constants.EventTypes.ImeTrackerDegraded, known);
|
||||
}
|
||||
|
||||
private static string FindRepoRoot()
|
||||
{
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (dir != null && !File.Exists(Path.Combine(dir.FullName, "AutopilotMonitor.sln")))
|
||||
{
|
||||
dir = dir.Parent;
|
||||
}
|
||||
Assert.NotNull(dir);
|
||||
return dir!.FullName;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ public class BuiltInRulesTests
|
||||
"healthScriptResult", "healthScriptDetectionResult",
|
||||
"captureExitCode", "captureHResult",
|
||||
"captureAppVersion", "captureAppTypeWinGet", "captureAppTypeMsi",
|
||||
"captureAttemptNumber", "captureDetectionResult"
|
||||
"captureAttemptNumber", "captureDetectionResult", "captureExitCodeClass"
|
||||
};
|
||||
|
||||
var patterns = BuiltInImeLogPatterns.GetAll();
|
||||
|
||||
@@ -224,17 +224,36 @@ public class CorporateIdentifierValidatorTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAsync_graphPermissionDenied_isCached_notRetried()
|
||||
public async Task ValidateAsync_graphPermissionDenied_isCached_afterOneFreshTokenRetry()
|
||||
{
|
||||
// Definitive permission failures are negative-cached so an agent retry storm does not
|
||||
// hammer Graph while consent is being fixed; the in-call retry loop must not fire either.
|
||||
// hammer Graph while consent is being fixed. Attempt 1 may have used a token minted before
|
||||
// the consent (GraphAuthFailure), so exactly ONE retry with a fresh token precedes the
|
||||
// verdict; the cached verdict then answers the next call without Graph.
|
||||
var (sut, handler) = BuildSut(Json("""{"error":{"code":"Forbidden"}}""", HttpStatusCode.Forbidden));
|
||||
|
||||
await sut.ValidateAsync(TenantId, "Microsoft Corporation", "Virtual Machine", Serial);
|
||||
var first = await sut.ValidateAsync(TenantId, "Microsoft Corporation", "Virtual Machine", Serial);
|
||||
var second = await sut.ValidateAsync(TenantId, "Microsoft Corporation", "Virtual Machine", Serial);
|
||||
|
||||
Assert.False(first.IsTransient);
|
||||
Assert.False(second.IsValid);
|
||||
Assert.Single(handler.Requests);
|
||||
Assert.Equal(2, handler.Requests.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ValidateAsync_staleTokenForbidden_thenFound_validatesWithTheFreshToken()
|
||||
{
|
||||
// Field case 2026-09-02 in this validator's shape: a stale roleless token gets 403, the
|
||||
// fresh one finds the identifier. Without the retry the stale token would have been cached
|
||||
// as "not permitted" for 5 minutes, every 5 minutes, until its 55-minute TTL.
|
||||
var (sut, handler) = BuildSut(
|
||||
Json("""{"error":{"code":"Forbidden"}}""", HttpStatusCode.Forbidden),
|
||||
Json($$"""{"value":[{"importedDeviceIdentityType":"manufacturerModelSerial","importedDeviceIdentifier":"{{StoredIdentifier}}"}]}"""));
|
||||
|
||||
var result = await sut.ValidateAsync(TenantId, "Microsoft Corporation", "Virtual Machine", Serial);
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
Assert.Equal(2, handler.Requests.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -182,6 +182,7 @@ public class CrossTenantAccessTests
|
||||
|
||||
[Theory]
|
||||
[InlineData("PATCH", "/api/config/{0}/plan")]
|
||||
[InlineData("GET", "/api/config/{0}/effective-agent-config")]
|
||||
[InlineData("POST", "/api/preview/whitelist/{0}")]
|
||||
[InlineData("DELETE", "/api/preview/whitelist/{0}")]
|
||||
[InlineData("POST", "/api/preview/send-welcome-email/{0}")]
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
public class EndpointNormalizerTests
|
||||
{
|
||||
[Fact]
|
||||
public void Normalize_StripsApiPrefixReplacesGuidsAndKeyChars()
|
||||
{
|
||||
var normalized = EndpointNormalizer.Normalize("/api/Sessions/0f8fad5b-d9cb-469f-a165-70867728950e/events?x=1");
|
||||
Assert.Equal("sessions_{id}_events_x=1", normalized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolNameKey_RealToolName_PassesThroughUnchanged()
|
||||
{
|
||||
// Existing UserUsageLog rows are keyed by "<tool>:<endpoint>"; a real tool name must keep its key.
|
||||
Assert.Equal("get_session_events", EndpointNormalizer.ToolNameKey("get_session_events"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolNameKey_NullOrEmpty_ReturnsEmpty()
|
||||
{
|
||||
Assert.Equal(string.Empty, EndpointNormalizer.ToolNameKey(null));
|
||||
Assert.Equal(string.Empty, EndpointNormalizer.ToolNameKey(string.Empty));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolNameKey_WithCrlfAndControlChars_StripsThem()
|
||||
{
|
||||
// The log-forging vector: a header that tries to inject a fake log line through the row key.
|
||||
var forged = $"get_metrics\r\n[McpQuota] FAKE{(char)0}{(char)27}{(char)0x2028}x";
|
||||
var key = EndpointNormalizer.ToolNameKey(forged);
|
||||
Assert.Equal("get_metrics[McpQuota] FAKEx", key);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolNameKey_WithTableKeyIllegalChars_ReplacesThem()
|
||||
{
|
||||
// '/', '\', '#', '?' are rejected by Table Storage in keys — a header carrying them would make
|
||||
// every usage increment fail with 400, so they are replaced the same way the path is.
|
||||
Assert.Equal("a_b_c_d_e", EndpointNormalizer.ToolNameKey("a/b\\c#d?e"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolNameKey_LongerThanCap_IsTruncated()
|
||||
{
|
||||
var key = EndpointNormalizer.ToolNameKey(new string('t', EndpointNormalizer.MaxToolNameLength + 10));
|
||||
Assert.Equal(EndpointNormalizer.MaxToolNameLength, key.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToolNameKey_OnlyControlChars_ReturnsEmpty()
|
||||
{
|
||||
Assert.Equal(string.Empty, EndpointNormalizer.ToolNameKey("\r\n "));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
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-APP-018 — pins the firing behaviour of the reboot-return-code rule on the agent's
|
||||
/// <c>exitCodeClass</c> payload (IME-EXITCODE-CLASS: the admin-defined return-code class of the
|
||||
/// installer exit code, one of Success/SoftReboot/HardReboot/Retry/Failed):
|
||||
/// - SoftReboot or HardReboot on an app_install_completed event fires at base confidence,
|
||||
/// - HardReboot and an observed system_reboot_detected add confidence (ESP-005's twin),
|
||||
/// - Success, Retry and Failed never fire, and neither does a class on app_install_failed alone.
|
||||
/// The required condition uses the comma-separated <c>in</c> operator; the matched event's
|
||||
/// data fields feed the {{appName}} / {{exitCode}} / {{exitCodeClass}} interpolation.
|
||||
/// </summary>
|
||||
public class ExitCodeClassRuleTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string SessionId = "11111111-2222-3333-4444-555555555555";
|
||||
private const string RuleId = "ANALYZE-APP-018";
|
||||
|
||||
private static AnalyzeRule Rule() => BuiltInAnalyzeRules.GetAll().First(r => r.RuleId == RuleId);
|
||||
|
||||
[Fact]
|
||||
public void Rule_is_a_warning_that_never_fails_the_session()
|
||||
{
|
||||
var rule = Rule();
|
||||
Assert.True(rule.Enabled);
|
||||
Assert.Equal("warning", rule.Severity);
|
||||
Assert.Equal("apps", rule.Category);
|
||||
Assert.False(rule.MarkSessionAsFailedDefault);
|
||||
Assert.Contains("whiteglove_sealed", rule.EvaluateOn ?? new List<string>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SoftReboot_on_a_completed_app_fires_at_base_confidence_without_an_observed_reboot()
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
AppCompleted("Contoso VPN Client", exitCode: "3010", exitCodeClass: "SoftReboot"),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
Assert.Equal(RuleId, result.RuleId);
|
||||
Assert.Equal("warning", result.Severity);
|
||||
Assert.Equal(60, result.ConfidenceScore);
|
||||
|
||||
// The evidence is persisted and interpolated at render time (portal, MCP
|
||||
// interpolate-rule-template.ts): {{exitCodeClass}} resolves through the condition's
|
||||
// field/value pair, {{appName}} and {{exitCode}} through the whitelisted payload keys
|
||||
// (AddDataFieldsToEvidence) — every token the rule text uses must be reachable here.
|
||||
var matched = AsDict(result.MatchedConditions["reboot_return_code"]);
|
||||
Assert.Equal("exitCodeClass", AsString(matched["field"]));
|
||||
Assert.Equal("SoftReboot", AsString(matched["value"]));
|
||||
Assert.Equal("Contoso VPN Client", AsString(matched["appName"]));
|
||||
Assert.Equal("3010", AsString(matched["exitCode"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HardReboot_with_an_observed_reboot_reaches_full_confidence()
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
AppCompleted("Contoso Security Agent", exitCode: "1641", exitCodeClass: "HardReboot", state: "Postponed"),
|
||||
RebootDetected(),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
Assert.Equal(100, result.ConfidenceScore);
|
||||
Assert.True(result.MatchedConditions.ContainsKey("hard_reboot_return_code"));
|
||||
Assert.True(result.MatchedConditions.ContainsKey("reboot_observed"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Success")]
|
||||
[InlineData("Retry")]
|
||||
[InlineData("Failed")]
|
||||
public async Task Other_return_code_classes_do_not_fire(string exitCodeClass)
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
AppCompleted("Contoso Reader", exitCode: "0", exitCodeClass: exitCodeClass),
|
||||
RebootDetected(),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(events);
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_completed_app_without_the_class_does_not_fire_even_with_a_reboot_exit_code()
|
||||
{
|
||||
// Older agents emit exitCode only on failures and never the class; 3010 alone is not
|
||||
// evidence of the mapping the admin chose.
|
||||
var evt = AppCompleted("Legacy App", exitCode: "3010", exitCodeClass: null);
|
||||
var outcome = await RunAsync(new List<EnrollmentEvent> { evt, RebootDetected() });
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_reboot_class_on_a_failed_app_alone_does_not_fire()
|
||||
{
|
||||
// The rule reads the terminal completed/postponed event; a failure carrying the class is
|
||||
// covered by the app-failure rules and must not double-report here.
|
||||
var failed = AppCompleted("Contoso Agent", exitCode: "1641", exitCodeClass: "HardReboot");
|
||||
failed.EventType = "app_install_failed";
|
||||
failed.Data!["state"] = "Error";
|
||||
failed.Data["isError"] = "true";
|
||||
|
||||
var outcome = await RunAsync(new List<EnrollmentEvent> { failed, RebootDetected() });
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
// ===== Event builders — mirror ImeLogTrackerAdapter.BuildAppStatePayload =====
|
||||
|
||||
private static int s_sequence = 10;
|
||||
|
||||
private static EnrollmentEvent AppCompleted(string appName, string exitCode, string? exitCodeClass, string state = "Installed")
|
||||
{
|
||||
var data = new Dictionary<string, object>
|
||||
{
|
||||
["appId"] = Guid.NewGuid().ToString(),
|
||||
["appName"] = appName,
|
||||
["state"] = state,
|
||||
["intent"] = "Install",
|
||||
["targeted"] = "Device",
|
||||
["runAs"] = "System",
|
||||
["progressPercent"] = "100",
|
||||
["bytesDownloaded"] = "0",
|
||||
["bytesTotal"] = "0",
|
||||
["isError"] = "false",
|
||||
["isCompleted"] = "true",
|
||||
["exitCode"] = exitCode,
|
||||
};
|
||||
if (exitCodeClass != null) data["exitCodeClass"] = exitCodeClass;
|
||||
|
||||
return new EnrollmentEvent
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
EventType = "app_install_completed",
|
||||
Timestamp = DateTime.UtcNow,
|
||||
Sequence = s_sequence++,
|
||||
Data = data,
|
||||
};
|
||||
}
|
||||
|
||||
private static EnrollmentEvent RebootDetected() => new()
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
EventType = "system_reboot_detected",
|
||||
Timestamp = DateTime.UtcNow.AddMinutes(2),
|
||||
Sequence = s_sequence++,
|
||||
Data = new Dictionary<string, object>
|
||||
{
|
||||
["bootTime"] = DateTime.UtcNow.AddMinutes(1).ToString("o"),
|
||||
},
|
||||
};
|
||||
|
||||
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<AnalysisOutcome> RunAsync(List<EnrollmentEvent> events)
|
||||
{
|
||||
var rule = Rule();
|
||||
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<ExitCodeClassRuleTests>.Instance);
|
||||
|
||||
return await engine.AnalyzeSessionAsync(TenantId, SessionId);
|
||||
}
|
||||
}
|
||||
@@ -147,11 +147,11 @@ public class FleetHealthPayloadTests
|
||||
var payload = MetricsMath.BuildFleetHealthPayload(sessions, days: 30);
|
||||
|
||||
Assert.Equal(6, payload.ModelHealth.Count);
|
||||
Assert.Equal("Contoso Model7", payload.ModelHealth[0].Model);
|
||||
Assert.Equal("Contoso Model7", payload.ModelHealth[0].Label);
|
||||
Assert.Equal(7, payload.ModelHealth[0].Total);
|
||||
Assert.Equal(7, payload.ModelHealth[0].Succeeded);
|
||||
// The smallest (volume 1) is dropped by the top-6 cut.
|
||||
Assert.DoesNotContain(payload.ModelHealth, m => m.Model == "Contoso Model1");
|
||||
Assert.DoesNotContain(payload.ModelHealth, m => m.Label == "Contoso Model1");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -182,7 +182,47 @@ public class FleetHealthPayloadTests
|
||||
new List<SessionSummary> { S(SessionStatus.Succeeded, manufacturer: "", model: "") },
|
||||
days: 7);
|
||||
|
||||
Assert.Equal("Unknown", Assert.Single(payload.ModelHealth).Model);
|
||||
var m = Assert.Single(payload.ModelHealth);
|
||||
Assert.Equal("Unknown", m.Label);
|
||||
Assert.Equal("", m.Manufacturer);
|
||||
Assert.Equal("", m.Model);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ModelBuckets_CarryManufacturerAndModelSeparately_OnAllThreeLists()
|
||||
{
|
||||
// The dashboard deep link addresses the two session fields as two qualified search
|
||||
// terms; a client must never have to split the label again.
|
||||
var sessions = new List<SessionSummary>
|
||||
{
|
||||
S(SessionStatus.Succeeded, durationSeconds: 600, manufacturer: " Contoso ", model: "EliteBook 840"),
|
||||
S(SessionStatus.Failed, manufacturer: "Contoso", model: "EliteBook 840"),
|
||||
};
|
||||
|
||||
var payload = MetricsMath.BuildFleetHealthPayload(sessions, days: 7);
|
||||
|
||||
var health = Assert.Single(payload.ModelHealth);
|
||||
Assert.Equal(("Contoso", "EliteBook 840", "Contoso EliteBook 840"), (health.Manufacturer, health.Model, health.Label));
|
||||
Assert.Equal(2, health.Total);
|
||||
var slow = Assert.Single(payload.SlowestModels);
|
||||
Assert.Equal(("Contoso", "EliteBook 840", "Contoso EliteBook 840"), (slow.Manufacturer, slow.Model, slow.Label));
|
||||
var failing = Assert.Single(payload.TopFailingModels);
|
||||
Assert.Equal(("Contoso", "EliteBook 840", "Contoso EliteBook 840"), (failing.Manufacturer, failing.Model, failing.Label));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ModelBuckets_GroupOnThePair_NotOnTheLabel()
|
||||
{
|
||||
var sessions = new List<SessionSummary>
|
||||
{
|
||||
S(SessionStatus.Succeeded, manufacturer: "Contoso", model: "A B"),
|
||||
S(SessionStatus.Succeeded, manufacturer: "Contoso A", model: "B"),
|
||||
};
|
||||
|
||||
var payload = MetricsMath.BuildFleetHealthPayload(sessions, days: 7);
|
||||
|
||||
Assert.Equal(2, payload.ModelHealth.Count);
|
||||
Assert.All(payload.ModelHealth, m => Assert.Equal("Contoso A B", m.Label));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -199,10 +239,10 @@ public class FleetHealthPayloadTests
|
||||
var payload = MetricsMath.BuildFleetHealthPayload(sessions, days: 30);
|
||||
|
||||
Assert.Equal(2, payload.SlowestModels.Count);
|
||||
Assert.Equal("Contoso Slow", payload.SlowestModels[0].Model);
|
||||
Assert.Equal("Contoso Slow", payload.SlowestModels[0].Label);
|
||||
Assert.Equal(30, payload.SlowestModels[0].AvgMinutes);
|
||||
Assert.Equal(1, payload.SlowestModels[0].Count);
|
||||
Assert.Equal("Contoso Fast", payload.SlowestModels[1].Model);
|
||||
Assert.Equal("Contoso Fast", payload.SlowestModels[1].Label);
|
||||
Assert.Equal(10, payload.SlowestModels[1].AvgMinutes);
|
||||
}
|
||||
|
||||
@@ -227,13 +267,13 @@ public class FleetHealthPayloadTests
|
||||
var payload = MetricsMath.BuildFleetHealthPayload(sessions, days: 30);
|
||||
|
||||
Assert.Equal(2, payload.TopFailingModels.Count);
|
||||
Assert.Equal("Contoso B", payload.TopFailingModels[0].Model);
|
||||
Assert.Equal("Contoso B", payload.TopFailingModels[0].Label);
|
||||
Assert.Equal(2, payload.TopFailingModels[0].Failed);
|
||||
Assert.Equal(100, payload.TopFailingModels[0].FailureRate);
|
||||
Assert.Equal("Contoso A", payload.TopFailingModels[1].Model);
|
||||
Assert.Equal("Contoso A", payload.TopFailingModels[1].Label);
|
||||
Assert.Equal(4, payload.TopFailingModels[1].Total);
|
||||
Assert.Equal(50, payload.TopFailingModels[1].FailureRate);
|
||||
Assert.DoesNotContain(payload.TopFailingModels, m => m.Model == "Contoso C");
|
||||
Assert.DoesNotContain(payload.TopFailingModels, m => m.Label == "Contoso C");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -129,6 +129,29 @@ public class GatherRuleScopeFieldsTests
|
||||
Assert.Null(mapped.ActivePhases);
|
||||
Assert.Null(mapped.ActiveFromPhase);
|
||||
Assert.Null(mapped.EmitMode);
|
||||
Assert.False(mapped.EnrichErrorCodes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Roundtrip_EnrichErrorCodes_SurvivesStoreAndMap()
|
||||
{
|
||||
var (service, lastUpserted) = BuildStorageHarness();
|
||||
var rule = new GatherRule
|
||||
{
|
||||
RuleId = "GATHER-ENRICH-001",
|
||||
Title = "MSI log parser",
|
||||
CollectorType = "logparser",
|
||||
Target = "C:\\Windows\\Temp\\msi.log",
|
||||
Trigger = "interval",
|
||||
IntervalSeconds = 60,
|
||||
OutputEventType = "gather_msi",
|
||||
EnrichErrorCodes = true,
|
||||
};
|
||||
|
||||
Assert.True(await service.StoreGatherRuleAsync(rule, "global"));
|
||||
var mapped = service.MapToGatherRule(lastUpserted()!);
|
||||
|
||||
Assert.True(mapped.EnrichErrorCodes);
|
||||
}
|
||||
|
||||
// ── ContentEquivalent ──────────────────────────────────────────────────
|
||||
@@ -175,6 +198,10 @@ public class GatherRuleScopeFieldsTests
|
||||
var emit = BaseRule();
|
||||
emit.EmitMode = "on_change";
|
||||
Assert.False(GatherRuleService.ContentEquivalent(baseline, emit));
|
||||
|
||||
var enrich = BaseRule();
|
||||
enrich.EnrichErrorCodes = true;
|
||||
Assert.False(GatherRuleService.ContentEquivalent(baseline, enrich));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -37,6 +37,7 @@ public class GatherRuleUpdatePartialMergeTests
|
||||
CreatedAt = new DateTime(2026, 1, 15, 12, 0, 0, DateTimeKind.Utc),
|
||||
ActiveFromPhase = "AccountSetup",
|
||||
EmitMode = "on_change",
|
||||
EnrichErrorCodes = true,
|
||||
};
|
||||
|
||||
private static (GatherRuleService service, Mock<IRuleRepository> repo, List<GatherRule> stored) BuildService(
|
||||
@@ -77,6 +78,7 @@ public class GatherRuleUpdatePartialMergeTests
|
||||
Assert.Equal("Version", written.Parameters["valueName"]);
|
||||
Assert.Equal("AccountSetup", written.ActiveFromPhase);
|
||||
Assert.Equal("on_change", written.EmitMode);
|
||||
Assert.True(written.EnrichErrorCodes);
|
||||
Assert.Equal(existing.CreatedAt, written.CreatedAt);
|
||||
Assert.Equal("Alice Admin", written.Author);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
using AutopilotMonitor.Functions.Functions.Config;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for <see cref="GetAgentConfigFunction.ParseAgentMajor"/> — the pure decision logic that picks
|
||||
/// Tests for <see cref="AgentConfigResolver.ParseAgentMajor"/> — the pure decision logic that picks
|
||||
/// the per-line hash-oracle field set based on the X-Agent-Version header value.
|
||||
/// </summary>
|
||||
public class GetAgentConfigFunctionTests
|
||||
@@ -29,7 +29,7 @@ public class GetAgentConfigFunctionTests
|
||||
[InlineData("vNEXT", 1)]
|
||||
public void ParseAgentMajor_ExtractsMajor(string? agentVersion, int expectedMajor)
|
||||
{
|
||||
var actual = GetAgentConfigFunction.ParseAgentMajor(agentVersion);
|
||||
var actual = AgentConfigResolver.ParseAgentMajor(agentVersion);
|
||||
Assert.Equal(expectedMajor, actual);
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ public class GetAgentConfigFunctionTests
|
||||
P(@"C:\Windows\SetupDiag\*.log", "tenant"),
|
||||
};
|
||||
|
||||
var merged = GetAgentConfigFunction.MergeDiagnosticsLogPaths(global, tenant);
|
||||
var merged = AgentConfigResolver.MergeDiagnosticsLogPaths(global, tenant);
|
||||
|
||||
Assert.Equal(new[]
|
||||
{
|
||||
@@ -63,7 +63,7 @@ public class GetAgentConfigFunctionTests
|
||||
[Fact]
|
||||
public void MergeDiagnosticsLogPaths_DropsBlankEntries()
|
||||
{
|
||||
var merged = GetAgentConfigFunction.MergeDiagnosticsLogPaths(
|
||||
var merged = AgentConfigResolver.MergeDiagnosticsLogPaths(
|
||||
new[] { P(""), P(" "), P(@"C:\Install\Log\*.log") },
|
||||
new DiagnosticsLogPath[] { null!, P(@"C:\Install\Log\*.log") });
|
||||
|
||||
@@ -90,7 +90,7 @@ public class GetAgentConfigFunctionTests
|
||||
public void ResolveDiagnosticsUploadEnabled_GatesOnSasOrHosted(
|
||||
string? diagnosticsBlobSasUrl, string? destination, bool expected)
|
||||
{
|
||||
var actual = GetAgentConfigFunction.ResolveDiagnosticsUploadEnabled(diagnosticsBlobSasUrl, destination);
|
||||
var actual = AgentConfigResolver.ResolveDiagnosticsUploadEnabled(diagnosticsBlobSasUrl, destination);
|
||||
Assert.Equal(expected, actual);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
using System.Net;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the shared 401/403 contract of the Graph-backed device validators: attempt 1 drops the
|
||||
/// tenant's cached token (it may predate the consent grant on this instance) and reports
|
||||
/// transient so the loop re-mints; attempt 2 and every other status leave the token alone.
|
||||
/// </summary>
|
||||
public class GraphAuthFailureTests
|
||||
{
|
||||
private const string TenantId = "11111111-1111-1111-1111-111111111111";
|
||||
|
||||
private static Mock<GraphTokenService> TokenService()
|
||||
{
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["EntraId:ClientId"] = "aaaaaaaa-0000-0000-0000-000000000001",
|
||||
["EntraId:ClientSecret"] = "secret",
|
||||
}).Build();
|
||||
var registry = new EntraAppRegistry(configuration, NullLogger<EntraAppRegistry>.Instance);
|
||||
var tenantConfig = new Mock<TenantConfigurationService>(
|
||||
Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache)
|
||||
{ CallBase = false };
|
||||
return new Mock<GraphTokenService>(
|
||||
NullLogger<GraphTokenService>.Instance, Mock.Of<IHttpClientFactory>(), cache,
|
||||
configuration, registry, tenantConfig.Object)
|
||||
{ CallBase = false };
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.Unauthorized)]
|
||||
[InlineData(HttpStatusCode.Forbidden)]
|
||||
public void AuthFailure_OnFirstAttempt_InvalidatesOnce_AndAsksForRetry(HttpStatusCode status)
|
||||
{
|
||||
var tokens = TokenService();
|
||||
|
||||
var retry = GraphAuthFailure.TryRecoverStaleToken(tokens.Object, NullLogger.Instance, "Test", TenantId, status, attempt: 1);
|
||||
|
||||
Assert.True(retry);
|
||||
tokens.Verify(t => t.InvalidateTenant(TenantId), Times.Once);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.Unauthorized)]
|
||||
[InlineData(HttpStatusCode.Forbidden)]
|
||||
public void AuthFailure_OnSecondAttempt_LeavesTheFreshToken_AndDefersToTheValidator(HttpStatusCode status)
|
||||
{
|
||||
var tokens = TokenService();
|
||||
|
||||
var retry = GraphAuthFailure.TryRecoverStaleToken(tokens.Object, NullLogger.Instance, "Test", TenantId, status, attempt: 2);
|
||||
|
||||
Assert.False(retry);
|
||||
tokens.Verify(t => t.InvalidateTenant(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.NotFound)]
|
||||
[InlineData(HttpStatusCode.BadRequest)]
|
||||
[InlineData(HttpStatusCode.TooManyRequests)]
|
||||
[InlineData(HttpStatusCode.InternalServerError)]
|
||||
[InlineData(HttpStatusCode.GatewayTimeout)]
|
||||
public void OtherStatuses_NeverTouchTheToken(HttpStatusCode status)
|
||||
{
|
||||
var tokens = TokenService();
|
||||
|
||||
var retry = GraphAuthFailure.TryRecoverStaleToken(tokens.Object, NullLogger.Instance, "Test", TenantId, status, attempt: 1);
|
||||
|
||||
Assert.False(retry);
|
||||
Assert.False(GraphAuthFailure.IsAuthFailure(status));
|
||||
tokens.Verify(t => t.InvalidateTenant(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PermissionMissingRetryAfter_IsLongerThanTheDefault_ButInsideTheAgentsPatience()
|
||||
{
|
||||
// 30 s is the SecurityValidator default for a transient failure; a consent gap needs more
|
||||
// than that to close, and the agent's replay logic honours any Retry-After.
|
||||
Assert.True(GraphAuthFailure.PermissionMissingRetryAfterSeconds > 30);
|
||||
Assert.True(GraphAuthFailure.PermissionMissingRetryAfterSeconds <= 300);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, null, null)]
|
||||
[InlineData(null, 120, 120)]
|
||||
[InlineData(30, null, 30)]
|
||||
[InlineData(30, 120, 120)]
|
||||
[InlineData(120, 30, 120)]
|
||||
public void SecurityValidator_KeepsTheLargestRetryAfter(int? accumulated, int? next, int? expected)
|
||||
=> Assert.Equal(expected, SecurityValidator.MaxRetryAfter(accumulated, next));
|
||||
}
|
||||
@@ -77,17 +77,62 @@ public class HealthCheckServiceMcpServerTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_TimeoutOrConnectionFailure_ReportsWarningForColdStart()
|
||||
public async Task Check_Timeout_ReportsWarmingSoTheCallerCanRePoll()
|
||||
{
|
||||
var svc = BuildServiceWithFactory(
|
||||
new ThrowingHttpClientFactory(new TaskCanceledException("timeout")));
|
||||
|
||||
var check = await svc.CheckMcpServerAsync();
|
||||
|
||||
// Failure to wake the scaled-to-zero container within the budget is a warning,
|
||||
// not a hard outage (a re-check may still succeed once it finishes warming).
|
||||
// A scaled-to-zero container that did not answer inside the budget is "warming",
|
||||
// NOT a fault: the caller re-checks and the activation we triggered keeps running.
|
||||
Assert.Equal("warming", check.Status);
|
||||
// The default budget is pinned here because it is set nowhere else in the repo —
|
||||
// the code default IS the live production value.
|
||||
Assert.Contains("3s", check.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_Timeout_HonoursConfiguredBudget()
|
||||
{
|
||||
var svc = BuildServiceWithFactory(
|
||||
new ThrowingHttpClientFactory(new TaskCanceledException("timeout")),
|
||||
extraConfig: new Dictionary<string, string?> { ["McpServerHealthTimeoutSeconds"] = "7" });
|
||||
|
||||
var check = await svc.CheckMcpServerAsync();
|
||||
|
||||
Assert.Equal("warming", check.Status);
|
||||
Assert.Contains("7s", check.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_ConnectionFailure_ReportsWarningNotWarmingAndKeepsTheHostOut()
|
||||
{
|
||||
var svc = BuildServiceWithFactory(
|
||||
new ThrowingHttpClientFactory(new System.Net.Http.HttpRequestException("no such host mcp.example.test")));
|
||||
|
||||
var check = await svc.CheckMcpServerAsync();
|
||||
|
||||
// Reaching the network and failing to connect is a real warning — distinct from
|
||||
// the expected cold-start path, so it must not be softened to "warming".
|
||||
Assert.Equal("warning", check.Status);
|
||||
Assert.Contains("could not be reached", check.Message);
|
||||
Assert.DoesNotContain("http", check.Message, System.StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("mcp.example.test", check.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(12, false)]
|
||||
[InlineData(750, false)]
|
||||
[InlineData(751, true)]
|
||||
[InlineData(2400, true)]
|
||||
public void McpReachableMessage_marksOnlyAnswersAboveTheWarmThresholdAsColdStart(long elapsedMs, bool expectColdStart)
|
||||
{
|
||||
var message = HealthCheckService.McpReachableMessage(elapsedMs);
|
||||
|
||||
// Both arms keep the word "reachable" — the healthy-path assertions rely on it.
|
||||
Assert.Contains("reachable", message);
|
||||
Assert.Contains($"{elapsedMs}ms", message);
|
||||
Assert.Equal(expectColdStart, message.Contains("cold start"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -101,13 +146,21 @@ public class HealthCheckServiceMcpServerTests
|
||||
return BuildServiceWithFactory(new StubHttpClientFactory(handler));
|
||||
}
|
||||
|
||||
private static HealthCheckService BuildServiceWithFactory(System.Net.Http.IHttpClientFactory factory)
|
||||
private static HealthCheckService BuildServiceWithFactory(
|
||||
System.Net.Http.IHttpClientFactory factory,
|
||||
Dictionary<string, string?>? extraConfig = null)
|
||||
{
|
||||
var settings = new Dictionary<string, string?>
|
||||
{
|
||||
["McpServerUrl"] = "https://mcp.example.test",
|
||||
};
|
||||
if (extraConfig != null)
|
||||
{
|
||||
foreach (var kv in extraConfig) settings[kv.Key] = kv.Value;
|
||||
}
|
||||
|
||||
var config = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["McpServerUrl"] = "https://mcp.example.test",
|
||||
})
|
||||
.AddInMemoryCollection(settings)
|
||||
.Build();
|
||||
|
||||
return new HealthCheckService(
|
||||
|
||||
@@ -28,6 +28,8 @@ public class InfrastructureWireParityTests
|
||||
var displayName = "Admin User";
|
||||
var objectId = "0b6f7a37-1111-4d61-9c93-0aa111111111";
|
||||
var managedTenantIds = new[] { "7b7b46b3-40c3-4f2f-9a1b-6d9f1a2b3c4e" };
|
||||
var platformSeen = new DateTime(2026, 9, 8, 10, 0, 0, DateTimeKind.Utc);
|
||||
var agentSeen = new DateTime(2026, 9, 8, 10, 5, 0, DateTimeKind.Utc);
|
||||
|
||||
AssertParity(
|
||||
new
|
||||
@@ -46,7 +48,9 @@ public class InfrastructureWireParityTests
|
||||
hasMcpAccess = true,
|
||||
homedApp = "primary",
|
||||
bootstrapTokenEnabled = true,
|
||||
unrestrictedModeEnabled = false
|
||||
unrestrictedModeEnabled = false,
|
||||
whatsNewSeenPlatformUtc = platformSeen,
|
||||
whatsNewSeenAgentUtc = agentSeen
|
||||
},
|
||||
new AuthMeResponse
|
||||
{
|
||||
@@ -64,7 +68,9 @@ public class InfrastructureWireParityTests
|
||||
HasMcpAccess = true,
|
||||
HomedApp = "primary",
|
||||
BootstrapTokenEnabled = true,
|
||||
UnrestrictedModeEnabled = false
|
||||
UnrestrictedModeEnabled = false,
|
||||
WhatsNewSeenPlatformUtc = platformSeen,
|
||||
WhatsNewSeenAgentUtc = agentSeen
|
||||
});
|
||||
}
|
||||
|
||||
@@ -78,6 +84,8 @@ public class InfrastructureWireParityTests
|
||||
var displayName = "Reader User";
|
||||
var objectId = "0b6f7a37-2222-4d61-9c93-0aa222222222";
|
||||
string? role = null;
|
||||
DateTime? whatsNewSeenPlatformUtc = null;
|
||||
DateTime? whatsNewSeenAgentUtc = null;
|
||||
|
||||
AssertParity(
|
||||
new
|
||||
@@ -96,7 +104,9 @@ public class InfrastructureWireParityTests
|
||||
hasMcpAccess = true,
|
||||
homedApp = "legacy",
|
||||
bootstrapTokenEnabled = false,
|
||||
unrestrictedModeEnabled = false
|
||||
unrestrictedModeEnabled = false,
|
||||
whatsNewSeenPlatformUtc,
|
||||
whatsNewSeenAgentUtc
|
||||
},
|
||||
new AuthMeResponse
|
||||
{
|
||||
@@ -114,7 +124,9 @@ public class InfrastructureWireParityTests
|
||||
HasMcpAccess = true,
|
||||
HomedApp = "legacy",
|
||||
BootstrapTokenEnabled = false,
|
||||
UnrestrictedModeEnabled = false
|
||||
UnrestrictedModeEnabled = false,
|
||||
WhatsNewSeenPlatformUtc = null,
|
||||
WhatsNewSeenAgentUtc = null
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+10
@@ -51,4 +51,14 @@ public class IngestStorageFailureClassificationTests
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, status);
|
||||
Assert.Null(retryAfter);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_connection_failure_without_status_is_503_with_retry_after()
|
||||
{
|
||||
var (status, _, retryAfter) = IngestTelemetryFunction.ClassifyStorageFailure(
|
||||
new RequestFailedException(0, "connection reset before a status arrived"));
|
||||
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, status);
|
||||
Assert.Equal(IngestTelemetryFunction.StorageRetryAfterSeconds, retryAfter);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ public class McpQuotaServiceTests
|
||||
cache ??= new MemoryCache(new MemoryCacheOptions());
|
||||
var mcpUserService = new McpUserService(
|
||||
adminRepo.Object, new StubAdminIdentityBindingService(bound), cache, NullLogger<McpUserService>.Instance,
|
||||
globalAdminService: null!, delegatedAdminService: null!, adminConfigService: null!, memberRoleResolver: null!);
|
||||
globalAdminService: null!, delegatedAdminService: null!, adminConfigService: null!, memberRoleResolver: null!, tenantConfigService: null!);
|
||||
|
||||
var configRepo = new Mock<IConfigRepository>();
|
||||
configRepo.Setup(r => r.GetAdminConfigurationAsync())
|
||||
|
||||
@@ -50,7 +50,8 @@ public class McpUserServiceAllMembersTests
|
||||
|
||||
_sut = new McpUserService(
|
||||
_adminRepo.Object, bindings, cache, NullLogger<McpUserService>.Instance,
|
||||
_globalAdmin.Object, _delegatedAdmin.Object, adminConfig.Object, _memberRoles);
|
||||
_globalAdmin.Object, _delegatedAdmin.Object, adminConfig.Object, _memberRoles,
|
||||
new TenantConfigurationService(Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache));
|
||||
}
|
||||
|
||||
private void MemberOf(string tenantId, string role) =>
|
||||
|
||||
@@ -54,7 +54,8 @@ public class McpUserServiceDelegatedTests
|
||||
|
||||
_sut = new McpUserService(
|
||||
_adminRepo.Object, bindings, cache, NullLogger<McpUserService>.Instance,
|
||||
_globalAdmin.Object, _delegatedAdmin.Object, _adminConfig.Object, _memberRoles);
|
||||
_globalAdmin.Object, _delegatedAdmin.Object, _adminConfig.Object, _memberRoles,
|
||||
new TenantConfigurationService(Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache));
|
||||
}
|
||||
|
||||
private void SetPolicy(McpAccessPolicy policy) =>
|
||||
|
||||
@@ -59,7 +59,8 @@ public class McpUserServiceIdentityBindingTests
|
||||
|
||||
_sut = new McpUserService(
|
||||
_adminRepo.Object, _bindings, cache, NullLogger<McpUserService>.Instance,
|
||||
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, _memberRoles);
|
||||
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, _memberRoles,
|
||||
new TenantConfigurationService(Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache));
|
||||
}
|
||||
|
||||
private void SetRow(bool enabled, string? plan = "pro") =>
|
||||
@@ -131,7 +132,8 @@ public class McpUserServiceIdentityBindingTests
|
||||
adminConfig.Setup(x => x.GetConfigurationAsync())
|
||||
.ReturnsAsync(new AdminConfiguration { McpAccessPolicy = McpAccessPolicy.WhitelistOnly.ToString() });
|
||||
var sut = new McpUserService(_adminRepo.Object, bindings, cache, NullLogger<McpUserService>.Instance,
|
||||
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, _memberRoles);
|
||||
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, _memberRoles,
|
||||
new TenantConfigurationService(Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache));
|
||||
_adminRepo.Setup(x => x.GetMcpUserAsync(It.IsAny<string>())).ReturnsAsync((McpUserEntry?)null);
|
||||
|
||||
var result = await sut.IsAllowedAsync(Upn, HomeTenant, Oid);
|
||||
@@ -171,7 +173,8 @@ public class McpUserServiceIdentityBindingTests
|
||||
adminConfig.Setup(x => x.GetConfigurationAsync())
|
||||
.ReturnsAsync(new AdminConfiguration { McpAccessPolicy = McpAccessPolicy.AllMembers.ToString() });
|
||||
var sut = new McpUserService(_adminRepo.Object, _bindings, cache, NullLogger<McpUserService>.Instance,
|
||||
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, _memberRoles);
|
||||
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, _memberRoles,
|
||||
new TenantConfigurationService(Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache));
|
||||
SetRow(enabled: false);
|
||||
|
||||
var bound = await sut.IsAllowedAsync(Upn, HomeTenant, Oid);
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
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>
|
||||
/// The tenant-level MCP switch (<see cref="TenantConfiguration.McpDisabled"/>, operator control) at the MCP
|
||||
/// front door: a closed HOME tenant denies every caller below the platform roles — members under AllMembers,
|
||||
/// delegated (MSP) admins and enabled McpUsers rows alike — with the operator's reason (or a neutral default),
|
||||
/// while Global Admin / Reader keep administering the tenant and other tenants are untouched. The read is
|
||||
/// side-effect-free: a tenant without a config row is not closed and no default row is ever persisted.
|
||||
/// </summary>
|
||||
public class McpUserServiceTenantMcpSwitchTests
|
||||
{
|
||||
private const string Upn = "operator@customer.example";
|
||||
private const string HomeTenant = "11111111-1111-1111-1111-111111111111";
|
||||
private const string OtherTenant = "22222222-2222-2222-2222-222222222222";
|
||||
private const string Oid = "aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa";
|
||||
|
||||
private readonly Mock<IAdminRepository> _adminRepo = new();
|
||||
private readonly Mock<IConfigRepository> _configRepo = new();
|
||||
private readonly Mock<GlobalAdminService> _globalAdmin;
|
||||
private readonly Mock<DelegatedAdminService> _delegatedAdmin;
|
||||
private readonly StubTenantMemberRoleResolver _memberRoles = new();
|
||||
private readonly McpUserService _sut;
|
||||
|
||||
public McpUserServiceTenantMcpSwitchTests()
|
||||
{
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
var bindings = new StubAdminIdentityBindingService(bound: true);
|
||||
_globalAdmin = new Mock<GlobalAdminService>(
|
||||
_adminRepo.Object, bindings, cache, NullLogger<GlobalAdminService>.Instance) { CallBase = false };
|
||||
_globalAdmin.Setup(x => x.GetGlobalRoleAsync(It.IsAny<AdminIdentity?>())).ReturnsAsync((string?)null);
|
||||
_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() });
|
||||
_adminRepo.Setup(x => x.GetMcpUserAsync(It.IsAny<string>())).ReturnsAsync((McpUserEntry?)null);
|
||||
// No tenant has a config row unless a test closes one — the service must treat "no row" as open.
|
||||
_configRepo.Setup(r => r.GetTenantConfigurationAsync(It.IsAny<string>())).ReturnsAsync((TenantConfiguration?)null);
|
||||
var tenantConfig = new TenantConfigurationService(_configRepo.Object, NullLogger<TenantConfigurationService>.Instance, cache);
|
||||
|
||||
_sut = new McpUserService(
|
||||
_adminRepo.Object, bindings, cache, NullLogger<McpUserService>.Instance,
|
||||
_globalAdmin.Object, _delegatedAdmin.Object, adminConfig.Object, _memberRoles, tenantConfig);
|
||||
}
|
||||
|
||||
private void MemberOf(string tenantId, string role) =>
|
||||
_memberRoles.Verdict = (tid, upn, _) =>
|
||||
string.Equals(tid, tenantId, StringComparison.OrdinalIgnoreCase) && upn == Upn
|
||||
? new MemberRoleInfo { Role = role }
|
||||
: null;
|
||||
|
||||
private void CloseMcp(string tenantId, string? reason = null) =>
|
||||
_configRepo.Setup(r => r.GetTenantConfigurationAsync(tenantId))
|
||||
.ReturnsAsync(new TenantConfiguration { TenantId = tenantId, McpDisabled = true, McpDisabledReason = reason });
|
||||
|
||||
[Fact]
|
||||
public async Task Member_OfClosedHomeTenant_IsDenied_WithOperatorReason()
|
||||
{
|
||||
MemberOf(HomeTenant, Constants.TenantRoles.Admin);
|
||||
CloseMcp(HomeTenant, "No AI access by customer request");
|
||||
|
||||
var result = await _sut.IsAllowedAsync(Upn, HomeTenant, Oid);
|
||||
|
||||
Assert.False(result.IsAllowed);
|
||||
Assert.Equal("No AI access by customer request", result.Reason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Member_OfClosedHomeTenant_WithoutReason_GetsNeutralDefault()
|
||||
{
|
||||
MemberOf(HomeTenant, Constants.TenantRoles.Admin);
|
||||
CloseMcp(HomeTenant);
|
||||
|
||||
var result = await _sut.IsAllowedAsync(Upn, HomeTenant, Oid);
|
||||
|
||||
Assert.False(result.IsAllowed);
|
||||
Assert.Contains("disabled for your organization", result.Reason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DelegatedAdmin_WhoseHomeTenantIsClosed_LosesMcp()
|
||||
{
|
||||
// Same reach as a suspension: the MSP's own organization said "no MCP" — its staff cannot route
|
||||
// around that by reading managed customers instead.
|
||||
_delegatedAdmin.Setup(x => x.GetScopeAsync(It.IsAny<AdminIdentity?>()))
|
||||
.ReturnsAsync(new DelegatedScope(new Dictionary<string, string>
|
||||
{
|
||||
[OtherTenant] = Constants.DelegatedRoles.DelegatedReader,
|
||||
}));
|
||||
CloseMcp(HomeTenant, "closed");
|
||||
|
||||
var result = await _sut.IsAllowedAsync(Upn, HomeTenant, Oid);
|
||||
|
||||
Assert.False(result.IsAllowed);
|
||||
Assert.Equal("closed", result.Reason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnabledMcpUsersRow_DoesNotOverride_ClosedHomeTenant()
|
||||
{
|
||||
_adminRepo.Setup(x => x.GetMcpUserAsync(Upn))
|
||||
.ReturnsAsync(new McpUserEntry { Upn = Upn, IsEnabled = true });
|
||||
CloseMcp(HomeTenant);
|
||||
|
||||
var result = await _sut.IsAllowedAsync(Upn, HomeTenant, Oid);
|
||||
|
||||
Assert.False(result.IsAllowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GlobalAdmin_OfClosedHomeTenant_StillAllowed()
|
||||
{
|
||||
_globalAdmin.Setup(x => x.GetGlobalRoleAsync(It.IsAny<AdminIdentity?>()))
|
||||
.ReturnsAsync(Constants.GlobalRoles.GlobalAdmin);
|
||||
CloseMcp(HomeTenant);
|
||||
|
||||
var result = await _sut.IsAllowedAsync(Upn, HomeTenant, Oid);
|
||||
|
||||
Assert.True(result.IsAllowed);
|
||||
Assert.Equal(Constants.GlobalRoles.GlobalAdmin, result.AccessGrant);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClosedTenant_DoesNotAffect_AnotherTenantsMember()
|
||||
{
|
||||
MemberOf(OtherTenant, Constants.TenantRoles.Viewer);
|
||||
CloseMcp(HomeTenant);
|
||||
|
||||
var result = await _sut.IsAllowedAsync(Upn, OtherTenant, Oid);
|
||||
|
||||
Assert.True(result.IsAllowed);
|
||||
Assert.Equal("AllMembers", result.AccessGrant);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TenantWithoutConfigRow_IsOpen_AndNoRowIsPersisted()
|
||||
{
|
||||
MemberOf(HomeTenant, Constants.TenantRoles.Operator);
|
||||
|
||||
var result = await _sut.IsAllowedAsync(Upn, HomeTenant, Oid);
|
||||
|
||||
Assert.True(result.IsAllowed);
|
||||
_configRepo.Verify(r => r.SaveTenantConfigurationAsync(It.IsAny<TenantConfiguration>()), Times.Never);
|
||||
_configRepo.Verify(r => r.SaveTenantConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void McpDisabledMessage_PrefersOperatorReason_ElseDefault()
|
||||
{
|
||||
Assert.Equal("why", McpUserService.McpDisabledMessage(new TenantConfiguration { McpDisabled = true, McpDisabledReason = "why" }));
|
||||
Assert.Contains("Contact your administrator", McpUserService.McpDisabledMessage(new TenantConfiguration { McpDisabled = true, McpDisabledReason = " " }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using AutopilotMonitor.Functions.Functions.Config;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The tenant-plan PATCH is the one body read as a document (absent key ≠ explicit null). Its
|
||||
/// handler walks the keys by name; this pins that key set to <see cref="PatchTenantPlanRequest"/>,
|
||||
/// the type the web and MCP compile against — a property added to the DTO without a handler
|
||||
/// branch (or the reverse) fails here instead of silently never binding.
|
||||
/// </summary>
|
||||
public class PlanPatchKeyParityTests
|
||||
{
|
||||
[Fact]
|
||||
public void HandlerKeysMatchTheWireDto()
|
||||
{
|
||||
var dtoKeys = typeof(PatchTenantPlanRequest)
|
||||
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Select(p => JsonNamingPolicy.CamelCase.ConvertName(p.Name))
|
||||
.OrderBy(k => k, System.StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
|
||||
var handlerKeys = PlanManagementFunction.PlanPatchKeys.All
|
||||
.OrderBy(k => k, System.StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
|
||||
Assert.Equal(dtoKeys, handlerKeys);
|
||||
Assert.Contains("trialExpiresUtc", handlerKeys); // the presence-sensitive key that motivated the document read
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using System.Threading;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
@@ -23,7 +24,7 @@ public class PlatformMetricsServiceWindowTests
|
||||
{
|
||||
var sessionRepo = new Mock<ISessionRepository>();
|
||||
sessionRepo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(EmptyPage());
|
||||
sessionRepo
|
||||
.Setup(r => r.GetSessionEventsAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>()))
|
||||
@@ -64,8 +65,8 @@ public class PlatformMetricsServiceWindowTests
|
||||
|
||||
int? capturedDays = null;
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?>((_, d, _, _, _, _) => capturedDays = d)
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?, CancellationToken>((_, d, _, _, _, _, _) => capturedDays = d)
|
||||
.ReturnsAsync(EmptyPage());
|
||||
|
||||
var result = await service.ComputePlatformMetricsAsync(days, limit: 50);
|
||||
@@ -89,8 +90,8 @@ public class PlatformMetricsServiceWindowTests
|
||||
|
||||
int? capturedPageSize = null;
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?>((_, _, ps, _, _, _) => capturedPageSize = ps)
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?, CancellationToken>((_, _, ps, _, _, _, _) => capturedPageSize = ps)
|
||||
.ReturnsAsync(EmptyPage());
|
||||
|
||||
var result = await service.ComputePlatformMetricsAsync(days: days, limit: limit);
|
||||
@@ -106,8 +107,8 @@ public class PlatformMetricsServiceWindowTests
|
||||
|
||||
int? capturedDays = null;
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?>((_, d, _, _, _, _) => capturedDays = d)
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?, CancellationToken>((_, d, _, _, _, _, _) => capturedDays = d)
|
||||
.ReturnsAsync(EmptyPage());
|
||||
|
||||
var result = await service.ComputePlatformMetricsAsync(0);
|
||||
@@ -140,7 +141,7 @@ public class PlatformMetricsServiceWindowTests
|
||||
var (service, repo) = CreateService();
|
||||
int callCount = 0;
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.Callback(() => callCount++)
|
||||
.ReturnsAsync(EmptyPage());
|
||||
|
||||
@@ -160,7 +161,7 @@ public class PlatformMetricsServiceWindowTests
|
||||
var (service, repo) = CreateService();
|
||||
var sessions = Enumerable.Range(1, 7).Select(MakeSession).ToList();
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(sessions, null));
|
||||
|
||||
var result = await service.ComputePlatformMetricsAsync(days: 77, limit: 50);
|
||||
@@ -177,7 +178,7 @@ public class PlatformMetricsServiceWindowTests
|
||||
var (service, repo) = CreateService();
|
||||
var sessions = Enumerable.Range(1, 25).Select(MakeSession).ToList();
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(sessions, null));
|
||||
|
||||
var fullFetchSessions = new List<string>();
|
||||
@@ -216,7 +217,7 @@ public class PlatformMetricsServiceWindowTests
|
||||
var (service, repo) = CreateService();
|
||||
var sessions = Enumerable.Range(1, 21).Select(MakeSession).ToList();
|
||||
repo
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
|
||||
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new RawPage<SessionSummary>(sessions, null));
|
||||
|
||||
var session21 = sessions[20].SessionId;
|
||||
|
||||
@@ -1676,4 +1676,115 @@ public class PolicyEnforcementMiddlewareTests
|
||||
Assert.True(result.Allowed);
|
||||
h.ConfigRepo.Verify(r => r.GetTenantConfigurationAsync(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
// ── Tenant MCP switch (TenantConfiguration.McpDisabled) — the per-request half ────────────
|
||||
// The MCP front door (McpUserService) already denies a caller whose home tenant is closed; this gate
|
||||
// is what makes the switch hold per request (front-door verdicts are cached) and what keeps a closed
|
||||
// tenant out of reach as a TARGET — a delegated read into it, or its rows in the MSP's aggregate.
|
||||
// It fires only for requests the MCP server forwards (X-Client-Source: mcp): the switch closes the AI
|
||||
// channel, not the tenant's own portal/API access.
|
||||
|
||||
private static void AsMcpDisabled(Harness h, string tenantId, string? reason = null) =>
|
||||
h.ConfigRepo.Setup(r => r.GetTenantConfigurationAsync(tenantId))
|
||||
.ReturnsAsync(new TenantConfiguration { TenantId = tenantId, McpDisabled = true, McpDisabledReason = reason });
|
||||
|
||||
[Fact]
|
||||
public async Task McpDisabled_HomeTenant_McpClient_IsForbidden_WithOperatorReason()
|
||||
{
|
||||
const string upn = "admin@contoso.com";
|
||||
var h = BuildHarness();
|
||||
h.AsTenantAdmin(TenantA, upn);
|
||||
AsMcpDisabled(h, TenantA, reason: "No AI access by customer request");
|
||||
|
||||
var result = await h.Middleware.DecideAsync("GET", "/api/sessions", null, AuthedPrincipal(TenantA, upn), isMcpClient: true);
|
||||
|
||||
Assert.False(result.Allowed);
|
||||
Assert.Equal(403, result.StatusCode);
|
||||
Assert.Equal("McpDisabled", result.ErrorCode);
|
||||
Assert.Equal("No AI access by customer request", result.ErrorMessage);
|
||||
Assert.Equal("McpDisabled", result.LogReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task McpDisabled_HomeTenant_PortalClient_IsAllowed()
|
||||
{
|
||||
// The same caller without the MCP marker is a portal user — the tenant keeps its own data access.
|
||||
const string upn = "admin@contoso.com";
|
||||
var h = BuildHarness();
|
||||
h.AsTenantAdmin(TenantA, upn);
|
||||
AsMcpDisabled(h, TenantA);
|
||||
|
||||
var result = await h.Middleware.DecideAsync("GET", "/api/sessions", null, AuthedPrincipal(TenantA, upn));
|
||||
|
||||
Assert.True(result.Allowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task McpDisabled_GlobalAdmin_McpClient_BypassesGate()
|
||||
{
|
||||
const string upn = "ga@platform.example";
|
||||
var h = BuildHarness();
|
||||
h.AsGlobalRole(Constants.GlobalRoles.GlobalAdmin);
|
||||
AsMcpDisabled(h, TenantA);
|
||||
AsMcpDisabled(h, TenantB);
|
||||
|
||||
var own = await h.Middleware.DecideAsync("GET", "/api/sessions", null, AuthedPrincipal(TenantA, upn), isMcpClient: true);
|
||||
var cross = await h.Middleware.DecideAsync("GET", $"/api/config/{TenantB}", null, AuthedPrincipal(TenantA, upn), isMcpClient: true);
|
||||
|
||||
Assert.True(own.Allowed);
|
||||
Assert.True(cross.Allowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task McpDisabled_DelegatedReader_TargetClosed_IsForbidden()
|
||||
{
|
||||
// The customer said "no MCP": its MSP cannot read it through MCP either, even with a valid grant.
|
||||
const string upn = "msp@partner.example";
|
||||
var h = BuildHarness();
|
||||
h.AsDelegated(TenantB);
|
||||
AsMcpDisabled(h, TenantB, reason: "closed");
|
||||
|
||||
var mcp = await h.Middleware.DecideAsync("GET", $"/api/config/{TenantB}", null, AuthedPrincipal(TenantA, upn), isMcpClient: true);
|
||||
var portal = await h.Middleware.DecideAsync("GET", $"/api/config/{TenantB}", null, AuthedPrincipal(TenantA, upn));
|
||||
|
||||
Assert.False(mcp.Allowed);
|
||||
Assert.Equal("McpDisabled", mcp.ErrorCode);
|
||||
Assert.Equal("closed", mcp.ErrorMessage);
|
||||
Assert.True(portal.Allowed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task McpDisabled_DelegatedAggregate_McpClient_NarrowsBound_NeverToNull()
|
||||
{
|
||||
// The bounded fleet aggregate drops the closed tenant instead of failing: the published bound shrinks
|
||||
// to the open subset (here: empty) and must never become null — null means "all tenants" downstream.
|
||||
const string upn = "msp@partner.example";
|
||||
var h = BuildHarness();
|
||||
h.AsDelegated(TenantB);
|
||||
AsMcpDisabled(h, TenantB);
|
||||
|
||||
var mcp = await h.Middleware.DecideAsync("GET", "/api/global/sessions", null, AuthedPrincipal(TenantA, upn), isMcpClient: true);
|
||||
var portal = await h.Middleware.DecideAsync("GET", "/api/global/sessions", null, AuthedPrincipal(TenantA, upn));
|
||||
|
||||
Assert.True(mcp.Allowed);
|
||||
Assert.NotNull(mcp.Context!.AllowedTenantIds);
|
||||
Assert.Empty(mcp.Context!.AllowedTenantIds!);
|
||||
Assert.True(mcp.Context!.IsDelegatedAggregate);
|
||||
Assert.Contains(TenantB.ToLowerInvariant(), portal.Context!.AllowedTenantIds!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Suspended_And_McpDisabled_SuspensionWins()
|
||||
{
|
||||
// Both flags set: the stronger, longer-standing verdict is reported so support reads the right cause.
|
||||
const string upn = "admin@contoso.com";
|
||||
var h = BuildHarness();
|
||||
h.AsTenantAdmin(TenantA, upn);
|
||||
h.ConfigRepo.Setup(r => r.GetTenantConfigurationAsync(TenantA))
|
||||
.ReturnsAsync(new TenantConfiguration { TenantId = TenantA, Disabled = true, McpDisabled = true });
|
||||
|
||||
var result = await h.Middleware.DecideAsync("GET", "/api/sessions", null, AuthedPrincipal(TenantA, upn), isMcpClient: true);
|
||||
|
||||
Assert.Equal("TenantSuspended", result.ErrorCode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
using System;
|
||||
using AutopilotMonitor.Functions.Telemetry;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The stall classifier turns two runtime snapshots around a late timer tick into a cause.
|
||||
/// GC wins when its pause clock covers at least half the drift; queued work or thread injection
|
||||
/// means starvation; otherwise the drift stays unexplained rather than guessed.
|
||||
/// </summary>
|
||||
public class ProcessStallClassifierTests
|
||||
{
|
||||
private static ProcessSnapshot Snapshot(
|
||||
double gcPauseMs = 0, int gen2 = 0, int threads = 8, long pending = 0, long completed = 0)
|
||||
=> new(
|
||||
GcPause: TimeSpan.FromMilliseconds(gcPauseMs),
|
||||
Gen0: 0, Gen1: 0, Gen2: gen2,
|
||||
ThreadPoolThreads: threads,
|
||||
PendingWorkItems: pending,
|
||||
CompletedWorkItems: completed,
|
||||
WorkingSetBytes: 0, HeapSizeBytes: 0, CommittedBytes: 0,
|
||||
LastGcGeneration: 0, LastGcPause: TimeSpan.Zero, LastGcCompacted: false);
|
||||
|
||||
[Fact]
|
||||
public void Gc_pause_covering_half_the_drift_is_a_gc_stall()
|
||||
{
|
||||
var before = Snapshot(gcPauseMs: 1000, gen2: 3);
|
||||
var after = Snapshot(gcPauseMs: 6200, gen2: 4, pending: 12);
|
||||
|
||||
var report = ProcessStallClassifier.Classify(TimeSpan.FromSeconds(10), before, after);
|
||||
|
||||
Assert.Equal(StallCause.Gc, report.Cause);
|
||||
Assert.Equal(TimeSpan.FromMilliseconds(5200), report.GcPauseDelta);
|
||||
Assert.Equal(1, report.Gen2Delta);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Queued_work_without_gc_is_thread_pool_starvation()
|
||||
{
|
||||
var before = Snapshot(gcPauseMs: 1000);
|
||||
var after = Snapshot(gcPauseMs: 1100, pending: 40);
|
||||
|
||||
var report = ProcessStallClassifier.Classify(TimeSpan.FromSeconds(8), before, after);
|
||||
|
||||
Assert.Equal(StallCause.ThreadPool, report.Cause);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Thread_injection_without_gc_is_thread_pool_starvation()
|
||||
{
|
||||
var before = Snapshot(threads: 8);
|
||||
var after = Snapshot(threads: 11);
|
||||
|
||||
var report = ProcessStallClassifier.Classify(TimeSpan.FromSeconds(3), before, after);
|
||||
|
||||
Assert.Equal(StallCause.ThreadPool, report.Cause);
|
||||
Assert.Equal(3, report.ThreadPoolThreadsDelta);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Drift_neither_clock_explains_stays_unknown()
|
||||
{
|
||||
var before = Snapshot(gcPauseMs: 500, threads: 8, completed: 100);
|
||||
var after = Snapshot(gcPauseMs: 900, threads: 8, completed: 130);
|
||||
|
||||
var report = ProcessStallClassifier.Classify(TimeSpan.FromSeconds(5), before, after);
|
||||
|
||||
Assert.Equal(StallCause.Unknown, report.Cause);
|
||||
Assert.Equal(30, report.CompletedWorkItemsDelta);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_wrapped_pause_clock_never_yields_a_negative_delta()
|
||||
{
|
||||
var before = Snapshot(gcPauseMs: 900);
|
||||
var after = Snapshot(gcPauseMs: 100);
|
||||
|
||||
var report = ProcessStallClassifier.Classify(TimeSpan.FromSeconds(2), before, after);
|
||||
|
||||
Assert.Equal(TimeSpan.Zero, report.GcPauseDelta);
|
||||
Assert.Equal(StallCause.Unknown, report.Cause);
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@ namespace AutopilotMonitor.Functions.Tests;
|
||||
/// is a new private parser copy — the state the 2026-09-04 API audit found six times over for
|
||||
/// <c>days</c> alone, each with its own default, cap and out-of-range rule. The baseline lists
|
||||
/// the sites that parse something other than a query parameter (a header, a stored cell, a
|
||||
/// version string); it only shrinks.
|
||||
/// version string); it only shrinks. The X-Agent-Version major parse moved to
|
||||
/// <c>Services/AgentConfigResolver.cs</c> (outside the scanned roots) with D-216.
|
||||
/// </summary>
|
||||
public class QueryParamGuardTests
|
||||
{
|
||||
@@ -19,29 +20,14 @@ public class QueryParamGuardTests
|
||||
/// <summary>Non-query parses, reviewed: file → why it is allowed.</summary>
|
||||
private static readonly IReadOnlyDictionary<string, string> Baseline = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["Functions/Config/GetAgentConfigFunction.cs"] = "major of the X-Agent-Version header",
|
||||
["Functions/Ingest/IngestTelemetryFunction.cs"] = "X-Send-Time-Utc header (RoundtripKind, deliberately not a query instant)",
|
||||
["Functions/Raw/QueryRawEventsFunction.cs"] = "Severity / Sequence cells of raw table rows",
|
||||
["Functions/Diagnostics/GetDiagnosticsUploadUrlFunction.cs"] = "se= expiry inside the tenant's stored SAS URL",
|
||||
// Content-Length header guard on body-taking routes (long.TryParse on the header value).
|
||||
["Functions/Admin/SubmitOffboardingFeedbackFunction.cs"] = "Content-Length header",
|
||||
["Functions/Bootstrap/BootstrapRegisterSessionFunction.cs"] = "Content-Length header",
|
||||
["Functions/Config/PatchTenantConfigurationFieldsFunction.cs"] = "Content-Length header",
|
||||
["Functions/Config/UpdateAdminConfigurationFunction.cs"] = "Content-Length header",
|
||||
["Functions/Config/UpdateTenantConfigurationFunction.cs"] = "Content-Length header",
|
||||
["Functions/Feedback/FeedbackFunction.cs"] = "Content-Length header",
|
||||
["Functions/Infrastructure/SignalRAddToGroupFunction.cs"] = "Content-Length header",
|
||||
["Functions/Infrastructure/SignalRRemoveFromGroupFunction.cs"] = "Content-Length header",
|
||||
["Functions/Ingest/ReportAgentErrorFunction.cs"] = "Content-Length header",
|
||||
["Functions/Ingest/ReportDistressFunction.cs"] = "Content-Length header",
|
||||
["Functions/Reports/SubmitDiagFilesReportFunction.cs"] = "Content-Length header",
|
||||
["Functions/Reports/SubmitSessionReportFunction.cs"] = "Content-Length header",
|
||||
["Functions/Rules/AnalyzeRulesFunction.cs"] = "Content-Length header",
|
||||
["Functions/Rules/DryRunAnalyzeRuleFunction.cs"] = "Content-Length header",
|
||||
["Functions/Rules/GatherRulesFunction.cs"] = "Content-Length header",
|
||||
["Functions/Rules/GlobalRulesFunction.cs"] = "Content-Length header",
|
||||
["Functions/Rules/ImeLogPatternsFunction.cs"] = "Content-Length header",
|
||||
["Functions/Rules/TestLogPatternFunction.cs"] = "Content-Length header",
|
||||
["Functions/Sessions/RegisterSessionFunction.cs"] = "Content-Length header",
|
||||
};
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using Xunit;
|
||||
|
||||
@@ -21,7 +22,8 @@ public class RateLimitResolverTests
|
||||
Assert.Equal(expected, RateLimitResolver.ResolveDeviceLimit(tenantOverride, globalDefault, entitlementFloor));
|
||||
}
|
||||
|
||||
// ── User path: GA → globalAdminDefault (override + floor never apply); else override ?? max(default, floor) ──
|
||||
// ── User path, integration surface (MCP server / integrations / app-only):
|
||||
// GA → globalAdminDefault (override + floor never apply); else override ?? max(default, floor) ──
|
||||
[Theory]
|
||||
[InlineData(false, null, 120, 600, null, 120)] // standard user, no override → global user default
|
||||
[InlineData(false, 300, 120, 600, null, 300)] // per-tenant user override wins over the global user default
|
||||
@@ -30,10 +32,26 @@ public class RateLimitResolverTests
|
||||
[InlineData(false, null, 200, 600, 150, 200)] // admin-raised default (200) must never be LOWERED by the floor
|
||||
[InlineData(false, 50, 120, 600, 150, 50)] // explicit override beats the floor
|
||||
[InlineData(true, null, 120, 600, 9999, 600)] // Global Admin: entitlement floor never applies
|
||||
public void ResolveUserLimit_respects_global_admin_override_and_floor(
|
||||
public void ResolveUserLimit_integration_respects_global_admin_override_and_floor(
|
||||
bool isGlobalAdmin, int? tenantUserOverride, int globalUserDefault, int globalAdminDefault, int? entitlementFloor, int expected)
|
||||
{
|
||||
const int portalDefault = 600;
|
||||
Assert.Equal(expected, RateLimitResolver.ResolveUserLimit(
|
||||
isGlobalAdmin, tenantUserOverride, globalUserDefault, globalAdminDefault, entitlementFloor));
|
||||
ThrottleSurface.Integration, isGlobalAdmin, tenantUserOverride, globalUserDefault, portalDefault, globalAdminDefault, entitlementFloor));
|
||||
}
|
||||
|
||||
// ── User path, portal surface (public-client token): one global knob — no override, no floor;
|
||||
// Global Admins keep their own budget on every surface ──
|
||||
[Theory]
|
||||
[InlineData(false, null, 120, 600, 900, null, 600)] // standard user → portal default, not the integration default
|
||||
[InlineData(false, 300, 120, 600, 900, null, 600)] // per-tenant override is an integration-budget concept
|
||||
[InlineData(false, null, 120, 600, 900, 150, 600)] // edition floor is an integration-budget concept
|
||||
[InlineData(false, null, 120, 50, 900, 150, 50)] // an admin-lowered portal default is honoured as set (no floor lifts it)
|
||||
[InlineData(true, 300, 120, 600, 900, 9999, 900)] // Global Admin: GA budget, whatever the surface
|
||||
public void ResolveUserLimit_portal_is_one_global_knob(
|
||||
bool isGlobalAdmin, int? tenantUserOverride, int globalUserDefault, int portalUserDefault, int globalAdminDefault, int? entitlementFloor, int expected)
|
||||
{
|
||||
Assert.Equal(expected, RateLimitResolver.ResolveUserLimit(
|
||||
ThrottleSurface.Portal, isGlobalAdmin, tenantUserOverride, globalUserDefault, portalUserDefault, globalAdminDefault, entitlementFloor));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Models.Backup;
|
||||
using Azure.Core.Serialization;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The one body reader (D-207): camelCase and PascalCase both bind, string enums bind, an empty
|
||||
/// or malformed body is a 400 envelope (never a 500), the optional variant treats "no body" as
|
||||
/// null, the byte cap and the Newtonsoft branch behave the same way.
|
||||
/// </summary>
|
||||
public class RequestBodyTests
|
||||
{
|
||||
private const string CorrelationId = "corr-123";
|
||||
|
||||
[Fact]
|
||||
public async Task CamelCase_body_binds()
|
||||
{
|
||||
var req = Build("{\"name\":\"Group A\"}");
|
||||
var read = await req.ReadAsync<CreateTenantGroupRequest>();
|
||||
Assert.Null(read.Error);
|
||||
Assert.Equal("Group A", read.Value!.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PascalCase_body_binds_too()
|
||||
{
|
||||
// Superset of the two former paths: the worker serializer was case-sensitive, Newtonsoft was not.
|
||||
var req = Build("{\"Name\":\"Group A\"}");
|
||||
var read = await req.ReadAsync<CreateTenantGroupRequest>();
|
||||
Assert.Null(read.Error);
|
||||
Assert.Equal("Group A", read.Value!.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task String_enum_binds()
|
||||
{
|
||||
var req = Build("{\"tableName\":\"t\",\"partitionKey\":\"p\",\"rowKey\":\"r\",\"mode\":\"Commit\"}");
|
||||
var read = await req.ReadAsync<RestoreRowRequest>();
|
||||
Assert.Null(read.Error);
|
||||
Assert.Equal(RestoreRowMode.Commit, read.Value!.Mode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Absent_nullable_key_stays_null_and_number_binds()
|
||||
{
|
||||
var req = Build("{\"tenantId\":\"t\",\"serialNumber\":\"s\",\"durationHours\":24}");
|
||||
var read = await req.ReadAsync<BlockDeviceRequest>();
|
||||
Assert.Null(read.Error);
|
||||
Assert.Equal(24, read.Value!.DurationHours);
|
||||
Assert.Null(read.Value.Action);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public async Task Empty_body_is_400_required(string body)
|
||||
{
|
||||
var req = Build(body);
|
||||
var read = await req.ReadAsync<CreateTenantGroupRequest>();
|
||||
await AssertBadRequest(read.Error, "Request body is required");
|
||||
Assert.Null(read.Value);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("{not json")]
|
||||
[InlineData("[]")]
|
||||
[InlineData("{\"durationHours\":\"twelve\",\"tenantId\":\"t\",\"serialNumber\":\"s\"}")] // string in an int slot
|
||||
public async Task Malformed_body_is_400_invalid(string body)
|
||||
{
|
||||
var req = Build(body);
|
||||
var read = await req.ReadAsync<BlockDeviceRequest>();
|
||||
await AssertBadRequest(read.Error, "Invalid JSON body");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Json_null_body_is_400_required()
|
||||
{
|
||||
var req = Build("null");
|
||||
var read = await req.ReadAsync<CreateTenantGroupRequest>();
|
||||
await AssertBadRequest(read.Error, "Request body is required");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Optional_reader_returns_empty_for_no_body_but_400_for_garbage()
|
||||
{
|
||||
var empty = await Build("").ReadOptionalAsync<DownloadTicketRequest>();
|
||||
Assert.Null(empty.Error);
|
||||
Assert.Null(empty.Value);
|
||||
|
||||
var present = await Build("{\"blobName\":\"b\"}").ReadOptionalAsync<DownloadTicketRequest>();
|
||||
Assert.Null(present.Error);
|
||||
Assert.Equal("b", present.Value!.BlobName);
|
||||
|
||||
var garbage = await Build("{oops").ReadOptionalAsync<DownloadTicketRequest>();
|
||||
await AssertBadRequest(garbage.Error, "Invalid JSON body");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Byte_cap_applies_only_when_given()
|
||||
{
|
||||
var capped = await Build("{\"name\":\"x\"}", contentLength: 2_000_000).ReadAsync<CreateTenantGroupRequest>(maxBytes: 1_048_576);
|
||||
await AssertBadRequest(capped.Error, "Request body too large");
|
||||
|
||||
var uncapped = await Build("{\"name\":\"x\"}", contentLength: 2_000_000).ReadAsync<CreateTenantGroupRequest>();
|
||||
Assert.Null(uncapped.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Newtonsoft_branch_has_the_same_contract()
|
||||
{
|
||||
var ok = await Build("{\"Fields\":{\"a\":1},\"reason\":\"r\"}").ReadNewtonsoftAsync<PatchTenantConfigurationFieldsRequest>();
|
||||
Assert.Null(ok.Error);
|
||||
Assert.Single(ok.Value!.Fields!);
|
||||
Assert.Equal("r", ok.Value.Reason);
|
||||
|
||||
var empty = await Build("").ReadNewtonsoftAsync<PatchTenantConfigurationFieldsRequest>();
|
||||
await AssertBadRequest(empty.Error, "Request body is required");
|
||||
|
||||
var bad = await Build("{oops").ReadNewtonsoftAsync<PatchTenantConfigurationFieldsRequest>();
|
||||
await AssertBadRequest(bad.Error, "Invalid JSON body");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Document_reader_requires_an_object_root()
|
||||
{
|
||||
var doc = await Build("{\"planTier\":\"pro\",\"trialExpiresUtc\":null}").ReadDocumentAsync();
|
||||
Assert.Null(doc.Error);
|
||||
var document = doc.Value!;
|
||||
using (document)
|
||||
{
|
||||
Assert.True(document.RootElement.TryGetProperty("trialExpiresUtc", out var trial));
|
||||
Assert.Equal(JsonValueKind.Null, trial.ValueKind); // presence survives — the reason this reader exists
|
||||
Assert.False(document.RootElement.TryGetProperty("maxDelegatedTenants", out _));
|
||||
}
|
||||
|
||||
var array = await Build("[1,2]").ReadDocumentAsync();
|
||||
await AssertBadRequest(array.Error, "Body must be a JSON object");
|
||||
}
|
||||
|
||||
// ── fakes ─────────────────────────────────────────────────────────────────
|
||||
|
||||
private static async Task AssertBadRequest(HttpResponseData? error, string message)
|
||||
{
|
||||
Assert.NotNull(error);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, error!.StatusCode);
|
||||
error.Body.Position = 0;
|
||||
var envelope = await JsonSerializer.DeserializeAsync<ApiErrorResponse>(error.Body, ApiJsonOptions.Read);
|
||||
Assert.NotNull(envelope);
|
||||
Assert.Equal(message, envelope!.Error);
|
||||
Assert.Equal(AutopilotMonitor.Shared.Constants.ApiErrorCodes.BadRequest, envelope!.Code);
|
||||
Assert.Equal(CorrelationId, envelope!.CorrelationId);
|
||||
}
|
||||
|
||||
private static HttpRequestData Build(string body, long? contentLength = null)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddOptions();
|
||||
services.Configure<WorkerOptions>(o => o.Serializer = new JsonObjectSerializer(ApiJsonOptions.Create()));
|
||||
var provider = services.BuildServiceProvider();
|
||||
|
||||
var context = new Mock<FunctionContext>();
|
||||
context.SetupGet(c => c.Items).Returns(new Dictionary<object, object> { ["CorrelationId"] = CorrelationId });
|
||||
context.SetupGet(c => c.InstanceServices).Returns(provider);
|
||||
|
||||
var headers = new HttpHeadersCollection();
|
||||
if (contentLength is long len) headers.Add("Content-Length", len.ToString());
|
||||
|
||||
var req = new Mock<HttpRequestData>(context.Object);
|
||||
req.SetupGet(r => r.Headers).Returns(headers);
|
||||
req.SetupGet(r => r.Body).Returns(new MemoryStream(Encoding.UTF8.GetBytes(body)));
|
||||
req.Setup(r => r.CreateResponse()).Returns(() => new FakeHttpResponseData(context.Object));
|
||||
return req.Object;
|
||||
}
|
||||
|
||||
private sealed class FakeHttpResponseData : HttpResponseData
|
||||
{
|
||||
public FakeHttpResponseData(FunctionContext context) : base(context) { }
|
||||
public override HttpStatusCode StatusCode { get; set; } = HttpStatusCode.OK;
|
||||
public override HttpHeadersCollection Headers { get; set; } = new();
|
||||
public override Stream Body { get; set; } = new MemoryStream();
|
||||
public override HttpCookies Cookies { get; } = new Mock<HttpCookies>().Object;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
@@ -76,7 +77,7 @@ public class RevokeEnforcementTests
|
||||
}
|
||||
|
||||
private static (TenantGroupManagementFunction Fn, Mock<IAdminRepository> Repo,
|
||||
Mock<IMaintenanceRepository> Audit, FakeSignalRNotificationService SignalR) BuildGroupFn()
|
||||
Mock<IMaintenanceRepository> Audit, FakeSignalRNotificationService SignalR) BuildGroupFn(ProConferralService? proConferral = null)
|
||||
{
|
||||
var repo = new Mock<IAdminRepository>();
|
||||
// Loose-mock defaults return a null Task — every repo read the flows touch needs a concrete setup.
|
||||
@@ -89,10 +90,17 @@ public class RevokeEnforcementTests
|
||||
var signalR = new FakeSignalRNotificationService();
|
||||
var fn = new TenantGroupManagementFunction(
|
||||
NullLogger<TenantGroupManagementFunction>.Instance, BuildService(repo), Resolver(), audit.Object, signalR, BuildSlots(repo),
|
||||
TestProConferral.Inert());
|
||||
proConferral ?? TestProConferral.Inert());
|
||||
return (fn, repo, audit, signalR);
|
||||
}
|
||||
|
||||
/// <summary>A recording conferral double (CallBase off, touches no storage): the group flows only need to prove WHAT they hand it.</summary>
|
||||
private static Mock<ProConferralService> RecordingProConferral() =>
|
||||
new(Mock.Of<IAdminRepository>(),
|
||||
new TenantConfigurationService(Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions())),
|
||||
ManagedTenantProIndex.None,
|
||||
NullLogger<ProConferralService>.Instance) { CallBase = false };
|
||||
|
||||
// --- ChargeHomeTenantQuota flip: audited under every tenant, no-op on an unchanged value ---
|
||||
|
||||
[Fact]
|
||||
@@ -361,4 +369,53 @@ public class RevokeEnforcementTests
|
||||
TenantA, "DELETE", "DelegatedGroupAccess", "*", "ga@vendor.example",
|
||||
It.IsAny<Dictionary<string, string>?>()), Times.Once);
|
||||
}
|
||||
|
||||
// --- Group delete ends conferred Pro: every member of an OWNED group gets its grace anchor ---
|
||||
|
||||
private const string OwnerTenant = "33333333-3333-3333-3333-333333333333";
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteGroupCore_OwnedGroup_RecordsLossForEveryMember_EvenWithoutAssignees()
|
||||
{
|
||||
var proConferral = RecordingProConferral();
|
||||
var (fn, repo, audit, _) = BuildGroupFn(proConferral.Object);
|
||||
var ownedGroupId = Constants.TenantGroupIds.ForHomeTenant(OwnerTenant);
|
||||
repo.Setup(r => r.GetTenantGroupAsync(ownedGroupId)).ReturnsAsync(new TenantGroup
|
||||
{
|
||||
GroupId = ownedGroupId,
|
||||
Name = "Customers of owner",
|
||||
OwnerTenantId = OwnerTenant,
|
||||
TenantIds = new List<string> { TenantA, TenantB, OwnerTenant },
|
||||
AssigneeCount = 0,
|
||||
});
|
||||
repo.Setup(r => r.DeleteTenantGroupAsync(ownedGroupId)).ReturnsAsync(true);
|
||||
|
||||
await fn.DeleteGroupCoreAsync(ownedGroupId, "ga@vendor.example");
|
||||
|
||||
// The anchor does not depend on assignees (no assignee ⇒ no access audit, but Pro still ends);
|
||||
// the owner itself is never a managed tenant of its own group.
|
||||
proConferral.Verify(p => p.RecordLossAsync(TenantA, OwnerTenant, "group-deleted"), Times.Once);
|
||||
proConferral.Verify(p => p.RecordLossAsync(TenantB, OwnerTenant, "group-deleted"), Times.Once);
|
||||
proConferral.Verify(p => p.RecordLossAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(2));
|
||||
VerifyNoAudit(audit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteGroupCore_OperatorGroup_RecordsNoLoss()
|
||||
{
|
||||
var proConferral = RecordingProConferral();
|
||||
var (fn, repo, _, _) = BuildGroupFn(proConferral.Object);
|
||||
repo.Setup(r => r.GetTenantGroupAsync(GroupId)).ReturnsAsync(new TenantGroup
|
||||
{
|
||||
GroupId = GroupId,
|
||||
Name = "MSP Customers",
|
||||
TenantIds = new List<string> { TenantA },
|
||||
AssigneeCount = 0,
|
||||
});
|
||||
repo.Setup(r => r.DeleteTenantGroupAsync(GroupId)).ReturnsAsync(true);
|
||||
|
||||
await fn.DeleteGroupCoreAsync(GroupId, "ga@vendor.example");
|
||||
|
||||
proConferral.Verify(p => p.RecordLossAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,10 @@ public sealed class ErrorCodeEnricherTests
|
||||
Data = data,
|
||||
};
|
||||
|
||||
/// <summary>The <c>*Info</c> sibling as the wire sees it: a string-keyed dictionary.</summary>
|
||||
private static Dictionary<string, object> Info(EnrollmentEvent evt, string key) =>
|
||||
Assert.IsType<Dictionary<string, object>>(evt.Data[key]);
|
||||
|
||||
[Fact]
|
||||
public void EnrichEvent_adds_errorCodeInfo_for_known_hex_code()
|
||||
{
|
||||
@@ -25,13 +29,13 @@ public sealed class ErrorCodeEnricherTests
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
|
||||
Assert.True(evt.Data.ContainsKey("errorCodeInfo"));
|
||||
var info = evt.Data["errorCodeInfo"];
|
||||
var description = info.GetType().GetProperty("description")?.GetValue(info)?.ToString();
|
||||
var confidence = info.GetType().GetProperty("confidence")?.GetValue(info)?.ToString();
|
||||
var source = info.GetType().GetProperty("source")?.GetValue(info)?.ToString();
|
||||
Assert.Contains("Access denied", description ?? "");
|
||||
Assert.Equal("high", confidence);
|
||||
Assert.False(string.IsNullOrEmpty(source));
|
||||
var info = Info(evt, "errorCodeInfo");
|
||||
Assert.Equal("Access is denied", info["description"]);
|
||||
Assert.Equal("high", info["confidence"]);
|
||||
Assert.StartsWith("msdoc:", (string)info["source"]);
|
||||
Assert.Equal("win32", info["category"]);
|
||||
Assert.Equal("ERROR_ACCESS_DENIED", info["symbol"]);
|
||||
Assert.False(info.ContainsKey("derivedFromWin32"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -41,29 +45,35 @@ public sealed class ErrorCodeEnricherTests
|
||||
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
|
||||
Assert.True(evt.Data.ContainsKey("exitCodeInfo"));
|
||||
var info = evt.Data["exitCodeInfo"];
|
||||
Assert.Contains("Fatal error", info.GetType().GetProperty("description")?.GetValue(info)?.ToString() ?? "");
|
||||
var info = Info(evt, "exitCodeInfo");
|
||||
Assert.Contains("fatal error", (string)info["description"]);
|
||||
Assert.Equal("ERROR_INSTALL_FAILURE", info["symbol"]);
|
||||
Assert.Equal("msi", info["category"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnrichEvent_handles_hresult_key()
|
||||
public void EnrichEvent_reports_hresult_from_win32_derivation_as_data()
|
||||
{
|
||||
var evt = EventWithData(new() { { "hresultFromWin32", "0x80070643" } });
|
||||
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
|
||||
var info = Info(evt, "hresultFromWin32Info");
|
||||
Assert.Equal(1603, info["derivedFromWin32"]);
|
||||
Assert.Equal("ERROR_INSTALL_FAILURE", info["symbol"]);
|
||||
Assert.DoesNotContain("1603", (string)info["description"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnrichEvent_omits_symbol_when_the_entry_has_none()
|
||||
{
|
||||
var evt = EventWithData(new() { { "hresult", "0x87d1041c" } });
|
||||
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
|
||||
Assert.True(evt.Data.ContainsKey("hresultInfo"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnrichEvent_handles_hresultFromWin32_key()
|
||||
{
|
||||
var evt = EventWithData(new() { { "hresultFromWin32", "0x80070005" } });
|
||||
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
|
||||
Assert.True(evt.Data.ContainsKey("hresultFromWin32Info"));
|
||||
var info = Info(evt, "hresultInfo");
|
||||
Assert.False(info.ContainsKey("symbol"));
|
||||
Assert.Equal("intune-win32", info["category"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -111,6 +121,127 @@ public sealed class ErrorCodeEnricherTests
|
||||
Assert.Same(existing, evt.Data["errorCodeInfo"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnrichEvent_adds_enforcementStateInfo_for_numeric_state()
|
||||
{
|
||||
// registry_app_state carries the IME enforcement state as a numeric string.
|
||||
var evt = EventWithData(new() { { "enforcementState", "1000" } });
|
||||
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
|
||||
var info = evt.Data["enforcementStateInfo"];
|
||||
Assert.Equal("Success", info.GetType().GetProperty("name")?.GetValue(info));
|
||||
Assert.False(string.IsNullOrEmpty(info.GetType().GetProperty("description")?.GetValue(info) as string));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnrichEvent_skips_unknown_enforcement_state_and_stays_idempotent()
|
||||
{
|
||||
var unknown = EventWithData(new() { { "enforcementState", "424242" } });
|
||||
ErrorCodeEnricher.EnrichEvent(unknown);
|
||||
Assert.False(unknown.Data.ContainsKey("enforcementStateInfo"));
|
||||
|
||||
var existing = new { name = "kept" };
|
||||
var evt = EventWithData(new() { { "enforcementState", "1000" }, { "enforcementStateInfo", existing } });
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
Assert.Same(existing, evt.Data["enforcementStateInfo"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnrichEvent_leaves_nested_objects_untouched()
|
||||
{
|
||||
// app_install_summary carries per-app objects; only top-level keys are enriched.
|
||||
var nested = new Dictionary<string, object> { { "exitCode", "1603" } };
|
||||
var evt = EventWithData(new() { { "apps", new List<object> { nested } } });
|
||||
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
|
||||
Assert.Single(evt.Data);
|
||||
Assert.Single(nested);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnrichEvent_skips_gather_rule_events_by_default()
|
||||
{
|
||||
// A logparser gather rule on HP Image Assistant.log captured `exitcode` — HPiA has its own
|
||||
// exit-code table, so the MSI/Win32 catalog meaning ("ERROR_SUCCESS") must not be attached
|
||||
// unless the rule opted in (no enrichErrorCodes marker here).
|
||||
var evt = new EnrollmentEvent
|
||||
{
|
||||
EventType = "HPiA-UpdateStatus",
|
||||
Source = "GatherRuleExecutor",
|
||||
Message = "Gather: HP Updater Log Analyze",
|
||||
Data = new()
|
||||
{
|
||||
{ "exitcode", "0" },
|
||||
{ "errorCode", "0x80070005" },
|
||||
{ "enforcementState", "1000" },
|
||||
{ "ruleId", "hpia-log-collect" },
|
||||
},
|
||||
};
|
||||
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
|
||||
Assert.DoesNotContain(evt.Data.Keys, k => k.EndsWith("Info"));
|
||||
Assert.Equal(4, evt.Data.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnrichEvent_matches_gather_rule_source_case_insensitively()
|
||||
{
|
||||
var evt = EventWithData(new() { { "exitCode", "1603" } });
|
||||
evt.Source = "gatherruleexecutor";
|
||||
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
|
||||
Assert.False(evt.Data.ContainsKey("exitCodeInfo"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)] // in-process CLR bool
|
||||
[InlineData("true")] // string form after DataJson roundtrip
|
||||
[InlineData("True")]
|
||||
public void EnrichEvent_enriches_gather_rule_events_that_opted_in(object marker)
|
||||
{
|
||||
// A rule that parses an msiexec log set enrichErrorCodes; the agent stamped the marker.
|
||||
var evt = EventWithData(new()
|
||||
{
|
||||
{ "exitCode", "1603" },
|
||||
{ "ruleId", "msi-log" },
|
||||
{ "enrichErrorCodes", marker },
|
||||
});
|
||||
evt.Source = "GatherRuleExecutor";
|
||||
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
|
||||
Assert.Equal("ERROR_INSTALL_FAILURE", Info(evt, "exitCodeInfo")["symbol"]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData("false")]
|
||||
[InlineData("")]
|
||||
public void EnrichEvent_ignores_gather_rule_marker_that_is_not_true(object marker)
|
||||
{
|
||||
var evt = EventWithData(new() { { "exitCode", "1603" }, { "enrichErrorCodes", marker } });
|
||||
evt.Source = "GatherRuleExecutor";
|
||||
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
|
||||
Assert.False(evt.Data.ContainsKey("exitCodeInfo"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnrichEvent_marker_on_non_gather_event_changes_nothing()
|
||||
{
|
||||
// Built-in events are always enriched; the marker is only consulted for gather events.
|
||||
var evt = EventWithData(new() { { "exitCode", "1603" }, { "enrichErrorCodes", false } });
|
||||
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
|
||||
Assert.True(evt.Data.ContainsKey("exitCodeInfo"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnrichEvent_handles_null_data_dictionary()
|
||||
{
|
||||
@@ -137,9 +268,7 @@ public sealed class ErrorCodeEnricherTests
|
||||
|
||||
ErrorCodeEnricher.EnrichEvent(evt);
|
||||
|
||||
Assert.True(evt.Data.ContainsKey("errorCodeInfo"));
|
||||
var info = evt.Data["errorCodeInfo"];
|
||||
Assert.Contains("Access denied", info.GetType().GetProperty("description")?.GetValue(info)?.ToString() ?? "");
|
||||
Assert.Equal("Access is denied", Info(evt, "errorCodeInfo")["description"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Pagination;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
@@ -7,13 +12,16 @@ using Xunit;
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Fragilitätsaudit P6.2: server-side free-text search (<c>q=</c>) for the dashboard search
|
||||
/// box, replacing the client's unbounded loadAll() sweep. The predicate must mirror the web
|
||||
/// dashboard's client-side searchable field set (minus derived-only tokens) — see the doc on
|
||||
/// <c>TableStorageService.MatchesFreeText</c>.
|
||||
/// Server-side free-text search (<c>q=</c>) for the dashboard search box. The predicate is the
|
||||
/// search grammar of <see cref="SessionSearchQuery"/> over the web dashboard's client-side
|
||||
/// searchable field set (minus derived-only tokens). Parity with the web parser is pinned by
|
||||
/// the shared case file <c>src/Web/autopilot-monitor-web/utils/session-search-syntax.cases.json</c>,
|
||||
/// which vitest runs against <c>app/dashboard/utils/sessionSearchQuery.ts</c>.
|
||||
/// </summary>
|
||||
public class SessionFreeTextSearchTests
|
||||
{
|
||||
private const string CasesRepoPath = "src/Web/autopilot-monitor-web/utils/session-search-syntax.cases.json";
|
||||
|
||||
private static SessionSummary Sample() => new()
|
||||
{
|
||||
SessionId = "22222222-2222-2222-2222-222222222222",
|
||||
@@ -66,6 +74,79 @@ public class SessionFreeTextSearchTests
|
||||
Assert.True(TableStorageService.MatchesFreeText(Sample(), string.Empty));
|
||||
}
|
||||
|
||||
// ---- Parity with the web parser (shared case file) ----
|
||||
|
||||
public static IEnumerable<object[]> SharedCases()
|
||||
{
|
||||
var doc = LoadCases();
|
||||
foreach (var c in doc.RootElement.GetProperty("cases").EnumerateArray())
|
||||
{
|
||||
// `extra` cases exercise client-derived tokens the server never sees.
|
||||
if (c.TryGetProperty("extra", out _)) continue;
|
||||
yield return new object[]
|
||||
{
|
||||
c.GetProperty("query").GetString()!,
|
||||
c.GetProperty("expected").GetBoolean(),
|
||||
c.GetProperty("note").GetString()!,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(SharedCases))]
|
||||
public void SharedCase_MatchesLikeTheWebParser(string query, bool expected, string note)
|
||||
{
|
||||
var session = SessionFromCaseFile();
|
||||
Assert.True(expected == SessionSearchQuery.Parse(query).Matches(session), $"{query} — {note}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SharedCaseFile_SampleSession_IsTheOneTheTestsUse()
|
||||
{
|
||||
// The case file's session drives both sides; the local Sample() mirrors it so the
|
||||
// InlineData theories above and the shared cases talk about the same rows.
|
||||
var fromFile = SessionFromCaseFile();
|
||||
var local = Sample();
|
||||
foreach (var field in SessionSearchQuery.Fields)
|
||||
Assert.Equal(field.Value(local), field.Value(fromFile));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SharedCaseFile_CoversEveryQualifier_AndEveryFieldHasAValue()
|
||||
{
|
||||
var doc = LoadCases();
|
||||
var queries = string.Join("\n", doc.RootElement.GetProperty("cases").EnumerateArray()
|
||||
.Select(c => c.GetProperty("query").GetString()!.ToLowerInvariant()));
|
||||
var session = SessionFromCaseFile();
|
||||
foreach (var field in SessionSearchQuery.Fields)
|
||||
{
|
||||
Assert.True(queries.Contains(field.Key + "=") || queries.Contains(field.Key + ":"),
|
||||
$"no shared case uses {field.Key}=");
|
||||
Assert.False(string.IsNullOrEmpty(field.Value(session)), $"sample carries no {field.Key}");
|
||||
}
|
||||
Assert.Equal(SessionSearchQuery.Fields.Count, SessionSearchQuery.Fields.Select(f => f.Key).Distinct().Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_ResolvesKnownQualifiers_AndKeepsUnknownOnesLiteral()
|
||||
{
|
||||
var q = SessionSearchQuery.Parse("Model=Surface -status:failed 14:30 foo=bar");
|
||||
Assert.Equal(new[]
|
||||
{
|
||||
new SessionSearchQuery.Term("Surface", "model"),
|
||||
new SessionSearchQuery.Term("14:30", null),
|
||||
new SessionSearchQuery.Term("foo=bar", null),
|
||||
}, q.Include);
|
||||
Assert.Equal(new[] { new SessionSearchQuery.Term("failed", "status") }, q.Exclude);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_LoneMinusOrBareQualifier_IsEmpty()
|
||||
{
|
||||
Assert.True(SessionSearchQuery.Parse(" - model= ").IsEmpty);
|
||||
Assert.True(SessionSearchQuery.Parse(null).IsEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fingerprint_BindsQ_SoContinuationCannotCrossQueries()
|
||||
{
|
||||
@@ -81,4 +162,45 @@ public class SessionFreeTextSearchTests
|
||||
Assert.NotEqual(fp1, fp2);
|
||||
Assert.NotEqual(fp1, fp3);
|
||||
}
|
||||
|
||||
private static JsonDocument LoadCases()
|
||||
{
|
||||
var path = Path.Combine(FindRepoRoot(), CasesRepoPath.Replace('/', Path.DirectorySeparatorChar));
|
||||
return JsonDocument.Parse(File.ReadAllText(path));
|
||||
}
|
||||
|
||||
private static SessionSummary SessionFromCaseFile()
|
||||
{
|
||||
var s = LoadCases().RootElement.GetProperty("session");
|
||||
string F(string name) => s.GetProperty(name).GetString()!;
|
||||
return new SessionSummary
|
||||
{
|
||||
DeviceName = F("deviceName"),
|
||||
SerialNumber = F("serialNumber"),
|
||||
Manufacturer = F("manufacturer"),
|
||||
Model = F("model"),
|
||||
Status = Enum.Parse<SessionStatus>(F("status")),
|
||||
SessionId = F("sessionId"),
|
||||
GeoCountry = F("geoCountry"),
|
||||
GeoRegion = F("geoRegion"),
|
||||
GeoCity = F("geoCity"),
|
||||
AgentVersion = F("agentVersion"),
|
||||
OsName = F("osName"),
|
||||
OsBuild = F("osBuild"),
|
||||
OsDisplayVersion = F("osDisplayVersion"),
|
||||
OsEdition = F("osEdition"),
|
||||
OsLanguage = F("osLanguage"),
|
||||
};
|
||||
}
|
||||
|
||||
private static string FindRepoRoot()
|
||||
{
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (dir != null && !File.Exists(Path.Combine(dir.FullName, "AutopilotMonitor.sln")))
|
||||
{
|
||||
dir = dir.Parent;
|
||||
}
|
||||
Assert.NotNull(dir);
|
||||
return dir!.FullName;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,83 @@
|
||||
#nullable enable
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the schemaVersion-2 catalog contract (generated by tools/error-codes/generate.mjs):
|
||||
/// key/source/category vocabulary, the HRESULT_FROM_WIN32 derivation, the symbol and
|
||||
/// enforcement-state indexes, and the handful of entries product code and rules rely on.
|
||||
/// </summary>
|
||||
public sealed class ErrorCodeCatalogTests
|
||||
{
|
||||
private static readonly Regex KeyPattern = new(@"^(0x[0-9a-f]{8}|\d+)$", RegexOptions.Compiled);
|
||||
private static readonly Regex SourcePattern = new(
|
||||
@"^(msdoc:https://learn\.microsoft\.com/\S+|ime:\d+(\.\d+)+|winerror\.h|rule:[A-Z]+-[A-Z]+-\d{3}|legacy-catalog-v1)$",
|
||||
RegexOptions.Compiled);
|
||||
private static readonly HashSet<string> Categories = new()
|
||||
{
|
||||
"msi", "win32", "com", "appx", "windows-update", "cbs", "intune-win32", "intune-mobile",
|
||||
"mdm-enrollment", "autopilot", "entra-join", "delivery-optimization",
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void All_loads_entries_from_embedded_resource()
|
||||
{
|
||||
var all = ErrorCodeCatalog.All;
|
||||
|
||||
Assert.NotEmpty(all);
|
||||
Assert.True(all.Count > 20, $"Expected catalog to have >20 entries, got {all.Count}");
|
||||
Assert.True(all.Count > 400, $"Expected the v2 catalog to have >400 entries, got {all.Count}");
|
||||
Assert.True(ErrorCodeCatalog.EnforcementStates.Count > 40, "Expected the IME enforcement states");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Every_entry_matches_the_schema_v2_vocabulary()
|
||||
{
|
||||
foreach (var (key, entry) in ErrorCodeCatalog.All)
|
||||
{
|
||||
Assert.Matches(KeyPattern, key);
|
||||
Assert.False(string.IsNullOrWhiteSpace(entry.Description), $"{key}: empty description");
|
||||
Assert.True(Categories.Contains(entry.Category), $"{key}: category '{entry.Category}' outside the catalog vocabulary");
|
||||
Assert.Matches(SourcePattern, entry.Source);
|
||||
if (entry.Symbol != null) Assert.Matches("^[A-Za-z][A-Za-z0-9_]{2,}$", entry.Symbol);
|
||||
}
|
||||
|
||||
// Decimal keys are MSI exit codes only; every other decimal exit code is installer-defined.
|
||||
foreach (var key in ErrorCodeCatalog.All.Keys.Where(k => !k.StartsWith("0x")))
|
||||
{
|
||||
var n = int.Parse(key);
|
||||
Assert.True(n == 0 || (n >= 1601 && n <= 1654) || n == 3010, $"decimal key {key} outside the MSI range");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Symbols_are_unique()
|
||||
{
|
||||
var duplicates = ErrorCodeCatalog.All.Values
|
||||
.Where(e => e.Symbol != null)
|
||||
.GroupBy(e => e.Symbol!)
|
||||
.Where(g => g.Count() > 1)
|
||||
.Select(g => g.Key)
|
||||
.ToList();
|
||||
Assert.Empty(duplicates);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Enforcement_states_are_numeric_keys_with_unique_names()
|
||||
{
|
||||
foreach (var (key, state) in ErrorCodeCatalog.EnforcementStates)
|
||||
{
|
||||
Assert.Matches("^-?\\d+$", key);
|
||||
Assert.Equal(key, state.Value);
|
||||
Assert.False(string.IsNullOrWhiteSpace(state.Name));
|
||||
Assert.False(string.IsNullOrWhiteSpace(state.Description));
|
||||
}
|
||||
Assert.Equal(ErrorCodeCatalog.EnforcementStates.Count, ErrorCodeCatalog.EnforcementStates.Values.Select(s => s.Name).Distinct().Count());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -29,6 +93,7 @@ public sealed class ErrorCodeCatalogTests
|
||||
{
|
||||
Assert.Null(ErrorCodeCatalog.TryLookup("0xDEADBEEF"));
|
||||
Assert.Null(ErrorCodeCatalog.TryLookup("99999"));
|
||||
Assert.Null(ErrorCodeCatalog.TryLookup("not-a-code"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -36,8 +101,11 @@ public sealed class ErrorCodeCatalogTests
|
||||
{
|
||||
var entry = ErrorCodeCatalog.TryLookup("0x80070005");
|
||||
Assert.NotNull(entry);
|
||||
Assert.Contains("Access denied", entry!.Description);
|
||||
Assert.Equal("Access is denied", entry!.Description);
|
||||
Assert.Equal(ErrorCodeConfidence.High, entry.Confidence);
|
||||
Assert.Equal("ERROR_ACCESS_DENIED", entry.Symbol);
|
||||
Assert.Equal("win32", entry.Category);
|
||||
Assert.True(entry.ImeRetriesDuringEsp, "Win32 error 5 is on the IME MSI retry list");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -45,26 +113,24 @@ public sealed class ErrorCodeCatalogTests
|
||||
{
|
||||
var entry = ErrorCodeCatalog.TryLookup("0X80070005");
|
||||
Assert.NotNull(entry);
|
||||
Assert.Contains("Access denied", entry!.Description);
|
||||
Assert.Equal("Access is denied", entry!.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryLookup_normalises_short_hex_without_leading_zeros()
|
||||
{
|
||||
// "0x70005" should pad to "0x00070005" — which doesn't exist; but "0x80070005" should
|
||||
// be reachable via "0X0000000080070005" (extra leading zeros).
|
||||
var entry = ErrorCodeCatalog.TryLookup("0x0000000080070005");
|
||||
Assert.NotNull(entry);
|
||||
Assert.Contains("Access denied", entry!.Description);
|
||||
Assert.Equal("Access is denied", entry!.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryLookup_converts_signed_decimal_hresult_to_hex()
|
||||
{
|
||||
// -2147024891 (signed decimal) == 0x80070005 (unsigned hex) == E_ACCESSDENIED
|
||||
// -2147024891 (signed decimal) == 0x80070005 (unsigned hex)
|
||||
var entry = ErrorCodeCatalog.TryLookup("-2147024891");
|
||||
Assert.NotNull(entry);
|
||||
Assert.Contains("Access denied", entry!.Description);
|
||||
Assert.Equal("Access is denied", entry!.Description);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -72,28 +138,151 @@ public sealed class ErrorCodeCatalogTests
|
||||
{
|
||||
var entry = ErrorCodeCatalog.TryLookup("1603");
|
||||
Assert.NotNull(entry);
|
||||
Assert.Contains("Fatal error", entry!.Description);
|
||||
Assert.Contains("fatal error", entry!.Description);
|
||||
Assert.Equal("ERROR_INSTALL_FAILURE", entry.Symbol);
|
||||
Assert.Equal("msi", entry.Category);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryLookup_finds_intune_specific_code()
|
||||
{
|
||||
// Wording pinned in the generator: rule explanations and the web tests depend on it.
|
||||
var entry = ErrorCodeCatalog.TryLookup("0x87d1041c");
|
||||
Assert.NotNull(entry);
|
||||
Assert.Contains("Application not detected", entry!.Description);
|
||||
Assert.Equal(ErrorCodeConfidence.High, entry.Confidence);
|
||||
Assert.Equal("intune-win32", entry.Category);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryLookup_preserves_confidence_levels()
|
||||
{
|
||||
var high = ErrorCodeCatalog.TryLookup("0x80070005");
|
||||
var medium = ErrorCodeCatalog.TryLookup("0x87d30000");
|
||||
var low = ErrorCodeCatalog.TryLookup("0x87d30004");
|
||||
var medium = ErrorCodeCatalog.TryLookup("0x87d30000"); // IME enum member paraphrase
|
||||
var low = ErrorCodeCatalog.TryLookup("0x87d00213"); // v1 entry without primary source
|
||||
|
||||
Assert.Equal(ErrorCodeConfidence.High, high!.Confidence);
|
||||
Assert.Equal(ErrorCodeConfidence.Medium, medium!.Confidence);
|
||||
Assert.StartsWith("ime:", medium.Source);
|
||||
Assert.Equal(ErrorCodeConfidence.Low, low!.Confidence);
|
||||
Assert.Equal("legacy-catalog-v1", low.Source);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Intune_detection_rule_codes_carry_the_ime_meaning()
|
||||
{
|
||||
// v1 glossed these two as download/size errors; the IME enum says detection-rule errors.
|
||||
Assert.Contains("unknown detection type", ErrorCodeCatalog.TryLookup("0x87d30004")!.Description);
|
||||
Assert.Contains("invalid detection value", ErrorCodeCatalog.TryLookup("0x87d30006")!.Description);
|
||||
Assert.Equal("UnzipError", ErrorCodeCatalog.TryLookup("0x87d30067")!.Symbol);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Success_hresult_has_an_explicit_entry()
|
||||
{
|
||||
var entry = ErrorCodeCatalog.TryLookup("0x00000000");
|
||||
Assert.NotNull(entry);
|
||||
Assert.Equal("S_OK", entry!.Symbol);
|
||||
// The decimal "0" stays the MSI exit code; the two never merge.
|
||||
Assert.Equal("ERROR_SUCCESS", ErrorCodeCatalog.TryLookup("0")?.Symbol);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryLookupDetailed_derives_msi_exit_code_from_hresult_from_win32()
|
||||
{
|
||||
var result = ErrorCodeCatalog.TryLookupDetailed("0x80070643");
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("1603", result!.Key);
|
||||
Assert.Equal(1603, result.DerivedFromWin32);
|
||||
Assert.Equal("ERROR_INSTALL_FAILURE", result.Entry.Symbol);
|
||||
Assert.Null(ErrorCodeCatalog.All.GetValueOrDefault("0x80070643"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryLookupDetailed_derives_from_signed_decimal_too()
|
||||
{
|
||||
// -2147023293 == 0x80070643
|
||||
var result = ErrorCodeCatalog.TryLookupDetailed("-2147023293");
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("1603", result!.Key);
|
||||
Assert.Equal(1603, result.DerivedFromWin32);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryLookupDetailed_never_derives_a_zero_low_word_to_success()
|
||||
{
|
||||
Assert.Null(ErrorCodeCatalog.TryLookupDetailed("0x80070000"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryLookupDetailed_prefers_the_direct_entry_over_derivation()
|
||||
{
|
||||
var result = ErrorCodeCatalog.TryLookupDetailed("0x80070005");
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("0x80070005", result!.Key);
|
||||
Assert.Null(result.DerivedFromWin32);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryLookupDetailed_does_not_derive_outside_the_msi_range()
|
||||
{
|
||||
// 0x80070999 → 2457: no decimal entry, no Win32 entry → miss, not a bogus derivation.
|
||||
Assert.Null(ErrorCodeCatalog.TryLookupDetailed("0x80070999"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryLookupBySymbol_resolves_symbols_case_insensitively()
|
||||
{
|
||||
var result = ErrorCodeCatalog.TryLookupBySymbol("ERROR_INSTALL_FAILURE");
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("1603", result!.Key);
|
||||
|
||||
Assert.Equal("0x80240022", ErrorCodeCatalog.TryLookupBySymbol("wu_e_all_updates_failed")?.Key);
|
||||
Assert.Null(ErrorCodeCatalog.TryLookupBySymbol("NOT_A_SYMBOL"));
|
||||
Assert.Null(ErrorCodeCatalog.TryLookupBySymbol(null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TryLookupEnforcementState_resolves_value_and_name()
|
||||
{
|
||||
var byValue = ErrorCodeCatalog.TryLookupEnforcementState("1000");
|
||||
Assert.NotNull(byValue);
|
||||
Assert.Equal("Success", byValue!.Name);
|
||||
|
||||
var byName = ErrorCodeCatalog.TryLookupEnforcementState("ErrorDownloadingContent");
|
||||
Assert.NotNull(byName);
|
||||
Assert.Equal("5003", byName!.Value);
|
||||
|
||||
Assert.Equal("NotAttemptedDependencyWithFailure", ErrorCodeCatalog.TryLookupEnforcementState("6001")?.Name);
|
||||
Assert.Null(ErrorCodeCatalog.TryLookupEnforcementState("424242"));
|
||||
Assert.Null(ErrorCodeCatalog.TryLookupEnforcementState(""));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Windows_update_symbols_the_agent_used_to_hardcode_are_present()
|
||||
{
|
||||
// WindowsUpdateTracker reads hresultSymbol from the catalog since the v2 catalog.
|
||||
Assert.Equal("WU_E_ALL_UPDATES_FAILED", ErrorCodeCatalog.TryLookup("0x80240022")!.Symbol);
|
||||
Assert.Equal("WU_E_UH_INSTALLERFAILURE", ErrorCodeCatalog.TryLookup("0x8024200B")!.Symbol);
|
||||
Assert.Equal("CBS_E_STORE_CORRUPTION", ErrorCodeCatalog.TryLookup("0x800F0831")!.Symbol);
|
||||
Assert.Equal("CBS_E_INSTALLERS_FAILED", ErrorCodeCatalog.TryLookup("0x800F0922")!.Symbol);
|
||||
Assert.Equal("PSFX_E_MISSING_PAYLOAD_FILE", ErrorCodeCatalog.TryLookup("0x800F0991")!.Symbol);
|
||||
Assert.Equal("ERROR_TIMEOUT", ErrorCodeCatalog.TryLookup("0x800705B4")!.Symbol);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Codes_named_by_analysis_rules_are_present()
|
||||
{
|
||||
foreach (var code in new[]
|
||||
{
|
||||
"0x800705b4", "0x801c03ea", "0x81039001", "0x81039023", "0x81039024", "0x80070490",
|
||||
"0x80180014", "0x80180018", "0xc1036501", "0x801c03f3", "0x80070774", "0x87d13b9c",
|
||||
"0x80073d02", "0x80073cf0", "0x80073cf9", "0x80073cff", "0x80004005", "1601", "1653", "1641",
|
||||
})
|
||||
{
|
||||
Assert.NotNull(ErrorCodeCatalog.TryLookup(code));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -101,6 +290,6 @@ public sealed class ErrorCodeCatalogTests
|
||||
{
|
||||
var entry = ErrorCodeCatalog.TryLookup("0x80070005");
|
||||
Assert.NotNull(entry);
|
||||
Assert.False(string.IsNullOrWhiteSpace(entry!.Source), "Source must not be empty");
|
||||
Assert.StartsWith("msdoc:https://learn.microsoft.com/", entry!.Source);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,13 +60,26 @@ public sealed class SharedManifestParityTests
|
||||
// v2: adds the "types" section (full wire-type graph) and drops v1's
|
||||
// "sessionSummary" (it had no TS consumer; SessionSummary now rides in "types").
|
||||
["schemaVersion"] = 2,
|
||||
// "defaults" = the value of every wire field on a freshly constructed instance (the C#
|
||||
// initializer): the web's "custom" highlight compares stored values against these
|
||||
// instead of a hand-copied map. Nested objects appear as null — they have their own section.
|
||||
["adminConfiguration"] = new Dictionary<string, object?>
|
||||
{
|
||||
["fields"] = WireFieldNames(typeof(AdminConfiguration)),
|
||||
["defaults"] = WireDefaults(typeof(AdminConfiguration)),
|
||||
},
|
||||
["tenantConfiguration"] = new Dictionary<string, object?>
|
||||
{
|
||||
["fields"] = WireFieldNames(typeof(TenantConfiguration)),
|
||||
["defaults"] = WireDefaults(typeof(TenantConfiguration)),
|
||||
},
|
||||
// What an agent receives (GET agent/config) at its class defaults — the runtime column of
|
||||
// the Tenant Config Report highlights every effective value that differs from these.
|
||||
["agentConfig"] = new Dictionary<string, object?>
|
||||
{
|
||||
["responseDefaults"] = WireDefaults(typeof(AgentConfigResponse)),
|
||||
["collectorDefaults"] = WireDefaults(typeof(CollectorConfiguration)),
|
||||
["analyzerDefaults"] = WireDefaults(typeof(AnalyzerConfiguration)),
|
||||
},
|
||||
// Enum member order is load-bearing (append-only ordinals) — declaration order kept.
|
||||
["sessionStatuses"] = Enum.GetNames(typeof(SessionStatus)),
|
||||
@@ -98,7 +111,7 @@ public sealed class SharedManifestParityTests
|
||||
// Declaration order kept: the web derives a union type from this list, order is cosmetic
|
||||
// but a stable order keeps the generated file diff-minimal.
|
||||
["signalRMessages"] = ConstStrings(typeof(Constants.SignalRMessages)),
|
||||
// Every IApiResponse implementer + [WireContract] type, transitively closed —
|
||||
// Every IApiResponse + IApiRequest implementer + [WireContract] type, transitively closed —
|
||||
// the source of utils/wire-types.generated.ts. See WireTypeManifestBuilder.
|
||||
["types"] = WireTypeManifestBuilder.BuildTypesSection(),
|
||||
};
|
||||
@@ -116,6 +129,29 @@ public sealed class SharedManifestParityTests
|
||||
private static string[] WireFieldNames(Type type)
|
||||
=> WireProperties(type).Select(p => JsonNamingPolicy.CamelCase.ConvertName(p.Name)).ToArray();
|
||||
|
||||
/// <summary>
|
||||
/// Wire name → initializer value of a fresh instance. Scalars, strings, enums (by name),
|
||||
/// DateTime (round-trip) and arrays/lists of those travel as-is; a nested object is null.
|
||||
/// </summary>
|
||||
private static Dictionary<string, object?> WireDefaults(Type type)
|
||||
{
|
||||
var instance = Activator.CreateInstance(type)!;
|
||||
return WireProperties(type).ToDictionary(
|
||||
p => JsonNamingPolicy.CamelCase.ConvertName(p.Name),
|
||||
p => DefaultValue(p.GetValue(instance)));
|
||||
}
|
||||
|
||||
private static object? DefaultValue(object? value) => value switch
|
||||
{
|
||||
null => null,
|
||||
string s => s,
|
||||
bool or int or long or double or float or decimal => value,
|
||||
Enum e => e.ToString(),
|
||||
DateTime d => d.ToString("O"),
|
||||
System.Collections.IEnumerable list => list.Cast<object?>().Select(DefaultValue).ToArray(),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static IEnumerable<PropertyInfo> WireProperties(Type type)
|
||||
=> type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Where(p => p.GetMethod != null && p.GetIndexParameters().Length == 0);
|
||||
|
||||
@@ -99,4 +99,47 @@ public class SingleFlightCacheTests
|
||||
// w1 is gone: its factory runs again.
|
||||
Assert.Equal("one-again", await cache.GetOrAddAsync("w1", Ttl, () => Task.FromResult("one-again")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Factory_exceeding_the_budget_faults_every_waiter_and_is_evicted()
|
||||
{
|
||||
var cache = new SingleFlightCache<int>(() => DateTime.UtcNow, factoryBudget: TimeSpan.FromMilliseconds(50));
|
||||
var runs = 0;
|
||||
|
||||
async Task<int> Hanging(CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref runs);
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
return 1;
|
||||
}
|
||||
|
||||
var first = cache.GetOrAddAsync("k", Ttl, Hanging);
|
||||
var second = cache.GetOrAddAsync("k", Ttl, Hanging);
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => first);
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => second);
|
||||
Assert.Equal(1, runs);
|
||||
Assert.Equal(0, cache.Count);
|
||||
|
||||
// The next caller starts a fresh run instead of inheriting the faulted one.
|
||||
Assert.Equal(7, await cache.GetOrAddAsync("k", Ttl, _ => Task.FromResult(7)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Factory_finishing_inside_the_budget_is_cached()
|
||||
{
|
||||
var cache = new SingleFlightCache<int>(() => DateTime.UtcNow, factoryBudget: TimeSpan.FromSeconds(5));
|
||||
var runs = 0;
|
||||
|
||||
Task<int> Quick(CancellationToken ct)
|
||||
{
|
||||
Assert.True(ct.CanBeCanceled);
|
||||
Interlocked.Increment(ref runs);
|
||||
return Task.FromResult(3);
|
||||
}
|
||||
|
||||
Assert.Equal(3, await cache.GetOrAddAsync("k", Ttl, Quick));
|
||||
Assert.Equal(3, await cache.GetOrAddAsync("k", Ttl, Quick));
|
||||
Assert.Equal(1, runs);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using Azure.Core;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The storage SDK budgets are sized so one hot-path operation — every attempt into its
|
||||
/// timeout, every backoff at its cap — finishes before the agent's 30 s upload timeout. A
|
||||
/// change to either side that breaks that relation turns a storage brownout into zombie
|
||||
/// requests plus agent replays (audit 2026-09-05 F09).
|
||||
/// </summary>
|
||||
public class StorageClientOptionsTests
|
||||
{
|
||||
[Fact]
|
||||
public void Table_worst_case_stays_under_the_agent_upload_timeout()
|
||||
{
|
||||
var worst = StorageClientOptions.WorstCase(StorageClientOptions.Table().Retry);
|
||||
Assert.True(worst < StorageClientOptions.AgentUploadTimeout, $"worst case {worst} must stay under {StorageClientOptions.AgentUploadTimeout}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Queue_worst_case_stays_under_the_agent_upload_timeout()
|
||||
{
|
||||
var worst = StorageClientOptions.WorstCase(StorageClientOptions.Queue().Retry);
|
||||
Assert.True(worst < StorageClientOptions.AgentUploadTimeout, $"worst case {worst} must stay under {StorageClientOptions.AgentUploadTimeout}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Blob_worst_case_is_bounded()
|
||||
{
|
||||
var worst = StorageClientOptions.WorstCase(StorageClientOptions.Blob().Retry);
|
||||
Assert.True(worst < TimeSpan.FromMinutes(5), $"worst case {worst} must stay under five minutes");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Worst_case_counts_every_attempt_and_every_capped_backoff()
|
||||
{
|
||||
// 3 attempts × 8 s + backoffs 0.5 s·1.2 and 1 s·1.2 (both under the 4 s cap) = 25.8 s.
|
||||
var retry = StorageClientOptions.Table().Retry;
|
||||
Assert.Equal(RetryMode.Exponential, retry.Mode);
|
||||
Assert.Equal(StorageClientOptions.HotPathMaxRetries, retry.MaxRetries);
|
||||
Assert.Equal(StorageClientOptions.HotPathNetworkTimeout, retry.NetworkTimeout);
|
||||
|
||||
var expected = TimeSpan.FromTicks(StorageClientOptions.HotPathNetworkTimeout.Ticks * 3)
|
||||
+ TimeSpan.FromTicks((long)(StorageClientOptions.HotPathRetryDelay.Ticks * 1.2))
|
||||
+ TimeSpan.FromTicks((long)(StorageClientOptions.HotPathRetryDelay.Ticks * 2 * 1.2));
|
||||
|
||||
Assert.Equal(expected, StorageClientOptions.WorstCase(retry));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Blob_worst_case_counts_four_attempts_and_three_backoffs()
|
||||
{
|
||||
var blob = StorageClientOptions.Blob().Retry;
|
||||
// 4 attempts × 60 s + backoffs 0.6 s, 1.2 s, 2.4 s (all under the 4 s cap).
|
||||
var expected = TimeSpan.FromTicks(StorageClientOptions.BlobNetworkTimeout.Ticks * 4)
|
||||
+ TimeSpan.FromMilliseconds(600) + TimeSpan.FromMilliseconds(1200) + TimeSpan.FromMilliseconds(2400);
|
||||
Assert.Equal(expected, StorageClientOptions.WorstCase(blob));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Queue_options_carry_the_requested_encoding()
|
||||
{
|
||||
Assert.Equal(Azure.Storage.Queues.QueueMessageEncoding.Base64,
|
||||
StorageClientOptions.Queue(Azure.Storage.Queues.QueueMessageEncoding.Base64).MessageEncoding);
|
||||
Assert.Equal(Azure.Storage.Queues.QueueMessageEncoding.None, StorageClientOptions.Queue().MessageEncoding);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
using Azure;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using Xunit;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
@@ -59,4 +62,40 @@ public class StorageErrorsTests
|
||||
Assert.False(StorageErrors.IsPayloadTooLarge(null!));
|
||||
Assert.False(StorageErrors.IsAlreadyExists(null!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void No_response_at_all_is_transient()
|
||||
=> Assert.True(StorageErrors.IsTransient(Failure(0)));
|
||||
|
||||
// ---- Exception overload: what an exhausted SDK budget looks like on a path without a caller token ----
|
||||
|
||||
[Fact]
|
||||
public void Sdk_network_timeout_is_transient()
|
||||
=> Assert.True(StorageErrors.IsTransient((Exception)new TaskCanceledException("exceeded the configured timeout")));
|
||||
|
||||
[Fact]
|
||||
public void Socket_failures_are_transient()
|
||||
{
|
||||
Assert.True(StorageErrors.IsTransient(new IOException("connection reset")));
|
||||
Assert.True(StorageErrors.IsTransient(new HttpRequestException("name resolution failed")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Aggregate_of_retried_attempts_is_transient_only_when_every_attempt_was()
|
||||
{
|
||||
var allTransient = new AggregateException(new TaskCanceledException(), Failure(503), new IOException());
|
||||
var mixed = new AggregateException(new TaskCanceledException(), Failure(404));
|
||||
|
||||
Assert.True(StorageErrors.IsTransient(allTransient));
|
||||
Assert.False(StorageErrors.IsTransient(mixed));
|
||||
Assert.False(StorageErrors.IsTransient(new AggregateException()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Ordinary_exceptions_are_not_transient()
|
||||
{
|
||||
Assert.False(StorageErrors.IsTransient(new InvalidOperationException()));
|
||||
Assert.False(StorageErrors.IsTransient((Exception)Failure(412)));
|
||||
Assert.False(StorageErrors.IsTransient((Exception?)null!));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Azure;
|
||||
using Azure.Data.Tables;
|
||||
using AutopilotMonitor.Functions.DataAccess.TableStorage;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The two MCP usage counters go through <see cref="TableCasRetry"/> with a retry budget sized for
|
||||
/// parallel tool calls of one user (2026-09-06: the previous three-attempt loop without backoff lost
|
||||
/// 3 of 6 concurrent increments). These tests pin the budget, the merge-patch shape and the
|
||||
/// create-with-AddEntity path against a mocked table surface.
|
||||
/// </summary>
|
||||
public class TableUserUsageRepositoryCasTests
|
||||
{
|
||||
private sealed class TableHarness
|
||||
{
|
||||
public Mock<TableClient> Table { get; } = new();
|
||||
public List<TableEntity> Added { get; } = new();
|
||||
public List<(TableEntity Entity, ETag ETag, TableUpdateMode Mode)> Updates { get; } = new();
|
||||
public Func<Response<TableEntity>> Read { get; set; } = () => throw new RequestFailedException(404, "not found");
|
||||
public Queue<Func<Response>> UpdateBehaviors { get; } = new();
|
||||
|
||||
public TableHarness()
|
||||
{
|
||||
Table.Setup(t => t.GetEntityAsync<TableEntity>(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(() => Task.FromResult(Read()));
|
||||
Table.Setup(t => t.AddEntityAsync(It.IsAny<TableEntity>(), It.IsAny<CancellationToken>()))
|
||||
.Returns<TableEntity, CancellationToken>((e, _) =>
|
||||
{
|
||||
Added.Add(e);
|
||||
return Task.FromResult(Mock.Of<Response>());
|
||||
});
|
||||
Table.Setup(t => t.UpdateEntityAsync(It.IsAny<TableEntity>(), It.IsAny<ETag>(), It.IsAny<TableUpdateMode>(), It.IsAny<CancellationToken>()))
|
||||
.Returns<TableEntity, ETag, TableUpdateMode, CancellationToken>((e, tag, mode, _) =>
|
||||
{
|
||||
Updates.Add((e, tag, mode));
|
||||
return Task.FromResult(UpdateBehaviors.Count > 0 ? UpdateBehaviors.Dequeue()() : Mock.Of<Response>());
|
||||
});
|
||||
}
|
||||
|
||||
public static Response<TableEntity> Row(string pk, string rk, long count, string etag)
|
||||
{
|
||||
var e = new TableEntity(pk, rk) { ["RequestCount"] = count };
|
||||
e.ETag = new ETag(etag);
|
||||
return Response.FromValue(e, Mock.Of<Response>());
|
||||
}
|
||||
|
||||
public static Func<Response> Conflict => () => throw new RequestFailedException(412, "precondition failed");
|
||||
}
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
public TableHarness Users { get; } = new();
|
||||
public TableHarness Tenants { get; } = new();
|
||||
public TableUserUsageRepository Repo { get; }
|
||||
|
||||
public Harness()
|
||||
{
|
||||
var service = new Mock<TableServiceClient>();
|
||||
service.Setup(s => s.GetTableClient(Constants.TableNames.UserUsageLog)).Returns(Users.Table.Object);
|
||||
service.Setup(s => s.GetTableClient(Constants.TableNames.McpTenantUsage)).Returns(Tenants.Table.Object);
|
||||
var storage = new TableStorageService(service.Object, NullLogger<TableStorageService>.Instance);
|
||||
Repo = new TableUserUsageRepository(storage, NullLogger<TableUserUsageRepository>.Instance);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Retry_budget_is_sized_for_parallel_tool_calls()
|
||||
{
|
||||
Assert.Equal(8, TableUserUsageRepository.UsageCounterRetries);
|
||||
Assert.True(TableUserUsageRepository.UsageCounterRetries > TableCasRetry.DefaultRetries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Four_consecutive_etag_conflicts_still_land_the_user_increment()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.Users.Read = () => TableHarness.Row("oid-1", "20260906_get_session_events:sessions_{id}_events", 5, "e1");
|
||||
for (var i = 0; i < 4; i++)
|
||||
h.Users.UpdateBehaviors.Enqueue(TableHarness.Conflict);
|
||||
|
||||
await h.Repo.IncrementUsageAsync("oid-1", "user@example.test", "tid-home", "get_session_events:sessions_{id}_events");
|
||||
|
||||
// The old loop gave up after three attempts; four conflicts plus the landing write = five updates.
|
||||
Assert.Equal(5, h.Users.Updates.Count);
|
||||
var (entity, etag, mode) = h.Users.Updates.Last();
|
||||
Assert.Equal(6L, entity.GetInt64("RequestCount"));
|
||||
Assert.Equal(new ETag("e1"), etag);
|
||||
Assert.Equal(TableUpdateMode.Merge, mode);
|
||||
Assert.Empty(h.Users.Added);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_user_row_is_created_with_add_and_full_attribution()
|
||||
{
|
||||
var h = new Harness();
|
||||
|
||||
await h.Repo.IncrementUsageAsync("oid-1", "user@example.test", "tid-home", "get_metrics:metrics");
|
||||
|
||||
var row = Assert.Single(h.Users.Added);
|
||||
Assert.Equal("oid-1", row.PartitionKey);
|
||||
Assert.EndsWith("_get_metrics:metrics", row.RowKey);
|
||||
Assert.Equal(1L, row.GetInt64("RequestCount"));
|
||||
Assert.Equal("user@example.test", row.GetString("UserPrincipalName"));
|
||||
Assert.Equal("tid-home", row.GetString("TenantId"));
|
||||
Assert.Equal("get_metrics:metrics", row.GetString("Endpoint"));
|
||||
Assert.Empty(h.Users.Updates);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Tenant_increment_merges_only_the_counter_and_attribution_columns()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.Tenants.Read = () => TableHarness.Row("tid-customer", "20260906_oid-1", 41, "t1");
|
||||
|
||||
await h.Repo.IncrementTenantUsageAsync("tid-customer", "oid-1", "msp@example.test", "tid-home");
|
||||
|
||||
var (entity, etag, mode) = Assert.Single(h.Tenants.Updates);
|
||||
Assert.Equal(TableUpdateMode.Merge, mode);
|
||||
Assert.Equal(new ETag("t1"), etag);
|
||||
Assert.Equal(42L, entity.GetInt64("RequestCount"));
|
||||
Assert.Equal("msp@example.test", entity.GetString("UserPrincipalName"));
|
||||
Assert.Equal("tid-home", entity.GetString("HomeTenantId"));
|
||||
Assert.NotNull(entity["LastRequestAt"]);
|
||||
// A merge patch never re-sends the identity columns of the row.
|
||||
Assert.False(entity.ContainsKey("Date"));
|
||||
Assert.False(entity.ContainsKey("UserId"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Tenant_increment_is_skipped_without_a_tenant_or_user()
|
||||
{
|
||||
var h = new Harness();
|
||||
|
||||
await h.Repo.IncrementTenantUsageAsync("", "oid-1", null, null);
|
||||
await h.Repo.IncrementTenantUsageAsync("tid-customer", " ", null, null);
|
||||
|
||||
Assert.Empty(h.Tenants.Updates);
|
||||
Assert.Empty(h.Tenants.Added);
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ public class TenantConfigProjectionTests
|
||||
{
|
||||
"tenantId", "domainName", "planTier", "trialExpiresUtc", "trialConsumed", "maxDelegatedTenantsOverride",
|
||||
"mcpUsagePlanOverride", "payingCustomer", "managedByProTenantId",
|
||||
"disabled", "disabledReason",
|
||||
"disabled", "disabledReason", "mcpDisabled", "mcpDisabledReason",
|
||||
"onboardedAt", "onboardedBy", "lastUpdated", "dataRetentionDays",
|
||||
"homedAppClientId", "lastAuthClientId", "lastAuthClientIdSince",
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using AutopilotMonitor.Functions.Functions.Rules;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
@@ -107,22 +108,22 @@ public class TestLogPatternFunctionTests
|
||||
public void Validate_RejectsMissingPatternAndLines()
|
||||
{
|
||||
Assert.Contains("pattern", TestLogPatternFunction.ValidateRequest(
|
||||
new TestLogPatternFunction.TestLogPatternRequest { SampleLines = new List<string> { "x" } })!);
|
||||
new TestLogPatternRequest { SampleLines = new List<string> { "x" } })!);
|
||||
Assert.Contains("sampleLines", TestLogPatternFunction.ValidateRequest(
|
||||
new TestLogPatternFunction.TestLogPatternRequest { Pattern = "a" })!);
|
||||
new TestLogPatternRequest { Pattern = "a" })!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_RejectsTooManyLines_AndBadFormat()
|
||||
{
|
||||
var tooMany = new TestLogPatternFunction.TestLogPatternRequest
|
||||
var tooMany = new TestLogPatternRequest
|
||||
{
|
||||
Pattern = "a",
|
||||
SampleLines = Enumerable.Repeat("line", TestLogPatternFunction.MaxSampleLines + 1).ToList(),
|
||||
};
|
||||
Assert.Contains("at most", TestLogPatternFunction.ValidateRequest(tooMany)!);
|
||||
|
||||
var badFormat = new TestLogPatternFunction.TestLogPatternRequest
|
||||
var badFormat = new TestLogPatternRequest
|
||||
{
|
||||
Pattern = "a",
|
||||
Format = "json",
|
||||
@@ -136,7 +137,7 @@ public class TestLogPatternFunctionTests
|
||||
{
|
||||
foreach (var format in new[] { null, "cmtrace", "text", "TEXT" })
|
||||
{
|
||||
Assert.Null(TestLogPatternFunction.ValidateRequest(new TestLogPatternFunction.TestLogPatternRequest
|
||||
Assert.Null(TestLogPatternFunction.ValidateRequest(new TestLogPatternRequest
|
||||
{
|
||||
Pattern = "a",
|
||||
Format = format,
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
using System.Security.Claims;
|
||||
using AutopilotMonitor.Functions.Extensions;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pins how a caller's rate-limit budget class is derived: from the signed client-authentication
|
||||
/// claim only. In production the portal SPA, the MCP server and the API share one app registration,
|
||||
/// so <c>appid</c>/<c>azp</c> cannot separate them — <c>appidacr</c> (v1.0) / <c>azpacr</c> (v2.0) can:
|
||||
/// 0 = public client (portal), 1/2 = client secret / certificate (MCP server, integrations). Anything
|
||||
/// else fails closed to the stricter integration budget, and no header can move a caller.
|
||||
/// </summary>
|
||||
public class ThrottleSurfaceTests
|
||||
{
|
||||
private static ClaimsPrincipal Principal(params (string Type, string Value)[] claims)
|
||||
=> new(new ClaimsIdentity(claims.Select(c => new Claim(c.Type, c.Value)), "TestAuth"));
|
||||
|
||||
private static readonly (string, string)[] Person = { ("tid", "11111111-1111-1111-1111-111111111111"), ("upn", "user@example.test"), ("oid", "22222222-2222-2222-2222-222222222222") };
|
||||
|
||||
[Fact]
|
||||
public void PublicClient_v1_appidacr0_isPortal()
|
||||
=> Assert.Equal(ThrottleSurface.Portal, Principal(Person.Append(("appidacr", "0")).ToArray()).GetThrottleSurface());
|
||||
|
||||
[Fact]
|
||||
public void PublicClient_v2_azpacr0_isPortal()
|
||||
=> Assert.Equal(ThrottleSurface.Portal, Principal(Person.Append(("azpacr", "0")).ToArray()).GetThrottleSurface());
|
||||
|
||||
[Theory]
|
||||
[InlineData("appidacr", "1")] // client secret — the MCP server in production
|
||||
[InlineData("appidacr", "2")] // certificate
|
||||
[InlineData("azpacr", "1")]
|
||||
[InlineData("azpacr", "2")]
|
||||
public void ConfidentialClient_isIntegration(string claim, string value)
|
||||
=> Assert.Equal(ThrottleSurface.Integration, Principal(Person.Append((claim, value)).ToArray()).GetThrottleSurface());
|
||||
|
||||
[Fact]
|
||||
public void MissingClaim_failsClosed_toIntegration()
|
||||
=> Assert.Equal(ThrottleSurface.Integration, Principal(Person).GetThrottleSurface());
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData("00")]
|
||||
[InlineData("zero")]
|
||||
public void MalformedClaim_failsClosed_toIntegration(string value)
|
||||
=> Assert.Equal(ThrottleSurface.Integration, Principal(Person.Append(("appidacr", value)).ToArray()).GetThrottleSurface());
|
||||
|
||||
[Fact]
|
||||
public void AppOnlyPrincipal_isIntegration_evenWithAcr0()
|
||||
{
|
||||
// idtyp=app wins: an application never gets the interactive budget, whatever its acr says.
|
||||
var principal = Principal(("tid", "11111111-1111-1111-1111-111111111111"), ("idtyp", "app"), ("appid", "33333333-3333-3333-3333-333333333333"), ("appidacr", "0"));
|
||||
Assert.Equal(ThrottleSurface.Integration, principal.GetThrottleSurface());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dimension_names_are_stable()
|
||||
{
|
||||
// Bucket keys and the ThrottleSurface request dimension (platform-health KQL) depend on these.
|
||||
Assert.Equal("portal", ThrottleSurface.Portal.ToDimension());
|
||||
Assert.Equal("integration", ThrottleSurface.Integration.ToDimension());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Request-side twin of <see cref="TypedResponseGuardTests"/> (D-207). Every HTTP request body is
|
||||
/// read through <see cref="RequestBody"/> into a Shared <see cref="IApiRequest"/> type, which the
|
||||
/// manifest exports to TypeScript — so the web and the MCP server compile against the same
|
||||
/// shape the backend deserialises. Three guards:
|
||||
/// A: no raw deserializer on a request body inside <c>Functions/</c> (source scan, EMPTY
|
||||
/// baseline except the permanent exemptions below),
|
||||
/// B: the Newtonsoft branch (<c>ReadNewtonsoftAsync</c>) only where the downstream is
|
||||
/// Newtonsoft-bound — a frozen per-file baseline that may only shrink,
|
||||
/// C: no request DTO declared in the Functions assembly (reflection).
|
||||
/// </summary>
|
||||
public class TypedRequestGuardTests
|
||||
{
|
||||
/// <summary>Raw body deserializers a handler must not call — RequestBody owns them.</summary>
|
||||
private static readonly Regex RawDeserializer = new(
|
||||
@"\b(ReadFromJsonAsync<|JsonConvert\.DeserializeObject<|JsonConvert\.DeserializeAnonymousType\(|JsonSerializer\.Deserialize(Async)?<|JObject\.Parse\(|JsonDocument\.Parse\()",
|
||||
RegexOptions.Compiled);
|
||||
|
||||
private static readonly Regex NewtonsoftBranch = new(@"\bReadNewtonsoftAsync<", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// Files where a raw parser is legitimate. Each entry names WHY; a new entry is a decision,
|
||||
/// not a convenience.
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, string> RawParserExemptions = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
// Agent-facing routes: wire frozen by D-200 fixtures; their reader is not this package's concern.
|
||||
["Functions/Sessions/RegisterSessionFunction.cs"] = "agent route (D-200)",
|
||||
["Functions/Bootstrap/BootstrapRegisterSessionFunction.cs"] = "agent route (D-200)",
|
||||
["Functions/Ingest/IngestTelemetryFunction.cs"] = "agent route, streamed Newtonsoft (D-200)",
|
||||
["Functions/Ingest/ReportDistressFunction.cs"] = "agent route (pre-auth)",
|
||||
["Functions/Ingest/ReportAgentErrorFunction.cs"] = "agent route",
|
||||
["Functions/Diagnostics/GetDiagnosticsUploadUrlFunction.cs"] = "agent route (D-200)",
|
||||
// Foreign schema: Azure Monitor common alert schema, not our contract.
|
||||
["Functions/Infrastructure/AzureMonitorAlertWebhookFunction.cs"] = "Azure Monitor alert schema",
|
||||
// Parses the UPSTREAM Kusto response, not the request body.
|
||||
["Functions/Raw/AppInsightsQueryFunction.cs"] = "upstream response parse",
|
||||
// Not request bodies at all: telemetry item payloads (agent wire, D-200) and stored table columns.
|
||||
["Functions/Ingest/TelemetryPayloadParser.cs"] = "telemetry item PayloadJson (agent wire, D-200)",
|
||||
["Functions/Config/ListTenantConfigBackupsFunction.cs"] = "stored backup diff column",
|
||||
["Functions/Vulnerability/GetCpeMappingsFunction.cs"] = "stored pattern-list columns",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The Newtonsoft-bound bodies: tenant/admin configuration (redaction restore + patch service
|
||||
/// merge via JsonConvert.PopulateObject) and the rule documents. Porting them is a
|
||||
/// roundtrip-proven change, tracked in the backlog; until then this list only shrinks.
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, int> NewtonsoftBaseline = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["Functions/Config/PatchTenantConfigurationFieldsFunction.cs"] = 1,
|
||||
["Functions/Config/UpdateAdminConfigurationFunction.cs"] = 1,
|
||||
["Functions/Config/UpdateTenantConfigurationFunction.cs"] = 1,
|
||||
["Functions/Rules/AnalyzeRulesFunction.cs"] = 2,
|
||||
["Functions/Rules/DryRunAnalyzeRuleFunction.cs"] = 1,
|
||||
["Functions/Rules/GatherRulesFunction.cs"] = 2,
|
||||
["Functions/Rules/GlobalRulesFunction.cs"] = 1,
|
||||
["Functions/Rules/ImeLogPatternsFunction.cs"] = 1,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void A_NoRawBodyDeserializerInHandlers()
|
||||
{
|
||||
var violations = new List<string>();
|
||||
foreach (var (relative, text) in HandlerSources())
|
||||
{
|
||||
if (RawParserExemptions.ContainsKey(relative)) continue;
|
||||
var count = RawDeserializer.Matches(text).Count;
|
||||
if (count > 0)
|
||||
violations.Add($"{relative}: {count} raw body deserializer(s) — read the body through RequestBody.ReadAsync<T> into a Shared IApiRequest type.");
|
||||
}
|
||||
|
||||
Assert.True(violations.Count == 0, "Raw request-body parsing in handlers:\n " + string.Join("\n ", violations));
|
||||
|
||||
// Every exemption must still exist and still parse something, or it is stale.
|
||||
var stale = RawParserExemptions.Keys
|
||||
.Where(rel => !HandlerSources().Any(s => s.Relative.Equals(rel, StringComparison.OrdinalIgnoreCase) && RawDeserializer.IsMatch(s.Text)))
|
||||
.ToList();
|
||||
Assert.True(stale.Count == 0, "Stale raw-parser exemptions (remove them):\n " + string.Join("\n ", stale));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void B_NewtonsoftBranchOnlyWhereBaselined()
|
||||
{
|
||||
var actual = HandlerSources()
|
||||
.Select(s => (s.Relative, Count: NewtonsoftBranch.Matches(s.Text).Count))
|
||||
.Where(x => x.Count > 0)
|
||||
.ToDictionary(x => x.Relative, x => x.Count, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
var violations = new List<string>();
|
||||
foreach (var (file, count) in actual.OrderBy(kv => kv.Key, StringComparer.Ordinal))
|
||||
{
|
||||
if (!NewtonsoftBaseline.TryGetValue(file, out var allowed))
|
||||
violations.Add($"{file}: {count} NEW ReadNewtonsoftAsync site(s) — use ReadAsync<T> (System.Text.Json); the Newtonsoft branch is frozen.");
|
||||
else if (count > allowed)
|
||||
violations.Add($"{file}: {count} ReadNewtonsoftAsync site(s), baseline allows {allowed}.");
|
||||
}
|
||||
foreach (var (file, allowed) in NewtonsoftBaseline.OrderBy(kv => kv.Key, StringComparer.Ordinal))
|
||||
{
|
||||
actual.TryGetValue(file, out var count);
|
||||
if (count < allowed)
|
||||
violations.Add($"{file}: baseline says {allowed} but only {count} remain — lower/remove its entry (ratchet down).");
|
||||
}
|
||||
|
||||
Assert.True(violations.Count == 0, "Newtonsoft body-reader baseline violated:\n " + string.Join("\n ", violations));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void C_NoRequestTypeDeclaredInFunctionsAssembly()
|
||||
{
|
||||
var functions = typeof(RequestBody).Assembly;
|
||||
|
||||
var implementers = functions.GetTypes()
|
||||
.Where(t => typeof(IApiRequest).IsAssignableFrom(t) && !t.IsInterface)
|
||||
.Select(t => t.FullName)
|
||||
.ToList();
|
||||
Assert.True(implementers.Count == 0,
|
||||
"IApiRequest implementers must live in AutopilotMonitor.Shared (manifest export):\n " + string.Join("\n ", implementers));
|
||||
|
||||
// Name-suffix sweep: a body DTO that forgot the marker would still be a `*Request` class here.
|
||||
var suspicious = functions.GetTypes()
|
||||
.Where(t => t.IsClass && t.Name.EndsWith("Request", StringComparison.Ordinal))
|
||||
.Where(t => !t.Name.EndsWith("FilterRequest", StringComparison.Ordinal)) // query-string parsing helpers
|
||||
.Where(t => t.Name != "MandrillSendRequest") // outbound Mandrill payload
|
||||
.Select(t => t.FullName)
|
||||
.ToList();
|
||||
Assert.True(suspicious.Count == 0,
|
||||
"Request-shaped classes in the Functions assembly — move them to Shared as IApiRequest, or exempt with a reason:\n " + string.Join("\n ", suspicious));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void D_EveryRequestTypeIsFlatAndInShared()
|
||||
{
|
||||
// Mirrors the response-side rule: flat (no base class outside object), declared in Shared,
|
||||
// no untyped slot except the one field map, so the TypeScript twin is exact.
|
||||
var shared = typeof(IApiRequest).Assembly;
|
||||
var offenders = new List<string>();
|
||||
foreach (var t in shared.GetTypes().Where(t => typeof(IApiRequest).IsAssignableFrom(t) && t.IsClass))
|
||||
{
|
||||
if (t.BaseType != typeof(object))
|
||||
offenders.Add($"{t.Name}: base type {t.BaseType?.Name} (request DTOs stay flat)");
|
||||
foreach (var p in t.GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
var slot = p.PropertyType;
|
||||
var isObjectMap = slot.IsGenericType && slot.GetGenericTypeDefinition() == typeof(Dictionary<,>) && slot.GetGenericArguments()[1] == typeof(object);
|
||||
if (slot == typeof(object))
|
||||
offenders.Add($"{t.Name}.{p.Name}: object slot (TypeScript gets unknown)");
|
||||
else if (isObjectMap && !(t == typeof(PatchTenantConfigurationFieldsRequest) && p.Name == nameof(PatchTenantConfigurationFieldsRequest.Fields)))
|
||||
offenders.Add($"{t.Name}.{p.Name}: untyped map (only the tenant-config field patch carries one by design)");
|
||||
}
|
||||
}
|
||||
Assert.True(offenders.Count == 0, "Request DTO shape violations:\n " + string.Join("\n ", offenders));
|
||||
}
|
||||
|
||||
private static IEnumerable<(string Relative, string Text)> HandlerSources()
|
||||
{
|
||||
var functionsRoot = Path.Combine(FindRepoRoot(), "src", "Backend", "AutopilotMonitor.Functions");
|
||||
var handlers = Path.Combine(functionsRoot, "Functions");
|
||||
foreach (var file in Directory.EnumerateFiles(handlers, "*.cs", SearchOption.AllDirectories))
|
||||
{
|
||||
var relative = Path.GetRelativePath(functionsRoot, file).Replace(Path.DirectorySeparatorChar, '/');
|
||||
if (relative.Contains("/bin/", StringComparison.OrdinalIgnoreCase) || relative.Contains("/obj/", StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
yield return (relative, File.ReadAllText(file));
|
||||
}
|
||||
}
|
||||
|
||||
private static string FindRepoRoot()
|
||||
{
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (dir != null && !File.Exists(Path.Combine(dir.FullName, "AutopilotMonitor.sln")))
|
||||
dir = dir.Parent;
|
||||
Assert.NotNull(dir);
|
||||
return dir!.FullName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using Azure;
|
||||
using Azure.Data.Tables;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
public class UserWhatsNewSeenStorageTests
|
||||
{
|
||||
private const string TenantId = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
|
||||
private const string Upn = "user@contoso.com";
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserWhatsNewSeen_MissingRow_ReturnsNullMarks()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.Table.Setup(t => t.GetEntityAsync<TableEntity>(
|
||||
TenantId,
|
||||
TableStorageService.PresenceRowKey(Upn),
|
||||
It.Is<IEnumerable<string>>(s => s.SequenceEqual(new[] { "WhatsNewSeenPlatformUtc", "WhatsNewSeenAgentUtc" })),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new RequestFailedException(404, "Not found"));
|
||||
|
||||
var seen = await h.Sut.GetUserWhatsNewSeenAsync(TenantId, Upn);
|
||||
|
||||
Assert.Null(seen.PlatformUtc);
|
||||
Assert.Null(seen.AgentUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MarkUserWhatsNewSeen_OlderThanExisting_DoesNotWrite()
|
||||
{
|
||||
var existing = new DateTime(2026, 9, 8, 10, 0, 0, DateTimeKind.Utc);
|
||||
var h = new Harness();
|
||||
h.SetupRead(new TableEntity(TenantId, TableStorageService.PresenceRowKey(Upn))
|
||||
{
|
||||
["WhatsNewSeenPlatformUtc"] = existing
|
||||
});
|
||||
|
||||
await h.Sut.MarkUserWhatsNewSeenAsync(TenantId, Upn, "platform", existing.AddMinutes(-1));
|
||||
|
||||
Assert.Empty(h.Upserts);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MarkUserWhatsNewSeen_NewerValue_MergeUpsertsOnlySelectedChannelAndUpn()
|
||||
{
|
||||
var existing = new DateTime(2026, 9, 8, 10, 0, 0, DateTimeKind.Utc);
|
||||
var newer = existing.AddMinutes(1);
|
||||
var h = new Harness();
|
||||
h.SetupRead(new TableEntity(TenantId, TableStorageService.PresenceRowKey(Upn))
|
||||
{
|
||||
["WhatsNewSeenAgentUtc"] = existing
|
||||
});
|
||||
|
||||
await h.Sut.MarkUserWhatsNewSeenAsync(TenantId, Upn, "agent", newer);
|
||||
|
||||
var (entity, mode) = Assert.Single(h.Upserts);
|
||||
Assert.Equal(TableUpdateMode.Merge, mode);
|
||||
Assert.Equal(Upn, entity.GetString("Upn"));
|
||||
Assert.Equal(newer, entity.GetDateTime("WhatsNewSeenAgentUtc"));
|
||||
Assert.False(entity.ContainsKey("LastSeen"));
|
||||
Assert.False(entity.ContainsKey("UserRole"));
|
||||
Assert.False(entity.ContainsKey("WhatsNewSeenPlatformUtc"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MarkUserWhatsNewSeen_MissingRow_MergeCreatesRowWithUpn()
|
||||
{
|
||||
var seen = new DateTime(2026, 9, 8, 10, 0, 0, DateTimeKind.Utc);
|
||||
var h = new Harness();
|
||||
h.Table.Setup(t => t.GetEntityAsync<TableEntity>(
|
||||
TenantId,
|
||||
TableStorageService.PresenceRowKey(Upn),
|
||||
It.IsAny<IEnumerable<string>>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new RequestFailedException(404, "Not found"));
|
||||
|
||||
await h.Sut.MarkUserWhatsNewSeenAsync(TenantId, Upn, "platform", seen);
|
||||
|
||||
var (entity, mode) = Assert.Single(h.Upserts);
|
||||
Assert.Equal(TableUpdateMode.Merge, mode);
|
||||
Assert.Equal(TenantId, entity.PartitionKey);
|
||||
Assert.Equal(TableStorageService.PresenceRowKey(Upn), entity.RowKey);
|
||||
Assert.Equal(Upn, entity.GetString("Upn"));
|
||||
Assert.Equal(seen, entity.GetDateTime("WhatsNewSeenPlatformUtc"));
|
||||
Assert.False(entity.ContainsKey("LastSeen"));
|
||||
Assert.False(entity.ContainsKey("UserRole"));
|
||||
}
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
public Mock<TableClient> Table { get; } = new();
|
||||
public TableStorageService Sut { get; }
|
||||
public List<(TableEntity Entity, TableUpdateMode Mode)> Upserts { get; } = new();
|
||||
|
||||
public Harness()
|
||||
{
|
||||
Table.Setup(t => t.UpsertEntityAsync(
|
||||
It.IsAny<TableEntity>(),
|
||||
It.IsAny<TableUpdateMode>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Returns<TableEntity, TableUpdateMode, CancellationToken>((e, mode, _) =>
|
||||
{
|
||||
Upserts.Add((e, mode));
|
||||
return Task.FromResult(Mock.Of<Response>());
|
||||
});
|
||||
|
||||
var serviceClient = new Mock<TableServiceClient>();
|
||||
serviceClient.Setup(c => c.GetTableClient(Constants.TableNames.UserPresence)).Returns(Table.Object);
|
||||
Sut = new TableStorageService(serviceClient.Object, NullLogger<TableStorageService>.Instance);
|
||||
}
|
||||
|
||||
public void SetupRead(TableEntity entity)
|
||||
{
|
||||
Table.Setup(t => t.GetEntityAsync<TableEntity>(
|
||||
entity.PartitionKey,
|
||||
entity.RowKey,
|
||||
It.IsAny<IEnumerable<string>>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(Response.FromValue(entity, Mock.Of<Response>()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,6 +88,24 @@ public class VulnerabilitySummaryAggregatorTests
|
||||
Assert.Equal(4, r.DistinctCves);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildsPriorityBreakdownFromTheMergedBand_legacyRowsCountInNone()
|
||||
{
|
||||
var act = Row("CVE-A", "s1", "Critical", 9.8, kev: true); act.Priority = "act";
|
||||
var attendHigh = Row("CVE-B", "s1", "Medium", 5.0); attendHigh.Priority = "attend";
|
||||
var attendLow = Row("CVE-B", "s2", "Medium", 5.0); attendLow.Priority = "track"; // merged band = attend
|
||||
var track = Row("CVE-C", "s2", "Low", 2.0); track.Priority = "TRACK"; // case-insensitive
|
||||
var legacy = Row("CVE-D", "s3", "High", 7.5); // empty priority
|
||||
|
||||
var r = VulnerabilitySummaryAggregator.Aggregate(new[] { act, attendHigh, attendLow, track, legacy }, false, 20, 30, false, Now);
|
||||
|
||||
Assert.Equal(1, r.PriorityBreakdown.Act);
|
||||
Assert.Equal(1, r.PriorityBreakdown.Attend);
|
||||
Assert.Equal(1, r.PriorityBreakdown.Track);
|
||||
Assert.Equal(4, r.DistinctCves);
|
||||
Assert.Equal(r.KevCves, r.PriorityBreakdown.Act);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RanksTopCvesByAffectedSessionsThenScore_andRespectsTopN()
|
||||
{
|
||||
|
||||
@@ -663,6 +663,7 @@ public class VulnerabilityWireParityTests
|
||||
public void CveExposureSummary_wire_shape_is_unchanged_by_the_IApiResponse_marker()
|
||||
{
|
||||
var breakdown = new SeverityBreakdown { Critical = 1, High = 2, Medium = 0, Low = 0 };
|
||||
var priorities = new PriorityBreakdown { Act = 1, Attend = 1, Track = 1 };
|
||||
var topCves = new List<TopCve>
|
||||
{
|
||||
new TopCve
|
||||
@@ -687,6 +688,7 @@ public class VulnerabilityWireParityTests
|
||||
distinctCves = 3,
|
||||
kevCves = 1,
|
||||
severityBreakdown = breakdown,
|
||||
priorityBreakdown = priorities,
|
||||
topCves,
|
||||
truncated = false,
|
||||
},
|
||||
@@ -698,6 +700,7 @@ public class VulnerabilityWireParityTests
|
||||
DistinctCves = 3,
|
||||
KevCves = 1,
|
||||
SeverityBreakdown = breakdown,
|
||||
PriorityBreakdown = priorities,
|
||||
TopCves = topCves,
|
||||
Truncated = false,
|
||||
});
|
||||
@@ -707,6 +710,7 @@ public class VulnerabilityWireParityTests
|
||||
public void CveExposureSummary_omits_totalAffectedTenants_on_a_tenant_scoped_read()
|
||||
{
|
||||
var breakdown = new SeverityBreakdown { Critical = 0, High = 0, Medium = 0, Low = 0 };
|
||||
var priorities = new PriorityBreakdown { Act = 0, Attend = 0, Track = 0 };
|
||||
var topCves = new List<TopCve>();
|
||||
|
||||
AssertParity(
|
||||
@@ -718,6 +722,7 @@ public class VulnerabilityWireParityTests
|
||||
distinctCves = 0,
|
||||
kevCves = 0,
|
||||
severityBreakdown = breakdown,
|
||||
priorityBreakdown = priorities,
|
||||
topCves,
|
||||
truncated = true,
|
||||
},
|
||||
@@ -729,6 +734,7 @@ public class VulnerabilityWireParityTests
|
||||
DistinctCves = 0,
|
||||
KevCves = 0,
|
||||
SeverityBreakdown = breakdown,
|
||||
PriorityBreakdown = priorities,
|
||||
TopCves = topCves,
|
||||
Truncated = true,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,453 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Functions.Services.Notifications;
|
||||
using AutopilotMonitor.Functions.Services.WhatsNew;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Models.Notifications;
|
||||
using AutopilotMonitor.Shared.Models.WhatsNew;
|
||||
using Microsoft.ApplicationInsights;
|
||||
using Microsoft.ApplicationInsights.Extensibility;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// What's new → channel digest: feed parsing, watermark semantics (baseline on first run, diff by
|
||||
/// entry key, claim-then-send with ETag CAS), per-channel opt-in routing, and the digest shape.
|
||||
/// </summary>
|
||||
public class WhatsNewNotificationServiceTests
|
||||
{
|
||||
// ── Fakes ─────────────────────────────────────────────────────────────
|
||||
|
||||
private sealed class InMemoryStateRepository : IWhatsNewNotificationStateRepository
|
||||
{
|
||||
private WhatsNewNotificationState? _row;
|
||||
private long _version = 0;
|
||||
public int ConflictsToInject { get; set; }
|
||||
public int Writes { get; private set; }
|
||||
|
||||
public WhatsNewNotificationState? Current => _row;
|
||||
|
||||
public void Seed(params string[] knownKeys)
|
||||
{
|
||||
_row = new WhatsNewNotificationState { KnownEntryKeys = new HashSet<string>(knownKeys, StringComparer.Ordinal) };
|
||||
_version++;
|
||||
}
|
||||
|
||||
public Task<(WhatsNewNotificationState? State, string? ETag)> GetWithETagAsync()
|
||||
=> Task.FromResult(_row == null ? ((WhatsNewNotificationState?)null, (string?)null) : (Clone(_row), _version.ToString()));
|
||||
|
||||
public Task<bool> TryUpsertAsync(WhatsNewNotificationState state, string? ifMatchETag)
|
||||
{
|
||||
if (ConflictsToInject > 0)
|
||||
{
|
||||
ConflictsToInject--;
|
||||
_version++;
|
||||
return Task.FromResult(false);
|
||||
}
|
||||
if (ifMatchETag is null && _row != null) return Task.FromResult(false);
|
||||
if (ifMatchETag is not null && ifMatchETag != _version.ToString()) return Task.FromResult(false);
|
||||
|
||||
_row = Clone(state);
|
||||
_version++;
|
||||
Writes++;
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
private static WhatsNewNotificationState Clone(WhatsNewNotificationState s) => new()
|
||||
{
|
||||
KnownEntryKeys = new HashSet<string>(s.KnownEntryKeys, StringComparer.Ordinal),
|
||||
LastDocsCommit = s.LastDocsCommit,
|
||||
LastRunUtc = s.LastRunUtc,
|
||||
LastNotifiedUtc = s.LastNotifiedUtc,
|
||||
LastNotifiedEntryCount = s.LastNotifiedEntryCount,
|
||||
};
|
||||
}
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
public InMemoryStateRepository StateRepo { get; } = new();
|
||||
public Mock<IWhatsNewFeedClient> Feed { get; } = new();
|
||||
public Mock<IConfigRepository> ConfigRepo { get; } = new();
|
||||
public Mock<NotificationChannelDispatcher> Dispatcher { get; }
|
||||
public List<(List<NotificationChannel> Channels, NotificationAlert Alert)> Sent { get; } = new();
|
||||
public WhatsNewNotificationService Service { get; }
|
||||
public DateTime Now { get; } = new(2026, 9, 8, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
public Harness()
|
||||
{
|
||||
var webhook = new WebhookNotificationService(new HttpClient(), NullLogger<WebhookNotificationService>.Instance);
|
||||
var telegram = new TelegramNotificationService(new HttpClient(), Mock.Of<IConfigRepository>(), NullLogger<TelegramNotificationService>.Instance);
|
||||
Dispatcher = new Mock<NotificationChannelDispatcher>(webhook, telegram);
|
||||
Dispatcher
|
||||
.Setup(d => d.SendToChannelsAsync(It.IsAny<IEnumerable<NotificationChannel>>(), It.IsAny<NotificationAlert>()))
|
||||
.Returns<IEnumerable<NotificationChannel>, NotificationAlert>((channels, alert) =>
|
||||
{
|
||||
Sent.Add((channels.ToList(), alert));
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
ConfigRepo.Setup(r => r.GetAllTenantConfigurationsAsync()).ReturnsAsync(new List<TenantConfiguration>());
|
||||
|
||||
Service = new WhatsNewNotificationService(
|
||||
Feed.Object,
|
||||
StateRepo,
|
||||
ConfigRepo.Object,
|
||||
Dispatcher.Object,
|
||||
new TelemetryClient(new TelemetryConfiguration()),
|
||||
NullLogger<WhatsNewNotificationService>.Instance,
|
||||
() => Now);
|
||||
}
|
||||
|
||||
public void SetFeed(WhatsNewFeed? feed)
|
||||
=> Feed.Setup(f => f.GetAsync(It.IsAny<CancellationToken>())).ReturnsAsync(feed);
|
||||
|
||||
public void SetTenants(params TenantConfiguration[] tenants)
|
||||
=> ConfigRepo.Setup(r => r.GetAllTenantConfigurationsAsync()).ReturnsAsync(tenants.ToList());
|
||||
}
|
||||
|
||||
private static WhatsNewFeedEntry Entry(string channel, string id, string? title = null, string body = "Body text.", int daysAgo = 0)
|
||||
=> new()
|
||||
{
|
||||
Channel = channel,
|
||||
Id = id,
|
||||
AddedUtc = new DateTime(2026, 9, 8, 0, 0, 0, DateTimeKind.Utc).AddDays(-daysAgo),
|
||||
Period = "September 2026",
|
||||
Title = title,
|
||||
Body = body,
|
||||
Link = null,
|
||||
};
|
||||
|
||||
private static WhatsNewFeed Feed(params WhatsNewFeedEntry[] entries) => new()
|
||||
{
|
||||
DocsCommit = "abc1234",
|
||||
Entries = entries,
|
||||
DocsUrls = new Dictionary<string, string>
|
||||
{
|
||||
[WhatsNewFeed.PlatformChannel] = Constants.DocsBaseUrl + "/changelog/platform-changelog",
|
||||
[WhatsNewFeed.AgentChannel] = Constants.DocsBaseUrl + "/changelog/agent-changelog",
|
||||
},
|
||||
};
|
||||
|
||||
private static TenantConfiguration Tenant(string id, params NotificationChannel[] channels) => new()
|
||||
{
|
||||
TenantId = id,
|
||||
NotificationChannelsJson = NotificationChannel.SerializeList(channels),
|
||||
};
|
||||
|
||||
private static NotificationChannel Channel(string id, bool whatsNew, bool enabled = true, string url = "https://hooks.example/x")
|
||||
=> new() { Id = id, Name = id, ProviderType = 20, Url = url, Enabled = enabled, NotifyOnWhatsNew = whatsNew, NotifyOnSuccess = true };
|
||||
|
||||
// ── Feed parsing ──────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Parse_ValidPayload_YieldsEntriesForBothChannels()
|
||||
{
|
||||
const string json = """
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"generatedUtc": "2026-09-08T10:00:00.000Z",
|
||||
"docsCommit": "deadbee",
|
||||
"channels": {
|
||||
"platform": { "docsUrl": "https://docs.autopilotmonitor.com/changelog/platform-changelog", "entries": [
|
||||
{ "id": "0a1b2c3d", "addedUtc": "2026-09-07T09:00:00.000Z", "period": "September 2026", "title": "**Bold lead**", "body": "Body with [link](https://docs.autopilotmonitor.com/x).", "link": "https://docs.autopilotmonitor.com/x" }
|
||||
] },
|
||||
"agent": { "docsUrl": "https://docs.autopilotmonitor.com/changelog/agent-changelog", "entries": [
|
||||
{ "id": "ffffffff", "addedUtc": "2026-09-01T09:00:00.000Z", "period": "September 2026", "title": null, "body": "Agent bullet.", "link": null }
|
||||
] }
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
var feed = WhatsNewFeed.Parse(json);
|
||||
|
||||
Assert.NotNull(feed);
|
||||
Assert.Equal("deadbee", feed!.DocsCommit);
|
||||
Assert.Equal(2, feed.Entries.Count);
|
||||
Assert.Equal("platform:0a1b2c3d", feed.Entries[0].Key);
|
||||
Assert.Equal("agent:ffffffff", feed.Entries[1].Key);
|
||||
Assert.Equal(new DateTime(2026, 9, 7, 9, 0, 0, DateTimeKind.Utc), feed.Entries[0].AddedUtc);
|
||||
Assert.Equal("https://docs.autopilotmonitor.com/changelog/agent-changelog", feed.DocsUrls[WhatsNewFeed.AgentChannel]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Parse_OffShape_YieldsNull()
|
||||
{
|
||||
Assert.Null(WhatsNewFeed.Parse(null));
|
||||
Assert.Null(WhatsNewFeed.Parse(""));
|
||||
Assert.Null(WhatsNewFeed.Parse("not json"));
|
||||
Assert.Null(WhatsNewFeed.Parse("""{"schemaVersion":2,"channels":{"platform":{"entries":[]},"agent":{"entries":[]}}}"""));
|
||||
// Missing channel
|
||||
Assert.Null(WhatsNewFeed.Parse("""{"schemaVersion":1,"channels":{"platform":{"entries":[]}}}"""));
|
||||
// Entry without id
|
||||
Assert.Null(WhatsNewFeed.Parse("""{"schemaVersion":1,"channels":{"platform":{"entries":[{"addedUtc":"2026-09-07T09:00:00Z","body":"x"}]},"agent":{"entries":[]}}}"""));
|
||||
}
|
||||
|
||||
// ── Run semantics ─────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Run_FeedUnavailable_DoesNotTouchStateOrSend()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.SetFeed(null);
|
||||
h.StateRepo.Seed("platform:old");
|
||||
|
||||
var result = await h.Service.RunAsync();
|
||||
|
||||
Assert.True(result.FeedUnavailable);
|
||||
Assert.Equal(0, h.StateRepo.Writes);
|
||||
Assert.Empty(h.Sent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_FirstRun_BaselinesWithoutSending()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.SetFeed(Feed(Entry("platform", "a"), Entry("agent", "b")));
|
||||
h.SetTenants(Tenant("t1", Channel("c1", whatsNew: true)));
|
||||
|
||||
var result = await h.Service.RunAsync();
|
||||
|
||||
Assert.True(result.Baselined);
|
||||
Assert.Empty(h.Sent);
|
||||
Assert.NotNull(h.StateRepo.Current);
|
||||
Assert.Equal(new[] { "agent:b", "platform:a" }, h.StateRepo.Current!.KnownEntryKeys.OrderBy(k => k));
|
||||
Assert.Equal("abc1234", h.StateRepo.Current.LastDocsCommit);
|
||||
Assert.Null(h.StateRepo.Current.LastNotifiedUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_EmptyKnownSet_IsTreatedAsBaseline()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.StateRepo.Seed(); // row exists, no keys
|
||||
h.SetFeed(Feed(Entry("platform", "a")));
|
||||
h.SetTenants(Tenant("t1", Channel("c1", whatsNew: true)));
|
||||
|
||||
var result = await h.Service.RunAsync();
|
||||
|
||||
Assert.True(result.Baselined);
|
||||
Assert.Empty(h.Sent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_NothingNew_NoSendAndNoWriteWhenUnchanged()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.StateRepo.Seed("platform:a", "agent:b");
|
||||
h.SetFeed(Feed(Entry("platform", "a"), Entry("agent", "b")));
|
||||
h.SetTenants(Tenant("t1", Channel("c1", whatsNew: true)));
|
||||
|
||||
var result = await h.Service.RunAsync();
|
||||
|
||||
Assert.Equal(0, result.NewEntries);
|
||||
Assert.Empty(h.Sent);
|
||||
Assert.Equal(0, h.StateRepo.Writes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_EntriesRolledOut_UpdatesWatermarkWithoutSending()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.StateRepo.Seed("platform:a", "platform:old");
|
||||
h.SetFeed(Feed(Entry("platform", "a")));
|
||||
|
||||
var result = await h.Service.RunAsync();
|
||||
|
||||
Assert.Equal(0, result.NewEntries);
|
||||
Assert.Empty(h.Sent);
|
||||
Assert.Equal(1, h.StateRepo.Writes);
|
||||
Assert.Equal(new[] { "platform:a" }, h.StateRepo.Current!.KnownEntryKeys.ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_NewEntries_SendsOneDigestPerTenantToOptedInChannelsOnly()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.StateRepo.Seed("platform:a");
|
||||
h.SetFeed(Feed(Entry("platform", "a"), Entry("platform", "b", title: "**New** thing"), Entry("agent", "c")));
|
||||
h.SetTenants(
|
||||
Tenant("opted-in", Channel("yes", whatsNew: true), Channel("no", whatsNew: false), Channel("disabled", whatsNew: true, enabled: false)),
|
||||
Tenant("not-opted-in", Channel("no", whatsNew: false)),
|
||||
Tenant("no-channels"));
|
||||
|
||||
var result = await h.Service.RunAsync();
|
||||
|
||||
Assert.Equal(2, result.NewEntries);
|
||||
Assert.Equal(1, result.TenantsNotified);
|
||||
Assert.Equal(1, result.ChannelsNotified);
|
||||
|
||||
var (channels, alert) = Assert.Single(h.Sent);
|
||||
Assert.Equal("yes", Assert.Single(channels).Id);
|
||||
Assert.Equal("whats_new", alert.EventType);
|
||||
Assert.Equal(2, alert.Sections.Count);
|
||||
Assert.Contains("2 new updates", alert.Summary);
|
||||
Assert.Contains("1 platform, 1 agent", alert.Summary);
|
||||
|
||||
// Watermark advanced to the full live set and marked as notified.
|
||||
var state = h.StateRepo.Current!;
|
||||
Assert.Equal(new[] { "agent:c", "platform:a", "platform:b" }, state.KnownEntryKeys.OrderBy(k => k));
|
||||
Assert.Equal(h.Now, state.LastNotifiedUtc);
|
||||
Assert.Equal(2, state.LastNotifiedEntryCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_SkipsDisabledTenants()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.StateRepo.Seed("platform:a");
|
||||
h.SetFeed(Feed(Entry("platform", "a"), Entry("platform", "b")));
|
||||
var disabled = Tenant("off", Channel("yes", whatsNew: true));
|
||||
disabled.Disabled = true;
|
||||
h.SetTenants(disabled);
|
||||
|
||||
var result = await h.Service.RunAsync();
|
||||
|
||||
Assert.Equal(1, result.NewEntries);
|
||||
Assert.Empty(h.Sent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_LostRace_DoesNotSend()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.StateRepo.Seed("platform:a");
|
||||
h.StateRepo.ConflictsToInject = 1;
|
||||
h.SetFeed(Feed(Entry("platform", "a"), Entry("platform", "b")));
|
||||
h.SetTenants(Tenant("t1", Channel("c1", whatsNew: true)));
|
||||
|
||||
var result = await h.Service.RunAsync();
|
||||
|
||||
Assert.True(result.LostRace);
|
||||
Assert.Empty(h.Sent);
|
||||
h.ConfigRepo.Verify(r => r.GetAllTenantConfigurationsAsync(), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_SecondRunAfterAnnouncement_IsQuiet()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.StateRepo.Seed("platform:a");
|
||||
h.SetFeed(Feed(Entry("platform", "a"), Entry("platform", "b")));
|
||||
h.SetTenants(Tenant("t1", Channel("c1", whatsNew: true)));
|
||||
|
||||
await h.Service.RunAsync();
|
||||
var second = await h.Service.RunAsync();
|
||||
|
||||
Assert.Equal(0, second.NewEntries);
|
||||
Assert.Single(h.Sent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Run_LegacySingleWebhookTenant_NeverReceivesWhatsNew()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.StateRepo.Seed("platform:a");
|
||||
h.SetFeed(Feed(Entry("platform", "a"), Entry("platform", "b")));
|
||||
h.SetTenants(new TenantConfiguration
|
||||
{
|
||||
TenantId = "legacy",
|
||||
WebhookUrl = "https://hooks.example/legacy",
|
||||
WebhookProviderType = 2,
|
||||
WebhookNotifyOnSuccess = true,
|
||||
});
|
||||
|
||||
var result = await h.Service.RunAsync();
|
||||
|
||||
Assert.Equal(1, result.NewEntries);
|
||||
Assert.Empty(h.Sent);
|
||||
}
|
||||
|
||||
// ── Digest shape ──────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void BuildWhatsNewAlert_NewestFirst_PlainText_Actions()
|
||||
{
|
||||
var entries = new List<WhatsNewFeedEntry>
|
||||
{
|
||||
Entry("agent", "old", body: "Older agent `fix` here.", daysAgo: 5),
|
||||
Entry("platform", "new", title: "**Rules editor** revamp", body: "Read the [guide](https://docs.autopilotmonitor.com/g) for _details_."),
|
||||
};
|
||||
var docs = new Dictionary<string, string>
|
||||
{
|
||||
[WhatsNewFeed.PlatformChannel] = Constants.DocsBaseUrl + "/changelog/platform-changelog",
|
||||
[WhatsNewFeed.AgentChannel] = Constants.DocsBaseUrl + "/changelog/agent-changelog",
|
||||
};
|
||||
|
||||
var alert = NotificationAlertBuilder.BuildWhatsNewAlert(entries, docs, WhatsNewNotificationService.PortalWhatsNewUrl("platform"));
|
||||
|
||||
Assert.Equal(2, alert.Sections.Count);
|
||||
Assert.StartsWith("Platform \u00b7 Sep 8, 2026 \u2014 Rules editor revamp", alert.Sections[0].Title);
|
||||
Assert.Equal("Read the guide for details.", alert.Sections[0].Text);
|
||||
Assert.StartsWith("Agent \u00b7 Sep 3, 2026", alert.Sections[1].Title);
|
||||
Assert.Equal("Older agent fix here.", alert.Sections[1].Text);
|
||||
|
||||
Assert.Equal(2, alert.Actions.Count);
|
||||
Assert.Equal(Constants.PortalBaseUrl + "/dashboard?whats-new=platform", alert.Actions[0].Url);
|
||||
// Tie (1 platform, 1 agent) → platform changelog.
|
||||
Assert.Equal(Constants.DocsBaseUrl + "/changelog/platform-changelog", alert.Actions[1].Url);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildWhatsNewAlert_CapsSectionsAndFoldsRemainder()
|
||||
{
|
||||
var entries = Enumerable.Range(0, NotificationAlertBuilder.WhatsNewMaxSections + 3)
|
||||
.Select(i => Entry("agent", $"id{i}", body: $"Bullet {i}", daysAgo: i))
|
||||
.ToList();
|
||||
|
||||
var alert = NotificationAlertBuilder.BuildWhatsNewAlert(entries, null, WhatsNewNotificationService.PortalWhatsNewUrl("agent"));
|
||||
|
||||
Assert.Equal(NotificationAlertBuilder.WhatsNewMaxSections + 1, alert.Sections.Count);
|
||||
Assert.Contains("+ 3 more updates", alert.Sections[^1].Text);
|
||||
Assert.Single(alert.Actions); // no docs URLs → only the portal button
|
||||
Assert.Contains($"{entries.Count} new updates", alert.Summary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildWhatsNewAlert_TelegramText_CarriesSectionsAndLinks()
|
||||
{
|
||||
var alert = NotificationAlertBuilder.BuildWhatsNewAlert(
|
||||
new List<WhatsNewFeedEntry> { Entry("platform", "p", title: "**Lead**", body: "Body.") },
|
||||
null,
|
||||
WhatsNewNotificationService.PortalWhatsNewUrl("platform"));
|
||||
|
||||
var text = TelegramNotificationService.RenderAlertText(alert);
|
||||
|
||||
Assert.Contains("What's new in Autopilot Monitor", text);
|
||||
Assert.Contains("Platform \u00b7 Sep 8, 2026 \u2014 Lead", text);
|
||||
Assert.Contains("Body.", text);
|
||||
Assert.Contains("Open What's new: " + Constants.PortalBaseUrl + "/dashboard?whats-new=platform", text);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("**Bold** text", "Bold text")]
|
||||
[InlineData("See [the docs](https://docs.autopilotmonitor.com/x) now", "See the docs now")]
|
||||
[InlineData("Run `agent.exe --verbose`", "Run agent.exe --verbose")]
|
||||
[InlineData("_emphasis_ and *more*", "emphasis and more")]
|
||||
[InlineData("snake_case_name stays", "snake_case_name stays")]
|
||||
[InlineData(" spaced out ", "spaced out")]
|
||||
[InlineData(null, "")]
|
||||
public void StripInlineMarkdown_Flattens(string? input, string expected)
|
||||
=> Assert.Equal(expected, NotificationAlertBuilder.StripInlineMarkdown(input));
|
||||
|
||||
// ── Channel model ─────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void NotifyOnWhatsNew_RoundTripsThroughJson_AndDefaultsOff()
|
||||
{
|
||||
var json = NotificationChannel.SerializeList(new[] { Channel("c", whatsNew: true) });
|
||||
Assert.Contains("\"notifyOnWhatsNew\":true", json);
|
||||
Assert.True(NotificationChannel.ParseList(json).Single().NotifyOnWhatsNew);
|
||||
|
||||
var legacyShape = "[{\"id\":\"x\",\"name\":\"x\",\"providerType\":20,\"url\":\"https://hooks.example/x\",\"enabled\":true}]";
|
||||
Assert.False(NotificationChannel.ParseList(legacyShape).Single().NotifyOnWhatsNew);
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,8 @@ namespace AutopilotMonitor.Functions.Tests;
|
||||
/// <summary>
|
||||
/// Builds the <c>types</c> section of shared-manifests.json (schemaVersion 2): a
|
||||
/// machine-readable description of every HTTP wire type in AutopilotMonitor.Shared —
|
||||
/// roots are all <see cref="IApiResponse"/> implementers plus every
|
||||
/// <see cref="WireContractAttribute"/>-marked type, closed transitively over
|
||||
/// roots are all <see cref="IApiResponse"/> and <see cref="IApiRequest"/> implementers plus
|
||||
/// every <see cref="WireContractAttribute"/>-marked type, closed transitively over
|
||||
/// references, collections, dictionaries, enums and <see cref="ProjectedItemsAttribute"/>
|
||||
/// item types. The web generator (scripts/generate-shared-manifest-types.js) turns it
|
||||
/// into utils/wire-types.generated.ts.
|
||||
@@ -36,6 +36,7 @@ internal static class WireTypeManifestBuilder
|
||||
var roots = assembly.GetTypes()
|
||||
.Where(t => !t.IsInterface && !t.IsAbstract &&
|
||||
(typeof(IApiResponse).IsAssignableFrom(t) ||
|
||||
typeof(IApiRequest).IsAssignableFrom(t) ||
|
||||
t.GetCustomAttribute<WireContractAttribute>() != null))
|
||||
.OrderBy(t => t.Name, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
@@ -128,10 +129,11 @@ internal static class WireTypeManifestBuilder
|
||||
{
|
||||
var info = nullability.Create(p);
|
||||
var descriptor = Describe(info.Type, info, queue, $"{type.Name}.{p.Name}");
|
||||
// Property-level null never reaches the wire (WhenWritingNull omits the KEY —
|
||||
// that's what "optional" says). Explicit nulls only exist INSIDE collections
|
||||
// and dictionary values, so the flag stays on nested descriptors only.
|
||||
descriptor.Remove("nullable");
|
||||
// Property-level null never reaches the wire on a RESPONSE (WhenWritingNull omits
|
||||
// the KEY — that's what "optional" says), so the flag stays on nested descriptors
|
||||
// only. A REQUEST body may carry an explicit null (a PATCH that clears an override:
|
||||
// absent = unchanged, null = clear), so IApiRequest types keep it: `field?: T | null`.
|
||||
if (!typeof(IApiRequest).IsAssignableFrom(type)) descriptor.Remove("nullable");
|
||||
field["type"] = descriptor;
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,8 @@ namespace AutopilotMonitor.Functions.DataAccess
|
||||
services.AddSingleton<INotificationRepository, TableNotificationRepository>();
|
||||
services.AddSingleton<ITenantNotificationRepository, TableTenantNotificationRepository>();
|
||||
services.AddSingleton<ISlaTenantStatusRepository, TableSlaTenantStatusRepository>();
|
||||
// What's new notifier watermark (single platform row in the AdminConfiguration table).
|
||||
services.AddSingleton<IWhatsNewNotificationStateRepository, TableWhatsNewNotificationStateRepository>();
|
||||
services.AddSingleton<IHardwareRejectionNotificationTracker, TableHardwareRejectionNotificationTracker>();
|
||||
services.AddSingleton<IDeviceSecurityRepository, TableDeviceSecurityRepository>();
|
||||
services.AddSingleton<IUserUsageRepository, TableUserUsageRepository>();
|
||||
|
||||
+6
@@ -667,6 +667,8 @@ namespace AutopilotMonitor.Functions.DataAccess.TableStorage
|
||||
{ "Disabled", config.Disabled },
|
||||
{ "DisabledReason", config.DisabledReason },
|
||||
{ "DisabledUntil", config.DisabledUntil },
|
||||
{ "McpDisabled", config.McpDisabled },
|
||||
{ "McpDisabledReason", config.McpDisabledReason },
|
||||
{ "CustomRateLimitRequestsPerMinute", config.CustomRateLimitRequestsPerMinute },
|
||||
{ "CustomUserRateLimitRequestsPerMinute", config.CustomUserRateLimitRequestsPerMinute },
|
||||
{ "ManufacturerWhitelist", config.ManufacturerWhitelist },
|
||||
@@ -778,6 +780,8 @@ namespace AutopilotMonitor.Functions.DataAccess.TableStorage
|
||||
Disabled = entity.GetBoolean("Disabled") ?? false,
|
||||
DisabledReason = entity.GetString("DisabledReason"),
|
||||
DisabledUntil = entity.GetDateTime("DisabledUntil"),
|
||||
McpDisabled = entity.GetBoolean("McpDisabled") ?? false,
|
||||
McpDisabledReason = entity.GetString("McpDisabledReason"),
|
||||
CustomRateLimitRequestsPerMinute = entity.GetInt32("CustomRateLimitRequestsPerMinute"),
|
||||
CustomUserRateLimitRequestsPerMinute = entity.GetInt32("CustomUserRateLimitRequestsPerMinute"),
|
||||
ManufacturerWhitelist = entity.GetString("ManufacturerWhitelist") ?? "Dell*,HP*,Lenovo*,Microsoft Corporation",
|
||||
@@ -935,6 +939,7 @@ namespace AutopilotMonitor.Functions.DataAccess.TableStorage
|
||||
// Rate limiting per-role settings
|
||||
{ "UserRateLimitRequestsPerMinute", config.UserRateLimitRequestsPerMinute },
|
||||
{ "GlobalAdminRateLimitRequestsPerMinute", config.GlobalAdminRateLimitRequestsPerMinute },
|
||||
{ "PortalUserRateLimitRequestsPerMinute", config.PortalUserRateLimitRequestsPerMinute },
|
||||
// Plan tier definitions
|
||||
{ "PlanTierDefinitionsJson", config.PlanTierDefinitionsJson ?? string.Empty },
|
||||
// Feedback settings
|
||||
@@ -1003,6 +1008,7 @@ namespace AutopilotMonitor.Functions.DataAccess.TableStorage
|
||||
// Rate limiting per-role settings
|
||||
UserRateLimitRequestsPerMinute = entity.GetInt32("UserRateLimitRequestsPerMinute") ?? 120,
|
||||
GlobalAdminRateLimitRequestsPerMinute = entity.GetInt32("GlobalAdminRateLimitRequestsPerMinute") ?? 600,
|
||||
PortalUserRateLimitRequestsPerMinute = entity.GetInt32("PortalUserRateLimitRequestsPerMinute") ?? 600,
|
||||
// Plan tier definitions
|
||||
PlanTierDefinitionsJson = entity.GetString("PlanTierDefinitionsJson"),
|
||||
// Feedback settings
|
||||
|
||||
+6
@@ -92,6 +92,12 @@ namespace AutopilotMonitor.Functions.DataAccess.TableStorage
|
||||
public Task RecordUserPresenceAsync(string tenantId, string upn, string userRole)
|
||||
=> _storage.RecordUserPresenceAsync(tenantId, upn, userRole);
|
||||
|
||||
public Task<UserWhatsNewSeen> GetUserWhatsNewSeenAsync(string tenantId, string upn)
|
||||
=> _storage.GetUserWhatsNewSeenAsync(tenantId, upn);
|
||||
|
||||
public Task MarkUserWhatsNewSeenAsync(string tenantId, string upn, string channel, DateTime seenUtc)
|
||||
=> _storage.MarkUserWhatsNewSeenAsync(tenantId, upn, channel, seenUtc);
|
||||
|
||||
public Task<List<UserPresenceEntry>> GetActivePresenceAsync(TimeSpan window)
|
||||
=> _storage.GetActivePresenceAsync(window);
|
||||
|
||||
|
||||
+2
-2
@@ -57,8 +57,8 @@ namespace AutopilotMonitor.Functions.DataAccess.TableStorage
|
||||
public Task<RawPage<SessionSummary>> GetSessionsPageAsync(string tenantId, int? days, int pageSize, string? continuation)
|
||||
=> _storage.GetSessionsPageAsync(tenantId, days, pageSize, continuation);
|
||||
|
||||
public Task<RawPage<SessionSummary>> GetAllSessionsPageAsync(string? tenantIdFilter, int? days, int pageSize, string? continuation, IReadOnlyCollection<string>? allowedTenantIds = null, IEnumerable<string>? select = null)
|
||||
=> _storage.GetAllSessionsPageAsync(tenantIdFilter, days, pageSize, continuation, allowedTenantIds, select);
|
||||
public Task<RawPage<SessionSummary>> GetAllSessionsPageAsync(string? tenantIdFilter, int? days, int pageSize, string? continuation, IReadOnlyCollection<string>? allowedTenantIds = null, IEnumerable<string>? select = null, CancellationToken cancellationToken = default)
|
||||
=> _storage.GetAllSessionsPageAsync(tenantIdFilter, days, pageSize, continuation, allowedTenantIds, select, cancellationToken);
|
||||
|
||||
public Task<SessionStats> GetSessionStatsAsync(string tenantId, int days)
|
||||
=> _storage.GetSessionStatsAsync(tenantId, days);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user