mirror of
https://github.com/okieselbach/AutopilotMonitor.git
synced 2026-10-25 05:00:07 +00:00
Compare commits
42 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fa31872903 | |||
| b08b79eafe | |||
| e43d916c24 | |||
| 14b185db35 | |||
| baa51102fd | |||
| 5577f5e7e5 | |||
| 61892592e4 | |||
| 1e2ca46946 | |||
| 8224c8f1a8 | |||
| d7f39895f5 | |||
| 790bd35385 | |||
| 34c9fd42fe | |||
| 19a336870c | |||
| 5ba5942d0b | |||
| aa20d9102c | |||
| 097be1700b | |||
| f1457d823d | |||
| 12e66299e6 | |||
| e9a01de9da | |||
| 5f793ea01a | |||
| e86f7efed3 | |||
| 78bfad0ec6 | |||
| f5efadfd07 | |||
| c26eca2f01 | |||
| 9f1879a9f3 | |||
| c24c7bf7ef | |||
| 5fac3d6004 | |||
| 7605d2e9f5 | |||
| 7bf5412d63 | |||
| b53ceb1a7c | |||
| 647581b4ff | |||
| db9b1995bc | |||
| 7563435837 | |||
| e39f2abb61 | |||
| 47dad7143f | |||
| d81f41dc72 | |||
| cc6be10532 | |||
| 0ac548bfce | |||
| 9c1d0586ef | |||
| 21ec5e4773 | |||
| e4a5a6654d | |||
| 01bc35aa97 |
+1
-1
Submodule .claude/commands updated: e57da4e431...b390397891
@@ -55,6 +55,10 @@ updates:
|
||||
- dependency-name: '*'
|
||||
update-types: ['version-update:semver-major']
|
||||
|
||||
# Every action is referenced by commit SHA with the version in a trailing comment;
|
||||
# action-pins.yml fails any workflow change that reintroduces a mutable tag. Dependabot
|
||||
# is what keeps those pins current: it rewrites the SHA and the comment together, so the
|
||||
# pins are reviewed in a PR instead of drifting silently or being bumped by hand.
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
name: Action Pin Gate
|
||||
|
||||
# Every third-party action must be referenced by a full commit SHA, never by a tag.
|
||||
# Tags are mutable: whoever controls an action repository can repoint v4 at new code,
|
||||
# and that code runs inside jobs that hold the code-signing identity, the storage
|
||||
# credentials and a token that can push to main. A SHA is the only reference an
|
||||
# upstream owner cannot change under us.
|
||||
#
|
||||
# Lives in its own workflow rather than in ci.yml: CI deliberately ignores changes to
|
||||
# the other workflow files, so a guard placed there would stay silent for exactly the
|
||||
# commits it needs to inspect.
|
||||
#
|
||||
# Like CI, this reports rather than blocks: main is deliberately unprotected, so a red
|
||||
# run is a signal to act on, not a merge barrier. Making it binding means adding
|
||||
# 'Verify action pins' as a required status check -- a branch-protection decision, not
|
||||
# something this file can assert.
|
||||
#
|
||||
# The pins are not maintained by hand — .github/dependabot.yml opens a monthly grouped
|
||||
# PR that rewrites both the SHA and the trailing version comment. The comment is
|
||||
# therefore required too: it is what makes a pinned line reviewable.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ['.github/workflows/**']
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths: ['.github/workflows/**']
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
verify-pins:
|
||||
name: Verify action pins
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- name: Every third-party action is pinned to a SHA
|
||||
run: |
|
||||
set -uo pipefail
|
||||
failed=0
|
||||
while IFS=: read -r file line ref; do
|
||||
# Reusable workflows from this repository move with the commit that calls
|
||||
# them, so there is nothing to pin.
|
||||
case "$ref" in ./*) continue ;; esac
|
||||
|
||||
if [[ "$ref" =~ ^[^@]+@[0-9a-f]{40}[[:space:]]+#[[:space:]]*[^[:space:]] ]]; then
|
||||
printf 'ok %s:%s %s\n' "$file" "$line" "$ref"
|
||||
continue
|
||||
fi
|
||||
|
||||
if [[ "$ref" =~ ^[^@]+@[0-9a-f]{40}[[:space:]]*$ ]]; then
|
||||
echo "::error file=$file,line=$line::Pinned but the version comment is missing: '$ref'. Write 'owner/action@<sha> # vN' so the line stays reviewable."
|
||||
else
|
||||
echo "::error file=$file,line=$line::Action '$ref' is not pinned to a commit SHA. Tags are mutable -- resolve it with: gh api repos/<owner>/<action>/git/ref/tags/<tag>"
|
||||
fi
|
||||
failed=1
|
||||
# -H is load-bearing: with a single matching file grep omits the name, the
|
||||
# fields shift by one and every diagnostic points at nothing.
|
||||
done < <(grep -nHE '^[[:space:]]*(-[[:space:]]+)?uses:' .github/workflows/*.yml \
|
||||
| sed -E 's/^([^:]+):([0-9]+):[[:space:]]*(-[[:space:]]+)?uses:[[:space:]]*/\1:\2:/')
|
||||
|
||||
if [ "$failed" -ne 0 ]; then
|
||||
echo "::error::Unpinned action references found -- fix them before this reaches main."
|
||||
exit 1
|
||||
fi
|
||||
echo "All action references are pinned to commit SHAs."
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
name: Bootstrap guard tests (PS 5.1)
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- name: Install Pester 5+
|
||||
shell: powershell
|
||||
|
||||
@@ -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:
|
||||
@@ -65,14 +72,66 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # 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
|
||||
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # 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,56 +417,66 @@ 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)
|
||||
uses: actions/attest-build-provenance@v4
|
||||
# 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@4d101475d8b20a2381f78447822ac1eab6504dd8 # 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
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: AutopilotMonitor-Agent-v${{ steps.version.outputs.version }}
|
||||
path: ${{ steps.artifact.outputs.versioned_zip_release }}
|
||||
|
||||
- name: Upload version metadata
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: version-metadata
|
||||
path: ${{ env.MANIFEST_NAME }}
|
||||
@@ -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
|
||||
```
|
||||
|
||||
+126
-16
@@ -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:
|
||||
@@ -33,10 +40,12 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # 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,8 +71,77 @@ 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 }}
|
||||
|
||||
# Exact version, not a "5.*" range: wix writes the bytes of the MSI that customers
|
||||
# install, so a compromised or simply broken point release must not flow into a build
|
||||
# unnoticed. Bumping is a reviewed commit.
|
||||
- name: Install WiX toolset
|
||||
run: dotnet tool install --global wix --version "5.*"
|
||||
run: dotnet tool install --global wix --version 5.0.2
|
||||
|
||||
# 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
|
||||
@@ -75,16 +153,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 +210,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,15 +233,17 @@ 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)
|
||||
uses: actions/attest-build-provenance@v4
|
||||
if: inputs.upload_blob
|
||||
uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4
|
||||
with:
|
||||
subject-path: ${{ env.STABLE_MSI }}
|
||||
|
||||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: AutopilotMonitor-Bootstrap-v${{ steps.version.outputs.version }}
|
||||
path: ${{ env.STABLE_MSI }}
|
||||
|
||||
+13
-11
@@ -35,6 +35,7 @@ on:
|
||||
# Every other workflow: nothing here builds or tests anything CI covers. paths-ignore
|
||||
# cannot negate, so they are listed one by one; ci.yml itself stays out of the list
|
||||
# so a change to CI runs CI. A new workflow file is opt-in — add it here too.
|
||||
- '.github/workflows/action-pins.yml'
|
||||
- '.github/workflows/bootstrap-script-gates.yml'
|
||||
- '.github/workflows/build-agent.yml'
|
||||
- '.github/workflows/build-msi.yml'
|
||||
@@ -67,6 +68,7 @@ on:
|
||||
# Every other workflow: nothing here builds or tests anything CI covers. paths-ignore
|
||||
# cannot negate, so they are listed one by one; ci.yml itself stays out of the list
|
||||
# so a change to CI runs CI. A new workflow file is opt-in — add it here too.
|
||||
- '.github/workflows/action-pins.yml'
|
||||
- '.github/workflows/bootstrap-script-gates.yml'
|
||||
- '.github/workflows/build-agent.yml'
|
||||
- '.github/workflows/build-msi.yml'
|
||||
@@ -94,9 +96,9 @@ jobs:
|
||||
# windows-latest is required: the agent test projects target net48.
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- uses: actions/setup-dotnet@v6
|
||||
- uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
@@ -125,9 +127,9 @@ jobs:
|
||||
run:
|
||||
working-directory: src/Web/autopilot-monitor-web
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
@@ -159,9 +161,9 @@ jobs:
|
||||
run:
|
||||
working-directory: src/McpServer/autopilot-monitor-mcp
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
@@ -179,7 +181,7 @@ jobs:
|
||||
# (run 31252869254). Persist the model across runs instead; HF_CACHE_DIR
|
||||
# is honored by vector-search-provider.ts.
|
||||
- name: Cache embedding model
|
||||
uses: actions/cache@v6
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||
with:
|
||||
path: ${{ github.workspace }}/.hf-cache
|
||||
key: hf-model-Xenova-all-MiniLM-L6-v2
|
||||
@@ -193,9 +195,9 @@ jobs:
|
||||
name: Generated guardrails match rules/guardrails.json
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
|
||||
with:
|
||||
node-version: '22'
|
||||
|
||||
@@ -214,9 +216,9 @@ jobs:
|
||||
name: Generated wire types match shared-manifests.json
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
|
||||
with:
|
||||
node-version: '22'
|
||||
|
||||
|
||||
@@ -102,15 +102,15 @@ jobs:
|
||||
build-mode: none
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- uses: actions/setup-dotnet@v6
|
||||
- uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6
|
||||
if: matrix.language == 'csharp'
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4.37.9
|
||||
uses: github/codeql-action/init@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix.build-mode }}
|
||||
@@ -121,6 +121,6 @@ jobs:
|
||||
run: dotnet build AutopilotMonitor.sln --configuration Release
|
||||
|
||||
- name: Analyze
|
||||
uses: github/codeql-action/analyze@v4.37.9
|
||||
uses: github/codeql-action/analyze@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9
|
||||
with:
|
||||
category: /language:${{ matrix.language }}
|
||||
|
||||
@@ -24,14 +24,17 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
|
||||
with:
|
||||
node-version: '22'
|
||||
|
||||
# Exact versions and no lifecycle scripts: this job holds contents:write and pushes to
|
||||
# main, so an install-time script from a hijacked package would run with a token that
|
||||
# can rewrite the repository. ajv is pure JS and needs no install hooks.
|
||||
- name: Install ajv-cli
|
||||
run: npm install -g ajv-cli ajv-formats
|
||||
run: npm install -g --ignore-scripts ajv-cli@5.0.0 ajv-formats@3.0.1
|
||||
|
||||
- name: Validate Gather Rules
|
||||
run: |
|
||||
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
name: Build and Deploy Backend
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- name: Login to Azure (OIDC)
|
||||
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||
|
||||
- name: Setup .NET 10
|
||||
uses: actions/setup-dotnet@v6
|
||||
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
name: Build and Deploy MCP Server
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
# The published customer documentation lives in its own PUBLIC repo and is
|
||||
# baked into the image as the search_docs corpus (see the Dockerfile). No
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
# re-run actually rolls a new revision). /health reports the SHA captured
|
||||
# below so that staleness is checkable.
|
||||
- name: Check out documentation bundle
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
repository: autopilotmonitor/autopilotmonitor-docs
|
||||
path: mcp-docs
|
||||
@@ -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
|
||||
|
||||
@@ -35,11 +35,20 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
name: Build and Deploy Job
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
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.
|
||||
@@ -47,7 +56,7 @@ jobs:
|
||||
# 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
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
repository: autopilotmonitor/autopilotmonitor-docs
|
||||
path: whats-new-docs
|
||||
@@ -57,7 +66,7 @@ jobs:
|
||||
id: docs
|
||||
run: echo "sha=$(git -C whats-new-docs rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
@@ -105,12 +114,12 @@ jobs:
|
||||
# commit, workflow file) in a public transparency log.
|
||||
# Verify: gh attestation verify portal-<sha>.tar.gz --repo okieselbach/AutopilotMonitor
|
||||
- name: Attest build provenance (portal export)
|
||||
uses: actions/attest-build-provenance@v4
|
||||
uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4
|
||||
with:
|
||||
subject-path: ${{ steps.package.outputs.archive }}
|
||||
|
||||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: portal-${{ github.sha }}
|
||||
path: ${{ steps.package.outputs.archive }}
|
||||
@@ -169,9 +178,9 @@ jobs:
|
||||
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
|
||||
@@ -43,14 +54,81 @@ jobs:
|
||||
needs: gates
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # 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@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: signed-scripts
|
||||
path: ${{ runner.temp }}/signed-scripts
|
||||
if-no-files-found: ignore
|
||||
|
||||
+1
-1
Submodule infra updated: 2c2687b6ab...742249e7e3
+1
-1
Submodule internal updated: 41d3f15126...6c79026c33
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"$schema": "../schema/analyze-rule.schema.json",
|
||||
"ruleId": "ANALYZE-ESP-004",
|
||||
"title": "ESP Timeout with 'Continue Anyway' (Soft Failure)",
|
||||
"description": "Detects an ESP terminal failure on a profile that allows 'Continue anyway'. The enrollment is reported as failed, but the user most likely dismissed the error screen and reached the desktop — a soft failure rather than an unusable device.",
|
||||
"title": "ESP Gave Up on a Blocking App with 'Continue Anyway' (Soft Failure)",
|
||||
"description": "Detects an ESP terminal failure where the ESP gave up while a blocking app was still installing (the agent's own esp_apps_timeout verdict — no per-app HRESULT was reported) on a profile that allows 'Continue anyway'. The enrollment is reported as failed, but the user most likely dismissed the error screen and reached the desktop — a soft failure rather than an unusable device. An ESP failure that carries a specific error code (a failed installer, a detection mismatch) is a different case and stays with the rule that explains that code.",
|
||||
"severity": "warning",
|
||||
"category": "esp",
|
||||
"version": "1.0.1",
|
||||
"version": "1.1.0",
|
||||
"enabled": true,
|
||||
"baseConfidence": 80,
|
||||
"conditions": [
|
||||
@@ -26,6 +26,27 @@
|
||||
"value": "true",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "esp_gave_up_on_app",
|
||||
"source": "event_type",
|
||||
"eventType": "app_install_failed",
|
||||
"dataField": "failureType",
|
||||
"operator": "equals",
|
||||
"value": "esp_apps_timeout",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "appName",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_failed",
|
||||
"dataField": "appName",
|
||||
"operator": "exists",
|
||||
"value": "",
|
||||
"filterField": "failureType",
|
||||
"filterOperator": "equals",
|
||||
"filterValue": "esp_apps_timeout",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"signal": "espSyncFailureTimeoutMinutes",
|
||||
"source": "event_type",
|
||||
@@ -38,34 +59,25 @@
|
||||
{
|
||||
"signal": "failedSubcategory",
|
||||
"source": "event_type",
|
||||
"eventType": "enrollment_failed",
|
||||
"eventType": "esp_failure_settle_started",
|
||||
"dataField": "failedSubcategory",
|
||||
"operator": "exists",
|
||||
"value": "",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"signal": "appName",
|
||||
"source": "event_type",
|
||||
"eventType": "app_install_failed",
|
||||
"dataField": "appName",
|
||||
"operator": "exists",
|
||||
"value": "",
|
||||
"required": false
|
||||
}
|
||||
],
|
||||
"confidenceFactors": [
|
||||
{ "signal": "appName", "condition": "exists", "weight": 10 }
|
||||
{ "signal": "failedSubcategory", "condition": "exists", "weight": 10 }
|
||||
],
|
||||
"explanation": "This enrollment was reported as **failed** because the Enrollment Status Page reached its configured terminal timeout (`{{espSyncFailureTimeoutMinutes}} min`) before all blocking items finished. The ESP profile, however, allows **'Continue anyway'** — so the user most likely dismissed the error screen and reached the desktop with a working, though not fully provisioned, device.\n\nThe agent only observes the ESP terminal failure on the device side; it cannot see what the user did after the failure screen. Treat this as a **soft failure**: the device may well be in productive use, while at least one blocking item (`{{failedSubcategory}}` subcategory / app `{{appName}}`) did not complete inside the ESP window.\n\nA cluster of these across a tenant almost always points at one slow blocking app holding the whole fleet at the ESP timeout wall, not at broken devices. Any field still shown as a literal `{{…}}` placeholder was simply not recorded for this session (e.g. a certificate-only failure has no failed app).",
|
||||
"explanation": "This enrollment was reported as **failed** because the Enrollment Status Page gave up while the blocking app **{{appName}}** was still installing — the agent recorded no per-app error code, only that the app never finished inside the ESP window (the profile's configured limit is `{{espSyncFailureTimeoutMinutes}} min`; the ESP may have stopped earlier than that). The ESP profile, however, allows **'Continue anyway'** — so the user most likely dismissed the error screen and reached the desktop with a working, though not fully provisioned, device.\n\nThe agent only observes the ESP terminal failure on the device side; it cannot see what the user did after the failure screen. Treat this as a **soft failure**: the device may well be in productive use, while the `{{failedSubcategory}}` subcategory did not complete inside the ESP window.\n\nA cluster of these across a tenant almost always points at one slow blocking app holding the whole fleet at the ESP limit, not at broken devices. This rule deliberately stays silent when the failed app reported a specific error code — a failed installer or a detection mismatch is explained by the rule for that code, and 'Continue anyway' does not make it a timing problem. Any field still shown as a literal `{{…}}` placeholder was simply not recorded for this session.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Relieve ESP pressure so enrollments finish inside the window",
|
||||
"steps": [
|
||||
"Identify the slow blocking app (`{{appName}}`) and either remove it from the ESP 'block device use until these required apps are installed' list, or raise the ESP installation timeout (currently {{espSyncFailureTimeoutMinutes}} min).",
|
||||
"If the app legitimately needs longer than the ESP allows, make it non-blocking and let it install after the desktop arrives.",
|
||||
"Verify the app's detection rule matches after install — an app that installs but fails detection times out the ESP on every device (see ANALYZE-APP-013).",
|
||||
"If a subcategory such as Certificates is reported under '{{failedSubcategory}}', confirm the certificate/connector actually delivers — 'Continue anyway' hides a missing certificate, it does not fix it."
|
||||
"Look at how long `{{appName}}` takes on a device that completes: if it legitimately needs longer than the ESP allows, make it non-blocking (remove it from 'block device use until these required apps are installed') and let it install after the desktop arrives.",
|
||||
"If the app must stay blocking, raise the ESP setting 'Show error when installation takes longer than' (configured at {{espSyncFailureTimeoutMinutes}} min) — a limit, not a target; it only helps when the app reliably finishes within the new value.",
|
||||
"Check the app's dependencies and install order: a blocking app waiting on a large dependency download (Delivery Optimization, proxy throughput) is the usual reason it never finishes in time.",
|
||||
"If the ESP reported a non-Apps subcategory under '{{failedSubcategory}}', confirm the certificate/connector actually delivers — 'Continue anyway' hides a missing certificate, it does not fix it."
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
"description": "Detects when a certificate with the configured subject is missing from the local machine personal store (LocalMachine\\My). Requires the gather rule GATHER-ID-002 (machine cert store inventory) to be enabled — the check runs against its gather_machine_cert_store output. A missing certificate may indicate that MDM enrollment certificate provisioning or SCEP certificate deployment failed.",
|
||||
"severity": "warning",
|
||||
"category": "identity",
|
||||
"author": "Community",
|
||||
"isCommunity": true,
|
||||
"enabled": false,
|
||||
"evaluateOn": [
|
||||
|
||||
+32
-19
@@ -2496,11 +2496,11 @@
|
||||
},
|
||||
{
|
||||
"ruleId": "ANALYZE-ESP-004",
|
||||
"title": "ESP Timeout with 'Continue Anyway' (Soft Failure)",
|
||||
"description": "Detects an ESP terminal failure on a profile that allows 'Continue anyway'. The enrollment is reported as failed, but the user most likely dismissed the error screen and reached the desktop — a soft failure rather than an unusable device.",
|
||||
"title": "ESP Gave Up on a Blocking App with 'Continue Anyway' (Soft Failure)",
|
||||
"description": "Detects an ESP terminal failure where the ESP gave up while a blocking app was still installing (the agent's own esp_apps_timeout verdict — no per-app HRESULT was reported) on a profile that allows 'Continue anyway'. The enrollment is reported as failed, but the user most likely dismissed the error screen and reached the desktop — a soft failure rather than an unusable device. An ESP failure that carries a specific error code (a failed installer, a detection mismatch) is a different case and stays with the rule that explains that code.",
|
||||
"severity": "warning",
|
||||
"category": "esp",
|
||||
"version": "1.0.1",
|
||||
"version": "1.1.0",
|
||||
"enabled": true,
|
||||
"baseConfidence": 80,
|
||||
"conditions": [
|
||||
@@ -2521,6 +2521,27 @@
|
||||
"value": "true",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "esp_gave_up_on_app",
|
||||
"source": "event_type",
|
||||
"eventType": "app_install_failed",
|
||||
"dataField": "failureType",
|
||||
"operator": "equals",
|
||||
"value": "esp_apps_timeout",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"signal": "appName",
|
||||
"source": "event_data",
|
||||
"eventType": "app_install_failed",
|
||||
"dataField": "appName",
|
||||
"operator": "exists",
|
||||
"value": "",
|
||||
"filterField": "failureType",
|
||||
"filterOperator": "equals",
|
||||
"filterValue": "esp_apps_timeout",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"signal": "espSyncFailureTimeoutMinutes",
|
||||
"source": "event_type",
|
||||
@@ -2533,38 +2554,29 @@
|
||||
{
|
||||
"signal": "failedSubcategory",
|
||||
"source": "event_type",
|
||||
"eventType": "enrollment_failed",
|
||||
"eventType": "esp_failure_settle_started",
|
||||
"dataField": "failedSubcategory",
|
||||
"operator": "exists",
|
||||
"value": "",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"signal": "appName",
|
||||
"source": "event_type",
|
||||
"eventType": "app_install_failed",
|
||||
"dataField": "appName",
|
||||
"operator": "exists",
|
||||
"value": "",
|
||||
"required": false
|
||||
}
|
||||
],
|
||||
"confidenceFactors": [
|
||||
{
|
||||
"signal": "appName",
|
||||
"signal": "failedSubcategory",
|
||||
"condition": "exists",
|
||||
"weight": 10
|
||||
}
|
||||
],
|
||||
"explanation": "This enrollment was reported as **failed** because the Enrollment Status Page reached its configured terminal timeout (`{{espSyncFailureTimeoutMinutes}} min`) before all blocking items finished. The ESP profile, however, allows **'Continue anyway'** — so the user most likely dismissed the error screen and reached the desktop with a working, though not fully provisioned, device.\n\nThe agent only observes the ESP terminal failure on the device side; it cannot see what the user did after the failure screen. Treat this as a **soft failure**: the device may well be in productive use, while at least one blocking item (`{{failedSubcategory}}` subcategory / app `{{appName}}`) did not complete inside the ESP window.\n\nA cluster of these across a tenant almost always points at one slow blocking app holding the whole fleet at the ESP timeout wall, not at broken devices. Any field still shown as a literal `{{…}}` placeholder was simply not recorded for this session (e.g. a certificate-only failure has no failed app).",
|
||||
"explanation": "This enrollment was reported as **failed** because the Enrollment Status Page gave up while the blocking app **{{appName}}** was still installing — the agent recorded no per-app error code, only that the app never finished inside the ESP window (the profile's configured limit is `{{espSyncFailureTimeoutMinutes}} min`; the ESP may have stopped earlier than that). The ESP profile, however, allows **'Continue anyway'** — so the user most likely dismissed the error screen and reached the desktop with a working, though not fully provisioned, device.\n\nThe agent only observes the ESP terminal failure on the device side; it cannot see what the user did after the failure screen. Treat this as a **soft failure**: the device may well be in productive use, while the `{{failedSubcategory}}` subcategory did not complete inside the ESP window.\n\nA cluster of these across a tenant almost always points at one slow blocking app holding the whole fleet at the ESP limit, not at broken devices. This rule deliberately stays silent when the failed app reported a specific error code — a failed installer or a detection mismatch is explained by the rule for that code, and 'Continue anyway' does not make it a timing problem. Any field still shown as a literal `{{…}}` placeholder was simply not recorded for this session.",
|
||||
"remediation": [
|
||||
{
|
||||
"title": "Relieve ESP pressure so enrollments finish inside the window",
|
||||
"steps": [
|
||||
"Identify the slow blocking app (`{{appName}}`) and either remove it from the ESP 'block device use until these required apps are installed' list, or raise the ESP installation timeout (currently {{espSyncFailureTimeoutMinutes}} min).",
|
||||
"If the app legitimately needs longer than the ESP allows, make it non-blocking and let it install after the desktop arrives.",
|
||||
"Verify the app's detection rule matches after install — an app that installs but fails detection times out the ESP on every device (see ANALYZE-APP-013).",
|
||||
"If a subcategory such as Certificates is reported under '{{failedSubcategory}}', confirm the certificate/connector actually delivers — 'Continue anyway' hides a missing certificate, it does not fix it."
|
||||
"Look at how long `{{appName}}` takes on a device that completes: if it legitimately needs longer than the ESP allows, make it non-blocking (remove it from 'block device use until these required apps are installed') and let it install after the desktop arrives.",
|
||||
"If the app must stay blocking, raise the ESP setting 'Show error when installation takes longer than' (configured at {{espSyncFailureTimeoutMinutes}} min) — a limit, not a target; it only helps when the app reliably finishes within the new value.",
|
||||
"Check the app's dependencies and install order: a blocking app waiting on a large dependency download (Delivery Optimization, proxy throughput) is the usual reason it never finishes in time.",
|
||||
"If the ESP reported a non-Apps subcategory under '{{failedSubcategory}}', confirm the certificate/connector actually delivers — 'Continue anyway' hides a missing certificate, it does not fix it."
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -2794,6 +2806,7 @@
|
||||
"description": "Detects when a certificate with the configured subject is missing from the local machine personal store (LocalMachine\\My). Requires the gather rule GATHER-ID-002 (machine cert store inventory) to be enabled — the check runs against its gather_machine_cert_store output. A missing certificate may indicate that MDM enrollment certificate provisioning or SCEP certificate deployment failed.",
|
||||
"severity": "warning",
|
||||
"category": "identity",
|
||||
"author": "Community",
|
||||
"isCommunity": true,
|
||||
"enabled": false,
|
||||
"evaluateOn": [
|
||||
|
||||
@@ -94,7 +94,11 @@
|
||||
"C:\\Windows\\Panther",
|
||||
"C:\\Windows\\SetupDiag",
|
||||
"C:\\ProgramData\\Microsoft\\DiagnosticLogCSP",
|
||||
"C:\\Windows\\SoftwareDistribution\\ReportingEvents.log"
|
||||
"C:\\Windows\\SoftwareDistribution\\ReportingEvents.log",
|
||||
"C:\\ProgramData\\RealmJoin\\choco\\logs"
|
||||
],
|
||||
"userProfileFilePrefixes": [
|
||||
"AppData\\Local\\RealmJoin"
|
||||
],
|
||||
"wmiQueryPrefixes": [
|
||||
"SELECT * FROM Win32_OperatingSystem",
|
||||
|
||||
@@ -190,7 +190,7 @@
|
||||
},
|
||||
"operator": {
|
||||
"type": "string",
|
||||
"description": "Comparison operator.",
|
||||
"description": "Comparison operator. exists/not_exists with a dataField test whether ANY event of the type carries a non-empty value at that field: not_exists matches when no event does — including when the event type is absent altogether — so a rule can gate on a missing field (e.g. an ESP failure without an HRESULT). Without a dataField they test only the presence of the event type.",
|
||||
"enum": ["equals", "not_equals", "contains", "not_contains", "regex", "not_regex", "gt", "lt", "gte", "lte", "exists", "not_exists", "count_gte", "count_per_group_gte", "in", "not_in"]
|
||||
},
|
||||
"value": {
|
||||
|
||||
@@ -8,6 +8,16 @@
|
||||
"$schema": { "type": "string" },
|
||||
"registryPrefixes": { "$ref": "#/$defs/categorizedList" },
|
||||
"filePrefixes": { "$ref": "#/$defs/stringList" },
|
||||
"userProfileFilePrefixes": {
|
||||
"description": "Folders under the signed-in user's profile that file collectors and diagnostics paths may read, RELATIVE to the profile root (e.g. \"AppData\\\\Local\\\\Vendor\"). Resolved against %LOGGED_ON_USER_PROFILE% at match time. Entries outside AppData\\Local / AppData\\Roaming are dropped at load: the C:\\Users hard block never admits them, so this list can only ever narrow what the block's exception already permits.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"allOf": [
|
||||
{ "$ref": "#/$defs/safeString" },
|
||||
{ "pattern": "^AppData\\\\(Local|Roaming)(\\\\|$)" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"wmiQueryPrefixes": { "$ref": "#/$defs/stringList" },
|
||||
"eventLogChannels": { "$ref": "#/$defs/categorizedList" },
|
||||
"blockedEventLogChannels": { "$ref": "#/$defs/stringList" },
|
||||
|
||||
@@ -208,6 +208,14 @@ export const ALLOWED_FILE_PREFIXES: readonly string[] = [
|
||||
${flatArray(guardrails.filePrefixes)}
|
||||
];
|
||||
|
||||
// Folders under the signed-in user's profile, RELATIVE to the profile root. The agent
|
||||
// resolves %LOGGED_ON_USER_PROFILE% at runtime; the portal validates against a placeholder
|
||||
// profile. These cannot live in ALLOWED_FILE_PREFIXES — that list is matched literally
|
||||
// against the already-expanded path, where the user name is unknown at authoring time.
|
||||
export const USER_PROFILE_FILE_PREFIXES: readonly string[] = [
|
||||
${flatArray(guardrails.userProfileFilePrefixes ?? [])}
|
||||
];
|
||||
|
||||
export const ALLOWED_WMI_QUERY_PREFIXES: readonly string[] = [
|
||||
${flatArray(guardrails.wmiQueryPrefixes)}
|
||||
];
|
||||
|
||||
@@ -14,6 +14,22 @@
|
||||
BeforeAll {
|
||||
. (Join-Path $PSScriptRoot 'Install-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 }
|
||||
}
|
||||
|
||||
function New-FakePayload {
|
||||
param([string[]]$Files)
|
||||
$dir = Join-Path $TestDrive ([guid]::NewGuid().ToString())
|
||||
New-Item -ItemType Directory -Path $dir -Force | Out-Null
|
||||
foreach ($f in $Files) { Set-Content -Path (Join-Path $dir $f) -Value 'x' }
|
||||
return $dir
|
||||
}
|
||||
|
||||
function New-FakeProfile {
|
||||
param([string]$Name, [double]$AgeMinutes)
|
||||
$p = Join-Path $TestDrive $Name
|
||||
@@ -305,3 +321,93 @@ Describe 'logging purity' {
|
||||
Get-Content $LogFile -Raw | Should -Match 'SKIP: Agent was previously deployed'
|
||||
}
|
||||
}
|
||||
|
||||
Describe 'Get-UnverifiedAgentBinaries' {
|
||||
# The publisher gate on the extracted payload. What matters is the DECISION: which
|
||||
# payload is accepted, which is refused, and which files are looked at at all.
|
||||
BeforeEach {
|
||||
Mock Write-Log { }
|
||||
$script:ours = 'CN=glueckkanja AG, O=glueckkanja AG, C=DE'
|
||||
}
|
||||
|
||||
It 'accepts a payload where every binary of ours is validly signed by us' {
|
||||
$dir = New-FakePayload -Files @('AutopilotMonitor.Agent.exe', 'AutopilotMonitor.Shared.dll')
|
||||
Mock Get-AuthenticodeSignature { New-FakeSignature -Status 'Valid' -Subject $script:ours }
|
||||
Get-UnverifiedAgentBinaries -Path $dir | Should -BeNullOrEmpty
|
||||
}
|
||||
|
||||
It 'checks the binaries we author and leaves third-party assemblies alone' {
|
||||
$dir = New-FakePayload -Files @(
|
||||
'AutopilotMonitor.Agent.exe',
|
||||
'AutopilotMonitor.Agent.exe.config',
|
||||
'AutopilotMonitor.Shared.dll',
|
||||
'Newtonsoft.Json.dll',
|
||||
'System.Management.Automation.dll'
|
||||
)
|
||||
$script:checked = @()
|
||||
Mock Get-AuthenticodeSignature {
|
||||
$script:checked += (Split-Path $FilePath -Leaf)
|
||||
New-FakeSignature -Status 'Valid' -Subject $script:ours
|
||||
}
|
||||
|
||||
Get-UnverifiedAgentBinaries -Path $dir | Should -BeNullOrEmpty
|
||||
$script:checked | Should -Be @('AutopilotMonitor.Agent.exe', 'AutopilotMonitor.Shared.dll')
|
||||
}
|
||||
|
||||
It 'refuses an unsigned agent executable' {
|
||||
$dir = New-FakePayload -Files @('AutopilotMonitor.Agent.exe')
|
||||
Mock Get-AuthenticodeSignature { New-FakeSignature -Status 'NotSigned' -Subject $null }
|
||||
(Get-UnverifiedAgentBinaries -Path $dir).Count | Should -Be 1
|
||||
}
|
||||
|
||||
It 'refuses a tampered binary (hash mismatch)' {
|
||||
$dir = New-FakePayload -Files @('AutopilotMonitor.Agent.exe')
|
||||
Mock Get-AuthenticodeSignature { New-FakeSignature -Status 'HashMismatch' -Subject $script:ours }
|
||||
(Get-UnverifiedAgentBinaries -Path $dir).Count | Should -Be 1
|
||||
}
|
||||
|
||||
It 'refuses a signature whose chain does not validate' {
|
||||
$dir = New-FakePayload -Files @('AutopilotMonitor.Agent.exe')
|
||||
Mock Get-AuthenticodeSignature { New-FakeSignature -Status 'UnknownError' -Subject $script:ours }
|
||||
(Get-UnverifiedAgentBinaries -Path $dir).Count | Should -Be 1
|
||||
}
|
||||
|
||||
It 'refuses a validly signed binary from a different publisher' {
|
||||
$dir = New-FakePayload -Files @('AutopilotMonitor.Agent.exe')
|
||||
Mock Get-AuthenticodeSignature { New-FakeSignature -Status 'Valid' -Subject 'CN=Somebody Else, O=Somebody Else Ltd, C=US' }
|
||||
(Get-UnverifiedAgentBinaries -Path $dir).Count | Should -Be 1
|
||||
}
|
||||
|
||||
It 'refuses the whole payload when a single DLL of ours is swapped' {
|
||||
$dir = New-FakePayload -Files @('AutopilotMonitor.Agent.exe', 'AutopilotMonitor.Shared.dll')
|
||||
Mock Get-AuthenticodeSignature {
|
||||
if ((Split-Path $FilePath -Leaf) -eq 'AutopilotMonitor.Shared.dll') {
|
||||
New-FakeSignature -Status 'Valid' -Subject 'CN=Somebody Else, O=Somebody Else Ltd, C=US'
|
||||
} else {
|
||||
New-FakeSignature -Status 'Valid' -Subject $script:ours
|
||||
}
|
||||
}
|
||||
$rejected = Get-UnverifiedAgentBinaries -Path $dir
|
||||
$rejected.Count | Should -Be 1
|
||||
$rejected[0] | Should -BeLike 'AutopilotMonitor.Shared.dll*'
|
||||
}
|
||||
|
||||
It 'refuses when the signature check itself throws' {
|
||||
$dir = New-FakePayload -Files @('AutopilotMonitor.Agent.exe')
|
||||
Mock Get-AuthenticodeSignature { throw 'access denied' }
|
||||
(Get-UnverifiedAgentBinaries -Path $dir).Count | Should -Be 1
|
||||
}
|
||||
|
||||
It 'refuses an empty payload instead of passing it' {
|
||||
$dir = New-FakePayload -Files @('Newtonsoft.Json.dll')
|
||||
Mock Get-AuthenticodeSignature { New-FakeSignature -Status 'Valid' -Subject $script:ours }
|
||||
(Get-UnverifiedAgentBinaries -Path $dir).Count | Should -Be 1
|
||||
}
|
||||
}
|
||||
|
||||
Describe 'publisher pin' {
|
||||
It 'pins the expected publisher by subject, not by thumbprint' {
|
||||
$ExpectedPublisher | Should -Be '*O=glueckkanja AG*'
|
||||
$ExpectedPublisher | Should -Not -Match '^[0-9A-Fa-f]{40}$'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,8 +12,9 @@
|
||||
2. Downloads the monitoring agent ZIP from Azure Blob Storage
|
||||
3. Verifies integrity via SHA-256 hash from the version manifest (mandatory)
|
||||
4. Extracts the agent into %ProgramData%\AutopilotMonitor\Agent
|
||||
5. Runs the agent in --install mode (registers Scheduled Task, spawns the runtime)
|
||||
6. Verifies the runtime process actually launched
|
||||
5. Verifies the Authenticode signature and publisher of every binary we author
|
||||
6. Runs the agent in --install mode (registers Scheduled Task, spawns the runtime)
|
||||
7. Verifies the runtime process actually launched
|
||||
Agent self-destructs when enrollment completes.
|
||||
|
||||
Relax flow (guards 2+3): a real user profile (or a real LastLoggedOnUser)
|
||||
@@ -76,6 +77,11 @@
|
||||
PowerShell 5.1 (IME) reads scripts without BOM as ANSI, corrupting multi-byte chars.
|
||||
|
||||
.CHANGELOG
|
||||
2026-09-08 v2.5 Publisher gate: every AutopilotMonitor binary in the extracted
|
||||
payload must carry a valid Authenticode signature from the
|
||||
expected publisher before --install runs. The SHA-256 manifest
|
||||
check stays and is unchanged; it proves the bytes, the signature
|
||||
proves the author.
|
||||
2026-08-08 v2.3 Windows 365 Cloud PC support: a positively identified Cloud PC
|
||||
(Windows365 registry key AND CloudManagedDesktopExtension
|
||||
service) now triggers the guard 2+3 relax alongside OOBE
|
||||
@@ -128,7 +134,12 @@ param(
|
||||
)
|
||||
|
||||
# Script version (bump on meaningful changes; see .CHANGELOG above)
|
||||
$ScriptVersion = "2.4"
|
||||
$ScriptVersion = "2.5"
|
||||
|
||||
# The publisher every binary we author must carry. A -like pattern on the subject, NOT a
|
||||
# thumbprint: certificates are renewed, deployed copies of this script are not. Same value
|
||||
# the loader pins for this script.
|
||||
$ExpectedPublisher = "*O=glueckkanja AG*"
|
||||
|
||||
# Configuration - Everything in ProgramData for easy cleanup
|
||||
$AgentBasePath = "$env:ProgramData\AutopilotMonitor"
|
||||
@@ -329,6 +340,56 @@ function Get-BootstrapDecision {
|
||||
return [pscustomobject]@{ Install = $true; ReasonCode = $null; RelaxActive = $relax.Active }
|
||||
}
|
||||
|
||||
# Returns the list of reasons why the extracted payload is not ours; an empty result means
|
||||
# every binary we author carries a valid Authenticode signature from the expected publisher.
|
||||
# Third-party assemblies keep their own publisher's signature and are not checked here.
|
||||
# Any error is a rejection: an unreadable signature is an unverified binary.
|
||||
function Get-UnverifiedAgentBinaries {
|
||||
param([string]$Path)
|
||||
|
||||
$rejected = @()
|
||||
$ourBinaries = @(
|
||||
Get-ChildItem -Path $Path -Filter 'AutopilotMonitor.*' -File -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.Extension -in @('.exe', '.dll') }
|
||||
)
|
||||
|
||||
# An empty set is a rejection, not a pass: it means the extraction produced nothing we
|
||||
# recognise, and the alternative would be a gate that silently approves an empty folder.
|
||||
# The comma keeps a single rejection an ARRAY: PowerShell unrolls a one-element result to
|
||||
# a bare string, and the caller reads .Count and indexes into it.
|
||||
if ($ourBinaries.Count -eq 0) {
|
||||
return , @("no AutopilotMonitor binaries found in $Path")
|
||||
}
|
||||
|
||||
foreach ($binary in $ourBinaries) {
|
||||
try {
|
||||
$sig = Get-AuthenticodeSignature -FilePath $binary.FullName -ErrorAction Stop
|
||||
}
|
||||
catch {
|
||||
$rejected += "$($binary.Name): signature check failed to run ($($_.Exception.Message))"
|
||||
continue
|
||||
}
|
||||
|
||||
if ($null -eq $sig) {
|
||||
$rejected += "$($binary.Name): signature check returned nothing"
|
||||
continue
|
||||
}
|
||||
|
||||
$subject = if ($sig.SignerCertificate) { $sig.SignerCertificate.Subject } else { '<unsigned>' }
|
||||
|
||||
if ($sig.Status -ne 'Valid') {
|
||||
$rejected += "$($binary.Name): signature status $($sig.Status)"
|
||||
continue
|
||||
}
|
||||
if ($subject -notlike $ExpectedPublisher) {
|
||||
$rejected += "$($binary.Name): unexpected publisher $subject"
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
return , $rejected
|
||||
}
|
||||
|
||||
# Main bootstrap flow. Only invoked when the script is run directly (see entry guard
|
||||
# at the bottom); never on dot-source.
|
||||
function Invoke-Bootstrap {
|
||||
@@ -445,6 +506,20 @@ function Invoke-Bootstrap {
|
||||
}
|
||||
}
|
||||
|
||||
# Publisher gate. The SHA-256 above proves the ZIP is the one the manifest names, but
|
||||
# that manifest lives in the same container as the ZIP and cannot outlive a compromise
|
||||
# of the download host. The expected publisher travels inside THIS script, which the
|
||||
# loader verified before running it, so the chain from the file an administrator
|
||||
# assigns to the process that starts here stays publisher-anchored end to end.
|
||||
# Fail-closed, exactly like the hash check: running unverified code as SYSTEM is the
|
||||
# risk being removed.
|
||||
Write-Log "Verifying Authenticode signatures of the agent binaries..."
|
||||
$unverified = Get-UnverifiedAgentBinaries -Path $AgentBinPath
|
||||
if ($unverified.Count -gt 0) {
|
||||
throw "Authenticode verification FAILED ($($unverified -join '; ')). Refusing to run an agent that is not signed by the expected publisher."
|
||||
}
|
||||
Write-Log "Authenticode verification passed (publisher pin: $ExpectedPublisher)"
|
||||
|
||||
Write-Log "Calling agent install mode (--install)..."
|
||||
& $agentExePath --install
|
||||
$installExitCode = $LASTEXITCODE
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals;
|
||||
using AutopilotMonitor.Agent.V2.Core.Orchestration;
|
||||
using AutopilotMonitor.Agent.V2.Core.SignalAdapters;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Orchestration;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring
|
||||
{
|
||||
/// <summary>
|
||||
/// Session 683f1eff — a Shell-Core 62407 failure (<c>WhiteGlove_Failed</c>) arrived four
|
||||
/// seconds into the provisioning tracker's 30-s settle window and terminalised the session
|
||||
/// with nothing but its failure type: the HRESULT (0x80070652) and the failed subcategory
|
||||
/// (Apps) the registry had already named never reached the terminal event, the backend
|
||||
/// FailureReason or the termination-time app classification. The coordinator now inherits
|
||||
/// the pending settle detail onto the Shell-Core args and records the terminal-failure
|
||||
/// snapshot from it.
|
||||
/// </summary>
|
||||
public sealed class EspAndHelloTrackerShellCoreFailureInheritanceTests
|
||||
{
|
||||
private static readonly DateTime Fixed = new DateTime(2026, 9, 8, 18, 11, 6, DateTimeKind.Utc);
|
||||
|
||||
private sealed class Fixture : IDisposable
|
||||
{
|
||||
public TempDirectory Tmp { get; } = new TempDirectory();
|
||||
public AgentLogger Logger { get; }
|
||||
public FakeSignalIngressSink Ingress { get; } = new FakeSignalIngressSink();
|
||||
public FakeSignalIngressSink TrackerPostSink { get; } = new FakeSignalIngressSink();
|
||||
public VirtualClock Clock { get; } = new VirtualClock(Fixed);
|
||||
public List<EspFailureDetectedEventArgs> Forwarded { get; } = new List<EspFailureDetectedEventArgs>();
|
||||
|
||||
public Fixture() { Logger = new AgentLogger(Tmp.Path, AgentLogLevel.Debug); }
|
||||
|
||||
public EspAndHelloTracker BuildCoordinator(Func<EspFailureDetectedEventArgs?> pendingProbe)
|
||||
{
|
||||
var coordinator = new EspAndHelloTracker(
|
||||
sessionId: "S1",
|
||||
tenantId: "T1",
|
||||
post: new InformationalEventPost(TrackerPostSink, Clock),
|
||||
logger: Logger,
|
||||
skipConfigProbe: () => ((bool?)false, (bool?)false),
|
||||
accountSetupActivityProbe: () => false,
|
||||
pendingEspFailureProbe: pendingProbe);
|
||||
coordinator.EspFailureDetected += (_, args) => Forwarded.Add(args);
|
||||
return coordinator;
|
||||
}
|
||||
|
||||
public FakeSignalIngressSink.PostedSignal TerminalSignal() =>
|
||||
Assert.Single(Ingress.Posted, p => p.Kind == DecisionSignalKind.EspTerminalFailure);
|
||||
|
||||
public void Dispose() { Tmp.Dispose(); }
|
||||
}
|
||||
|
||||
private static EspFailureDetectedEventArgs PendingAppsFailure() => new EspFailureDetectedEventArgs(
|
||||
failureType: "Provisioning_DeviceSetup_Apps_Failed",
|
||||
errorCode: "0x80070652",
|
||||
failedSubcategory: "Apps",
|
||||
category: "DeviceSetup",
|
||||
likelyCulpritApps: new[] { "ESP Finalizer US" });
|
||||
|
||||
[Fact]
|
||||
public void ShellCore_failure_inside_the_settle_window_inherits_the_registry_detail()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var coordinator = f.BuildCoordinator(PendingAppsFailure);
|
||||
using var adapter = new EspAndHelloTrackerAdapter(coordinator, f.Ingress, f.Clock);
|
||||
|
||||
coordinator.TriggerShellCoreEspFailureForTest("WhiteGlove_Failed");
|
||||
|
||||
var args = Assert.Single(f.Forwarded);
|
||||
Assert.Equal("WhiteGlove_Failed", args.FailureType); // the signal that terminalised
|
||||
Assert.Equal("0x80070652", args.ErrorCode);
|
||||
Assert.Equal("Apps", args.FailedSubcategory);
|
||||
Assert.Equal("DeviceSetup", args.Category);
|
||||
Assert.Equal(new[] { "ESP Finalizer US" }, args.LikelyCulpritApps);
|
||||
|
||||
// Wire-through: the EspTerminalFailure signal payload carries the detail the
|
||||
// DecisionEngine copies onto enrollment_failed.
|
||||
var signal = f.TerminalSignal();
|
||||
Assert.Equal("WhiteGlove_Failed", signal.Payload!["failureType"]);
|
||||
Assert.Equal("0x80070652", signal.Payload["errorCode"]);
|
||||
Assert.Equal("Apps", signal.Payload["failedSubcategory"]);
|
||||
Assert.Equal("DeviceSetup", signal.Payload["category"]);
|
||||
Assert.Equal("ESP Finalizer US", signal.Payload["likelyCulpritApps"]);
|
||||
|
||||
// Termination-time classification reads the same context.
|
||||
Assert.NotNull(coordinator.LastEspTerminalFailure);
|
||||
Assert.Equal("0x80070652", coordinator.LastEspTerminalFailure.ErrorCode);
|
||||
Assert.True(coordinator.LastEspTerminalFailure.IsAppsSubcategory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ShellCore_failure_without_a_pending_window_stays_bare()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var coordinator = f.BuildCoordinator(() => null);
|
||||
using var adapter = new EspAndHelloTrackerAdapter(coordinator, f.Ingress, f.Clock);
|
||||
|
||||
coordinator.TriggerShellCoreEspFailureForTest("ESPProgress_Timeout");
|
||||
|
||||
var args = Assert.Single(f.Forwarded);
|
||||
Assert.Equal("ESPProgress_Timeout", args.FailureType);
|
||||
Assert.Null(args.ErrorCode);
|
||||
Assert.Null(args.FailedSubcategory);
|
||||
Assert.Null(args.Category);
|
||||
Assert.Empty(args.LikelyCulpritApps);
|
||||
Assert.Null(coordinator.LastEspTerminalFailure);
|
||||
|
||||
var signal = f.TerminalSignal();
|
||||
Assert.False(signal.Payload!.ContainsKey("errorCode"));
|
||||
Assert.False(signal.Payload.ContainsKey("failedSubcategory"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_throwing_probe_degrades_to_the_bare_failure()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
using var coordinator = f.BuildCoordinator(() => throw new InvalidOperationException("probe"));
|
||||
|
||||
coordinator.TriggerShellCoreEspFailureForTest("WhiteGlove_Failed");
|
||||
|
||||
var args = Assert.Single(f.Forwarded);
|
||||
Assert.Equal("WhiteGlove_Failed", args.FailureType);
|
||||
Assert.Null(args.ErrorCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
+119
@@ -456,5 +456,124 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
|
||||
|
||||
SingleSecurityWarning();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// %LOGGED_ON_USER_PROFILE% exception (userProfilePath overload)
|
||||
//
|
||||
// The token lifts the C:\Users hard block for AppData\Local and
|
||||
// AppData\Roaming — and nothing more. The allowlist still decides,
|
||||
// which is what the cases below pin down: the exception is a gate the
|
||||
// allowlist has to open, never an allowance of its own.
|
||||
// -------------------------------------------------------------------
|
||||
|
||||
private const string TestProfile = @"C:\Users\TestUser";
|
||||
|
||||
[Fact]
|
||||
public void UserProfile_AppDataPath_WithoutAllowlistEntry_IsStillBlocked()
|
||||
{
|
||||
// The lifted hard block alone admits nothing: without a matching
|
||||
// userProfileFilePrefixes entry the path falls through to the
|
||||
// allowlist and is refused there.
|
||||
Assert.False(GatherRuleGuards.IsFilePathAllowed(
|
||||
TestProfile + @"\AppData\Local\UnlistedVendor\app.log",
|
||||
unrestrictedMode: false, userProfilePath: TestProfile));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserProfile_OutsideAppData_IsBlockedByTheHardBlock()
|
||||
{
|
||||
foreach (var target in new[] { @"\Desktop\secret.txt", @"\Documents\notes.txt", @"\ntuser.dat" })
|
||||
{
|
||||
Assert.False(GatherRuleGuards.IsFilePathAllowed(
|
||||
TestProfile + target, unrestrictedMode: false, userProfilePath: TestProfile));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserProfile_NullProfile_KeepsTheUsersHardBlock()
|
||||
{
|
||||
// No interactive user detected — the exception cannot apply and the
|
||||
// path stays under the plain C:\Users block.
|
||||
Assert.False(GatherRuleGuards.IsFilePathAllowed(
|
||||
@"C:\Users\TestUser\AppData\Local\UnlistedVendor\app.log",
|
||||
unrestrictedMode: false, userProfilePath: null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserProfile_TraversalOutOfAppData_IsBlocked()
|
||||
{
|
||||
// Spelling Documents as a traversal out of AppData must not survive
|
||||
// Path.GetFullPath normalisation.
|
||||
const string traversal = @"C:\Users\TestUser\AppData\Local\..\..\Documents\secret.txt";
|
||||
|
||||
Assert.Equal(@"C:\Users\TestUser\Documents\secret.txt", Path.GetFullPath(traversal));
|
||||
Assert.False(GatherRuleGuards.IsFilePathAllowed(
|
||||
traversal, unrestrictedMode: false, userProfilePath: TestProfile));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserProfile_ForeignProfile_IsBlockedEvenUnderAppData()
|
||||
{
|
||||
// The exception is scoped to the DETECTED profile — a rule must not
|
||||
// reach a second user's AppData by spelling the path out.
|
||||
Assert.False(GatherRuleGuards.IsFilePathAllowed(
|
||||
@"C:\Users\OtherUser\AppData\Local\UnlistedVendor\app.log",
|
||||
unrestrictedMode: false, userProfilePath: TestProfile));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserProfile_AllowlistedVendorFolder_IsAllowed()
|
||||
{
|
||||
// AppData\Local\RealmJoin is on userProfileFilePrefixes: the file itself, a
|
||||
// subfolder below it, and the folder itself all pass.
|
||||
foreach (var target in new[] { @"\tray.log", @"\Logs\rj.log", "" })
|
||||
{
|
||||
Assert.True(GatherRuleGuards.IsFilePathAllowed(
|
||||
TestProfile + @"\AppData\Local\RealmJoin" + target,
|
||||
unrestrictedMode: false, userProfilePath: TestProfile),
|
||||
$"expected allowed: ...\\RealmJoin{target}");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserProfile_SiblingOfAnAllowlistedVendorFolder_IsBlocked()
|
||||
{
|
||||
// Segment-bounded: "RealmJoin" must not admit "RealmJoinSomethingElse".
|
||||
Assert.False(GatherRuleGuards.IsFilePathAllowed(
|
||||
TestProfile + @"\AppData\Local\RealmJoinSomethingElse\tray.log",
|
||||
unrestrictedMode: false, userProfilePath: TestProfile));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserProfile_AllowlistedVendorFolder_InAForeignProfile_IsBlocked()
|
||||
{
|
||||
// The allowlist is anchored to the DETECTED profile, not to C:\Users\*.
|
||||
Assert.False(GatherRuleGuards.IsFilePathAllowed(
|
||||
@"C:\Users\OtherUser\AppData\Local\RealmJoin\tray.log",
|
||||
unrestrictedMode: false, userProfilePath: TestProfile));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserProfile_AllowlistedVendorFolder_WithoutADetectedUser_IsBlocked()
|
||||
{
|
||||
Assert.False(GatherRuleGuards.IsFilePathAllowed(
|
||||
@"C:\Users\TestUser\AppData\Local\RealmJoin\tray.log",
|
||||
unrestrictedMode: false, userProfilePath: null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserProfile_AppDataPath_IsAllowedInUnrestrictedMode()
|
||||
{
|
||||
// Where the exception does bite today: unrestricted mode returns
|
||||
// before the allowlist, so the lifted hard block is the whole story.
|
||||
Assert.True(GatherRuleGuards.IsFilePathAllowed(
|
||||
TestProfile + @"\AppData\Local\UnlistedVendor\app.log",
|
||||
unrestrictedMode: true, userProfilePath: TestProfile));
|
||||
|
||||
// ...but only under AppData — Documents stays blocked even there.
|
||||
Assert.False(GatherRuleGuards.IsFilePathAllowed(
|
||||
TestProfile + @"\Documents\secret.txt",
|
||||
unrestrictedMode: true, userProfilePath: TestProfile));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
using System;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals;
|
||||
using AutopilotMonitor.Agent.V2.Core.Orchestration;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Orchestration;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
|
||||
{
|
||||
/// <summary>
|
||||
/// <see cref="ProvisioningStatusTracker.TryGetPendingFailureArgs"/> exposes the registry
|
||||
/// failure detail while its settle window is open and nothing once the window has fired —
|
||||
/// the coordinator reads it when a Shell-Core failure terminalises first (session 683f1eff).
|
||||
/// </summary>
|
||||
public sealed class ProvisioningStatusTrackerPendingFailureTests
|
||||
{
|
||||
private static readonly DateTime Fixed = new DateTime(2026, 9, 8, 18, 11, 2, DateTimeKind.Utc);
|
||||
|
||||
private const string InProgressJson = @"{
|
||||
""categorySucceeded"": null,
|
||||
""AppsSubcategory"": {""subcategoryState"":""inProgress"",""subcategoryStatusText"":""Apps (Working)""}
|
||||
}";
|
||||
private const string AppsFailedJson = @"{
|
||||
""categorySucceeded"": null,
|
||||
""AppsSubcategory"": {""subcategoryState"":""failed"",""subcategoryStatusText"":""Apps (0x80070652)""}
|
||||
}";
|
||||
|
||||
private sealed class Fixture : IDisposable
|
||||
{
|
||||
public TempDirectory Tmp { get; } = new TempDirectory();
|
||||
public ProvisioningStatusTracker Tracker { get; }
|
||||
|
||||
public Fixture()
|
||||
{
|
||||
var post = new InformationalEventPost(new FakeSignalIngressSink(), new VirtualClock(Fixed));
|
||||
var logger = new AgentLogger(Tmp.Path, AgentLogLevel.Info);
|
||||
Tracker = new ProvisioningStatusTracker(
|
||||
sessionId: "S1",
|
||||
tenantId: "T1",
|
||||
post: post,
|
||||
logger: logger,
|
||||
appxScanner: new FakeAppxDeploymentFailureScanner(),
|
||||
backgroundDispatcher: action => action());
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Tracker.Dispose();
|
||||
Tmp.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Nothing_pending_before_any_failure()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
Assert.Null(f.Tracker.TryGetPendingFailureArgs());
|
||||
|
||||
f.Tracker.ProcessCategoryStatusForTest("DeviceSetupCategory.Status", InProgressJson);
|
||||
Assert.Null(f.Tracker.TryGetPendingFailureArgs());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Armed_settle_window_exposes_the_registry_detail()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
f.Tracker.ProcessCategoryStatusForTest("DeviceSetupCategory.Status", InProgressJson);
|
||||
f.Tracker.ProcessCategoryStatusForTest("DeviceSetupCategory.Status", AppsFailedJson);
|
||||
|
||||
var pending = f.Tracker.TryGetPendingFailureArgs();
|
||||
|
||||
Assert.NotNull(pending);
|
||||
Assert.Equal("Provisioning_DeviceSetup_Apps_Failed", pending!.FailureType);
|
||||
Assert.Equal("0x80070652", pending.ErrorCode);
|
||||
Assert.Equal("Apps", pending.FailedSubcategory);
|
||||
Assert.Equal("DeviceSetup", pending.Category);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Expired_settle_window_leaves_nothing_pending()
|
||||
{
|
||||
using var f = new Fixture();
|
||||
f.Tracker.ProcessCategoryStatusForTest("DeviceSetupCategory.Status", InProgressJson);
|
||||
f.Tracker.ProcessCategoryStatusForTest("DeviceSetupCategory.Status", AppsFailedJson);
|
||||
|
||||
f.Tracker.TriggerSettleTimerForTest("DeviceSetupCategory.Status");
|
||||
|
||||
Assert.Null(f.Tracker.TryGetPendingFailureArgs());
|
||||
}
|
||||
}
|
||||
}
|
||||
+25
@@ -56,6 +56,31 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Telemetry.Gather
|
||||
LoadEmbeddedGuardrails()["maxCommandLength"]!.Value<int>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void User_profile_prefixes_are_all_accepted_by_the_loader()
|
||||
{
|
||||
// The loader drops entries outside AppData\Local / AppData\Roaming (the hard block
|
||||
// would never release them anyway). A dropped entry is invisible at runtime — it
|
||||
// just never matches — so a typo in the JSON must fail here instead.
|
||||
var json = LoadEmbeddedGuardrails()["userProfileFilePrefixes"]?.ToObject<string[]>()
|
||||
?? new string[0];
|
||||
|
||||
Assert.Equal(
|
||||
json.Select(p => p.Trim().TrimEnd('\\')).OrderBy(p => p),
|
||||
GatherRuleGuards.AllowedUserProfileFilePrefixes.OrderBy(p => p));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void User_profile_prefixes_stay_under_the_hard_blocks_exception()
|
||||
{
|
||||
Assert.All(
|
||||
GatherRuleGuards.AllowedUserProfileFilePrefixes,
|
||||
prefix => Assert.Contains(
|
||||
GatherRuleGuards.AllowedUserProfileSubdirs,
|
||||
subdir => prefix.StartsWith(subdir, System.StringComparison.OrdinalIgnoreCase) &&
|
||||
(prefix.Length == subdir.Length || prefix[subdir.Length] == '\\')));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Blocked_event_log_channels_match_code_constants()
|
||||
{
|
||||
|
||||
+36
@@ -265,6 +265,42 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
|
||||
sut.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deadline_fired_late_keeps_the_due_time_as_stamp_and_carries_it_in_the_payload()
|
||||
{
|
||||
// A deadline that was due while the device slept (or the agent was down) fires only
|
||||
// afterwards. The signal keeps the due time as OccurredAtUtc (D-238: the outage must not
|
||||
// become session duration) and repeats it in the payload so the stale-fire guards
|
||||
// identify the incarnation independently of the stamp.
|
||||
using var rig = new EnrollmentOrchestratorRig(At);
|
||||
var sut = rig.Build();
|
||||
sut.Start();
|
||||
|
||||
var dueAt = At.AddMinutes(-5);
|
||||
var scheduler = GetScheduler(sut);
|
||||
scheduler.Schedule(new ActiveDeadline(
|
||||
name: "hello_safety",
|
||||
dueAtUtc: dueAt,
|
||||
firesSignalKind: DecisionSignalKind.DeadlineFired,
|
||||
firesPayload: new Dictionary<string, string> { [SignalPayloadKeys.Deadline] = "hello_safety" }));
|
||||
|
||||
var signalLog = GetSignalLog(sut);
|
||||
Assert.True(SpinWait.SpinUntil(() => ContainsDeadlineFired(signalLog), 3000));
|
||||
|
||||
DecisionSignal? fired = null;
|
||||
foreach (var sig in signalLog.ReadAll())
|
||||
{
|
||||
if (sig.Kind == DecisionSignalKind.DeadlineFired) { fired = sig; break; }
|
||||
}
|
||||
Assert.NotNull(fired);
|
||||
Assert.Equal(dueAt, fired!.OccurredAtUtc);
|
||||
Assert.NotNull(fired.Payload);
|
||||
Assert.Equal("hello_safety", fired.Payload![SignalPayloadKeys.Deadline]);
|
||||
Assert.Equal(dueAt.ToString("O"), fired.Payload[SignalPayloadKeys.DeadlineDueAtUtc]);
|
||||
|
||||
sut.Stop();
|
||||
}
|
||||
|
||||
// ========================================================================= Quarantine
|
||||
|
||||
[Fact]
|
||||
|
||||
+10
-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
|
||||
|
||||
+65
-19
@@ -44,6 +44,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
private readonly Func<bool> _userEspAppsSettledProbe;
|
||||
private readonly Func<System.Collections.Generic.IReadOnlyList<Ime.AppPackageState>> _starvedUserEspAppsProbe;
|
||||
private readonly Func<System.Collections.Generic.IReadOnlyList<Ime.AppPackageState>> _packageStatesProbe;
|
||||
// Session 683f1eff: registry failure detail still sitting in an open settle window,
|
||||
// consulted when a Shell-Core failure terminalises first (see OnShellCoreEspFailureDetected).
|
||||
private readonly Func<EspFailureDetectedEventArgs> _pendingEspFailureProbe;
|
||||
|
||||
// Session caa6cf50 gate-starvation fix (2026-06-11) — fire-once guard for the
|
||||
// user-ESP-apps-settled AccountSetup synthesis (see MaybeSynthesizeAccountSetupComplete).
|
||||
@@ -174,8 +177,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
/// late "Installing-→-Error" promotion can classify the failure correctly
|
||||
/// AND refuse to promote when the failure originated outside the Apps
|
||||
/// subcategory (a non-Apps HRESULT does not describe per-app outcome).
|
||||
/// Null when no HRESULT-carrying ESP failure has fired (or all observed
|
||||
/// failures came from ShellCoreTracker, which has no HRESULT surface).
|
||||
/// Null when no registry-derived failure detail has been observed — neither from
|
||||
/// a settle window that expired nor from one a Shell-Core failure inherited.
|
||||
/// </summary>
|
||||
public Termination.EspTerminalFailureSnapshot LastEspTerminalFailure { get; private set; }
|
||||
|
||||
@@ -243,7 +246,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
Func<bool> accountSetupActivityProbe = null,
|
||||
Func<bool> userEspAppsSettledProbe = null,
|
||||
Func<System.Collections.Generic.IReadOnlyList<Ime.AppPackageState>> starvedUserEspAppsProbe = null,
|
||||
Func<System.Collections.Generic.IReadOnlyList<Ime.AppPackageState>> packageStatesProbe = null)
|
||||
Func<System.Collections.Generic.IReadOnlyList<Ime.AppPackageState>> packageStatesProbe = null,
|
||||
Func<EspFailureDetectedEventArgs> pendingEspFailureProbe = null)
|
||||
{
|
||||
_sessionId = sessionId ?? throw new ArgumentNullException(nameof(sessionId));
|
||||
_tenantId = tenantId ?? throw new ArgumentNullException(nameof(tenantId));
|
||||
@@ -277,6 +281,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
// provisioning tracker name not-completed apps on an Apps-subcategory failure.
|
||||
_packageStatesProbe = packageStatesProbe
|
||||
?? (() => Array.Empty<Ime.AppPackageState>());
|
||||
// Test seam: defaults to the provisioning tracker's open settle window (null when
|
||||
// none is armed or the tracker is not running, e.g. Device Preparation).
|
||||
_pendingEspFailureProbe = pendingEspFailureProbe
|
||||
?? (() => _provisioningTracker?.TryGetPendingFailureArgs());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -658,6 +666,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
internal void TriggerEspExitedForTest(DateTime occurredAtUtc) =>
|
||||
OnEspExited(this, new EspExitedEventArgs(occurredAtUtc));
|
||||
|
||||
// Test seam for a Shell-Core 62407 failure — drives the coordinator forwarder including
|
||||
// the pending-settle inheritance, without a real ShellCoreTracker.
|
||||
internal void TriggerShellCoreEspFailureForTest(string failureType) =>
|
||||
OnShellCoreEspFailureDetected(this, failureType);
|
||||
|
||||
// Test seam for HelloWizardStarted — same contract as TriggerEspExitedForTest.
|
||||
internal void TriggerHelloWizardStartedForTest(DateTime occurredAtUtc) =>
|
||||
OnHelloWizardStarted(this, new HelloWizardStartedEventArgs(occurredAtUtc));
|
||||
@@ -673,33 +686,56 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
// Forwarder for ShellCoreTracker (event-log-derived ESP failures, e.g. Shell-Core 62407
|
||||
// failure descriptions). Source-event timestamp is mirrored so the adapter can stamp the
|
||||
// DecisionSignal with the historical instant on backfill. ShellCoreTracker has no HRESULT
|
||||
// surface, so only FailureType is set on the args.
|
||||
// surface; the registry detail is inherited from an open settle window (see below).
|
||||
private void OnShellCoreEspFailureDetected(object sender, string failureType)
|
||||
{
|
||||
LastEventOccurredAtUtc = (sender as ShellCoreTracker)?.LastEventOccurredAtUtc;
|
||||
try
|
||||
{
|
||||
EspFailureDetected?.Invoke(this, new EspFailureDetectedEventArgs(failureType));
|
||||
EspFailureDetected?.Invoke(this, BuildShellCoreFailureArgs(failureType));
|
||||
}
|
||||
catch (Exception ex) { _logger.Error($"Error forwarding ShellCore EspFailureDetected for '{failureType}'", ex); }
|
||||
finally { LastEventOccurredAtUtc = null; }
|
||||
}
|
||||
|
||||
// Forwarder for ProvisioningStatusTracker (registry-derived ESP failures). Args carry the
|
||||
// full failure detail (FailureType, ErrorCode, FailedSubcategory, Category) extracted
|
||||
// from the failed subcategory's statusText. Provisioning has no source-event timestamp
|
||||
// surfaced today, so the adapter falls back to clock.
|
||||
private void OnProvisioningEspFailureDetected(object sender, EspFailureDetectedEventArgs args)
|
||||
// Session 683f1eff: the Shell-Core 62407 failure usually lands INSIDE the provisioning
|
||||
// tracker's 30-s settle window — after the registry named the failed subcategory and its
|
||||
// HRESULT, before the settle timer would have forwarded them. The engine terminalises on
|
||||
// the first EspTerminalFailure and the agent stops seconds later, so whatever this signal
|
||||
// carries is all the terminal event, the backend FailureReason and the termination-time
|
||||
// app classification ever see (a third of all ESP terminal failures took this path). The
|
||||
// pending detail is inherited here; FailureType stays the Shell-Core value because that
|
||||
// is the signal that actually terminalised.
|
||||
private EspFailureDetectedEventArgs BuildShellCoreFailureArgs(string failureType)
|
||||
{
|
||||
EspFailureDetectedEventArgs pending = null;
|
||||
try { pending = _pendingEspFailureProbe(); }
|
||||
catch (Exception ex) { _logger.Warning($"EspAndHelloTracker: pending ESP failure probe threw: {ex.Message}"); }
|
||||
|
||||
if (pending == null)
|
||||
return new EspFailureDetectedEventArgs(failureType);
|
||||
|
||||
RecordTerminalFailureSnapshot(pending);
|
||||
_logger.Info(
|
||||
$"EspAndHelloTracker: Shell-Core failure '{failureType}' inherits the pending provisioning failure detail " +
|
||||
$"(category={pending.Category ?? "n/a"}, failedSubcategory={pending.FailedSubcategory ?? "n/a"}, " +
|
||||
$"errorCode={pending.ErrorCode ?? "n/a"})");
|
||||
return new EspFailureDetectedEventArgs(
|
||||
failureType,
|
||||
errorCode: pending.ErrorCode,
|
||||
failedSubcategory: pending.FailedSubcategory,
|
||||
category: pending.Category,
|
||||
likelyCulpritApps: pending.LikelyCulpritApps);
|
||||
}
|
||||
|
||||
// Session 080edee9 follow-up + Codex review (P2/P3) — snapshot the full failure context
|
||||
// (HRESULT + failedSubcategory + category) so EnrollmentTerminationHandler can read it on
|
||||
// the terminal-failure pathway. Only update when the args carry at least one of the three
|
||||
// fields, so a bare Shell-Core failure cannot wipe out the registry snapshot. Deliberately
|
||||
// NOT gated on ErrorCode alone — a non-Apps subcategory failure without HRESULT is still
|
||||
// useful for downstream "should we promote?" gating.
|
||||
private void RecordTerminalFailureSnapshot(EspFailureDetectedEventArgs args)
|
||||
{
|
||||
LastEventOccurredAtUtc = null;
|
||||
// Session 080edee9 follow-up + Codex review (P2/P3) — snapshot the full
|
||||
// failure context (HRESULT + failedSubcategory + category) before
|
||||
// forwarding so EnrollmentTerminationHandler can read it on the terminal-
|
||||
// failure pathway. Only update when the args carry at least one of the
|
||||
// three fields, so a later ShellCore-derived failure (which has none of
|
||||
// them) cannot wipe out the registry snapshot. We deliberately do NOT
|
||||
// gate on ErrorCode alone — a non-Apps subcategory failure without
|
||||
// HRESULT is still useful for downstream "should we promote?" gating.
|
||||
if (!string.IsNullOrEmpty(args?.ErrorCode)
|
||||
|| !string.IsNullOrEmpty(args?.FailedSubcategory)
|
||||
|| !string.IsNullOrEmpty(args?.Category))
|
||||
@@ -709,6 +745,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
failedSubcategory: args.FailedSubcategory,
|
||||
category: args.Category);
|
||||
}
|
||||
}
|
||||
|
||||
// Forwarder for ProvisioningStatusTracker (registry-derived ESP failures). Args carry the
|
||||
// full failure detail (FailureType, ErrorCode, FailedSubcategory, Category) extracted
|
||||
// from the failed subcategory's statusText. Provisioning has no source-event timestamp
|
||||
// surfaced today, so the adapter falls back to clock.
|
||||
private void OnProvisioningEspFailureDetected(object sender, EspFailureDetectedEventArgs args)
|
||||
{
|
||||
LastEventOccurredAtUtc = null;
|
||||
RecordTerminalFailureSnapshot(args);
|
||||
try
|
||||
{
|
||||
EspFailureDetected?.Invoke(this, args);
|
||||
|
||||
+31
@@ -80,6 +80,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
"AccountSetupCategory.Status"
|
||||
};
|
||||
|
||||
// Order in which TryGetPendingFailureArgs resolves concurrently armed settle windows.
|
||||
private static readonly string[] PendingFailurePreference =
|
||||
{
|
||||
"DeviceSetupCategory.Status",
|
||||
"AccountSetupCategory.Status",
|
||||
"DevicePreparationCategory.Status"
|
||||
};
|
||||
|
||||
private readonly AgentLogger _logger;
|
||||
private readonly string _sessionId;
|
||||
private readonly string _tenantId;
|
||||
@@ -1711,6 +1719,29 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
internal void TriggerSettleTimerForTest(string categoryName)
|
||||
=> OnProvisioningFailureSettleExpired(categoryName);
|
||||
|
||||
/// <summary>
|
||||
/// The registry-derived failure detail of a settle window that is still open (armed,
|
||||
/// not yet expired or retracted) — null when none is pending. Read by the coordinator
|
||||
/// when a Shell-Core 62407 failure arrives inside the window, so the terminal signal
|
||||
/// inherits HRESULT / failed subcategory / category instead of racing them away
|
||||
/// (session 683f1eff). Windows fail one category at a time, but should two be armed
|
||||
/// the device-phase category wins: it is the one the ESP page reports.
|
||||
/// </summary>
|
||||
internal EspFailureDetectedEventArgs TryGetPendingFailureArgs()
|
||||
{
|
||||
lock (_stateLock)
|
||||
{
|
||||
if (_provisioningFailureSettleArgs == null || _provisioningFailureSettleArgs.Count == 0)
|
||||
return null;
|
||||
foreach (var category in PendingFailurePreference)
|
||||
{
|
||||
if (_provisioningFailureSettleArgs.TryGetValue(category, out var args) && args != null)
|
||||
return args;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private bool HasCategorySucceededChanged(string categoryName, bool? newValue)
|
||||
{
|
||||
if (!_lastCategorySucceeded.TryGetValue(categoryName, out var oldValue))
|
||||
|
||||
+7
-40
@@ -70,12 +70,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
@"C:\Windows\System32\config", // SAM, SECURITY, SYSTEM hives
|
||||
};
|
||||
|
||||
// Allowed subdirectories under a user profile (used with %LOGGED_ON_USER_PROFILE% token)
|
||||
private static readonly string[] AllowedUserProfileSubdirs = new[]
|
||||
{
|
||||
@"AppData\Local",
|
||||
@"AppData\Roaming",
|
||||
};
|
||||
// The allowed user-profile subdirectories and the vendor allowlist under them live in
|
||||
// GatherRuleGuards, which owns the embedded guardrails.json — one copy for both guards.
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if the given path is allowed for diagnostics collection.
|
||||
@@ -135,7 +131,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
(normalizedDir.Length == BlockedUsersPrefix.Length ||
|
||||
normalizedDir[BlockedUsersPrefix.Length] == Path.DirectorySeparatorChar))
|
||||
{
|
||||
if (!IsUserProfileSubpathAllowed(normalizedDir, userProfilePath))
|
||||
if (!GatherRuleGuards.IsUserProfileSubpathAllowed(normalizedDir, userProfilePath))
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -169,7 +165,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
// Vendor folders under the signed-in user's profile — same allowlist the file
|
||||
// collectors use, since it answers the same question: which folders below a
|
||||
// profile carry enrollment-relevant logs rather than the user's own data.
|
||||
return GatherRuleGuards.IsUserProfilePathOnAllowlist(normalizedDir, userProfilePath);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -178,38 +177,6 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if the normalized path falls under one of the allowed subdirectories
|
||||
/// of the detected user profile (AppData\Local, AppData\Roaming).
|
||||
/// Only applies when %LOGGED_ON_USER_PROFILE% was used to resolve the path.
|
||||
/// </summary>
|
||||
internal static bool IsUserProfileSubpathAllowed(string normalizedPath, string userProfilePath)
|
||||
{
|
||||
if (string.IsNullOrEmpty(userProfilePath))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
var normalizedProfile = Path.GetFullPath(userProfilePath);
|
||||
foreach (var subdir in AllowedUserProfileSubdirs)
|
||||
{
|
||||
var allowedPrefix = Path.GetFullPath(Path.Combine(normalizedProfile, subdir));
|
||||
if (normalizedPath.StartsWith(allowedPrefix, StringComparison.OrdinalIgnoreCase) &&
|
||||
(normalizedPath.Length == allowedPrefix.Length ||
|
||||
normalizedPath[allowedPrefix.Length] == Path.DirectorySeparatorChar))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Path normalization failure — deny
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether any component of the path (directories or file) is a symlink,
|
||||
/// junction, or other reparse point. Returns true if a reparse point is detected.
|
||||
|
||||
+110
-6
@@ -32,6 +32,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
// -----------------------------------------------------------------------
|
||||
public static readonly IReadOnlyList<string> AllowedRegistryPrefixes;
|
||||
public static readonly IReadOnlyList<string> AllowedFilePrefixes;
|
||||
|
||||
/// <summary>
|
||||
/// Folders under the signed-in user's profile that file collectors and
|
||||
/// admin-configured diagnostics paths may read, RELATIVE to the profile root
|
||||
/// (e.g. <c>AppData\Local\Vendor</c>). Resolved against the path
|
||||
/// %LOGGED_ON_USER_PROFILE% produced, at match time — the profile name is not
|
||||
/// known when the list is authored, which is why these entries cannot live in
|
||||
/// <see cref="AllowedFilePrefixes"/> (matched literally against the expanded path).
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> AllowedUserProfileFilePrefixes;
|
||||
public static readonly IReadOnlyList<string> AllowedWmiQueryPrefixes;
|
||||
public static readonly IReadOnlyCollection<string> AllowedCommands;
|
||||
public static readonly IReadOnlyList<string> AllowedEventLogChannels;
|
||||
@@ -63,8 +73,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
Path.GetFullPath(@"C:\Windows\System32\config"), // SAM, SECURITY, SYSTEM hives
|
||||
};
|
||||
|
||||
// Allowed subdirectories under a user profile (used with %LOGGED_ON_USER_PROFILE% token)
|
||||
private static readonly string[] AllowedUserProfileSubdirs = new[]
|
||||
// The only subdirectories of a user profile the C:\Users hard block will ever
|
||||
// release (used with %LOGGED_ON_USER_PROFILE%). Single copy for both guards —
|
||||
// DiagnosticsPathGuards delegates here.
|
||||
internal static readonly string[] AllowedUserProfileSubdirs = new[]
|
||||
{
|
||||
@"AppData\Local",
|
||||
@"AppData\Roaming",
|
||||
@@ -118,6 +130,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
|
||||
AllowedRegistryPrefixes = FlattenCategorized(obj, "registryPrefixes", "prefixes");
|
||||
AllowedFilePrefixes = obj["filePrefixes"]?.ToObject<List<string>>() ?? new List<string>();
|
||||
AllowedUserProfileFilePrefixes = LoadUserProfilePrefixes(obj);
|
||||
AllowedWmiQueryPrefixes = obj["wmiQueryPrefixes"]?.ToObject<List<string>>() ?? new List<string>();
|
||||
|
||||
var commands = FlattenCategorized(obj, "allowedCommands", "commands");
|
||||
@@ -136,6 +149,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
|
||||
AllowedRegistryPrefixes = new List<string>();
|
||||
AllowedFilePrefixes = new List<string>();
|
||||
AllowedUserProfileFilePrefixes = new List<string>();
|
||||
AllowedWmiQueryPrefixes = new List<string>();
|
||||
AllowedCommands = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
AllowedEventLogChannels = new List<string>();
|
||||
@@ -143,6 +157,43 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
ResidualWmiPrefixes = new List<string>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads <c>userProfileFilePrefixes</c> and drops every entry that is rooted, carries a
|
||||
/// traversal, or does not sit under one of <see cref="AllowedUserProfileSubdirs"/>.
|
||||
/// The C:\Users hard block releases nothing outside AppData, so such an entry could only
|
||||
/// ever be dead text — dropping it at load keeps the list honest instead of silently
|
||||
/// ineffective, and no configuration can widen the hard block's exception.
|
||||
/// </summary>
|
||||
private static List<string> LoadUserProfilePrefixes(JObject obj)
|
||||
{
|
||||
var raw = obj["userProfileFilePrefixes"]?.ToObject<List<string>>() ?? new List<string>();
|
||||
var result = new List<string>();
|
||||
|
||||
foreach (var entry in raw)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(entry))
|
||||
continue;
|
||||
|
||||
var trimmed = entry.Trim().TrimEnd('\\');
|
||||
if (Path.IsPathRooted(trimmed))
|
||||
continue;
|
||||
if (trimmed.IndexOf("..", StringComparison.Ordinal) >= 0)
|
||||
continue;
|
||||
|
||||
foreach (var subdir in AllowedUserProfileSubdirs)
|
||||
{
|
||||
if (trimmed.StartsWith(subdir, StringComparison.OrdinalIgnoreCase) &&
|
||||
(trimmed.Length == subdir.Length || trimmed[subdir.Length] == '\\'))
|
||||
{
|
||||
result.Add(trimmed);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void DeriveWmiClassAllowlist(
|
||||
IReadOnlyList<string> entries,
|
||||
out HashSet<string> classes,
|
||||
@@ -265,12 +316,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
|
||||
// C:\Users block always applies (even in unrestricted mode)
|
||||
// Exception: paths under <userProfilePath>\AppData\Local or AppData\Roaming
|
||||
// are allowed when the %LOGGED_ON_USER_PROFILE% token was used.
|
||||
// are allowed when the %LOGGED_ON_USER_PROFILE% token was used. The exception
|
||||
// only LIFTS the block — in restricted mode the allowlist below still decides.
|
||||
if (normalizedPath.StartsWith(BlockedUsersPrefix, StringComparison.OrdinalIgnoreCase) &&
|
||||
(normalizedPath.Length == BlockedUsersPrefix.Length ||
|
||||
normalizedPath[BlockedUsersPrefix.Length] == Path.DirectorySeparatorChar))
|
||||
{
|
||||
if (!DiagnosticsPathGuards.IsUserProfileSubpathAllowed(normalizedPath, userProfilePath))
|
||||
if (!IsUserProfileSubpathAllowed(normalizedPath, userProfilePath))
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -288,9 +340,61 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
if (unrestrictedMode)
|
||||
return true;
|
||||
|
||||
return AllowedFilePrefixes.Any(prefix =>
|
||||
if (AllowedFilePrefixes.Any(prefix =>
|
||||
normalizedPath.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) &&
|
||||
(normalizedPath.Length == prefix.Length || normalizedPath[prefix.Length] == '\\'));
|
||||
(normalizedPath.Length == prefix.Length || normalizedPath[prefix.Length] == '\\')))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// Vendor folders under the signed-in user's profile. Only reachable when the rule
|
||||
// spelled %LOGGED_ON_USER_PROFILE% and the resolver found an interactive user —
|
||||
// a null profile denies, so a machine with nobody signed in cannot widen anything.
|
||||
return IsUserProfilePathOnAllowlist(normalizedPath, userProfilePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when the normalized path sits under one of <see cref="AllowedUserProfileSubdirs"/>
|
||||
/// of the detected user profile. This is the C:\Users hard block's only exception; it
|
||||
/// releases the block and nothing else. A null profile denies.
|
||||
/// </summary>
|
||||
internal static bool IsUserProfileSubpathAllowed(string normalizedPath, string userProfilePath)
|
||||
=> AllowedUserProfileSubdirs.Any(subdir =>
|
||||
MatchesProfileRelativePrefix(normalizedPath, userProfilePath, subdir));
|
||||
|
||||
/// <summary>
|
||||
/// True when the normalized path is admitted by an entry of
|
||||
/// <see cref="AllowedUserProfileFilePrefixes"/> under the detected user profile.
|
||||
/// </summary>
|
||||
internal static bool IsUserProfilePathOnAllowlist(string normalizedPath, string userProfilePath)
|
||||
=> AllowedUserProfileFilePrefixes.Any(prefix =>
|
||||
MatchesProfileRelativePrefix(normalizedPath, userProfilePath, prefix));
|
||||
|
||||
/// <summary>
|
||||
/// Segment-bounded match of <paramref name="normalizedPath"/> against
|
||||
/// <profile>\<relativePrefix>. Both sides go through Path.GetFullPath, so a
|
||||
/// traversal spelled into either one cannot slip past the boundary check.
|
||||
/// </summary>
|
||||
private static bool MatchesProfileRelativePrefix(
|
||||
string normalizedPath, string userProfilePath, string relativePrefix)
|
||||
{
|
||||
if (string.IsNullOrEmpty(normalizedPath) || string.IsNullOrEmpty(userProfilePath))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
var allowedPrefix = Path.GetFullPath(
|
||||
Path.Combine(Path.GetFullPath(userProfilePath), relativePrefix));
|
||||
|
||||
return normalizedPath.StartsWith(allowedPrefix, StringComparison.OrdinalIgnoreCase) &&
|
||||
(normalizedPath.Length == allowedPrefix.Length ||
|
||||
normalizedPath[allowedPrefix.Length] == Path.DirectorySeparatorChar);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Path normalization failure — deny.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -9,9 +9,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
/// <para>
|
||||
/// The orchestrator consumes this event and translates it into a synthetic
|
||||
/// <c>DeadlineFired</c>-<see cref="AutopilotMonitor.DecisionCore.Signals.DecisionSignal"/>
|
||||
/// whose <c>OccurredAtUtc</c> equals the deadline's <see cref="ActiveDeadline.DueAtUtc"/>,
|
||||
/// not the wall-clock firing time — so replay stays deterministic even if the agent
|
||||
/// restarts long after the deadline has passed.
|
||||
/// whose <c>OccurredAtUtc</c> equals the deadline's <see cref="ActiveDeadline.DueAtUtc"/>
|
||||
/// (the policy instant the wait expired), with the due time repeated in the payload. The
|
||||
/// firing clock is deliberately NOT the stamp: a timer due during Modern Standby or a
|
||||
/// reboot fires only afterwards, and the outage would otherwise become session duration
|
||||
/// (D-238).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class DeadlineFiredEventArgs : EventArgs
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -1159,7 +1160,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
var evidence = new Evidence(
|
||||
kind: EvidenceKind.Synthetic,
|
||||
identifier: e.Deadline.Name,
|
||||
summary: $"deadline '{e.Deadline.Name}' fired at {e.Deadline.DueAtUtc:O}");
|
||||
summary: $"deadline '{e.Deadline.Name}' due {e.Deadline.DueAtUtc:O} fired at {e.FiredAtUtc:O}");
|
||||
|
||||
// The reducer reads the deadline name under SignalPayloadKeys.Deadline
|
||||
// (see HandleDeadlineFiredV1 in DecisionEngine.Shared). Forward the
|
||||
@@ -1180,7 +1181,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
payload[SignalPayloadKeys.Deadline] = e.Deadline.Name;
|
||||
}
|
||||
|
||||
// OccurredAtUtc = DueAtUtc (not firedAt) — replay-determinism per DeadlineFiredEventArgs doc.
|
||||
// OccurredAtUtc = DueAtUtc, not the firing clock (D-238). Every effect of the
|
||||
// resulting step (phase_transition, enrollment_complete) is stamped with the signal
|
||||
// time; a timer that came due during Modern Standby or a reboot fires only afterwards,
|
||||
// and the firing clock would make the verdict — and the session duration — grow by
|
||||
// the whole outage (measured: days for devices closed right after provisioning).
|
||||
// The due time also travels in the payload so the stale-fire guards identify the
|
||||
// deadline incarnation independently of the stamp.
|
||||
payload[SignalPayloadKeys.DeadlineDueAtUtc] = e.Deadline.DueAtUtc.ToString("O", CultureInfo.InvariantCulture);
|
||||
|
||||
_ingress.Post(
|
||||
kind: DecisionSignalKind.DeadlineFired,
|
||||
occurredAtUtc: e.Deadline.DueAtUtc,
|
||||
|
||||
@@ -39,7 +39,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
|
||||
/// <summary>
|
||||
/// Wird vom Timer-Thread geraised, wenn ein Deadline fällig wird. Subscriber
|
||||
/// ist typischerweise der Orchestrator, der daraus ein synthetisches
|
||||
/// <c>DeadlineFired</c>-Signal mit <c>OccurredAtUtc = deadline.DueAtUtc</c> erzeugt.
|
||||
/// <c>DeadlineFired</c>-Signal mit <c>OccurredAtUtc = deadline.DueAtUtc</c> erzeugt; die
|
||||
/// Fälligkeit reist zusätzlich im Payload (<c>SignalPayloadKeys.DeadlineDueAtUtc</c>).
|
||||
/// </summary>
|
||||
event EventHandler<DeadlineFiredEventArgs>? Fired;
|
||||
|
||||
|
||||
@@ -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,191 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using AutopilotMonitor.DecisionCore.Engine;
|
||||
using AutopilotMonitor.DecisionCore.Signals;
|
||||
using AutopilotMonitor.DecisionCore.State;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.DecisionCore.Tests
|
||||
{
|
||||
/// <summary>
|
||||
/// The reducer identifies a deadline incarnation through the due time carried in the
|
||||
/// payload (<see cref="SignalPayloadKeys.DeadlineDueAtUtc"/>), never through the signal
|
||||
/// time: the host stamps <c>DeadlineFired</c> with the due time (D-238), but the guards
|
||||
/// must stay correct for any stamp — a late fire after Modern Standby or a restart, a
|
||||
/// replayed signal, or a future switch to the firing clock. Without the key they fall back
|
||||
/// to the signal time (pre-key signal logs, where the two were equal by contract).
|
||||
/// </summary>
|
||||
public sealed class DeadlineFireTimeStampTests
|
||||
{
|
||||
private static readonly DateTime T0 = new DateTime(2026, 9, 9, 6, 31, 0, DateTimeKind.Utc);
|
||||
|
||||
private static DecisionSignal MakeSignal(
|
||||
long ordinal,
|
||||
DecisionSignalKind kind,
|
||||
DateTime occurredAtUtc,
|
||||
IReadOnlyDictionary<string, string>? payload = null) =>
|
||||
new DecisionSignal(
|
||||
sessionSignalOrdinal: ordinal,
|
||||
sessionTraceOrdinal: ordinal,
|
||||
kind: kind,
|
||||
kindSchemaVersion: 1,
|
||||
occurredAtUtc: occurredAtUtc,
|
||||
sourceOrigin: "test",
|
||||
evidence: new Evidence(EvidenceKind.Synthetic, $"t-{kind}-{ordinal}", $"synthetic {kind}"),
|
||||
payload: payload);
|
||||
|
||||
/// <summary>What the host posts: name plus due time, OccurredAtUtc = firing clock.</summary>
|
||||
private static Dictionary<string, string> FiredPayload(string deadlineName, DateTime dueAtUtc) =>
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
[SignalPayloadKeys.Deadline] = deadlineName,
|
||||
[SignalPayloadKeys.DeadlineDueAtUtc] = dueAtUtc.ToString("O", CultureInfo.InvariantCulture),
|
||||
};
|
||||
|
||||
// ============================================================== helper
|
||||
|
||||
[Fact]
|
||||
public void DeadlineDueAtUtc_reads_the_payload_and_falls_back_to_the_signal_time()
|
||||
{
|
||||
var due = T0.AddMinutes(5);
|
||||
var fired = T0.AddMinutes(9);
|
||||
|
||||
var withKey = MakeSignal(1, DecisionSignalKind.DeadlineFired, fired, FiredPayload(DeadlineNames.HelloSafety, due));
|
||||
Assert.Equal(due, DecisionEngine.DeadlineDueAtUtc(withKey));
|
||||
Assert.Equal(DateTimeKind.Utc, DecisionEngine.DeadlineDueAtUtc(withKey).Kind);
|
||||
|
||||
var withoutKey = MakeSignal(2, DecisionSignalKind.DeadlineFired, fired,
|
||||
new Dictionary<string, string> { [SignalPayloadKeys.Deadline] = DeadlineNames.HelloSafety });
|
||||
Assert.Equal(fired, DecisionEngine.DeadlineDueAtUtc(withoutKey));
|
||||
|
||||
var garbage = MakeSignal(3, DecisionSignalKind.DeadlineFired, fired,
|
||||
new Dictionary<string, string> { [SignalPayloadKeys.DeadlineDueAtUtc] = "not-a-time" });
|
||||
Assert.Equal(fired, DecisionEngine.DeadlineDueAtUtc(garbage));
|
||||
}
|
||||
|
||||
// ============================================================== Classic: standby at the Hello prompt
|
||||
|
||||
[Fact]
|
||||
public void Late_HelloSafety_fire_stamps_the_resolution_and_the_grace_window_from_the_firing_clock()
|
||||
{
|
||||
// Session ac5660b8 shape: ESP exits, the user leaves the device at the Hello prompt, it
|
||||
// enters Modern Standby, HelloSafety is due during the sleep and fires ~3 min late after
|
||||
// wake. Fed with the firing clock as signal time, the reducer must stamp the Hello
|
||||
// timeout fact, the Finalizing step and the FinalizingGrace due time from that time —
|
||||
// the stamp policy is the host's choice (D-238), the reducer follows the signal.
|
||||
var engine = new DecisionEngine();
|
||||
var state = DecisionState.CreateInitial("sess-standby", "tenant", T0);
|
||||
state = engine.Reduce(state, MakeSignal(0, DecisionSignalKind.SessionStarted, T0)).NewState;
|
||||
state = engine.Reduce(state, MakeSignal(1, DecisionSignalKind.EspPhaseChanged, T0.AddMinutes(1),
|
||||
new Dictionary<string, string> { [SignalPayloadKeys.EspPhase] = "AccountSetup" })).NewState;
|
||||
state = engine.Reduce(state, MakeSignal(2, DecisionSignalKind.AccountSetupProvisioningComplete, T0.AddMinutes(2))).NewState;
|
||||
state = engine.Reduce(state, MakeSignal(3, DecisionSignalKind.DesktopArrived, T0.AddMinutes(3))).NewState;
|
||||
|
||||
var espExit = T0.AddMinutes(6).AddSeconds(50.2144855);
|
||||
state = engine.Reduce(state, MakeSignal(4, DecisionSignalKind.EspExiting, espExit)).NewState;
|
||||
var helloSafety = Assert.Single(state.Deadlines, d => d.Name == DeadlineNames.HelloSafety);
|
||||
Assert.Equal(espExit.AddSeconds(300), helloSafety.DueAtUtc);
|
||||
|
||||
// Timer fires after wake, 2m 54s past due.
|
||||
var firedAt = helloSafety.DueAtUtc.AddSeconds(174);
|
||||
var finalizing = engine.Reduce(state, MakeSignal(5, DecisionSignalKind.DeadlineFired, firedAt,
|
||||
FiredPayload(DeadlineNames.HelloSafety, helloSafety.DueAtUtc)));
|
||||
|
||||
Assert.True(finalizing.Transition.Taken);
|
||||
Assert.Equal(SessionStage.Finalizing, finalizing.NewState.Stage);
|
||||
Assert.Equal("Timeout", finalizing.NewState.HelloOutcome!.Value);
|
||||
Assert.Equal(firedAt, finalizing.NewState.HelloResolvedUtc!.Value);
|
||||
|
||||
var grace = Assert.Single(finalizing.NewState.Deadlines, d => d.Name == DeadlineNames.FinalizingGrace);
|
||||
Assert.Equal(firedAt.AddSeconds(5), grace.DueAtUtc);
|
||||
|
||||
// The chained grace fires on time and completes; nothing carries the old due time.
|
||||
var completed = engine.Reduce(finalizing.NewState, MakeSignal(6, DecisionSignalKind.DeadlineFired, grace.DueAtUtc,
|
||||
FiredPayload(DeadlineNames.FinalizingGrace, grace.DueAtUtc)));
|
||||
Assert.Equal(SessionStage.Completed, completed.NewState.Stage);
|
||||
Assert.Equal(SessionOutcome.EnrollmentComplete, completed.NewState.Outcome);
|
||||
Assert.Contains(completed.Effects, e =>
|
||||
e.Kind == DecisionEffectKind.EmitEventTimelineEntry
|
||||
&& e.Parameters != null
|
||||
&& e.Parameters.TryGetValue("eventType", out var et) && et == "enrollment_complete");
|
||||
}
|
||||
|
||||
// ============================================================== SelfDeploying guard C
|
||||
|
||||
[Fact]
|
||||
public void SelfDeploying_guard_C_matches_the_incarnation_by_payload_due_time_not_by_firing_clock()
|
||||
{
|
||||
var engine = new DecisionEngine();
|
||||
var state = DecisionState.CreateInitial("sd-late", "t", T0);
|
||||
state = engine.Reduce(state, MakeSignal(0, DecisionSignalKind.SessionStarted, T0)).NewState;
|
||||
state = engine.Reduce(state, MakeSignal(1, DecisionSignalKind.EspPhaseChanged, T0.AddMinutes(1),
|
||||
new Dictionary<string, string> { [SignalPayloadKeys.EspPhase] = "DeviceSetup" })).NewState;
|
||||
state = engine.Reduce(state, MakeSignal(2, DecisionSignalKind.DeviceSetupProvisioningComplete, T0.AddMinutes(3))).NewState;
|
||||
var armed = Assert.Single(state.Deadlines, d => d.Name == DeadlineNames.DeviceOnlyEspDetection);
|
||||
Assert.Equal(T0.AddMinutes(8), armed.DueAtUtc);
|
||||
|
||||
// A stale fire of an OLDER incarnation (due T+5) arriving late: dead-end, deadline kept.
|
||||
var stale = engine.Reduce(state, MakeSignal(3, DecisionSignalKind.DeadlineFired, T0.AddMinutes(12),
|
||||
FiredPayload(DeadlineNames.DeviceOnlyEspDetection, T0.AddMinutes(5))));
|
||||
Assert.False(stale.Transition.Taken);
|
||||
Assert.Equal("device_only_esp_detection_stale_due_at_mismatch", stale.Transition.DeadEndReason);
|
||||
Assert.Single(stale.NewState.Deadlines, d => d.Name == DeadlineNames.DeviceOnlyEspDetection);
|
||||
|
||||
// The real fire, 4 min late (standby), carries the armed due time: terminal.
|
||||
var real = engine.Reduce(stale.NewState, MakeSignal(4, DecisionSignalKind.DeadlineFired, T0.AddMinutes(12),
|
||||
FiredPayload(DeadlineNames.DeviceOnlyEspDetection, armed.DueAtUtc)));
|
||||
Assert.True(real.Transition.Taken);
|
||||
Assert.Equal(SessionStage.Completed, real.NewState.Stage);
|
||||
}
|
||||
|
||||
// ============================================================== RealmJoin re-arm guard
|
||||
|
||||
[Fact]
|
||||
public void RealmJoin_rearm_guard_compares_the_payload_due_time_not_the_firing_clock()
|
||||
{
|
||||
var engine = new DecisionEngine();
|
||||
var state = DecisionState.CreateInitial("rj-late", "t", T0);
|
||||
state = engine.Reduce(state, MakeSignal(0, DecisionSignalKind.SessionStarted, T0)).NewState;
|
||||
state = engine.Reduce(state, MakeSignal(1, DecisionSignalKind.EspPhaseChanged, T0.AddMinutes(1),
|
||||
new Dictionary<string, string> { [SignalPayloadKeys.EspPhase] = "DeviceSetup" })).NewState;
|
||||
state = engine.Reduce(state, MakeSignal(2, DecisionSignalKind.EspPhaseChanged, T0.AddMinutes(2),
|
||||
new Dictionary<string, string> { [SignalPayloadKeys.EspPhase] = "AccountSetup" })).NewState;
|
||||
state = engine.Reduce(state, MakeSignal(3, DecisionSignalKind.EspExiting, T0.AddMinutes(3))).NewState;
|
||||
state = engine.Reduce(state, MakeSignal(4, DecisionSignalKind.HelloResolved, T0.AddMinutes(4),
|
||||
new Dictionary<string, string> { [SignalPayloadKeys.HelloOutcome] = "Success" })).NewState;
|
||||
state = engine.Reduce(state, MakeSignal(5, DecisionSignalKind.RealmJoinDetected, T0.AddMinutes(5),
|
||||
new Dictionary<string, string> { [DecisionEngine.RealmJoinPayloadKeys.DeploymentPhase] = "100" })).NewState;
|
||||
state = engine.Reduce(state, MakeSignal(6, DecisionSignalKind.DesktopArrived, T0.AddMinutes(6))).NewState;
|
||||
var first = Assert.Single(state.Deadlines, d => d.Name == DeadlineNames.RealmJoinTimeout);
|
||||
|
||||
// Simulate the activity-based re-arm: the armed incarnation is now due later.
|
||||
var rearmedDue = first.DueAtUtc.AddMinutes(25);
|
||||
var rearmed = state.ToBuilder()
|
||||
.CancelDeadline(DeadlineNames.RealmJoinTimeout)
|
||||
.AddDeadline(new ActiveDeadline(
|
||||
name: DeadlineNames.RealmJoinTimeout,
|
||||
dueAtUtc: rearmedDue,
|
||||
firesSignalKind: DecisionSignalKind.DeadlineFired,
|
||||
firesPayload: new Dictionary<string, string> { [SignalPayloadKeys.Deadline] = DeadlineNames.RealmJoinTimeout }))
|
||||
.Build();
|
||||
|
||||
// The OLD incarnation's fire arrives late — after the re-armed due time on the clock.
|
||||
// Only the payload due time identifies it as superseded.
|
||||
var firedAt = rearmedDue.AddMinutes(1);
|
||||
var stale = engine.Reduce(rearmed, MakeSignal(7, DecisionSignalKind.DeadlineFired, firedAt,
|
||||
FiredPayload(DeadlineNames.RealmJoinTimeout, first.DueAtUtc)));
|
||||
Assert.False(stale.Transition.Taken);
|
||||
Assert.Equal("realmjoin_timeout_stale_superseded_by_rearm", stale.Transition.DeadEndReason);
|
||||
Assert.Null(stale.NewState.RealmJoinFacts.Outcome);
|
||||
|
||||
// The re-armed incarnation's own fire, same firing clock: timeout is applied.
|
||||
var real = engine.Reduce(stale.NewState, MakeSignal(8, DecisionSignalKind.DeadlineFired, firedAt,
|
||||
FiredPayload(DeadlineNames.RealmJoinTimeout, rearmedDue)));
|
||||
Assert.True(real.Transition.Taken);
|
||||
Assert.Equal("Timeout", real.NewState.RealmJoinFacts.Outcome!.Value);
|
||||
Assert.Equal(SessionStage.Finalizing, real.NewState.Stage);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -706,7 +706,7 @@ namespace AutopilotMonitor.DecisionCore.Tests
|
||||
var deadline = Assert.Single(signalStep.NewState.Deadlines, d => d.Name == DeadlineNames.DeviceOnlyEspDetection);
|
||||
Assert.Equal(T0.AddMinutes(7), deadline.DueAtUtc);
|
||||
|
||||
// DeadlineFired (OccurredAtUtc = DueAtUtc per scheduler contract) → terminal.
|
||||
// DeadlineFired at the due time (no payload due key → helper falls back to the signal time) → terminal.
|
||||
var step = engine.Reduce(signalStep.NewState, MakeSignal(3, DecisionSignalKind.DeadlineFired, T0.AddMinutes(7),
|
||||
new Dictionary<string, string> { [SignalPayloadKeys.Deadline] = DeadlineNames.DeviceOnlyEspDetection }));
|
||||
|
||||
|
||||
@@ -443,8 +443,9 @@ namespace AutopilotMonitor.DecisionCore.Tests
|
||||
{
|
||||
// Cancel-then-rearm race: old deadline (DueAt=T+8) fires queued; before processing,
|
||||
// DeviceSetupProvisioningComplete arrives (signal at T+10) → cancel+rearm to DueAt=T+15.
|
||||
// The queued OLD fire (OccurredAtUtc=T+8) arrives. Guard C must dead-end WITHOUT
|
||||
// cancelling the new deadline.
|
||||
// The queued OLD fire arrives carrying its due time T+8 (no payload key here, so the
|
||||
// helper falls back to the signal time). Guard C must dead-end WITHOUT cancelling the
|
||||
// new deadline.
|
||||
var engine = new DecisionEngine();
|
||||
var state = PrimeDeviceSetup(engine, DecisionState.CreateInitial("sd-11", "t", T0));
|
||||
|
||||
@@ -467,7 +468,7 @@ namespace AutopilotMonitor.DecisionCore.Tests
|
||||
firesPayload: new Dictionary<string, string> { [SignalPayloadKeys.Deadline] = DeadlineNames.DeviceOnlyEspDetection }));
|
||||
state = rearmedBuilder.Build();
|
||||
|
||||
// OLD queued fire arrives with OccurredAtUtc=T+8 — mismatches new deadline at T+15.
|
||||
// OLD queued fire arrives with due time T+8 — mismatches the new deadline at T+15.
|
||||
var step = engine.Reduce(state, MakeSignal(99, DecisionSignalKind.DeadlineFired, T0.AddMinutes(8),
|
||||
new Dictionary<string, string> { [SignalPayloadKeys.Deadline] = DeadlineNames.DeviceOnlyEspDetection }));
|
||||
|
||||
|
||||
@@ -54,6 +54,37 @@ namespace AutopilotMonitor.DecisionCore.Tests
|
||||
Assert.Equal("AccountSetup", roundtripped.Payload!["phase"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SignalSerializer_roundtrip_keeps_date_like_payload_strings_verbatim()
|
||||
{
|
||||
// The shared reader tokenizes ISO-8601 strings as dates; the string dictionaries must
|
||||
// still come back as the round-trip text the writer produced, never culture-formatted
|
||||
// (the DeadlineFired due time is parsed back with the "o" format on replay).
|
||||
var due = new DateTime(2026, 4, 20, 9, 55, 0, DateTimeKind.Utc);
|
||||
var original = new DecisionSignal(
|
||||
sessionSignalOrdinal: 7,
|
||||
sessionTraceOrdinal: 7,
|
||||
kind: DecisionSignalKind.DeadlineFired,
|
||||
kindSchemaVersion: 1,
|
||||
occurredAtUtc: due.AddMinutes(5),
|
||||
sourceOrigin: "DeadlineScheduler",
|
||||
evidence: new Evidence(
|
||||
kind: EvidenceKind.Synthetic,
|
||||
identifier: "hello_safety",
|
||||
summary: "deadline fired",
|
||||
derivationInputs: new Dictionary<string, string> { ["armedAt"] = "2026-04-20T09:50:00.0000000Z" }),
|
||||
payload: new Dictionary<string, string>
|
||||
{
|
||||
["deadline"] = "hello_safety",
|
||||
["deadlineDueAtUtc"] = due.ToString("O"),
|
||||
});
|
||||
|
||||
var roundtripped = SignalSerializer.Deserialize(SignalSerializer.Serialize(original));
|
||||
|
||||
Assert.Equal("2026-04-20T09:55:00.0000000Z", roundtripped.Payload!["deadlineDueAtUtc"]);
|
||||
Assert.Equal("2026-04-20T09:50:00.0000000Z", roundtripped.Evidence.DerivationInputs!["armedAt"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SignalSerializer_Deserialize_MissingEvidence_throws()
|
||||
{
|
||||
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using AutopilotMonitor.Functions.Functions.Rules;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Azure.Core.Serialization;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Analyze twin of <see cref="GatherRulesFunctionAuthorEndpointTests"/>: the rule Author is
|
||||
/// stamped from the caller's JWT on create, on a PUT-upsert of an unknown rule and on the
|
||||
/// template copy, and a true update keeps the original creator over editor and body.
|
||||
/// Before this pin, custom analyze rules were created as "Autopilot Monitor" and the edit
|
||||
/// path let the browser choose the author.
|
||||
/// </summary>
|
||||
public class AnalyzeRulesFunctionAuthorEndpointTests
|
||||
{
|
||||
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
|
||||
private const string RuleId = "ANALYZE-CUSTOM-777";
|
||||
private const string TemplateRuleId = "ANALYZE-SEC-004";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private static FunctionContext BuildContext(ClaimsPrincipal? principal)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddOptions();
|
||||
services.Configure<WorkerOptions>(o => o.Serializer =
|
||||
new JsonObjectSerializer(ApiJsonOptions.Create()));
|
||||
var provider = services.BuildServiceProvider();
|
||||
|
||||
var items = new Dictionary<object, object>();
|
||||
if (principal != null)
|
||||
{
|
||||
items["ClaimsPrincipal"] = principal;
|
||||
}
|
||||
|
||||
var context = new Mock<FunctionContext>();
|
||||
context.SetupGet(c => c.Items).Returns(items);
|
||||
context.SetupGet(c => c.InstanceServices).Returns(provider);
|
||||
return context.Object;
|
||||
}
|
||||
|
||||
private static HttpRequestData BuildRequest(ClaimsPrincipal? principal, object body)
|
||||
{
|
||||
var context = BuildContext(principal);
|
||||
var req = new Mock<HttpRequestData>(context);
|
||||
req.SetupGet(r => r.Headers).Returns(new HttpHeadersCollection());
|
||||
req.SetupGet(r => r.Body).Returns(
|
||||
new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(body))));
|
||||
req.Setup(r => r.CreateResponse()).Returns(() => new FakeHttpResponseData(context));
|
||||
return req.Object;
|
||||
}
|
||||
|
||||
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 ClaimsPrincipal AlicePrincipal()
|
||||
=> Principal(("tid", TenantId), ("name", "Alice Admin"), ("upn", "alice@contoso.com"));
|
||||
|
||||
private static (AnalyzeRulesFunction function, List<AnalyzeRule> stored) BuildFunction(
|
||||
AnalyzeRule? existingTenantRule = null, AnalyzeRule? globalRule = null)
|
||||
{
|
||||
var repo = new Mock<IRuleRepository>(MockBehavior.Loose);
|
||||
var stored = new List<AnalyzeRule>();
|
||||
|
||||
repo.Setup(r => r.AnalyzeRuleExistsAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(false);
|
||||
repo.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(
|
||||
globalRule == null ? new List<AnalyzeRule>() : new List<AnalyzeRule> { globalRule });
|
||||
repo.Setup(r => r.GetAnalyzeRulesAsync(TenantId)).ReturnsAsync(
|
||||
existingTenantRule == null ? new List<AnalyzeRule>() : new List<AnalyzeRule> { existingTenantRule });
|
||||
repo.Setup(r => r.GetRuleStatesAsync(TenantId)).ReturnsAsync(new Dictionary<string, RuleState>());
|
||||
repo.Setup(r => r.StoreRuleStateAsync(TenantId, It.IsAny<string>(), It.IsAny<RuleState>())).ReturnsAsync(true);
|
||||
repo.Setup(r => r.StoreAnalyzeRuleAsync(It.IsAny<AnalyzeRule>(), TenantId))
|
||||
.Callback<AnalyzeRule, string>((rule, _) => stored.Add(rule))
|
||||
.ReturnsAsync(true);
|
||||
|
||||
var service = new AnalyzeRuleService(repo.Object, NullLogger<AnalyzeRuleService>.Instance);
|
||||
return (new AnalyzeRulesFunction(NullLogger<AnalyzeRulesFunction>.Instance, service), stored);
|
||||
}
|
||||
|
||||
private static AnalyzeRule SpoofedPayload() => new()
|
||||
{
|
||||
RuleId = RuleId,
|
||||
Title = "Proxy PAC unreachable",
|
||||
Description = "Custom",
|
||||
Severity = "warning",
|
||||
Category = "network",
|
||||
Explanation = "The PAC file could not be fetched.",
|
||||
IsBuiltIn = false,
|
||||
IsCommunity = false,
|
||||
Enabled = true,
|
||||
Author = "Spoofed Author",
|
||||
Conditions = new List<RuleCondition>
|
||||
{
|
||||
new() { Signal = "pac_failed", Source = "event_type", EventType = "network_pac_failed", Required = true }
|
||||
},
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task CreateRule_stamps_author_from_jwt_not_from_body()
|
||||
{
|
||||
var (function, stored) = BuildFunction();
|
||||
var req = BuildRequest(AlicePrincipal(), SpoofedPayload());
|
||||
|
||||
var response = await function.CreateRule(req);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var written = Assert.Single(stored);
|
||||
Assert.Equal("Alice Admin", written.Author);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateRule_falls_back_to_product_name_without_identifying_claims()
|
||||
{
|
||||
var (function, stored) = BuildFunction();
|
||||
var req = BuildRequest(Principal(("tid", TenantId)), SpoofedPayload());
|
||||
|
||||
var response = await function.CreateRule(req);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var written = Assert.Single(stored);
|
||||
Assert.Equal("Autopilot Monitor", written.Author);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateRule_upsert_of_unknown_rule_stamps_author_from_jwt()
|
||||
{
|
||||
var (function, stored) = BuildFunction(existingTenantRule: null);
|
||||
var req = BuildRequest(AlicePrincipal(), SpoofedPayload());
|
||||
|
||||
var response = await function.UpdateRule(req, RuleId);
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var written = Assert.Single(stored);
|
||||
Assert.Equal("Alice Admin", written.Author);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateRule_true_update_keeps_original_author_over_editor_and_body()
|
||||
{
|
||||
var existing = SpoofedPayload();
|
||||
existing.Author = "Original Creator";
|
||||
existing.CreatedAt = new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc);
|
||||
var (function, stored) = BuildFunction(existing);
|
||||
var req = BuildRequest(
|
||||
Principal(("tid", TenantId), ("name", "Bob Editor")), SpoofedPayload());
|
||||
|
||||
var response = await function.UpdateRule(req, RuleId);
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var written = Assert.Single(stored);
|
||||
Assert.Equal("Original Creator", written.Author);
|
||||
Assert.Equal(existing.CreatedAt, written.CreatedAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateFromTemplate_stamps_the_copying_admin_not_the_template_author()
|
||||
{
|
||||
var template = new AnalyzeRule
|
||||
{
|
||||
RuleId = TemplateRuleId,
|
||||
Title = "AutoLogon enabled for an unexpected user",
|
||||
Description = "Template",
|
||||
Severity = "warning",
|
||||
Category = "security",
|
||||
Explanation = "Template",
|
||||
IsBuiltIn = true,
|
||||
Author = "Autopilot Monitor",
|
||||
Conditions = new List<RuleCondition>
|
||||
{
|
||||
new() { Signal = "autologon", Source = "event_type", EventType = "autologon_analysis", Operator = "equals", Value = "PLACEHOLDER", Required = true }
|
||||
},
|
||||
TemplateVariables = new List<TemplateVariable>
|
||||
{
|
||||
new() { Name = "allowed", Label = "Allowed", ConditionIndex = 0, Field = "value" }
|
||||
},
|
||||
};
|
||||
var (function, stored) = BuildFunction(globalRule: template);
|
||||
var req = BuildRequest(AlicePrincipal(), new { variables = new Dictionary<string, string> { ["allowed"] = "KIOSK-1" } });
|
||||
|
||||
var response = await function.CreateFromTemplate(req, TemplateRuleId);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var written = Assert.Single(stored);
|
||||
Assert.Equal("Alice Admin", written.Author);
|
||||
Assert.Equal(TemplateRuleId, written.DerivedFromTemplateRuleId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using Azure.Data.Tables;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Observation-end closure of app rows: a row still InProgress when the session's observation
|
||||
/// ended becomes "Incomplete" (terminal, non-failure, outcome unknown). Pins the pure per-row
|
||||
/// predicate behind <see cref="TableStorageService.CloseOpenAppInstallsForSessionAsync"/> and
|
||||
/// the disclosed bucket in the app-metrics payload.
|
||||
/// </summary>
|
||||
public class AppInstallIncompleteCloseTests
|
||||
{
|
||||
private static TableEntity Row(string? status, DateTimeOffset? completedAt = null)
|
||||
{
|
||||
var row = new TableEntity("tenant", "session_App");
|
||||
if (status != null) row["Status"] = status;
|
||||
if (completedAt.HasValue) row["CompletedAt"] = completedAt.Value;
|
||||
return row;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("InProgress")]
|
||||
[InlineData("")]
|
||||
[InlineData(null)]
|
||||
public void ShouldClose_OpenRow(string? status)
|
||||
=> Assert.True(TableStorageService.ShouldCloseAsIncomplete(Row(status)));
|
||||
|
||||
[Theory]
|
||||
[InlineData("Succeeded")]
|
||||
[InlineData("Failed")]
|
||||
[InlineData("Incomplete")]
|
||||
public void ShouldClose_LeavesTerminalRowsAlone(string status)
|
||||
=> Assert.False(TableStorageService.ShouldCloseAsIncomplete(Row(status)));
|
||||
|
||||
[Fact]
|
||||
public void ShouldClose_NeverClosesARowWithAnEnd()
|
||||
{
|
||||
// Out-of-order arrival can leave a CompletedAt on a row whose status batch is late —
|
||||
// an end is an end.
|
||||
Assert.False(TableStorageService.ShouldCloseAsIncomplete(Row("InProgress", DateTimeOffset.UtcNow)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AppMetrics_DisclosesIncompleteOutsideTheRate()
|
||||
{
|
||||
var payload = MetricsMath.BuildAppMetricsPayload(new[]
|
||||
{
|
||||
new AppInstallSummary { AppName = "App", Status = "Succeeded", TerminalState = "Installed", DurationSeconds = 30 },
|
||||
new AppInstallSummary { AppName = "App", Status = "Failed", TerminalState = "Error", DurationSeconds = 30 },
|
||||
new AppInstallSummary { AppName = "App", Status = "Incomplete" },
|
||||
});
|
||||
|
||||
var group = Assert.Single(payload.TopFailingApps);
|
||||
Assert.Equal(3, group.TotalInstalls);
|
||||
Assert.Equal(1, group.Incomplete);
|
||||
Assert.Equal(50.0, group.FailureRate);
|
||||
Assert.Equal(1, payload.TotalIncomplete);
|
||||
}
|
||||
}
|
||||
+24
@@ -155,6 +155,30 @@ public class AppInstallTerminalStateAndReconcileTests
|
||||
Assert.Equal("Succeeded", summary.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_IncompleteIsSticky_AgainstLateProgressBatch()
|
||||
{
|
||||
// Closed by the observation-end step; a straggling started/progress batch must not reopen it.
|
||||
var existing = new TableEntity("tenant", "session_App") { ["Status"] = "Incomplete" };
|
||||
var summary = new AppInstallSummary { AppName = "App", Status = "InProgress", StartedAt = T0 };
|
||||
|
||||
TableStorageService.ReconcileAppInstallSummaryWithExisting(summary, existing);
|
||||
|
||||
Assert.Equal("Incomplete", summary.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_RealTerminalOverridesIncomplete()
|
||||
{
|
||||
// The completion arrived after the close step: real evidence beats the hedge.
|
||||
var existing = new TableEntity("tenant", "session_App") { ["Status"] = "Incomplete" };
|
||||
var summary = new AppInstallSummary { AppName = "App", Status = "Succeeded", StartedAt = T0 };
|
||||
|
||||
TableStorageService.ReconcileAppInstallSummaryWithExisting(summary, existing);
|
||||
|
||||
Assert.Equal("Succeeded", summary.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reconcile_Q4Guard_DoesNotFireWithoutStoredCompletedAt()
|
||||
{
|
||||
|
||||
@@ -10,7 +10,7 @@ using Microsoft.Extensions.Logging.Abstractions;
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for <see cref="LatestVersionsService"/> — the 12h-cached reader for the
|
||||
/// Tests for <see cref="LatestVersionsService"/> — the short-TTL reader for the
|
||||
/// public <c>version.json</c> blob. Verifies cache hit/miss, forceRefresh bypass,
|
||||
/// and failure fallback without hammering the blob on every call.
|
||||
/// </summary>
|
||||
@@ -140,6 +140,28 @@ public class LatestVersionsServiceTests
|
||||
Assert.Equal(1, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_HttpFailure_AfterSuccess_ServesLastKnownGood()
|
||||
{
|
||||
var (svc, handler, _) = Create();
|
||||
|
||||
await svc.GetAsync(forceRefresh: false, CancellationToken.None);
|
||||
handler.Responder = _ => new HttpResponseMessage(HttpStatusCode.InternalServerError);
|
||||
|
||||
// The refresh fails, but the version line must not blank out: the last good
|
||||
// value stands until the blob answers again.
|
||||
var afterFailure = await svc.GetAsync(forceRefresh: true, CancellationToken.None);
|
||||
|
||||
Assert.NotNull(afterFailure);
|
||||
Assert.Equal("1.0.706", afterFailure!.AgentVersion);
|
||||
Assert.True(afterFailure.FromCache);
|
||||
|
||||
// ...and it is what the short failure cache serves to the next callers, too.
|
||||
var next = await svc.GetAsync(forceRefresh: false, CancellationToken.None);
|
||||
Assert.Equal("1.0.706", next!.AgentVersion);
|
||||
Assert.Equal(2, handler.CallCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAsync_MalformedJson_ReturnsNull()
|
||||
{
|
||||
|
||||
@@ -7,19 +7,21 @@ using Moq;
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pins ANALYZE-ESP-004 ("ESP Timeout with 'Continue Anyway' — Soft Failure").
|
||||
/// Pins ANALYZE-ESP-004 ("ESP Gave Up on a Blocking App with 'Continue Anyway' — Soft Failure").
|
||||
///
|
||||
/// Background (tenant c9787ba2, session cb7036a6): a slow blocking app (Encompass
|
||||
/// Hybrid Installer) does not finish inside the 30-min Device-ESP window, so the ESP
|
||||
/// fails terminally in DeviceSetup. The profile allows "Continue anyway", so the user
|
||||
/// most likely dismissed the failure screen and reached the desktop — but the agent
|
||||
/// only ever sees the terminal failure and the session is recorded as Failed. The
|
||||
/// DecisionEngine already stamps the enrollment_failed event with
|
||||
/// <c>mayHaveContinuedAnyway=true</c>; this rule turns that into a customer-visible
|
||||
/// "soft failure" advisory with the root-cause remediation.
|
||||
/// only ever sees the terminal failure and the session is recorded as Failed.
|
||||
///
|
||||
/// The rule keys ONLY on <c>mayHaveContinuedAnyway==true</c> (set exclusively on the
|
||||
/// ESP terminal-failure path), so an ordinary hard failure must not trip it.
|
||||
/// The rule needs THREE facts: the terminal enrollment_failed, the DecisionEngine's
|
||||
/// <c>mayHaveContinuedAnyway=true</c> stamp (profile allows the button), and the agent's own
|
||||
/// timeout verdict — an app_install_failed promoted with <c>failureType=esp_apps_timeout</c>
|
||||
/// (ESP gave up while the app was still installing, no per-app HRESULT). Session 683f1eff:
|
||||
/// an ESP failure with a real HRESULT (0x80070652, installer collision) on a Continue-anyway
|
||||
/// profile fired the rule and rendered the configured 90-min limit as if it had elapsed —
|
||||
/// the continue-anyway flag alone proves nothing about timing.
|
||||
/// </summary>
|
||||
public class RuleEngineEspSoftFailureTests
|
||||
{
|
||||
@@ -37,8 +39,9 @@ public class RuleEngineEspSoftFailureTests
|
||||
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
SettleStartedEvent(errorCode: null),
|
||||
EnrollmentFailedEvent(mayHaveContinuedAnyway: "true"),
|
||||
AppInstallFailed(),
|
||||
AppInstallFailed(failureType: "esp_apps_timeout"),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(rule, events);
|
||||
@@ -47,13 +50,15 @@ public class RuleEngineEspSoftFailureTests
|
||||
Assert.Equal("ANALYZE-ESP-004", result.RuleId);
|
||||
Assert.Equal("warning", result.Severity);
|
||||
|
||||
// Required gate matched on the continue-anyway flag.
|
||||
// Required gates: the continue-anyway flag AND the agent's timeout verdict.
|
||||
var gate = AsDict(result.MatchedConditions["may_have_continued"]);
|
||||
Assert.Equal("true", AsString(gate["value"]));
|
||||
var verdict = AsDict(result.MatchedConditions["esp_gave_up_on_app"]);
|
||||
Assert.Equal("esp_apps_timeout", AsString(verdict["value"]));
|
||||
|
||||
// Interpolation material for the explanation / remediation templates is present:
|
||||
// {{espSyncFailureTimeoutMinutes}}, {{failedSubcategory}} (from enrollment_failed)
|
||||
// and {{appName}} (from app_install_failed).
|
||||
// Interpolation material: {{espSyncFailureTimeoutMinutes}} (enrollment_failed),
|
||||
// {{failedSubcategory}} (esp_failure_settle_started — the terminal event drops it when
|
||||
// the Shell-Core failure wins the race) and {{appName}} (the promoted app).
|
||||
var timeout = AsDict(result.MatchedConditions["espSyncFailureTimeoutMinutes"]);
|
||||
Assert.Equal("30", AsString(timeout["value"]));
|
||||
|
||||
@@ -65,6 +70,48 @@ public class RuleEngineEspSoftFailureTests
|
||||
Assert.Equal(FailedAppName, AsString(failedApp["value"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ANALYZE_ESP_004_stays_silent_on_a_hard_failure_with_continue_anyway()
|
||||
{
|
||||
// Session 683f1eff: continue-anyway profile, but the ESP failed on a real installer
|
||||
// error (0x80070652 / MSI 1618) after 19 minutes. The failed app carries no
|
||||
// esp_apps_timeout verdict — the rule must not turn an installer collision into
|
||||
// "the ESP reached its 90-min timeout".
|
||||
var rule = BuiltInAnalyzeRules.GetAll().First(r => r.RuleId == "ANALYZE-ESP-004");
|
||||
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
SettleStartedEvent(errorCode: "0x80070652"),
|
||||
EnrollmentFailedEvent(mayHaveContinuedAnyway: "true"),
|
||||
AppInstallFailed(failureType: null, exitCodeClass: "Retry"),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(rule, events);
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ANALYZE_ESP_004_names_the_timed_out_app_not_another_failed_one()
|
||||
{
|
||||
// Two failed apps: one hard installer failure earlier in the run, one promoted
|
||||
// esp_apps_timeout at the terminal. {{appName}} must be the timed-out app.
|
||||
var rule = BuiltInAnalyzeRules.GetAll().First(r => r.RuleId == "ANALYZE-ESP-004");
|
||||
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
AppInstallFailed(failureType: null, exitCodeClass: "Failed", appName: "Contoso Agent", sequence: 100),
|
||||
SettleStartedEvent(errorCode: null),
|
||||
EnrollmentFailedEvent(mayHaveContinuedAnyway: "true"),
|
||||
AppInstallFailed(failureType: "esp_apps_timeout"),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(rule, events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
var failedApp = AsDict(result.MatchedConditions["appName"]);
|
||||
Assert.Equal(FailedAppName, AsString(failedApp["value"]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ANALYZE_ESP_004_does_not_fire_when_continue_anyway_is_false()
|
||||
{
|
||||
@@ -75,7 +122,7 @@ public class RuleEngineEspSoftFailureTests
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
EnrollmentFailedEvent(mayHaveContinuedAnyway: "false"),
|
||||
AppInstallFailed(),
|
||||
AppInstallFailed(failureType: "esp_apps_timeout"),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(rule, events);
|
||||
@@ -92,7 +139,7 @@ public class RuleEngineEspSoftFailureTests
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
EnrollmentFailedEvent(mayHaveContinuedAnyway: null),
|
||||
AppInstallFailed(),
|
||||
AppInstallFailed(failureType: "esp_apps_timeout"),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(rule, events);
|
||||
@@ -132,23 +179,61 @@ public class RuleEngineEspSoftFailureTests
|
||||
return data;
|
||||
}
|
||||
|
||||
private static EnrollmentEvent AppInstallFailed() => new()
|
||||
private static EnrollmentEvent SettleStartedEvent(string? errorCode)
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
EventType = "app_install_failed",
|
||||
Timestamp = DateTime.UtcNow,
|
||||
Sequence = 220,
|
||||
Data = new Dictionary<string, object>
|
||||
var data = new Dictionary<string, object>
|
||||
{
|
||||
["appName"] = FailedAppName,
|
||||
["category"] = "DeviceSetup",
|
||||
["failedSubcategory"] = "Certificates",
|
||||
["failureType"] = "Provisioning_DeviceSetup_Certificates_Failed",
|
||||
["settleSeconds"] = 30,
|
||||
["reason"] = "wait_for_late_ime_signals",
|
||||
};
|
||||
if (errorCode != null)
|
||||
data["errorCode"] = errorCode;
|
||||
return new EnrollmentEvent
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
EventType = "esp_failure_settle_started",
|
||||
Timestamp = DateTime.UtcNow,
|
||||
Sequence = 212,
|
||||
Data = data,
|
||||
};
|
||||
}
|
||||
|
||||
private static EnrollmentEvent AppInstallFailed(
|
||||
string? failureType,
|
||||
string? exitCodeClass = null,
|
||||
string appName = FailedAppName,
|
||||
int sequence = 220)
|
||||
{
|
||||
var data = new Dictionary<string, object>
|
||||
{
|
||||
["appName"] = appName,
|
||||
["state"] = "Error",
|
||||
["targeted"] = "Device",
|
||||
["failureType"] = "esp_apps_timeout",
|
||||
["errorDetail"] = "Install status unconfirmed — ESP gave up while this app was still installing.",
|
||||
};
|
||||
if (failureType != null)
|
||||
{
|
||||
data["failureType"] = failureType;
|
||||
data["confidence"] = "presumed";
|
||||
data["errorDetail"] = "Install status unconfirmed — ESP gave up while this app was still installing.";
|
||||
}
|
||||
};
|
||||
if (exitCodeClass != null)
|
||||
data["exitCodeClass"] = exitCodeClass;
|
||||
return new EnrollmentEvent
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
SessionId = SessionId,
|
||||
EventType = "app_install_failed",
|
||||
Timestamp = DateTime.UtcNow,
|
||||
Sequence = sequence,
|
||||
Data = data,
|
||||
};
|
||||
}
|
||||
|
||||
private static Dictionary<string, object> AsDict(object o)
|
||||
{
|
||||
|
||||
+116
-12
@@ -7,12 +7,17 @@ using Moq;
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the absence gate on <c>event_type</c> conditions: <c>not_exists</c> without a
|
||||
/// <c>dataField</c> matches when no event of that type occurs in the session and is disproved by
|
||||
/// a single such event. Before this branch an absent type always evaluated false, so a required
|
||||
/// "must not have happened" condition could never be expressed (ANALYZE-ID-004 v2 relies on it).
|
||||
/// The dataField variant keeps its historical meaning (some event of the type has an empty field)
|
||||
/// and is not touched here.
|
||||
/// Pins the absence gates on conditions.
|
||||
///
|
||||
/// Without a <c>dataField</c>, <c>not_exists</c> matches when no event of that type occurs in
|
||||
/// the session and is disproved by a single such event (ANALYZE-ID-004 v2 relies on it).
|
||||
///
|
||||
/// With a <c>dataField</c>, <c>not_exists</c> matches when no event of the type carries a
|
||||
/// non-empty value at that field — including when the type is absent — and is disproved by a
|
||||
/// single non-empty value; on <c>event_data</c> the same-event filter narrows the inspected set
|
||||
/// first. Before this the per-event loop's null short-circuit rejected a missing field before
|
||||
/// the operator ever ran, so "the ESP failure carried no HRESULT" (session 683f1eff) could not be
|
||||
/// expressed at all, while the precondition gate already had the absence semantics.
|
||||
/// </summary>
|
||||
public class RuleEngineEventTypeNotExistsTests
|
||||
{
|
||||
@@ -24,7 +29,7 @@ public class RuleEngineEventTypeNotExistsTests
|
||||
{
|
||||
var events = new List<EnrollmentEvent> { Event("marker_seen", 1) };
|
||||
|
||||
var outcome = await RunAsync(Rule(), events);
|
||||
var outcome = await RunAsync(TypeAbsenceRule(), events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
var evidence = Assert.IsType<Dictionary<string, object>>(result.MatchedConditions["disproof_absent"]);
|
||||
@@ -37,12 +42,111 @@ public class RuleEngineEventTypeNotExistsTests
|
||||
{
|
||||
var events = new List<EnrollmentEvent> { Event("marker_seen", 1), Event("disproof", 2) };
|
||||
|
||||
var outcome = await RunAsync(Rule(), events);
|
||||
var outcome = await RunAsync(TypeAbsenceRule(), events);
|
||||
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
private static AnalyzeRule Rule() => new()
|
||||
[Fact]
|
||||
public async Task Field_not_exists_matches_when_no_event_carries_the_field()
|
||||
{
|
||||
// The event type is present, the field is not — the shape of an ESP failure without an
|
||||
// HRESULT (esp_failure_settle_started without errorCode).
|
||||
var events = new List<EnrollmentEvent> { Event("marker_seen", 1), Event("disproof", 2) };
|
||||
|
||||
var outcome = await RunAsync(FieldAbsenceRule("event_type"), events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
var evidence = Assert.IsType<Dictionary<string, object>>(result.MatchedConditions["code_absent"]);
|
||||
Assert.Equal("disproof", evidence["eventType"]);
|
||||
Assert.Equal("errorCode", evidence["field"]);
|
||||
Assert.Equal(1, evidence["count"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Field_not_exists_matches_when_the_event_type_is_absent()
|
||||
{
|
||||
var events = new List<EnrollmentEvent> { Event("marker_seen", 1) };
|
||||
|
||||
var outcome = await RunAsync(FieldAbsenceRule("event_type"), events);
|
||||
|
||||
var result = Assert.Single(outcome.Results);
|
||||
var evidence = Assert.IsType<Dictionary<string, object>>(result.MatchedConditions["code_absent"]);
|
||||
Assert.Equal(0, evidence["count"]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("event_type")]
|
||||
[InlineData("event_data")]
|
||||
public async Task A_non_empty_value_on_any_event_vetoes_a_required_field_not_exists(string source)
|
||||
{
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
Event("marker_seen", 1),
|
||||
Event("disproof", 2),
|
||||
Event("disproof", 3, ("errorCode", "0x80070652")),
|
||||
};
|
||||
|
||||
var outcome = await RunAsync(FieldAbsenceRule(source), events);
|
||||
|
||||
Assert.Empty(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_empty_string_does_not_count_as_a_carried_value()
|
||||
{
|
||||
var events = new List<EnrollmentEvent> { Event("marker_seen", 1), Event("disproof", 2, ("errorCode", "")) };
|
||||
|
||||
var outcome = await RunAsync(FieldAbsenceRule("event_type"), events);
|
||||
|
||||
Assert.Single(outcome.Results);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Event_data_field_not_exists_inspects_only_the_filtered_events()
|
||||
{
|
||||
// The carrier of the field is filtered out (kind=a); among kind=b events nobody carries it.
|
||||
var events = new List<EnrollmentEvent>
|
||||
{
|
||||
Event("marker_seen", 1),
|
||||
Event("disproof", 2, ("kind", "a"), ("errorCode", "0x80070652")),
|
||||
Event("disproof", 3, ("kind", "b")),
|
||||
};
|
||||
|
||||
var matched = await RunAsync(FieldAbsenceRule("event_data", filterKind: "b"), events);
|
||||
var result = Assert.Single(matched.Results);
|
||||
var evidence = Assert.IsType<Dictionary<string, object>>(result.MatchedConditions["code_absent"]);
|
||||
Assert.Equal(1, evidence["count"]);
|
||||
|
||||
var vetoed = await RunAsync(FieldAbsenceRule("event_data", filterKind: "a"), events);
|
||||
Assert.Empty(vetoed.Results);
|
||||
}
|
||||
|
||||
private static AnalyzeRule TypeAbsenceRule() => Rule(
|
||||
new RuleCondition { Signal = "disproof_absent", Source = "event_type", EventType = "disproof", Operator = "not_exists", Value = "", Required = true });
|
||||
|
||||
private static AnalyzeRule FieldAbsenceRule(string source, string? filterKind = null)
|
||||
{
|
||||
var absence = new RuleCondition
|
||||
{
|
||||
Signal = "code_absent",
|
||||
Source = source,
|
||||
EventType = "disproof",
|
||||
DataField = "errorCode",
|
||||
Operator = "not_exists",
|
||||
Value = "",
|
||||
Required = true,
|
||||
};
|
||||
if (filterKind != null)
|
||||
{
|
||||
absence.FilterField = "kind";
|
||||
absence.FilterOperator = "equals";
|
||||
absence.FilterValue = filterKind;
|
||||
}
|
||||
return Rule(absence);
|
||||
}
|
||||
|
||||
private static AnalyzeRule Rule(RuleCondition absence) => new()
|
||||
{
|
||||
// Custom-namespace rule: a built-in ID outside the live catalog is hidden by the
|
||||
// sunset filter in AnalyzeRuleService (IsBuiltIn defaults to true).
|
||||
@@ -58,11 +162,11 @@ public class RuleEngineEventTypeNotExistsTests
|
||||
Conditions = new List<RuleCondition>
|
||||
{
|
||||
new() { Signal = "marker", Source = "event_type", EventType = "marker_seen", Operator = "exists", Value = "", Required = true },
|
||||
new() { Signal = "disproof_absent", Source = "event_type", EventType = "disproof", Operator = "not_exists", Value = "", Required = true },
|
||||
absence,
|
||||
},
|
||||
};
|
||||
|
||||
private static EnrollmentEvent Event(string eventType, int sequence) => new()
|
||||
private static EnrollmentEvent Event(string eventType, int sequence, params (string key, string value)[] data) => new()
|
||||
{
|
||||
EventId = Guid.NewGuid().ToString(),
|
||||
TenantId = TenantId,
|
||||
@@ -70,7 +174,7 @@ public class RuleEngineEventTypeNotExistsTests
|
||||
EventType = eventType,
|
||||
Timestamp = DateTime.UtcNow.AddMinutes(sequence),
|
||||
Sequence = sequence,
|
||||
Data = new Dictionary<string, object>(),
|
||||
Data = data.ToDictionary(d => d.key, d => (object)d.value),
|
||||
};
|
||||
|
||||
private static async Task<AnalysisOutcome> RunAsync(AnalyzeRule rule, List<EnrollmentEvent> events)
|
||||
|
||||
@@ -0,0 +1,530 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The pure pieces of <see cref="RuleSubmissionService"/> (id suggestion, repo file, snapshot
|
||||
/// stripping, attribution shape) and the review state machine against mocked repositories.
|
||||
/// </summary>
|
||||
public class RuleSubmissionServiceTests
|
||||
{
|
||||
private const string TenantId = "11111111-1111-1111-1111-111111111111";
|
||||
|
||||
// ── id suggestion ───────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Suggest_is_max_plus_one_and_never_fills_a_gap()
|
||||
{
|
||||
// 001 and 003 exist, 002 is a retired id — the next is 004, not 002.
|
||||
var taken = new[] { "ANALYZE-NET-001", "ANALYZE-NET-003", "ANALYZE-APP-018", "GATHER-NET-009" };
|
||||
Assert.Equal("ANALYZE-NET-004", RuleSubmissionService.SuggestPublishedRuleId("analyze", "network", taken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Suggest_starts_at_001_for_an_empty_category_and_maps_the_kind_convention()
|
||||
{
|
||||
Assert.Equal("ANALYZE-NET-001", RuleSubmissionService.SuggestPublishedRuleId("analyze", "network", Array.Empty<string>()));
|
||||
Assert.Equal("GATHER-DEVICE-001", RuleSubmissionService.SuggestPublishedRuleId("gather", "device", Array.Empty<string>()));
|
||||
Assert.Equal("ANALYZE-DEV-001", RuleSubmissionService.SuggestPublishedRuleId("analyze", "device", Array.Empty<string>()));
|
||||
Assert.Equal("ANALYZE-ENRL-001", RuleSubmissionService.SuggestPublishedRuleId("analyze", "enrollment", Array.Empty<string>()));
|
||||
Assert.Equal("GATHER-ENROLL-001", RuleSubmissionService.SuggestPublishedRuleId("gather", "enrollment", Array.Empty<string>()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Suggest_is_case_insensitive_over_taken_ids()
|
||||
{
|
||||
Assert.Equal("ANALYZE-SEC-008", RuleSubmissionService.SuggestPublishedRuleId("analyze", "security", new[] { "analyze-sec-007" }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Suggest_falls_back_to_the_upper_cased_category_when_unmapped()
|
||||
{
|
||||
Assert.Equal("ANALYZE-OFFICE-001", RuleSubmissionService.SuggestPublishedRuleId("analyze", "office", Array.Empty<string>()));
|
||||
}
|
||||
|
||||
// ── freeze + repo file ──────────────────────────────────────────────────
|
||||
|
||||
private static AnalyzeRule CustomAnalyzeRule() => new()
|
||||
{
|
||||
RuleId = "ANALYZE-CUSTOM-003",
|
||||
Title = "Proxy PAC unreachable",
|
||||
Description = "PAC download fails",
|
||||
Severity = "warning",
|
||||
Category = "network",
|
||||
Version = "1.2.0",
|
||||
Author = "Alice Admin",
|
||||
Enabled = false,
|
||||
IsBuiltIn = false,
|
||||
IsCommunity = false,
|
||||
Provenance = "embedded",
|
||||
MarkSessionAsFailed = true,
|
||||
Notify = true,
|
||||
NotifyChannelIds = new List<string> { "chan-1" },
|
||||
DerivedFromTemplateRuleId = "ANALYZE-SEC-004",
|
||||
Explanation = "The PAC file could not be fetched.",
|
||||
Conditions = new List<RuleCondition>
|
||||
{
|
||||
new() { Signal = "pac_failed", Source = "event_type", EventType = "network_pac_failed", Required = true },
|
||||
},
|
||||
CreatedAt = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc),
|
||||
UpdatedAt = new DateTime(2026, 2, 1, 0, 0, 0, DateTimeKind.Utc),
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Freeze_strips_server_and_tenant_fields_and_keeps_the_rule()
|
||||
{
|
||||
var json = RuleSubmissionService.FreezeRule(CustomAnalyzeRule());
|
||||
var node = JsonNode.Parse(json)!.AsObject();
|
||||
|
||||
foreach (var stripped in new[] { "isBuiltIn", "provenance", "createdAt", "updatedAt", "markSessionAsFailed", "notifyDefault", "notify", "notifyChannelIds" })
|
||||
Assert.False(node.ContainsKey(stripped), $"{stripped} must not be frozen");
|
||||
|
||||
Assert.Equal("ANALYZE-CUSTOM-003", node["ruleId"]!.GetValue<string>());
|
||||
Assert.Equal("Alice Admin", node["author"]!.GetValue<string>());
|
||||
Assert.Equal("ANALYZE-SEC-004", node["derivedFromTemplateRuleId"]!.GetValue<string>());
|
||||
Assert.Single(node["conditions"]!.AsArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RepoFile_carries_schema_pointer_assigned_id_credit_and_community_flag_in_repo_order()
|
||||
{
|
||||
var s = new RuleSubmission
|
||||
{
|
||||
RuleKind = RuleSubmissionKinds.Analyze,
|
||||
RuleJson = RuleSubmissionService.FreezeRule(CustomAnalyzeRule()),
|
||||
AttributionName = RuleAttributionModes.AnonymousAuthor,
|
||||
};
|
||||
|
||||
var file = RuleSubmissionService.BuildRepoFile(s, "ANALYZE-NET-002");
|
||||
|
||||
Assert.Equal("rules/analyze/ANALYZE-NET-002.json", file.Path);
|
||||
Assert.EndsWith("\n", file.Content);
|
||||
var node = JsonNode.Parse(file.Content)!.AsObject();
|
||||
var keys = node.Select(kv => kv.Key).ToList();
|
||||
Assert.Equal(new[] { "$schema", "ruleId", "title", "description", "severity", "category", "version", "author", "enabled", "isCommunity" }, keys.Take(10));
|
||||
Assert.Equal("../schema/analyze-rule.schema.json", node["$schema"]!.GetValue<string>());
|
||||
Assert.Equal("ANALYZE-NET-002", node["ruleId"]!.GetValue<string>());
|
||||
Assert.Equal("Community contribution", node["author"]!.GetValue<string>());
|
||||
Assert.True(node["isCommunity"]!.GetValue<bool>());
|
||||
// Analyze rules ship enabled — the tenant's own toggle state does not travel.
|
||||
Assert.True(node["enabled"]!.GetValue<bool>());
|
||||
Assert.False(node.ContainsKey("derivedFromTemplateRuleId"));
|
||||
Assert.False(node.ContainsKey("isBuiltIn"));
|
||||
Assert.Contains("\"explanation\": \"The PAC file could not be fetched.\"", file.Content);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RepoFile_for_a_gather_rule_ships_disabled_and_without_severity()
|
||||
{
|
||||
var gather = new GatherRule
|
||||
{
|
||||
RuleId = "GATHER-CUSTOM-001",
|
||||
Title = "BIOS config",
|
||||
Description = "Reads the BIOS registry block",
|
||||
Category = "device",
|
||||
Enabled = true,
|
||||
IsBuiltIn = false,
|
||||
CollectorType = "registry",
|
||||
Target = "HKLM\\SOFTWARE\\Vendor\\BIOS",
|
||||
Trigger = "startup",
|
||||
OutputEventType = "gather_bios_config",
|
||||
};
|
||||
var s = new RuleSubmission
|
||||
{
|
||||
RuleKind = RuleSubmissionKinds.Gather,
|
||||
RuleJson = RuleSubmissionService.FreezeRule(gather),
|
||||
AttributionName = "Contoso IT",
|
||||
};
|
||||
|
||||
var file = RuleSubmissionService.BuildRepoFile(s, "GATHER-DEVICE-009");
|
||||
|
||||
Assert.Equal("rules/gather/GATHER-DEVICE-009.json", file.Path);
|
||||
var node = JsonNode.Parse(file.Content)!.AsObject();
|
||||
Assert.Equal("../schema/gather-rule.schema.json", node["$schema"]!.GetValue<string>());
|
||||
Assert.False(node["enabled"]!.GetValue<bool>());
|
||||
Assert.Equal("Contoso IT", node["author"]!.GetValue<string>());
|
||||
Assert.False(node.ContainsKey("severity"));
|
||||
// No \u escaping of the backslash-heavy registry path beyond JSON's own rules.
|
||||
Assert.Contains("HKLM\\\\SOFTWARE\\\\Vendor\\\\BIOS", file.Content);
|
||||
}
|
||||
|
||||
// ── attribution ─────────────────────────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData("Alice A.")]
|
||||
[InlineData("Contoso IT & Ops (EMEA)")]
|
||||
[InlineData("Zoë Müller-Lüdenscheidt")]
|
||||
public void AttributionName_accepts_names(string name)
|
||||
=> Assert.Equal(name, RuleSubmissionService.ValidateAttributionName(name));
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("<script>")]
|
||||
[InlineData("https://example.com")]
|
||||
[InlineData("line\nbreak")]
|
||||
public void AttributionName_rejects_markup_urls_and_control_characters(string name)
|
||||
=> Assert.Throws<ArgumentException>(() => RuleSubmissionService.ValidateAttributionName(name));
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, null)]
|
||||
[InlineData("", null)]
|
||||
[InlineData(" alice@contoso.com ", "alice@contoso.com")]
|
||||
public void Email_is_trimmed_or_null(string? input, string? expected)
|
||||
=> Assert.Equal(expected, RuleSubmissionService.NormalizeEmail(input));
|
||||
|
||||
[Theory]
|
||||
[InlineData("alice")]
|
||||
[InlineData("@contoso.com")]
|
||||
[InlineData("alice@")]
|
||||
[InlineData("a@b@c")]
|
||||
[InlineData("alice @contoso.com")]
|
||||
public void Email_rejects_non_addresses(string input)
|
||||
=> Assert.Throws<ArgumentException>(() => RuleSubmissionService.NormalizeEmail(input));
|
||||
|
||||
// ── review state machine ────────────────────────────────────────────────
|
||||
|
||||
private static (RuleSubmissionService service, Mock<IRuleSubmissionRepository> repo) Build(
|
||||
RuleSubmission row, IEnumerable<string>? globalAnalyzeIds = null, IEnumerable<string>? reservedIds = null)
|
||||
{
|
||||
var repo = new Mock<IRuleSubmissionRepository>(MockBehavior.Loose);
|
||||
repo.Setup(r => r.GetAsync(row.SubmissionId)).ReturnsAsync(row);
|
||||
repo.Setup(r => r.UpdateAsync(It.IsAny<RuleSubmission>())).ReturnsAsync(true);
|
||||
repo.Setup(r => r.GetReservedPublishedRuleIdsAsync())
|
||||
.ReturnsAsync(new HashSet<string>(reservedIds ?? Array.Empty<string>(), StringComparer.OrdinalIgnoreCase));
|
||||
|
||||
var rules = new Mock<IRuleRepository>(MockBehavior.Loose);
|
||||
rules.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(
|
||||
(globalAnalyzeIds ?? Array.Empty<string>()).Select(id => new AnalyzeRule { RuleId = id, IsBuiltIn = true }).ToList());
|
||||
rules.Setup(r => r.GetGatherRulesAsync("global")).ReturnsAsync(new List<GatherRule>());
|
||||
|
||||
var metrics = new Mock<IMetricsRepository>(MockBehavior.Loose);
|
||||
var config = new Mock<TenantConfigurationService>(MockBehavior.Loose,
|
||||
Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
|
||||
|
||||
var service = new RuleSubmissionService(repo.Object, rules.Object, metrics.Object, config.Object,
|
||||
NullLogger<RuleSubmissionService>.Instance);
|
||||
return (service, repo);
|
||||
}
|
||||
|
||||
private static RuleSubmission PendingRow() => new()
|
||||
{
|
||||
SubmissionId = "a1b2c3d4e5f6",
|
||||
BatchId = "b",
|
||||
TenantId = TenantId,
|
||||
RuleKind = RuleSubmissionKinds.Analyze,
|
||||
SourceRuleId = "ANALYZE-CUSTOM-003",
|
||||
Title = "Proxy PAC unreachable",
|
||||
Category = "network",
|
||||
RuleJson = RuleSubmissionService.FreezeRule(CustomAnalyzeRule()),
|
||||
SubmittedBy = "alice@contoso.com",
|
||||
SubmittedByName = "Alice Admin",
|
||||
SubmittedAt = DateTime.UtcNow,
|
||||
Status = RuleSubmissionStatuses.Pending,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task Approve_requires_a_reserved_id_of_the_same_kind()
|
||||
{
|
||||
var (service, _) = Build(PendingRow());
|
||||
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve" }, "ga@example.com"));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-CUSTOM-009" }, "ga@example.com"));
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "GATHER-NET-002" }, "ga@example.com"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Approve_refuses_an_id_taken_by_the_catalog_or_another_approval()
|
||||
{
|
||||
var (service, _) = Build(PendingRow(), globalAnalyzeIds: new[] { "ANALYZE-NET-001" }, reservedIds: new[] { "ANALYZE-NET-002" });
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-NET-001" }, "ga@example.com"));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-NET-002" }, "ga@example.com"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Approve_stores_id_comment_adaptation_flag_and_reviewer()
|
||||
{
|
||||
var (service, repo) = Build(PendingRow());
|
||||
RuleSubmission? written = null;
|
||||
repo.Setup(r => r.UpdateAsync(It.IsAny<RuleSubmission>())).Callback<RuleSubmission>(s => written = s).ReturnsAsync(true);
|
||||
|
||||
var result = await service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-NET-003", ReviewComment = "Taken, will generalise the title.", WillBeAdapted = true },
|
||||
"ga@example.com");
|
||||
|
||||
Assert.Same(result, written);
|
||||
Assert.Equal(RuleSubmissionStatuses.Approved, result.Status);
|
||||
Assert.Equal("ANALYZE-NET-003", result.PublishedRuleId);
|
||||
Assert.True(result.WillBeAdapted);
|
||||
Assert.Equal("Taken, will generalise the title.", result.ReviewComment);
|
||||
Assert.Equal("ga@example.com", result.ReviewedBy);
|
||||
Assert.NotNull(result.ReviewedAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Decline_requires_a_comment_and_clears_the_published_id()
|
||||
{
|
||||
var row = PendingRow();
|
||||
row.Status = RuleSubmissionStatuses.Approved;
|
||||
row.PublishedRuleId = "ANALYZE-NET-003";
|
||||
var (service, _) = Build(row);
|
||||
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "decline" }, "ga@example.com"));
|
||||
|
||||
var result = await service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "decline", ReviewComment = "Too tenant-specific." }, "ga@example.com");
|
||||
|
||||
Assert.Equal(RuleSubmissionStatuses.Declined, result.Status);
|
||||
Assert.Null(result.PublishedRuleId);
|
||||
Assert.False(result.WillBeAdapted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Published_is_derived_and_final()
|
||||
{
|
||||
var row = PendingRow();
|
||||
row.Status = RuleSubmissionStatuses.Approved;
|
||||
row.PublishedRuleId = "ANALYZE-NET-003";
|
||||
var (service, _) = Build(row, globalAnalyzeIds: new[] { "ANALYZE-NET-003" });
|
||||
|
||||
var items = await service.ToItemsAsync(new[] { row });
|
||||
Assert.Equal(RuleSubmissionStatuses.Published, items[0].Status);
|
||||
Assert.Equal(RuleSubmissionStatuses.Approved, row.Status);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "decline", ReviewComment = "too late" }, "ga@example.com"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Approved_but_unpublished_stays_approved_on_the_wire()
|
||||
{
|
||||
var row = PendingRow();
|
||||
row.Status = RuleSubmissionStatuses.Approved;
|
||||
row.PublishedRuleId = "ANALYZE-NET-003";
|
||||
var (service, _) = Build(row, globalAnalyzeIds: new[] { "ANALYZE-NET-001" });
|
||||
|
||||
var items = await service.ToItemsAsync(new[] { row });
|
||||
Assert.Equal(RuleSubmissionStatuses.Approved, items[0].Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Withdraw_only_pending_and_only_own_tenant()
|
||||
{
|
||||
var row = PendingRow();
|
||||
var (service, _) = Build(row);
|
||||
|
||||
Assert.False(await service.WithdrawAsync("22222222-2222-2222-2222-222222222222", "a1b2c3d4e5f6", crossTenantAllowed: false));
|
||||
Assert.True(await service.WithdrawAsync(TenantId, "a1b2c3d4e5f6", crossTenantAllowed: false));
|
||||
Assert.Equal(RuleSubmissionStatuses.Withdrawn, row.Status);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => service.WithdrawAsync(TenantId, "a1b2c3d4e5f6", crossTenantAllowed: false));
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-NET-003" }, "ga@example.com"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Operator_delete_passes_through_to_the_repository()
|
||||
{
|
||||
var (service, repo) = Build(PendingRow());
|
||||
repo.Setup(r => r.DeleteAsync("a1b2c3d4e5f6")).ReturnsAsync(true);
|
||||
|
||||
Assert.True(await service.DeleteAsync("a1b2c3d4e5f6"));
|
||||
repo.Verify(r => r.DeleteAsync("a1b2c3d4e5f6"), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unknown_decision_is_a_bad_request()
|
||||
{
|
||||
var (service, _) = Build(PendingRow());
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
|
||||
new ReviewRuleSubmissionRequest { Decision = "maybe" }, "ga@example.com"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Detail_returns_the_typed_rule_suggested_id_and_repo_file()
|
||||
{
|
||||
var (service, _) = Build(PendingRow(), globalAnalyzeIds: new[] { "ANALYZE-NET-001" });
|
||||
|
||||
var detail = await service.GetDetailAsync("a1b2c3d4e5f6");
|
||||
|
||||
Assert.NotNull(detail);
|
||||
Assert.NotNull(detail!.AnalyzeRule);
|
||||
Assert.Null(detail.GatherRule);
|
||||
Assert.Equal("ANALYZE-CUSTOM-003", detail.AnalyzeRule!.RuleId);
|
||||
Assert.False(detail.AnalyzeRule.IsBuiltIn);
|
||||
Assert.Equal("ANALYZE-NET-002", detail.SuggestedPublishedRuleId);
|
||||
Assert.Equal("rules/analyze/ANALYZE-NET-002.json", detail.RepoFile!.Path);
|
||||
}
|
||||
|
||||
// ── submit ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static (RuleSubmissionService service, List<RuleSubmission> stored) BuildForSubmit(
|
||||
List<AnalyzeRule> tenantAnalyze, List<RuleSubmission>? existing = null, TenantConfiguration? config = null)
|
||||
{
|
||||
var stored = new List<RuleSubmission>();
|
||||
var repo = new Mock<IRuleSubmissionRepository>(MockBehavior.Loose);
|
||||
repo.Setup(r => r.GetForTenantAsync(TenantId)).ReturnsAsync(existing ?? new List<RuleSubmission>());
|
||||
repo.Setup(r => r.AddAsync(It.IsAny<RuleSubmission>())).Callback<RuleSubmission>(stored.Add).ReturnsAsync(true);
|
||||
repo.Setup(r => r.GetReservedPublishedRuleIdsAsync()).ReturnsAsync(new HashSet<string>());
|
||||
|
||||
var rules = new Mock<IRuleRepository>(MockBehavior.Loose);
|
||||
rules.Setup(r => r.GetAnalyzeRulesAsync(TenantId)).ReturnsAsync(tenantAnalyze);
|
||||
rules.Setup(r => r.GetGatherRulesAsync(TenantId)).ReturnsAsync(new List<GatherRule>());
|
||||
rules.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(new List<AnalyzeRule>());
|
||||
rules.Setup(r => r.GetGatherRulesAsync("global")).ReturnsAsync(new List<GatherRule>());
|
||||
|
||||
var metrics = new Mock<IMetricsRepository>(MockBehavior.Loose);
|
||||
metrics.Setup(m => m.GetRuleStatsAsync(TenantId, It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<int>()))
|
||||
.ReturnsAsync(new List<RuleStatsEntry>
|
||||
{
|
||||
new() { RuleId = "ANALYZE-CUSTOM-003", FireCount = 4, SessionsEvaluated = 40, EvaluationCount = 41 },
|
||||
new() { RuleId = "ANALYZE-CUSTOM-003", FireCount = 1, SessionsEvaluated = 10, EvaluationCount = 10 },
|
||||
new() { RuleId = "ANALYZE-CUSTOM-999", FireCount = 99, SessionsEvaluated = 99, EvaluationCount = 99 },
|
||||
});
|
||||
|
||||
var configRepo = new Mock<IConfigRepository>(MockBehavior.Loose);
|
||||
var configService = new Mock<TenantConfigurationService>(MockBehavior.Loose, configRepo.Object,
|
||||
NullLogger<TenantConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
|
||||
configService.Setup(c => c.GetConfigurationIfExistsAsync(TenantId)).ReturnsAsync(config);
|
||||
|
||||
var service = new RuleSubmissionService(repo.Object, rules.Object, metrics.Object, configService.Object,
|
||||
NullLogger<RuleSubmissionService>.Instance);
|
||||
return (service, stored);
|
||||
}
|
||||
|
||||
private static SubmitRuleSubmissionsRequest Request(params string[] ruleIds) => new()
|
||||
{
|
||||
TenantId = TenantId,
|
||||
Items = ruleIds.Select(id => new RuleSubmissionItemRef { Kind = "analyze", RuleId = id }).ToList(),
|
||||
Comment = "Fires when the PAC download fails during ESP.",
|
||||
AttributionMode = RuleAttributionModes.Anonymous,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_freezes_the_tenant_rule_records_findings_and_fire_stats()
|
||||
{
|
||||
var (service, stored) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() });
|
||||
|
||||
var created = await service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003"), "alice@contoso.com", "Alice Admin");
|
||||
|
||||
var s = Assert.Single(created);
|
||||
Assert.Same(s, Assert.Single(stored));
|
||||
Assert.Equal(12, s.SubmissionId.Length);
|
||||
Assert.Equal(12, s.BatchId.Length);
|
||||
Assert.Equal(RuleSubmissionStatuses.Pending, s.Status);
|
||||
Assert.Equal("Community contribution", s.AttributionName);
|
||||
Assert.Null(s.ContactEmail);
|
||||
Assert.Equal("Proxy PAC unreachable", s.Title);
|
||||
Assert.Equal("network", s.Category);
|
||||
Assert.Equal("ANALYZE-SEC-004", s.DerivedFromTemplateRuleId);
|
||||
Assert.Contains(s.ValidationFindings, f => f.Level == "info" && f.Message.Contains("ANALYZE-SEC-004"));
|
||||
Assert.DoesNotContain(s.ValidationFindings, f => f.Level == "error");
|
||||
Assert.Equal(5, s.SourceFireStats!.FireCount);
|
||||
Assert.Equal(50, s.SourceFireStats.SessionsEvaluated);
|
||||
Assert.DoesNotContain("isBuiltIn", s.RuleJson);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_rejects_built_in_and_unknown_rules_without_storing_anything()
|
||||
{
|
||||
var builtIn = CustomAnalyzeRule();
|
||||
builtIn.RuleId = "ANALYZE-NET-001";
|
||||
builtIn.IsBuiltIn = true;
|
||||
var (service, stored) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule(), builtIn });
|
||||
|
||||
var ex = await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003", "ANALYZE-NET-001", "ANALYZE-CUSTOM-404"), "alice@contoso.com", "Alice Admin"));
|
||||
|
||||
Assert.Contains("ANALYZE-NET-001", ex.Message);
|
||||
Assert.Contains("ANALYZE-CUSTOM-404", ex.Message);
|
||||
Assert.Empty(stored);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_rejects_a_rule_whose_draft_validation_fails()
|
||||
{
|
||||
var broken = CustomAnalyzeRule();
|
||||
broken.Conditions = new List<RuleCondition>();
|
||||
var (service, stored) = BuildForSubmit(new List<AnalyzeRule> { broken });
|
||||
|
||||
var ex = await Assert.ThrowsAsync<ArgumentException>(() =>
|
||||
service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003"), "alice@contoso.com", "Alice Admin"));
|
||||
|
||||
Assert.Contains("at least one condition", ex.Message);
|
||||
Assert.Empty(stored);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_refuses_a_second_pending_submission_of_the_same_rule()
|
||||
{
|
||||
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() }, existing: new List<RuleSubmission> { PendingRow() });
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003"), "alice@contoso.com", "Alice Admin"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_enforces_the_daily_cap()
|
||||
{
|
||||
var existing = Enumerable.Range(0, RuleSubmissionService.MaxSubmissionsPerTenantPerDay)
|
||||
.Select(i => { var r = PendingRow(); r.SourceRuleId = $"OTHER-{i}"; r.Status = RuleSubmissionStatuses.Declined; return r; })
|
||||
.ToList();
|
||||
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() }, existing);
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003"), "alice@contoso.com", "Alice Admin"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_organization_attribution_uses_the_company_name_and_fails_without_one()
|
||||
{
|
||||
var withName = new TenantConfiguration { TenantId = TenantId, DomainName = "contoso.example", CompanyName = "Contoso Ltd." };
|
||||
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() }, config: withName);
|
||||
var request = Request("ANALYZE-CUSTOM-003");
|
||||
request.AttributionMode = RuleAttributionModes.Organization;
|
||||
|
||||
var created = await service.SubmitAsync(TenantId, request, "alice@contoso.com", "Alice Admin");
|
||||
Assert.Equal("Contoso Ltd.", created[0].AttributionName);
|
||||
|
||||
var (noConfig, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() }, config: null);
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => noConfig.SubmitAsync(TenantId, request, "alice@contoso.com", "Alice Admin"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_stores_the_contact_email_when_given()
|
||||
{
|
||||
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() });
|
||||
var request = Request("ANALYZE-CUSTOM-003");
|
||||
request.Email = " alice.reply@contoso.com ";
|
||||
|
||||
var created = await service.SubmitAsync(TenantId, request, "alice@contoso.com", "Alice Admin");
|
||||
Assert.Equal("alice.reply@contoso.com", created[0].ContactEmail);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Submit_person_attribution_freezes_the_requested_name()
|
||||
{
|
||||
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() });
|
||||
var request = Request("ANALYZE-CUSTOM-003");
|
||||
request.AttributionMode = RuleAttributionModes.Person;
|
||||
request.AttributionName = " Alice A. ";
|
||||
|
||||
var created = await service.SubmitAsync(TenantId, request, "alice@contoso.com", "Alice Admin");
|
||||
Assert.Equal("Alice A.", created[0].AttributionName);
|
||||
Assert.Equal(RuleAttributionModes.Person, created[0].AttributionMode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Wire pins for the rule-submission responses (typed from the start — the anonymous side is
|
||||
/// the literal a client sees, so a reordered or renamed property fails here first).
|
||||
/// </summary>
|
||||
public class RuleSubmissionsWireParityTests
|
||||
{
|
||||
private static readonly DateTime T0 = new(2026, 9, 9, 10, 30, 0, DateTimeKind.Utc);
|
||||
|
||||
private static RuleSubmissionItem Item() => new()
|
||||
{
|
||||
SubmissionId = "a1b2c3d4e5f6",
|
||||
BatchId = "0f0e0d0c0b0a",
|
||||
TenantId = "11111111-1111-1111-1111-111111111111",
|
||||
RuleKind = "analyze",
|
||||
SourceRuleId = "ANALYZE-CUSTOM-003",
|
||||
Title = "Proxy PAC unreachable",
|
||||
Category = "network",
|
||||
Comment = "Fires when the PAC download fails.",
|
||||
SubmittedBy = "alice@contoso.com",
|
||||
SubmittedByName = "Alice Admin",
|
||||
ContactEmail = "alice.reply@contoso.com",
|
||||
AttributionMode = "anonymous",
|
||||
AttributionName = "Community contribution",
|
||||
SubmittedAt = T0,
|
||||
Status = "approved",
|
||||
ValidationFindings = new List<RuleSubmissionFinding> { new() { Level = "info", Message = "Derived from template ANALYZE-SEC-004" } },
|
||||
SourceFireStats = new RuleSubmissionFireStats { Days = 30, FireCount = 42, SessionsEvaluated = 310, EvaluationCount = 312 },
|
||||
ReviewedBy = "ga@example.com",
|
||||
ReviewedAt = T0.AddDays(1),
|
||||
ReviewComment = "Taken.",
|
||||
WillBeAdapted = true,
|
||||
PublishedRuleId = "ANALYZE-NET-002",
|
||||
DerivedFromTemplateRuleId = "ANALYZE-SEC-004",
|
||||
};
|
||||
|
||||
private static object ItemLiteral() => new
|
||||
{
|
||||
submissionId = "a1b2c3d4e5f6",
|
||||
batchId = "0f0e0d0c0b0a",
|
||||
tenantId = "11111111-1111-1111-1111-111111111111",
|
||||
ruleKind = "analyze",
|
||||
sourceRuleId = "ANALYZE-CUSTOM-003",
|
||||
title = "Proxy PAC unreachable",
|
||||
category = "network",
|
||||
comment = "Fires when the PAC download fails.",
|
||||
submittedBy = "alice@contoso.com",
|
||||
submittedByName = "Alice Admin",
|
||||
contactEmail = "alice.reply@contoso.com",
|
||||
attributionMode = "anonymous",
|
||||
attributionName = "Community contribution",
|
||||
submittedAt = T0,
|
||||
status = "approved",
|
||||
validationFindings = new List<object> { new { level = "info", message = "Derived from template ANALYZE-SEC-004" } },
|
||||
sourceFireStats = new { days = 30, fireCount = 42, sessionsEvaluated = 310, evaluationCount = 312 },
|
||||
reviewedBy = "ga@example.com",
|
||||
reviewedAt = T0.AddDays(1),
|
||||
reviewComment = "Taken.",
|
||||
willBeAdapted = true,
|
||||
publishedRuleId = "ANALYZE-NET-002",
|
||||
derivedFromTemplateRuleId = "ANALYZE-SEC-004",
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Submit_response_shape()
|
||||
{
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new { success = true, message = "Rule submitted for review.", batchId = "0f0e0d0c0b0a", submissions = new List<object> { ItemLiteral() } },
|
||||
new SubmitRuleSubmissionsResponse { Success = true, Message = "Rule submitted for review.", BatchId = "0f0e0d0c0b0a", Submissions = new List<RuleSubmissionItem> { Item() } });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void List_nonPaged_has_no_nextLink_key()
|
||||
{
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new { success = true, count = 1, submissions = new List<object> { ItemLiteral() } },
|
||||
new RuleSubmissionListResponse { Success = true, Count = 1, Submissions = new List<RuleSubmissionItem> { Item() } });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void List_paged_carries_nextLink()
|
||||
{
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new { success = true, count = 1, submissions = new List<object> { ItemLiteral() }, nextLink = "/api/global/rule-submissions?pageSize=20&continuation=abc" },
|
||||
new RuleSubmissionListResponse { Success = true, Count = 1, Submissions = new List<RuleSubmissionItem> { Item() }, NextLink = "/api/global/rule-submissions?pageSize=20&continuation=abc" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void List_last_page_drops_the_nextLink_key()
|
||||
{
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new { success = true, count = 0, submissions = new List<object>() },
|
||||
new RuleSubmissionListResponse { Success = true, Count = 0, Submissions = new List<RuleSubmissionItem>(), NextLink = null });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Detail_shape_with_analyze_rule_omits_the_gather_slot()
|
||||
{
|
||||
var rule = new AnalyzeRule
|
||||
{
|
||||
RuleId = "ANALYZE-CUSTOM-003", Title = "Proxy PAC unreachable", Description = "d", Severity = "warning", Category = "network",
|
||||
Explanation = "e", IsBuiltIn = false, Conditions = new List<RuleCondition>(),
|
||||
};
|
||||
var typed = new RuleSubmissionDetailResponse
|
||||
{
|
||||
Success = true,
|
||||
Submission = Item(),
|
||||
AnalyzeRule = rule,
|
||||
LiveFireStats = new RuleSubmissionFireStats { Days = 30, FireCount = 1, SessionsEvaluated = 2, EvaluationCount = 3 },
|
||||
SuggestedPublishedRuleId = "ANALYZE-NET-002",
|
||||
RepoFile = new RuleSubmissionRepoFile { Path = "rules/analyze/ANALYZE-NET-002.json", Content = "{}\n" },
|
||||
};
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new
|
||||
{
|
||||
success = true,
|
||||
submission = ItemLiteral(),
|
||||
analyzeRule = rule,
|
||||
liveFireStats = new { days = 30, fireCount = 1, sessionsEvaluated = 2, evaluationCount = 3 },
|
||||
suggestedPublishedRuleId = "ANALYZE-NET-002",
|
||||
repoFile = new { path = "rules/analyze/ANALYZE-NET-002.json", content = "{}\n" },
|
||||
},
|
||||
typed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Review_response_shape()
|
||||
{
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new { success = true, message = "Submission approved.", submission = ItemLiteral() },
|
||||
new ReviewRuleSubmissionResponse { Success = true, Message = "Submission approved.", Submission = Item() });
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ using Xunit;
|
||||
namespace AutopilotMonitor.Functions.Tests.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the schemaVersion-2 catalog contract (generated by scripts/error-codes/generate.mjs):
|
||||
/// 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>
|
||||
|
||||
@@ -88,6 +88,12 @@ public sealed class SharedManifestParityTests
|
||||
["webhookProviderTypes"] = EnumMap<WebhookProviderType>(),
|
||||
["annotationLanes"] = AnnotationLanes.All,
|
||||
["annotationVerdicts"] = AnnotationVerdicts.All,
|
||||
// Community rule submissions: kinds, effective statuses (incl. the derived "published"),
|
||||
// attribution modes and reviewer decisions — the MCP tool schemas enumerate these.
|
||||
["ruleSubmissionKinds"] = RuleSubmissionKinds.All,
|
||||
["ruleSubmissionStatuses"] = RuleSubmissionStatuses.All,
|
||||
["ruleAttributionModes"] = RuleAttributionModes.All,
|
||||
["ruleSubmissionDecisions"] = RuleSubmissionDecisions.All,
|
||||
// Ops vocabularies. Declaration order kept for severities — it IS the ladder
|
||||
// (Info < Warning < Error < Critical), and the MCP renders it in that order.
|
||||
["opsEventCategories"] = ConstStrings(typeof(OpsEventCategory)),
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
using AutopilotMonitor.Functions.DataAccess.TableStorage;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Round-trip pins for the RuleSubmissions Store/Map pair (memory:
|
||||
/// feedback_table_storage_serialization — every new field in <see cref="RuleSubmission"/>
|
||||
/// MUST be exercised in Store+Map so silent drops surface here), plus the key and filter shapes.
|
||||
/// </summary>
|
||||
public class TableRuleSubmissionRepositoryTests
|
||||
{
|
||||
private const string TenantId = "11111111-1111-1111-1111-111111111111";
|
||||
|
||||
private static RuleSubmission Full() => new()
|
||||
{
|
||||
SubmissionId = "a1b2c3d4e5f6",
|
||||
BatchId = "0f0e0d0c0b0a",
|
||||
TenantId = TenantId,
|
||||
RuleKind = RuleSubmissionKinds.Analyze,
|
||||
SourceRuleId = "ANALYZE-CUSTOM-003",
|
||||
Title = "Proxy PAC unreachable",
|
||||
Category = "network",
|
||||
RuleJson = "{\"ruleId\":\"ANALYZE-CUSTOM-003\",\"title\":\"Proxy PAC unreachable\"}",
|
||||
Comment = "Fires when the PAC download fails during ESP.",
|
||||
SubmittedBy = "alice@contoso.com",
|
||||
SubmittedByName = "Alice Admin",
|
||||
ContactEmail = "alice.reply@contoso.com",
|
||||
AttributionMode = RuleAttributionModes.Person,
|
||||
AttributionName = "Alice A.",
|
||||
SubmittedAt = new DateTime(2026, 9, 9, 10, 30, 0, DateTimeKind.Utc),
|
||||
Status = RuleSubmissionStatuses.Approved,
|
||||
ValidationFindings = new List<RuleSubmissionFinding>
|
||||
{
|
||||
new() { Level = "info", Message = "Derived from template ANALYZE-SEC-004" },
|
||||
},
|
||||
SourceFireStats = new RuleSubmissionFireStats { Days = 30, FireCount = 42, SessionsEvaluated = 310, EvaluationCount = 312 },
|
||||
ReviewedBy = "ga@example.com",
|
||||
ReviewedAt = new DateTime(2026, 9, 10, 8, 0, 0, DateTimeKind.Utc),
|
||||
ReviewComment = "Taken, generalised for the community.",
|
||||
WillBeAdapted = true,
|
||||
PublishedRuleId = "ANALYZE-NET-002",
|
||||
DerivedFromTemplateRuleId = "ANALYZE-SEC-004",
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Roundtrip_all_fields_survive_store_and_map()
|
||||
{
|
||||
var original = Full();
|
||||
|
||||
var mapped = TableRuleSubmissionRepository.MapSubmission(
|
||||
TableRuleSubmissionRepository.StoreSubmission(original));
|
||||
|
||||
Assert.Equal(original.SubmissionId, mapped.SubmissionId);
|
||||
Assert.Equal(original.BatchId, mapped.BatchId);
|
||||
Assert.Equal(original.TenantId, mapped.TenantId);
|
||||
Assert.Equal(original.RuleKind, mapped.RuleKind);
|
||||
Assert.Equal(original.SourceRuleId, mapped.SourceRuleId);
|
||||
Assert.Equal(original.Title, mapped.Title);
|
||||
Assert.Equal(original.Category, mapped.Category);
|
||||
Assert.Equal(original.RuleJson, mapped.RuleJson);
|
||||
Assert.Equal(original.Comment, mapped.Comment);
|
||||
Assert.Equal(original.SubmittedBy, mapped.SubmittedBy);
|
||||
Assert.Equal(original.SubmittedByName, mapped.SubmittedByName);
|
||||
Assert.Equal(original.ContactEmail, mapped.ContactEmail);
|
||||
Assert.Equal(original.AttributionMode, mapped.AttributionMode);
|
||||
Assert.Equal(original.AttributionName, mapped.AttributionName);
|
||||
Assert.Equal(original.SubmittedAt, mapped.SubmittedAt);
|
||||
Assert.Equal(original.Status, mapped.Status);
|
||||
Assert.Single(mapped.ValidationFindings);
|
||||
Assert.Equal("info", mapped.ValidationFindings[0].Level);
|
||||
Assert.Equal(original.ValidationFindings[0].Message, mapped.ValidationFindings[0].Message);
|
||||
Assert.NotNull(mapped.SourceFireStats);
|
||||
Assert.Equal(42, mapped.SourceFireStats!.FireCount);
|
||||
Assert.Equal(310, mapped.SourceFireStats.SessionsEvaluated);
|
||||
Assert.Equal(312, mapped.SourceFireStats.EvaluationCount);
|
||||
Assert.Equal(30, mapped.SourceFireStats.Days);
|
||||
Assert.Equal(original.ReviewedBy, mapped.ReviewedBy);
|
||||
Assert.Equal(original.ReviewedAt, mapped.ReviewedAt);
|
||||
Assert.Equal(original.ReviewComment, mapped.ReviewComment);
|
||||
Assert.True(mapped.WillBeAdapted);
|
||||
Assert.Equal(original.PublishedRuleId, mapped.PublishedRuleId);
|
||||
Assert.Equal(original.DerivedFromTemplateRuleId, mapped.DerivedFromTemplateRuleId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Roundtrip_pending_row_keeps_nulls_null()
|
||||
{
|
||||
var original = Full();
|
||||
original.Status = RuleSubmissionStatuses.Pending;
|
||||
original.Comment = null;
|
||||
original.ContactEmail = null;
|
||||
original.SourceFireStats = null;
|
||||
original.ValidationFindings = new List<RuleSubmissionFinding>();
|
||||
original.ReviewedBy = null;
|
||||
original.ReviewedAt = null;
|
||||
original.ReviewComment = null;
|
||||
original.WillBeAdapted = false;
|
||||
original.PublishedRuleId = null;
|
||||
original.DerivedFromTemplateRuleId = null;
|
||||
|
||||
var mapped = TableRuleSubmissionRepository.MapSubmission(
|
||||
TableRuleSubmissionRepository.StoreSubmission(original));
|
||||
|
||||
Assert.Null(mapped.Comment);
|
||||
Assert.Null(mapped.ContactEmail);
|
||||
Assert.Null(mapped.SourceFireStats);
|
||||
Assert.Empty(mapped.ValidationFindings);
|
||||
Assert.Null(mapped.ReviewedBy);
|
||||
Assert.Null(mapped.ReviewedAt);
|
||||
Assert.Null(mapped.ReviewComment);
|
||||
Assert.False(mapped.WillBeAdapted);
|
||||
Assert.Null(mapped.PublishedRuleId);
|
||||
Assert.Null(mapped.DerivedFromTemplateRuleId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Store_uses_the_single_partition_and_an_inverted_tick_row_key()
|
||||
{
|
||||
var s = Full();
|
||||
var entity = TableRuleSubmissionRepository.StoreSubmission(s);
|
||||
|
||||
Assert.Equal("submissions", entity.PartitionKey);
|
||||
Assert.Equal($"{RowKeyCodec.InvertedTicks(s.SubmittedAt)}_{s.SubmissionId}", entity.RowKey);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Newer_submission_sorts_first()
|
||||
{
|
||||
var older = Full();
|
||||
var newer = Full();
|
||||
newer.SubmittedAt = older.SubmittedAt.AddMinutes(5);
|
||||
|
||||
var olderKey = TableRuleSubmissionRepository.StoreSubmission(older).RowKey;
|
||||
var newerKey = TableRuleSubmissionRepository.StoreSubmission(newer).RowKey;
|
||||
|
||||
Assert.True(string.CompareOrdinal(newerKey, olderKey) < 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Map_tolerates_a_corrupt_json_column()
|
||||
{
|
||||
var entity = TableRuleSubmissionRepository.StoreSubmission(Full());
|
||||
entity["ValidationFindingsJson"] = "{not json";
|
||||
entity["SourceFireStatsJson"] = "[]";
|
||||
|
||||
var mapped = TableRuleSubmissionRepository.MapSubmission(entity);
|
||||
|
||||
Assert.Empty(mapped.ValidationFindings);
|
||||
Assert.Null(mapped.SourceFireStats);
|
||||
}
|
||||
|
||||
// ── retention rule (shared by the sweep and this pin) ──
|
||||
|
||||
private static readonly DateTime Now = new(2026, 12, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
[Theory]
|
||||
[InlineData("withdrawn", 29, false)]
|
||||
[InlineData("withdrawn", 30, true)]
|
||||
[InlineData("declined", 89, false)]
|
||||
[InlineData("declined", 90, true)]
|
||||
[InlineData("pending", 400, false)]
|
||||
[InlineData("approved", 400, false)]
|
||||
public void Retention_expires_only_closed_rows_at_their_window(string status, int ageDays, bool expired)
|
||||
{
|
||||
var s = Full();
|
||||
s.Status = status;
|
||||
s.SubmittedAt = Now.AddDays(-ageDays);
|
||||
s.ReviewedAt = status == "declined" ? Now.AddDays(-ageDays) : null;
|
||||
|
||||
Assert.Equal(expired, RuleSubmissionRetention.IsExpired(s, Now));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Retention_of_a_declined_row_counts_from_the_decision_not_the_submission()
|
||||
{
|
||||
var s = Full();
|
||||
s.Status = RuleSubmissionStatuses.Declined;
|
||||
s.SubmittedAt = Now.AddDays(-200);
|
||||
s.ReviewedAt = Now.AddDays(-10);
|
||||
|
||||
Assert.False(RuleSubmissionRetention.IsExpired(s, Now));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, null, "PartitionKey eq 'submissions'")]
|
||||
[InlineData("t'1", null, "PartitionKey eq 'submissions' and TenantId eq 't''1'")]
|
||||
[InlineData(null, "pending", "PartitionKey eq 'submissions' and Status eq 'pending'")]
|
||||
[InlineData("t1", "approved", "PartitionKey eq 'submissions' and TenantId eq 't1' and Status eq 'approved'")]
|
||||
public void Filter_escapes_and_composes(string? tenantId, string? status, string expected)
|
||||
{
|
||||
Assert.Equal(expected, TableRuleSubmissionRepository.BuildFilter(tenantId, status));
|
||||
}
|
||||
}
|
||||
@@ -184,6 +184,7 @@ public class TypedContractCompletionWireParityTests
|
||||
totalInstalls = 4,
|
||||
totalSkipped = 1,
|
||||
totalUnmeasured = 1,
|
||||
totalIncomplete = 0,
|
||||
totalCollisionExcluded = 0,
|
||||
slowestApps = new[]
|
||||
{
|
||||
@@ -195,6 +196,7 @@ public class TypedContractCompletionWireParityTests
|
||||
skipped = 1,
|
||||
unmeasured = 1,
|
||||
failed = 1,
|
||||
incomplete = 0,
|
||||
failureRate = 33.3,
|
||||
avgDurationSeconds = 120.0,
|
||||
maxDurationSeconds = 240,
|
||||
@@ -225,6 +227,7 @@ public class TypedContractCompletionWireParityTests
|
||||
TotalInstalls = 4,
|
||||
TotalSkipped = 1,
|
||||
TotalUnmeasured = 1,
|
||||
TotalIncomplete = 0,
|
||||
TotalCollisionExcluded = 0,
|
||||
SlowestApps = new[]
|
||||
{
|
||||
@@ -236,6 +239,7 @@ public class TypedContractCompletionWireParityTests
|
||||
Skipped = 1,
|
||||
Unmeasured = 1,
|
||||
Failed = 1,
|
||||
Incomplete = 0,
|
||||
FailureRate = 33.3,
|
||||
AvgDurationSeconds = 120.0,
|
||||
MaxDurationSeconds = 240,
|
||||
@@ -684,6 +688,7 @@ public class TypedContractCompletionWireParityTests
|
||||
skipped = 0,
|
||||
unmeasured = 0,
|
||||
failed = 0,
|
||||
incomplete = 0,
|
||||
failureRate = 0.0,
|
||||
avgDurationSeconds = 0.0,
|
||||
p95DurationSeconds = 0,
|
||||
@@ -715,6 +720,7 @@ public class TypedContractCompletionWireParityTests
|
||||
Skipped = 0,
|
||||
Unmeasured = 0,
|
||||
Failed = 0,
|
||||
Incomplete = 0,
|
||||
FailureRate = 0.0,
|
||||
AvgDurationSeconds = 0.0,
|
||||
P95DurationSeconds = 0,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -34,8 +34,11 @@ namespace AutopilotMonitor.Functions.DataAccess
|
||||
services.AddSingleton<ISessionAnnotationRepository, TableSessionAnnotationRepository>();
|
||||
services.AddSingleton<IBootstrapRepository, TableBootstrapRepository>();
|
||||
services.AddSingleton<INotificationRepository, TableNotificationRepository>();
|
||||
services.AddSingleton<IRuleSubmissionRepository, TableRuleSubmissionRepository>();
|
||||
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>();
|
||||
|
||||
+3
@@ -142,6 +142,9 @@ namespace AutopilotMonitor.Functions.DataAccess.TableStorage
|
||||
public Task ResolveEspBlockingForSessionAsync(string tenantId, string sessionId)
|
||||
=> _storage.ResolveEspBlockingForSessionAsync(tenantId, sessionId);
|
||||
|
||||
public Task<int> CloseOpenAppInstallsForSessionAsync(string tenantId, string sessionId)
|
||||
=> _storage.CloseOpenAppInstallsForSessionAsync(tenantId, sessionId);
|
||||
|
||||
public Task<bool> SaveTimeAttributionAggregateAsync(TimeAttributionDailyAggregate aggregate)
|
||||
=> _storage.SaveTimeAttributionAggregateAsync(aggregate);
|
||||
|
||||
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Pagination;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
using Azure;
|
||||
using Azure.Data.Tables;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.DataAccess.TableStorage
|
||||
{
|
||||
/// <summary>
|
||||
/// Table-storage implementation of <see cref="IRuleSubmissionRepository"/>.
|
||||
/// PK = <see cref="PartitionKey"/> for every tenant, RK = inverted ticks + id (newest first).
|
||||
/// </summary>
|
||||
public class TableRuleSubmissionRepository : IRuleSubmissionRepository
|
||||
{
|
||||
internal const string PartitionKey = "submissions";
|
||||
|
||||
private readonly TableClient _tableClient;
|
||||
private readonly ILogger<TableRuleSubmissionRepository> _logger;
|
||||
|
||||
public TableRuleSubmissionRepository(TableStorageService storage, ILogger<TableRuleSubmissionRepository> logger)
|
||||
{
|
||||
_tableClient = storage.GetTableClient(Constants.TableNames.RuleSubmissions);
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<bool> AddAsync(RuleSubmission submission)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _tableClient.AddEntityAsync(StoreSubmission(submission));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to store rule submission {SubmissionId}", submission.SubmissionId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<RuleSubmission?> GetAsync(string submissionId)
|
||||
{
|
||||
var entity = await FindEntityAsync(submissionId);
|
||||
return entity == null ? null : MapSubmission(entity);
|
||||
}
|
||||
|
||||
public async Task<List<RuleSubmission>> GetForTenantAsync(string tenantId)
|
||||
{
|
||||
var results = new List<RuleSubmission>();
|
||||
try
|
||||
{
|
||||
await foreach (var entity in _tableClient.QueryAsync<TableEntity>(filter: BuildFilter(tenantId, status: null)))
|
||||
{
|
||||
results.Add(MapSubmission(entity));
|
||||
}
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 404)
|
||||
{
|
||||
_logger.LogDebug("RuleSubmissions table does not exist yet, returning empty list");
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public async Task<RawPage<RuleSubmission>> GetPageAsync(string? tenantId, string? status, int pageSize, string? continuation)
|
||||
{
|
||||
if (pageSize < 1) throw new ArgumentOutOfRangeException(nameof(pageSize));
|
||||
try
|
||||
{
|
||||
var (entities, nextRawToken) = await AzureTablesPaginator.FetchPageAsync<TableEntity>(
|
||||
client: _tableClient,
|
||||
filter: BuildFilter(tenantId, status),
|
||||
pageSize: pageSize,
|
||||
continuation: continuation);
|
||||
|
||||
var page = new List<RuleSubmission>(entities.Count);
|
||||
foreach (var entity in entities) page.Add(MapSubmission(entity));
|
||||
// RowKey is the inverted tick of SubmittedAt — newest first by construction.
|
||||
return new RawPage<RuleSubmission>(page, nextRawToken);
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 404)
|
||||
{
|
||||
_logger.LogDebug("RuleSubmissions table does not exist yet, returning empty page");
|
||||
return RawPage<RuleSubmission>.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAsync(RuleSubmission submission)
|
||||
{
|
||||
var existing = await FindEntityAsync(submission.SubmissionId);
|
||||
if (existing == null)
|
||||
{
|
||||
_logger.LogWarning("UpdateAsync: rule submission {SubmissionId} not found", submission.SubmissionId);
|
||||
return false;
|
||||
}
|
||||
|
||||
var entity = StoreSubmission(submission);
|
||||
entity.RowKey = existing.RowKey;
|
||||
entity.ETag = existing.ETag;
|
||||
try
|
||||
{
|
||||
// If-Match on the ETag: two reviewers deciding the same submission cannot both win.
|
||||
await _tableClient.UpdateEntityAsync(entity, existing.ETag, TableUpdateMode.Replace);
|
||||
return true;
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 412)
|
||||
{
|
||||
_logger.LogWarning("UpdateAsync: rule submission {SubmissionId} changed underneath the reviewer", submission.SubmissionId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<HashSet<string>> GetReservedPublishedRuleIdsAsync()
|
||||
{
|
||||
var ids = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
try
|
||||
{
|
||||
await foreach (var entity in _tableClient.QueryAsync<TableEntity>(
|
||||
filter: BuildFilter(tenantId: null, status: RuleSubmissionStatuses.Approved),
|
||||
select: new[] { "PublishedRuleId" }))
|
||||
{
|
||||
var id = entity.GetString("PublishedRuleId");
|
||||
if (!string.IsNullOrEmpty(id)) ids.Add(id!);
|
||||
}
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 404)
|
||||
{
|
||||
_logger.LogDebug("RuleSubmissions table does not exist yet");
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
public async Task<int> DeleteExpiredAsync(DateTime nowUtc)
|
||||
{
|
||||
var deleted = 0;
|
||||
try
|
||||
{
|
||||
// The expiry rule is the shared RuleSubmissionRetention, so the sweep and its
|
||||
// test cannot disagree; only the two closed statuses are scanned.
|
||||
foreach (var status in new[] { RuleSubmissionStatuses.Withdrawn, RuleSubmissionStatuses.Declined })
|
||||
{
|
||||
var expired = new List<TableEntity>();
|
||||
await foreach (var entity in _tableClient.QueryAsync<TableEntity>(filter: BuildFilter(tenantId: null, status)))
|
||||
{
|
||||
if (RuleSubmissionRetention.IsExpired(MapSubmission(entity), nowUtc)) expired.Add(entity);
|
||||
}
|
||||
foreach (var entity in expired)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _tableClient.DeleteEntityAsync(entity.PartitionKey, entity.RowKey);
|
||||
deleted++;
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 404)
|
||||
{
|
||||
// Already gone — a parallel sweep or a tenant offboarding won the race.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 404)
|
||||
{
|
||||
_logger.LogDebug("RuleSubmissions table does not exist yet");
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(string submissionId)
|
||||
{
|
||||
var existing = await FindEntityAsync(submissionId);
|
||||
if (existing == null) return false;
|
||||
try
|
||||
{
|
||||
await _tableClient.DeleteEntityAsync(existing.PartitionKey, existing.RowKey);
|
||||
return true;
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 404)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<TableEntity?> FindEntityAsync(string submissionId)
|
||||
{
|
||||
try
|
||||
{
|
||||
await foreach (var entity in _tableClient.QueryAsync<TableEntity>(
|
||||
filter: $"PartitionKey eq '{PartitionKey}' and SubmissionId eq '{Escape(submissionId)}'"))
|
||||
{
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 404)
|
||||
{
|
||||
_logger.LogDebug("RuleSubmissions table does not exist yet");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
internal static string BuildFilter(string? tenantId, string? status)
|
||||
{
|
||||
var filter = $"PartitionKey eq '{PartitionKey}'";
|
||||
if (!string.IsNullOrEmpty(tenantId)) filter += $" and TenantId eq '{Escape(tenantId!)}'";
|
||||
if (!string.IsNullOrEmpty(status)) filter += $" and Status eq '{Escape(status!)}'";
|
||||
return filter;
|
||||
}
|
||||
|
||||
private static string Escape(string value) => value.Replace("'", "''");
|
||||
|
||||
// ── Store / Map ─────────────────────────────────────────────────────────
|
||||
// internal static: pinned by round-trip unit tests — every property must survive
|
||||
// Store→Map, so any new field lands in BOTH methods plus the test.
|
||||
|
||||
internal static TableEntity StoreSubmission(RuleSubmission s) =>
|
||||
new(PartitionKey, $"{RowKeyCodec.InvertedTicks(s.SubmittedAt)}_{s.SubmissionId}")
|
||||
{
|
||||
["SubmissionId"] = s.SubmissionId,
|
||||
["BatchId"] = s.BatchId,
|
||||
["TenantId"] = s.TenantId,
|
||||
["RuleKind"] = s.RuleKind,
|
||||
["SourceRuleId"] = s.SourceRuleId,
|
||||
["Title"] = s.Title,
|
||||
["Category"] = s.Category,
|
||||
["RuleJson"] = s.RuleJson,
|
||||
["Comment"] = s.Comment ?? string.Empty,
|
||||
["SubmittedBy"] = s.SubmittedBy,
|
||||
["SubmittedByName"] = s.SubmittedByName,
|
||||
["ContactEmail"] = s.ContactEmail ?? string.Empty,
|
||||
["AttributionMode"] = s.AttributionMode,
|
||||
["AttributionName"] = s.AttributionName,
|
||||
["SubmittedAt"] = s.SubmittedAt,
|
||||
["Status"] = s.Status,
|
||||
["ValidationFindingsJson"] = JsonSerializer.Serialize(s.ValidationFindings),
|
||||
["SourceFireStatsJson"] = s.SourceFireStats == null ? string.Empty : JsonSerializer.Serialize(s.SourceFireStats),
|
||||
["ReviewedBy"] = s.ReviewedBy ?? string.Empty,
|
||||
["ReviewedAt"] = s.ReviewedAt,
|
||||
["ReviewComment"] = s.ReviewComment ?? string.Empty,
|
||||
["WillBeAdapted"] = s.WillBeAdapted,
|
||||
["PublishedRuleId"] = s.PublishedRuleId ?? string.Empty,
|
||||
["DerivedFromTemplateRuleId"] = s.DerivedFromTemplateRuleId ?? string.Empty,
|
||||
};
|
||||
|
||||
internal static RuleSubmission MapSubmission(TableEntity e) => new()
|
||||
{
|
||||
SubmissionId = e.GetString("SubmissionId") ?? string.Empty,
|
||||
BatchId = e.GetString("BatchId") ?? string.Empty,
|
||||
TenantId = e.GetString("TenantId") ?? string.Empty,
|
||||
RuleKind = e.GetString("RuleKind") ?? string.Empty,
|
||||
SourceRuleId = e.GetString("SourceRuleId") ?? string.Empty,
|
||||
Title = e.GetString("Title") ?? string.Empty,
|
||||
Category = e.GetString("Category") ?? string.Empty,
|
||||
RuleJson = e.GetString("RuleJson") ?? string.Empty,
|
||||
Comment = NullIfEmpty(e.GetString("Comment")),
|
||||
SubmittedBy = e.GetString("SubmittedBy") ?? string.Empty,
|
||||
SubmittedByName = e.GetString("SubmittedByName") ?? string.Empty,
|
||||
ContactEmail = NullIfEmpty(e.GetString("ContactEmail")),
|
||||
AttributionMode = e.GetString("AttributionMode") ?? RuleAttributionModes.Anonymous,
|
||||
AttributionName = e.GetString("AttributionName") ?? RuleAttributionModes.AnonymousAuthor,
|
||||
SubmittedAt = e.GetDateTimeOffset("SubmittedAt")?.UtcDateTime ?? DateTime.MinValue,
|
||||
Status = e.GetString("Status") ?? RuleSubmissionStatuses.Pending,
|
||||
ValidationFindings = DeserializeOrDefault<List<RuleSubmissionFinding>>(e.GetString("ValidationFindingsJson")) ?? new List<RuleSubmissionFinding>(),
|
||||
SourceFireStats = DeserializeOrDefault<RuleSubmissionFireStats>(e.GetString("SourceFireStatsJson")),
|
||||
ReviewedBy = NullIfEmpty(e.GetString("ReviewedBy")),
|
||||
ReviewedAt = e.GetDateTimeOffset("ReviewedAt")?.UtcDateTime,
|
||||
ReviewComment = NullIfEmpty(e.GetString("ReviewComment")),
|
||||
WillBeAdapted = e.GetBoolean("WillBeAdapted") ?? false,
|
||||
PublishedRuleId = NullIfEmpty(e.GetString("PublishedRuleId")),
|
||||
DerivedFromTemplateRuleId = NullIfEmpty(e.GetString("DerivedFromTemplateRuleId")),
|
||||
};
|
||||
|
||||
private static T? DeserializeOrDefault<T>(string? json) where T : class
|
||||
{
|
||||
if (string.IsNullOrEmpty(json)) return null;
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize<T>(json!);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// A corrupt column must not hide the submission itself.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? NullIfEmpty(string? value) => string.IsNullOrEmpty(value) ? null : value;
|
||||
}
|
||||
}
|
||||
+7
@@ -101,6 +101,13 @@ namespace AutopilotMonitor.Functions.DataAccess.TableStorage
|
||||
// complete. Positive evidence only (listed ⇒ EspBlocking=true, absent ⇒ stays
|
||||
// unknown). Idempotent + fail-soft like the counter reconcile above.
|
||||
await _storage.ResolveEspBlockingForSessionAsync(tenantId, sessionId);
|
||||
// Observation end: app rows still InProgress on a terminal session never get a
|
||||
// terminal event — close them as Incomplete (outcome unknown, not a failure).
|
||||
// Early for the ingest path (verdict batch, the agent may still be watching),
|
||||
// never wrong in the end state: a real terminal arriving later still wins via
|
||||
// the sticky-status reconcile, and the shutdown batch re-runs the close for rows
|
||||
// opened after the verdict. Idempotent + fail-soft.
|
||||
await _storage.CloseOpenAppInstallsForSessionAsync(tenantId, sessionId);
|
||||
|
||||
// F1 PR2: compute + persist the time-attribution breakdown once, now that the
|
||||
// terminal write stamped CompletedAt/DurationSeconds and the event stream is
|
||||
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models.WhatsNew;
|
||||
using Azure;
|
||||
using Azure.Data.Tables;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.DataAccess.TableStorage
|
||||
{
|
||||
/// <summary>
|
||||
/// Table Storage implementation of <see cref="IWhatsNewNotificationStateRepository"/>.
|
||||
/// Lives as a side row in the AdminConfiguration table (PartitionKey
|
||||
/// <see cref="PartitionKey"/>, RowKey <see cref="RowKey"/>) — platform-scoped state next to the
|
||||
/// table-schema sentinel, so no new table is needed. Deliberately NOT a field on the
|
||||
/// AdminConfiguration row itself: that row is round-tripped wholesale by the Global Admin
|
||||
/// settings UI, and a stale save there would roll the watermark back and re-announce entries.
|
||||
/// </summary>
|
||||
public class TableWhatsNewNotificationStateRepository : IWhatsNewNotificationStateRepository
|
||||
{
|
||||
internal const string PartitionKey = "WhatsNewNotifications";
|
||||
internal const string RowKey = "state";
|
||||
|
||||
private const string KnownEntryKeysProperty = "KnownEntryKeysJson";
|
||||
private const string LastDocsCommitProperty = "LastDocsCommit";
|
||||
private const string LastRunUtcProperty = "LastRunUtc";
|
||||
private const string LastNotifiedUtcProperty = "LastNotifiedUtc";
|
||||
private const string LastNotifiedEntryCountProperty = "LastNotifiedEntryCount";
|
||||
|
||||
private readonly TableClient _table;
|
||||
private readonly ILogger<TableWhatsNewNotificationStateRepository> _logger;
|
||||
|
||||
public TableWhatsNewNotificationStateRepository(
|
||||
TableStorageService storage,
|
||||
ILogger<TableWhatsNewNotificationStateRepository> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
_table = storage.GetTableClient(Constants.TableNames.AdminConfiguration);
|
||||
}
|
||||
|
||||
public async Task<(WhatsNewNotificationState? State, string? ETag)> GetWithETagAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await _table.GetEntityIfExistsAsync<TableEntity>(PartitionKey, RowKey);
|
||||
if (!response.HasValue)
|
||||
return (null, null);
|
||||
|
||||
var entity = response.Value!;
|
||||
return (MapFromEntity(entity), entity.ETag.ToString());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to load What's new notification state");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> TryUpsertAsync(WhatsNewNotificationState state, string? ifMatchETag)
|
||||
{
|
||||
if (state == null)
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
var entity = MapToEntity(state);
|
||||
|
||||
if (ifMatchETag is null)
|
||||
{
|
||||
await _table.AddEntityAsync(entity);
|
||||
return true;
|
||||
}
|
||||
|
||||
await _table.UpdateEntityAsync(entity, new ETag(ifMatchETag), TableUpdateMode.Replace);
|
||||
return true;
|
||||
}
|
||||
catch (RequestFailedException ex) when (ex.Status == 409 || ex.Status == 412)
|
||||
{
|
||||
// 409 EntityAlreadyExists (AddEntity) or 412 PreconditionFailed (ETag mismatch):
|
||||
// a parallel run committed first — the caller must not send.
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed conditional upsert of What's new notification state");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static TableEntity MapToEntity(WhatsNewNotificationState state)
|
||||
{
|
||||
var entity = new TableEntity(PartitionKey, RowKey)
|
||||
{
|
||||
[KnownEntryKeysProperty] = JsonSerializer.Serialize(state.KnownEntryKeys),
|
||||
[LastNotifiedEntryCountProperty] = state.LastNotifiedEntryCount,
|
||||
};
|
||||
|
||||
if (!string.IsNullOrEmpty(state.LastDocsCommit))
|
||||
entity[LastDocsCommitProperty] = state.LastDocsCommit;
|
||||
if (state.LastRunUtc.HasValue)
|
||||
entity[LastRunUtcProperty] = DateTime.SpecifyKind(state.LastRunUtc.Value, DateTimeKind.Utc);
|
||||
if (state.LastNotifiedUtc.HasValue)
|
||||
entity[LastNotifiedUtcProperty] = DateTime.SpecifyKind(state.LastNotifiedUtc.Value, DateTimeKind.Utc);
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
private WhatsNewNotificationState MapFromEntity(TableEntity entity)
|
||||
{
|
||||
var known = new HashSet<string>(StringComparer.Ordinal);
|
||||
var json = entity.GetString(KnownEntryKeysProperty);
|
||||
if (!string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
try
|
||||
{
|
||||
var parsed = JsonSerializer.Deserialize<List<string>>(json!);
|
||||
if (parsed != null)
|
||||
{
|
||||
foreach (var key in parsed)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(key))
|
||||
known.Add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
// Treated as an empty watermark: the service then re-baselines silently
|
||||
// (empty known set + existing row = "first run" semantics), never re-announces.
|
||||
_logger.LogWarning(ex, "What's new notification state has malformed KnownEntryKeysJson — re-baselining");
|
||||
}
|
||||
}
|
||||
|
||||
return new WhatsNewNotificationState
|
||||
{
|
||||
KnownEntryKeys = known,
|
||||
LastDocsCommit = entity.GetString(LastDocsCommitProperty),
|
||||
LastRunUtc = entity.GetDateTime(LastRunUtcProperty),
|
||||
LastNotifiedUtc = entity.GetDateTime(LastNotifiedUtcProperty),
|
||||
LastNotifiedEntryCount = entity.GetInt32(LastNotifiedEntryCountProperty) ?? 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -291,6 +291,7 @@ namespace AutopilotMonitor.Functions.Functions.Apps
|
||||
var measured = installed.Where(MetricsMath.HasMeasuredDuration).ToList();
|
||||
var succeeded = installed.Count;
|
||||
var failed = summaries.Count(s => s.Status == "Failed");
|
||||
var incomplete = summaries.Count(s => s.Status == "Incomplete");
|
||||
var failureRate = MetricsMath.TerminalFailureRatePct(failed, succeeded);
|
||||
var avgDurationSeconds = measured.Count > 0 ? Math.Round(measured.Average(s => s.DurationSeconds), 0) : 0;
|
||||
var p95DurationSeconds = Percentile(measured.Select(s => s.DurationSeconds).ToList(), 0.95);
|
||||
@@ -423,6 +424,7 @@ namespace AutopilotMonitor.Functions.Functions.Apps
|
||||
Skipped = skipped,
|
||||
Unmeasured = installed.Count - measured.Count,
|
||||
Failed = failed,
|
||||
Incomplete = incomplete,
|
||||
FailureRate = failureRate,
|
||||
AvgDurationSeconds = avgDurationSeconds,
|
||||
P95DurationSeconds = p95DurationSeconds,
|
||||
|
||||
+7
-4
@@ -13,7 +13,7 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the latest published agent + bootstrap script versions.
|
||||
/// Cached in-memory for 12h; supports <c>?refresh=true</c> to bypass the cache.
|
||||
/// Cached in-memory for a few minutes; supports <c>?refresh=true</c> to bypass the cache.
|
||||
/// Authenticated users only (read-only metadata).
|
||||
/// </summary>
|
||||
public class GetLatestVersionsFunction
|
||||
@@ -44,15 +44,18 @@ namespace AutopilotMonitor.Functions.Functions.Config
|
||||
|
||||
var response = req.CreateResponse(HttpStatusCode.OK);
|
||||
|
||||
// Force-refresh responses MUST NOT be browser-cached.
|
||||
// Normal cached responses may be stored for up to 1h (aligns with 12h backend cache).
|
||||
// Force-refresh responses MUST NOT be browser-cached. Normal responses are
|
||||
// held for a minute only: the portal announces this number as "Latest agent
|
||||
// version" right after a release, and a browser cache measured in hours would
|
||||
// keep showing the previous release long after the backend refreshed. The
|
||||
// payload is a few dozen bytes, so revalidating often is free.
|
||||
if (forceRefresh)
|
||||
{
|
||||
response.Headers.Add("Cache-Control", "no-store");
|
||||
}
|
||||
else
|
||||
{
|
||||
response.Headers.Add("Cache-Control", "public, max-age=3600");
|
||||
response.Headers.Add("Cache-Control", "public, max-age=60");
|
||||
}
|
||||
|
||||
await response.WriteAsJsonAsync(new GetLatestVersionsResponse
|
||||
|
||||
@@ -55,6 +55,10 @@ namespace AutopilotMonitor.Functions.Functions.Rules
|
||||
return await req.BadRequestAsync("Invalid rule data");
|
||||
}
|
||||
|
||||
// Author is stamped from the creator's token, never from the payload
|
||||
// (anti-spoof), and stays immutable through every later update.
|
||||
rule.Author = TenantHelper.GetUserDisplayName(req) ?? "Autopilot Monitor";
|
||||
|
||||
try
|
||||
{
|
||||
var success = await _ruleService.CreateRuleAsync(tenantId, rule);
|
||||
@@ -88,6 +92,11 @@ namespace AutopilotMonitor.Functions.Functions.Rules
|
||||
|
||||
rule.RuleId = ruleId;
|
||||
|
||||
// Same anti-spoof stamp as CreateRule: on a true update the service replaces
|
||||
// this with the original author (immutable attribution), but a full-payload PUT
|
||||
// that upserts a rule with no existing row must not store the payload's author.
|
||||
rule.Author = TenantHelper.GetUserDisplayName(req) ?? "Autopilot Monitor";
|
||||
|
||||
try
|
||||
{
|
||||
var success = await _ruleService.UpdateRuleAsync(tenantId, rule);
|
||||
@@ -124,7 +133,8 @@ namespace AutopilotMonitor.Functions.Functions.Rules
|
||||
|
||||
try
|
||||
{
|
||||
var newRule = await _ruleService.CreateFromTemplateAsync(tenantId, ruleId, variables);
|
||||
var author = TenantHelper.GetUserDisplayName(req) ?? "Autopilot Monitor";
|
||||
var newRule = await _ruleService.CreateFromTemplateAsync(tenantId, ruleId, variables, author);
|
||||
|
||||
var response = req.CreateResponse(HttpStatusCode.Created);
|
||||
await response.WriteAsJsonAsync(new CreateAnalyzeRuleFromTemplateResponse { Success = true, Rule = newRule, Message = "Custom rule created from template" });
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
|
||||
{
|
||||
/// <summary>
|
||||
/// Operator hard delete of a submission (test/demo rows, or a tenant's request). The row
|
||||
/// vanishes from both lists; a published rule in the repo is untouched.
|
||||
/// </summary>
|
||||
public class DeleteGlobalRuleSubmissionFunction
|
||||
{
|
||||
private readonly ILogger<DeleteGlobalRuleSubmissionFunction> _logger;
|
||||
private readonly RuleSubmissionService _service;
|
||||
|
||||
public DeleteGlobalRuleSubmissionFunction(ILogger<DeleteGlobalRuleSubmissionFunction> logger, RuleSubmissionService service)
|
||||
{
|
||||
_logger = logger;
|
||||
_service = service;
|
||||
}
|
||||
|
||||
[Function("DeleteGlobalRuleSubmission")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "global/rule-submissions/{submissionId}")] HttpRequestData req,
|
||||
string submissionId)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Authentication + GlobalAdminOnly authorization enforced by PolicyEnforcementMiddleware
|
||||
var user = TenantHelper.GetUserIdentifier(req);
|
||||
if (string.IsNullOrWhiteSpace(submissionId)) return await req.BadRequestAsync("submissionId is required.");
|
||||
|
||||
var existing = await _service.GetAsync(submissionId);
|
||||
if (existing == null) return await req.NotFoundAsync("Submission not found.");
|
||||
|
||||
if (!await _service.DeleteAsync(submissionId)) return await req.NotFoundAsync("Submission not found.");
|
||||
|
||||
// Warning on purpose: an operator delete is rare and must be visible in App Insights.
|
||||
_logger.LogWarning("Rule submission {SubmissionId} ({RuleId}, tenant {TenantId}, status {Status}) deleted by {User}",
|
||||
submissionId, existing.SourceRuleId, existing.TenantId, existing.Status, user);
|
||||
return await req.OkAsync(new SuccessMessageResponse { Success = true, Message = "Submission deleted." });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return await req.InternalServerErrorAsync(_logger, ex, "DeleteGlobalRuleSubmission");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
|
||||
{
|
||||
/// <summary>One submission with the frozen rule, live fire stats, the suggested id and the repo file.</summary>
|
||||
public class GetGlobalRuleSubmissionFunction
|
||||
{
|
||||
private readonly ILogger<GetGlobalRuleSubmissionFunction> _logger;
|
||||
private readonly RuleSubmissionService _service;
|
||||
|
||||
public GetGlobalRuleSubmissionFunction(ILogger<GetGlobalRuleSubmissionFunction> logger, RuleSubmissionService service)
|
||||
{
|
||||
_logger = logger;
|
||||
_service = service;
|
||||
}
|
||||
|
||||
[Function("GetGlobalRuleSubmission")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "global/rule-submissions/{submissionId}")] HttpRequestData req,
|
||||
string submissionId)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Authentication + GlobalReadOrAdmin authorization enforced by PolicyEnforcementMiddleware
|
||||
if (string.IsNullOrWhiteSpace(submissionId)) return await req.BadRequestAsync("submissionId is required.");
|
||||
|
||||
var detail = await _service.GetDetailAsync(submissionId);
|
||||
if (detail == null) return await req.NotFoundAsync("Submission not found.");
|
||||
return await req.OkAsync(detail);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return await req.InternalServerErrorAsync(_logger, ex, "GetGlobalRuleSubmission");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
using System.Web;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Pagination;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
|
||||
{
|
||||
/// <summary>Operator list across tenants: <c>?tenantId=</c> and <c>?status=</c> are server-side filters, paging as for session reports.</summary>
|
||||
public class GetGlobalRuleSubmissionsFunction
|
||||
{
|
||||
private readonly ILogger<GetGlobalRuleSubmissionsFunction> _logger;
|
||||
private readonly RuleSubmissionService _service;
|
||||
|
||||
public GetGlobalRuleSubmissionsFunction(ILogger<GetGlobalRuleSubmissionsFunction> logger, RuleSubmissionService service)
|
||||
{
|
||||
_logger = logger;
|
||||
_service = service;
|
||||
}
|
||||
|
||||
[Function("GetGlobalRuleSubmissions")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "global/rule-submissions")] HttpRequestData req)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Authentication + GlobalReadOrAdmin authorization enforced by PolicyEnforcementMiddleware
|
||||
var callerTenantId = TenantHelper.GetTenantId(req);
|
||||
|
||||
var query = HttpUtility.ParseQueryString(req.Url.Query ?? string.Empty);
|
||||
var parsed = RuleSubmissionsPagination.ParseQuery(query);
|
||||
if (parsed.Error != null) return await req.BadRequestAsync(parsed.Error);
|
||||
|
||||
var pageSize = parsed.PageSize ?? RuleSubmissionsPagination.DefaultPageSize;
|
||||
|
||||
string? azureToken = null;
|
||||
if (parsed.Continuation != null)
|
||||
{
|
||||
if (!RuleSubmissionsPagination.TryAcceptContinuation(
|
||||
parsed.Continuation, callerTenantId, parsed.FilterTenantId, parsed.FilterStatus,
|
||||
out azureToken, out var rejectReason))
|
||||
{
|
||||
_logger.LogWarning("GetGlobalRuleSubmissions: continuation rejected ({Reason})", rejectReason);
|
||||
return await req.BadRequestAsync($"Invalid continuation token ({rejectReason}). Restart pagination from the first page.");
|
||||
}
|
||||
}
|
||||
|
||||
var page = await _service.GetPageAsync(parsed.FilterTenantId, parsed.FilterStatus, pageSize, azureToken);
|
||||
var items = await _service.ToItemsAsync(page.Items);
|
||||
|
||||
string? nextLink = null;
|
||||
if (!string.IsNullOrEmpty(page.NextRawToken))
|
||||
{
|
||||
var fp = RuleSubmissionsPagination.Fingerprint(callerTenantId, parsed.FilterTenantId, parsed.FilterStatus);
|
||||
var wireToken = ContinuationToken.Encode(page.NextRawToken!, callerTenantId, fp);
|
||||
nextLink = RuleSubmissionsPagination.BuildNextLink(pageSize, wireToken, parsed.FilterTenantId, parsed.FilterStatus);
|
||||
}
|
||||
|
||||
return await req.OkAsync(new RuleSubmissionListResponse
|
||||
{
|
||||
Success = true,
|
||||
Count = items.Count,
|
||||
Submissions = items,
|
||||
NextLink = nextLink,
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return await req.InternalServerErrorAsync(_logger, ex, "GetGlobalRuleSubmissions");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
|
||||
{
|
||||
/// <summary>The submitting tenant's own submissions, newest first, with the effective status.</summary>
|
||||
public class GetRuleSubmissionsFunction
|
||||
{
|
||||
private readonly ILogger<GetRuleSubmissionsFunction> _logger;
|
||||
private readonly RuleSubmissionService _service;
|
||||
|
||||
public GetRuleSubmissionsFunction(ILogger<GetRuleSubmissionsFunction> logger, RuleSubmissionService service)
|
||||
{
|
||||
_logger = logger;
|
||||
_service = service;
|
||||
}
|
||||
|
||||
[Function("GetRuleSubmissions")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "rules/submissions")] HttpRequestData req)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Authentication + TenantAdminOrGA authorization enforced by PolicyEnforcementMiddleware.
|
||||
// Always the JWT tenant — a GA reads foreign tenants through global/rule-submissions?tenantId=.
|
||||
var tenantId = req.GetRequestContext().TenantId;
|
||||
var rows = await _service.GetForTenantAsync(tenantId);
|
||||
var items = await _service.ToItemsAsync(rows);
|
||||
return await req.OkAsync(new RuleSubmissionListResponse { Success = true, Count = items.Count, Submissions = items });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return await req.InternalServerErrorAsync(_logger, ex, "GetRuleSubmissions");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
|
||||
{
|
||||
/// <summary>The reviewer's decision (portal or MCP). The submitter is told through a tenant notification.</summary>
|
||||
public class ReviewRuleSubmissionFunction
|
||||
{
|
||||
private readonly ILogger<ReviewRuleSubmissionFunction> _logger;
|
||||
private readonly RuleSubmissionService _service;
|
||||
private readonly TenantNotificationService _tenantNotifications;
|
||||
|
||||
public ReviewRuleSubmissionFunction(
|
||||
ILogger<ReviewRuleSubmissionFunction> logger,
|
||||
RuleSubmissionService service,
|
||||
TenantNotificationService tenantNotifications)
|
||||
{
|
||||
_logger = logger;
|
||||
_service = service;
|
||||
_tenantNotifications = tenantNotifications;
|
||||
}
|
||||
|
||||
[Function("ReviewRuleSubmission")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = "global/rule-submissions/{submissionId}")] HttpRequestData req,
|
||||
string submissionId)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Authentication + GlobalAdminOnly authorization enforced by PolicyEnforcementMiddleware
|
||||
var reviewer = TenantHelper.GetUserIdentifier(req);
|
||||
if (string.IsNullOrWhiteSpace(submissionId)) return await req.BadRequestAsync("submissionId is required.");
|
||||
|
||||
var read = await req.ReadAsync<ReviewRuleSubmissionRequest>();
|
||||
if (read.Error != null) return read.Error;
|
||||
|
||||
RuleSubmission updated;
|
||||
try
|
||||
{
|
||||
updated = await _service.ReviewAsync(submissionId, read.Value!, reviewer);
|
||||
}
|
||||
catch (KeyNotFoundException ex)
|
||||
{
|
||||
return await req.NotFoundAsync(ex.Message);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
return await req.BadRequestAsync(ex.Message);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return await req.ConflictAsync(ex.Message);
|
||||
}
|
||||
|
||||
var approved = updated.Status == RuleSubmissionStatuses.Approved;
|
||||
var title = approved
|
||||
? $"Rule submission approved: {updated.SourceRuleId}"
|
||||
: $"Rule submission declined: {updated.SourceRuleId}";
|
||||
var message = approved
|
||||
? (updated.WillBeAdapted
|
||||
? $"\"{updated.Title}\" will be published as {updated.PublishedRuleId} after a small adaptation for the community."
|
||||
: $"\"{updated.Title}\" will be published as {updated.PublishedRuleId}.")
|
||||
: $"\"{updated.Title}\" was not accepted for the community pool.";
|
||||
if (!string.IsNullOrEmpty(updated.ReviewComment)) message += $" Reviewer: {updated.ReviewComment}";
|
||||
|
||||
// Best effort; the submissions list carries the same facts.
|
||||
_ = _tenantNotifications.CreateNotificationAsync(
|
||||
updated.TenantId, "rule_submission_decided", title, message,
|
||||
href: updated.RuleKind == RuleSubmissionKinds.Analyze ? "/analyze-rules" : "/gather-rules");
|
||||
|
||||
_logger.LogInformation("Rule submission {SubmissionId} {Status} by {Reviewer} (published id {PublishedRuleId})",
|
||||
submissionId, updated.Status, reviewer, updated.PublishedRuleId ?? "-");
|
||||
|
||||
var item = (await _service.ToItemsAsync(new[] { updated }))[0];
|
||||
return await req.OkAsync(new ReviewRuleSubmissionResponse
|
||||
{
|
||||
Success = true,
|
||||
Message = approved ? "Submission approved." : "Submission declined.",
|
||||
Submission = item,
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return await req.InternalServerErrorAsync(_logger, ex, "ReviewRuleSubmission");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
|
||||
{
|
||||
/// <summary>
|
||||
/// A tenant admin submits one or more of the tenant's custom rules for the community pool.
|
||||
/// The body carries only rule references; the service freezes the rules server-side.
|
||||
/// </summary>
|
||||
public class SubmitRuleSubmissionsFunction
|
||||
{
|
||||
private readonly ILogger<SubmitRuleSubmissionsFunction> _logger;
|
||||
private readonly RuleSubmissionService _service;
|
||||
private readonly IMaintenanceRepository _maintenanceRepo;
|
||||
private readonly TelegramNotificationService _telegram;
|
||||
private readonly GlobalNotificationService _globalNotifications;
|
||||
|
||||
public SubmitRuleSubmissionsFunction(
|
||||
ILogger<SubmitRuleSubmissionsFunction> logger,
|
||||
RuleSubmissionService service,
|
||||
IMaintenanceRepository maintenanceRepo,
|
||||
TelegramNotificationService telegram,
|
||||
GlobalNotificationService globalNotifications)
|
||||
{
|
||||
_logger = logger;
|
||||
_service = service;
|
||||
_maintenanceRepo = maintenanceRepo;
|
||||
_telegram = telegram;
|
||||
_globalNotifications = globalNotifications;
|
||||
}
|
||||
|
||||
[Function("SubmitRuleSubmissions")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "rules/submissions")] HttpRequestData req)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Authentication + TenantAdminOrGA authorization enforced by PolicyEnforcementMiddleware
|
||||
var requestCtx = req.GetRequestContext();
|
||||
var tenantId = requestCtx.TenantId;
|
||||
var userIdentifier = requestCtx.UserPrincipalName;
|
||||
|
||||
var read = await req.ReadAsync<SubmitRuleSubmissionsRequest>(262_144);
|
||||
if (read.Error != null) return read.Error;
|
||||
var request = read.Value!;
|
||||
|
||||
// Same tenant-tamper gate as the session report: non-GAs submit for their JWT
|
||||
// tenant only; a GA may submit on behalf of a foreign tenant and must name it.
|
||||
if (!requestCtx.IsGlobalAdmin)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(request.TenantId)
|
||||
&& !string.Equals(request.TenantId, tenantId, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"SubmitRuleSubmissions: BLOCKED cross-tenant body for non-GA user={User} jwtTenant={JwtTenant} bodyTenant={BodyTenant}",
|
||||
userIdentifier, tenantId, request.TenantId);
|
||||
return await req.ForbiddenAsync("Body tenantId must match your authenticated tenant.");
|
||||
}
|
||||
request.TenantId = tenantId;
|
||||
}
|
||||
else if (string.IsNullOrEmpty(request.TenantId))
|
||||
{
|
||||
return await req.BadRequestAsync("tenantId is required in body for Global Admin submissions.");
|
||||
}
|
||||
|
||||
if (!SecurityValidator.IsValidGuid(request.TenantId))
|
||||
return await req.BadRequestAsync("Invalid tenantId.");
|
||||
|
||||
var displayName = TenantHelper.GetUserDisplayName(req) ?? userIdentifier;
|
||||
List<RuleSubmission> created;
|
||||
try
|
||||
{
|
||||
created = await _service.SubmitAsync(request.TenantId, request, userIdentifier, displayName);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
return await req.BadRequestAsync(ex.Message);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return await req.ConflictAsync(ex.Message);
|
||||
}
|
||||
|
||||
if (!requestCtx.IsGlobalAdmin)
|
||||
{
|
||||
foreach (var s in created)
|
||||
{
|
||||
await _maintenanceRepo.LogAuditEntryAsync(
|
||||
request.TenantId, "CREATE", "RuleSubmission", s.SubmissionId, userIdentifier,
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
{ "Action", "SubmitRuleSubmission" },
|
||||
{ "RuleKind", s.RuleKind },
|
||||
{ "RuleId", s.SourceRuleId },
|
||||
{ "BatchId", s.BatchId },
|
||||
{ "AttributionMode", s.AttributionMode },
|
||||
{ "HasComment", (s.Comment != null).ToString() },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Operator notifications — best effort, one per rule so every id has its own deep link.
|
||||
foreach (var s in created)
|
||||
{
|
||||
_ = _telegram.SendRuleSubmissionAsync(s.SubmissionId, request.TenantId, userIdentifier, s.RuleKind, s.SourceRuleId, s.Title, s.Comment ?? string.Empty);
|
||||
_ = _globalNotifications.CreateNotificationAsync(
|
||||
"rule_submission",
|
||||
$"Rule submission {s.SubmissionId}",
|
||||
$"{s.SourceRuleId} \"{s.Title}\" ({s.RuleKind}) — {userIdentifier} (Tenant: {request.TenantId})",
|
||||
href: $"/admin/reports/rule-submissions?submissionId={Uri.EscapeDataString(s.SubmissionId)}");
|
||||
}
|
||||
|
||||
_logger.LogInformation("Rule submissions stored: {Count} rule(s), batch {BatchId}, tenant {TenantId}, by {User}",
|
||||
created.Count, created[0].BatchId, request.TenantId, userIdentifier);
|
||||
|
||||
var items = await _service.ToItemsAsync(created);
|
||||
return await req.OkAsync(new SubmitRuleSubmissionsResponse
|
||||
{
|
||||
Success = true,
|
||||
Message = created.Count == 1 ? "Rule submitted for review." : $"{created.Count} rules submitted for review.",
|
||||
BatchId = created[0].BatchId,
|
||||
Submissions = items,
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return await req.InternalServerErrorAsync(_logger, ex, "SubmitRuleSubmissions");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Azure.Functions.Worker.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
|
||||
{
|
||||
/// <summary>The submitter takes a pending submission back. The row stays (status withdrawn) for the audit trail.</summary>
|
||||
public class WithdrawRuleSubmissionFunction
|
||||
{
|
||||
private readonly ILogger<WithdrawRuleSubmissionFunction> _logger;
|
||||
private readonly RuleSubmissionService _service;
|
||||
|
||||
public WithdrawRuleSubmissionFunction(ILogger<WithdrawRuleSubmissionFunction> logger, RuleSubmissionService service)
|
||||
{
|
||||
_logger = logger;
|
||||
_service = service;
|
||||
}
|
||||
|
||||
[Function("WithdrawRuleSubmission")]
|
||||
public async Task<HttpResponseData> Run(
|
||||
[HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "rules/submissions/{submissionId}")] HttpRequestData req,
|
||||
string submissionId)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Authentication + TenantAdminOrGA authorization enforced by PolicyEnforcementMiddleware
|
||||
var requestCtx = req.GetRequestContext();
|
||||
if (string.IsNullOrWhiteSpace(submissionId)) return await req.BadRequestAsync("submissionId is required.");
|
||||
|
||||
bool withdrawn;
|
||||
try
|
||||
{
|
||||
// A foreign tenant's submission answers 404 for a non-GA — the row's existence is not theirs to learn.
|
||||
withdrawn = await _service.WithdrawAsync(requestCtx.TenantId, submissionId, crossTenantAllowed: requestCtx.IsGlobalAdmin);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return await req.ConflictAsync(ex.Message);
|
||||
}
|
||||
|
||||
if (!withdrawn) return await req.NotFoundAsync("Submission not found.");
|
||||
|
||||
_logger.LogInformation("Rule submission {SubmissionId} withdrawn by {User}", submissionId, requestCtx.UserPrincipalName);
|
||||
return await req.OkAsync(new SuccessMessageResponse { Success = true, Message = "Submission withdrawn." });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return await req.InternalServerErrorAsync(_logger, ex, "WithdrawRuleSubmission");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Services.WhatsNew;
|
||||
using Microsoft.Azure.Functions.Worker;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Functions.WhatsNew
|
||||
{
|
||||
/// <summary>
|
||||
/// Hourly timer: diffs the portal's live <c>/whats-new.json</c> against the platform watermark
|
||||
/// and sends one digest of the newly published entries to every tenant channel that opted in
|
||||
/// (<c>NotificationChannel.NotifyOnWhatsNew</c>). Hourly — not on deploy — because the payload
|
||||
/// only changes with a web deploy and a delay of up to an hour is fine for product news.
|
||||
/// Offset to :20 so it does not collide with the :00 maintenance/SLA timers or the :30 sweep.
|
||||
/// </summary>
|
||||
public class WhatsNewNotificationFunction
|
||||
{
|
||||
private readonly WhatsNewNotificationService _service;
|
||||
private readonly ILogger<WhatsNewNotificationFunction> _logger;
|
||||
|
||||
public WhatsNewNotificationFunction(
|
||||
WhatsNewNotificationService service,
|
||||
ILogger<WhatsNewNotificationFunction> logger)
|
||||
{
|
||||
_service = service;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[Function("WhatsNewNotification")]
|
||||
public async Task Run([TimerTrigger("0 20 * * * *")] object timer)
|
||||
{
|
||||
_logger.LogInformation("What's new notification timer fired at {Time}", System.DateTime.UtcNow);
|
||||
await _service.RunAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,8 @@ public static class MetricsMath
|
||||
/// <summary>
|
||||
/// App-install failure rate over finished installs only: Failed / (Failed + Succeeded), one
|
||||
/// decimal, 0 when nothing finished. The same outcome-quota convention as the enrollment
|
||||
/// success rate — "InProgress" rows (still installing, or orphaned by a session that died
|
||||
/// mid-install) never dilute the rate. Shared by the app-metrics payload and the Apps
|
||||
/// success rate — "InProgress" rows (still installing) and "Incomplete" rows (observation
|
||||
/// ended before any outcome) never dilute the rate. Shared by the app-metrics payload and the Apps
|
||||
/// dashboard aggregations so the definition can't drift between panes.
|
||||
/// </summary>
|
||||
public static double TerminalFailureRatePct(int failed, int succeeded)
|
||||
@@ -94,6 +94,8 @@ public static class MetricsMath
|
||||
var installed = succeededAll.Where(s => !IsSkipTerminalState(s)).ToList();
|
||||
var measured = installed.Where(HasMeasuredDuration).ToList();
|
||||
var failed = g.Where(s => s.Status == "Failed").ToList();
|
||||
// Observation ended before any outcome — disclosed, outside the rate and the durations.
|
||||
var incomplete = g.Count(s => s.Status == "Incomplete");
|
||||
var total = g.Count();
|
||||
|
||||
// DoAggregator is the single source for the DO rollup: it filters rows that actually
|
||||
@@ -109,6 +111,7 @@ public static class MetricsMath
|
||||
Skipped = skipped.Count,
|
||||
Unmeasured = installed.Count - measured.Count,
|
||||
Failed = failed.Count,
|
||||
Incomplete = incomplete,
|
||||
// Skips leave the rate (they are not attempts); legacy rows stay in it.
|
||||
FailureRate = TerminalFailureRatePct(failed.Count, installed.Count),
|
||||
AvgDurationSeconds = measured.Count > 0 ? Math.Round(measured.Average(s => s.DurationSeconds), 0) : 0,
|
||||
@@ -151,6 +154,7 @@ public static class MetricsMath
|
||||
TotalInstalls = summaryList.Count,
|
||||
TotalSkipped = appGroups.Sum(a => a.Skipped),
|
||||
TotalUnmeasured = appGroups.Sum(a => a.Unmeasured),
|
||||
TotalIncomplete = appGroups.Sum(a => a.Incomplete),
|
||||
TotalCollisionExcluded = totalCollisionExcluded,
|
||||
SlowestApps = slowestApps,
|
||||
TopFailingApps = topFailingApps,
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Pagination
|
||||
{
|
||||
/// <summary>
|
||||
/// Pure helpers for the <c>GET /api/global/rule-submissions</c> pagination surface — the
|
||||
/// SessionReportsPagination contract with a second server-side filter (<c>status</c>). Both
|
||||
/// filters are bound into the continuation fingerprint so a token issued for one view cannot
|
||||
/// resume another.
|
||||
/// </summary>
|
||||
public static class RuleSubmissionsPagination
|
||||
{
|
||||
public const int DefaultPageSize = 200;
|
||||
|
||||
public static string Fingerprint(string callerTenantId, string? filterTenantId, string? filterStatus) =>
|
||||
ContinuationToken.ComputeFingerprint(new[]
|
||||
{
|
||||
new KeyValuePair<string, string?>("scope", "rule-submissions"),
|
||||
new KeyValuePair<string, string?>("tenantId", callerTenantId),
|
||||
new KeyValuePair<string, string?>("filterTenantId", filterTenantId),
|
||||
new KeyValuePair<string, string?>("filterStatus", filterStatus),
|
||||
});
|
||||
|
||||
public sealed class Parsed
|
||||
{
|
||||
public string? FilterTenantId { get; init; }
|
||||
public string? FilterStatus { get; init; }
|
||||
public int? PageSize { get; init; }
|
||||
public string? Continuation { get; init; }
|
||||
public string? Error { get; init; }
|
||||
}
|
||||
|
||||
public static Parsed ParseQuery(NameValueCollection? query)
|
||||
{
|
||||
var filterTenantIdRaw = query?["tenantId"];
|
||||
var filterStatusRaw = query?["status"];
|
||||
var pageSizeRaw = query?["pageSize"];
|
||||
var continuationRaw = query?["continuation"];
|
||||
|
||||
if (!QueryParams.TryPageSize(pageSizeRaw, out var pageSize, out var pageSizeError))
|
||||
return new Parsed { Error = pageSizeError };
|
||||
|
||||
if (!string.IsNullOrEmpty(filterStatusRaw)
|
||||
&& System.Array.IndexOf(Shared.Models.RuleSubmissionStatuses.Stored, filterStatusRaw) < 0)
|
||||
{
|
||||
return new Parsed { Error = $"status must be one of: {string.Join(", ", Shared.Models.RuleSubmissionStatuses.Stored)}" };
|
||||
}
|
||||
|
||||
var continuation = pageSize.HasValue && !string.IsNullOrEmpty(continuationRaw)
|
||||
? continuationRaw
|
||||
: null;
|
||||
|
||||
return new Parsed
|
||||
{
|
||||
FilterTenantId = string.IsNullOrEmpty(filterTenantIdRaw) ? null : filterTenantIdRaw,
|
||||
FilterStatus = string.IsNullOrEmpty(filterStatusRaw) ? null : filterStatusRaw,
|
||||
PageSize = pageSize,
|
||||
Continuation = continuation,
|
||||
};
|
||||
}
|
||||
|
||||
public static bool TryAcceptContinuation(
|
||||
string raw,
|
||||
string callerTenantId,
|
||||
string? filterTenantId,
|
||||
string? filterStatus,
|
||||
out string azureToken,
|
||||
out string? rejectReason)
|
||||
{
|
||||
var fp = Fingerprint(callerTenantId, filterTenantId, filterStatus);
|
||||
return ContinuationToken.TryDecode(raw, callerTenantId, fp, out azureToken, out rejectReason);
|
||||
}
|
||||
|
||||
public static string BuildNextLink(int pageSize, string wireContinuation, string? filterTenantId, string? filterStatus)
|
||||
{
|
||||
var sb = new StringBuilder("/api/global/rule-submissions");
|
||||
sb.Append('?');
|
||||
sb.Append("pageSize=").Append(pageSize.ToString(CultureInfo.InvariantCulture));
|
||||
sb.Append("&continuation=").Append(System.Uri.EscapeDataString(wireContinuation));
|
||||
if (!string.IsNullOrEmpty(filterTenantId))
|
||||
sb.Append("&tenantId=").Append(System.Uri.EscapeDataString(filterTenantId!));
|
||||
if (!string.IsNullOrEmpty(filterStatus))
|
||||
sb.Append("&status=").Append(System.Uri.EscapeDataString(filterStatus!));
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -318,6 +318,7 @@ builder.Services.AddSingleton<AutopilotMonitor.Functions.Services.Diagnostics.Di
|
||||
builder.Services.AddSingleton<AutopilotMonitor.Functions.Services.Diagnostics.DiagnosticsBlobCascadeDeleter>();
|
||||
builder.Services.AddSingleton<AutopilotMonitor.Functions.Services.Diagnostics.SessionReportDiagnosticsArchiveCopier>();
|
||||
builder.Services.AddSingleton<SessionReportService>();
|
||||
builder.Services.AddSingleton<RuleSubmissionService>();
|
||||
builder.Services.AddSingleton<BootstrapSessionService>();
|
||||
|
||||
// Queue producers + handlers. Consumers are [QueueTrigger] functions under Functions/Queue/
|
||||
@@ -468,6 +469,13 @@ builder.Services.AddHttpClient<TelegramNotificationService>()
|
||||
// Channel-level send API — routes each NotificationChannel to its transport (webhook renderer
|
||||
// vs. the platform Telegram bot). Transient: both transports are typed HttpClients.
|
||||
builder.Services.AddTransient<AutopilotMonitor.Functions.Services.Notifications.NotificationChannelDispatcher>();
|
||||
// What's new → channel digest (hourly timer). The feed client is a typed HttpClient reading the
|
||||
// portal's static whats-new.json; the service is transient because the dispatcher it wraps is.
|
||||
builder.Services.AddHttpClient<AutopilotMonitor.Functions.Services.WhatsNew.IWhatsNewFeedClient,
|
||||
AutopilotMonitor.Functions.Services.WhatsNew.WhatsNewFeedClient>()
|
||||
.ConfigureHttpClient(client => client.Timeout = TimeSpan.FromSeconds(15))
|
||||
.AddPolicyHandler((sp, _) => sp.GetRequiredService<ResiliencePolicies>().ExternalDataApi);
|
||||
builder.Services.AddTransient<AutopilotMonitor.Functions.Services.WhatsNew.WhatsNewNotificationService>();
|
||||
// Durable channel notifications from the agent hot paths (ingest terminal alerts, hardware
|
||||
// rejection): the producer enqueues channel ids + alert, Functions/Queue/NotificationDispatchQueueFunction
|
||||
// re-resolves the channels from the tenant config and sends. Handler is transient because the
|
||||
|
||||
@@ -354,6 +354,11 @@ public static class EndpointAccessPolicyCatalog
|
||||
// troubleshooting action, not a config change — a support-driven Operator may use it.
|
||||
// Viewer and the read-only Global Reader stay excluded (the tier admits no Viewer/Reader).
|
||||
new("POST", "diagnostics/files", EndpointPolicy.TenantAdminOrOperator),
|
||||
// Community rule submissions: the tenant admin submits references to own custom rules
|
||||
// (frozen server-side), lists and withdraws them for the JWT tenant only.
|
||||
new("POST", "rules/submissions", EndpointPolicy.TenantAdminOrGA),
|
||||
new("GET", "rules/submissions", EndpointPolicy.TenantAdminOrGA),
|
||||
new("DELETE", "rules/submissions/{submissionId}", EndpointPolicy.TenantAdminOrGA),
|
||||
new("DELETE", "sessions/{sessionId}", EndpointPolicy.TenantAdminOrGA, TenantScoping.QueryParam),
|
||||
new("GET", "tenants/{tenantId}/admins", EndpointPolicy.TenantAdminOrGA, TenantScoping.RouteParam),
|
||||
new("POST", "tenants/{tenantId}/admins", EndpointPolicy.TenantAdminOrGA, TenantScoping.RouteParam),
|
||||
@@ -513,6 +518,11 @@ public static class EndpointAccessPolicyCatalog
|
||||
new("POST", "global/session-reports/download-ticket", EndpointPolicy.GlobalReadOrAdmin),
|
||||
new("GET", "global/session-reports/download-url", EndpointPolicy.GlobalReadOrAdmin),
|
||||
new("PATCH", "global/session-reports/{reportId}/note", EndpointPolicy.GlobalAdminOnly),
|
||||
// Community rule submissions, operator side: cross-tenant read (Global Reader included), decision GA-only.
|
||||
new("GET", "global/rule-submissions", EndpointPolicy.GlobalReadOrAdmin, TenantScoping.QueryParam),
|
||||
new("GET", "global/rule-submissions/{submissionId}", EndpointPolicy.GlobalReadOrAdmin),
|
||||
new("PATCH", "global/rule-submissions/{submissionId}", EndpointPolicy.GlobalAdminOnly),
|
||||
new("DELETE", "global/rule-submissions/{submissionId}", EndpointPolicy.GlobalAdminOnly),
|
||||
// Flywheel evaluation stream: all annotation lanes across tenants (verdict/rule filters).
|
||||
new("GET", "global/session-annotations", EndpointPolicy.GlobalReadOrAdmin, TenantScoping.QueryParam),
|
||||
new("GET", "global/rules/gather", EndpointPolicy.GlobalReadOrAdmin, TenantScoping.QueryParam),
|
||||
|
||||
@@ -322,6 +322,16 @@ namespace AutopilotMonitor.Functions.Services
|
||||
rule.Notify = null;
|
||||
}
|
||||
|
||||
var existing = (await _ruleRepo.GetAnalyzeRulesAsync(tenantId))
|
||||
.FirstOrDefault(r => r.RuleId == rule.RuleId && !r.IsBuiltIn && !r.IsCommunity);
|
||||
if (existing != null)
|
||||
{
|
||||
rule.CreatedAt = existing.CreatedAt;
|
||||
// Author is stamped from the creator's token at create time and is
|
||||
// immutable afterwards — updates (incl. cross-tenant GA edits) keep it.
|
||||
rule.Author = existing.Author;
|
||||
}
|
||||
|
||||
rule.UpdatedAt = DateTime.UtcNow;
|
||||
return await _ruleRepo.StoreAnalyzeRuleAsync(rule, tenantId);
|
||||
}
|
||||
@@ -333,7 +343,8 @@ namespace AutopilotMonitor.Functions.Services
|
||||
public async Task<AnalyzeRule> CreateFromTemplateAsync(
|
||||
string tenantId,
|
||||
string templateRuleId,
|
||||
Dictionary<string, string> variableValues)
|
||||
Dictionary<string, string> variableValues,
|
||||
string? author = null)
|
||||
{
|
||||
var allRules = await GetAllRulesForTenantAsync(tenantId);
|
||||
var template = allRules.FirstOrDefault(r => r.RuleId == templateRuleId);
|
||||
@@ -370,6 +381,8 @@ namespace AutopilotMonitor.Functions.Services
|
||||
customRule.RuleId = $"{templateRuleId}-CUSTOM";
|
||||
customRule.IsBuiltIn = false;
|
||||
customRule.IsCommunity = false;
|
||||
// The copy is the tenant's rule, not the template author's.
|
||||
customRule.Author = string.IsNullOrWhiteSpace(author) ? "Autopilot Monitor" : author!;
|
||||
customRule.Enabled = true;
|
||||
customRule.DerivedFromTemplateRuleId = templateRuleId;
|
||||
customRule.TemplateVariables = new List<TemplateVariable>();
|
||||
|
||||
+11
@@ -92,6 +92,9 @@ namespace AutopilotMonitor.Functions.Services
|
||||
classification.HasCompletionEvidenceCandidate = true;
|
||||
break;
|
||||
case "agent_shutting_down":
|
||||
// Every shutdown ends this agent run's observation; the max-lifetime
|
||||
// flavour additionally carries the verdict mapping below.
|
||||
classification.AgentShutdownEvent = evt;
|
||||
if (IsMaxLifetimeAgentShutdown(evt))
|
||||
classification.AgentMaxLifetimeShutdownEvent = evt;
|
||||
break;
|
||||
@@ -705,6 +708,14 @@ namespace AutopilotMonitor.Functions.Services
|
||||
public EnrollmentEvent? EspFailureEvent { get; set; }
|
||||
public EnrollmentEvent? SessionStalledEvent { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Any <c>agent_shutting_down</c> in the batch — the agent's last word for this run.
|
||||
/// After the status write, a terminal session closes its still-open app rows on this
|
||||
/// batch: apps that started after the verdict (the agent keeps watching after
|
||||
/// enrollment_complete) got their row only after the terminal seam had already run.
|
||||
/// </summary>
|
||||
public EnrollmentEvent? AgentShutdownEvent { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// <c>agent_shutting_down</c> with <c>Data.reason == "max_lifetime"</c> — the V2
|
||||
/// watchdog shutdown that deliberately carries no enrollment verdict. Mapped to a
|
||||
|
||||
@@ -276,6 +276,21 @@ namespace AutopilotMonitor.Functions.Services
|
||||
updatedSession?.AgentVersion, skewScan);
|
||||
}
|
||||
|
||||
// Observation end: the batch carrying agent_shutting_down is the agent's last word.
|
||||
// On a terminal session an app row still InProgress now will never get a terminal
|
||||
// event — close it as Incomplete. The terminal seam already did this on the verdict
|
||||
// batch; this re-run catches rows opened after the verdict (the IME keeps installing
|
||||
// and the agent keeps watching after enrollment_complete). Non-terminal sessions
|
||||
// (reboot shutdown, WhiteGlove part 1) keep their rows open. Idempotent + fail-soft.
|
||||
if (classification.AgentShutdownEvent != null
|
||||
&& updatedSession != null
|
||||
&& (updatedSession.Status == SessionStatus.Succeeded
|
||||
|| updatedSession.Status == SessionStatus.Failed
|
||||
|| updatedSession.Status == SessionStatus.Incomplete))
|
||||
{
|
||||
await _metricsRepo.CloseOpenAppInstallsForSessionAsync(request.TenantId, request.SessionId);
|
||||
}
|
||||
|
||||
// Auto-analyze fan-out: enqueue a queue message instead of running fire-and-forget
|
||||
// Task.Run inside the function. The previous in-function approach could be killed
|
||||
// mid-flight by Functions scale-in (HTTP 200 returned → worker unloaded → rules
|
||||
|
||||
@@ -11,8 +11,14 @@ namespace AutopilotMonitor.Functions.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Exposes the latest published agent/bootstrap versions as read from the
|
||||
/// public <c>version.json</c> blob. Caches the result in memory for 12h
|
||||
/// (short TTL on transient failures). Admin endpoint can force-refresh.
|
||||
/// public <c>version.json</c> blob. The TTL is deliberately short: this number is
|
||||
/// what the portal announces right after a release ("Latest agent version" in the
|
||||
/// What's new panel), so a long cache shows the previous release for hours — and
|
||||
/// because the cache is per Function instance, different instances would announce
|
||||
/// different versions at the same time. The origin is a 200-byte no-cache blob
|
||||
/// behind the download alias, so refetching it every few minutes costs nothing.
|
||||
/// On a fetch failure the last known good value is kept rather than blanking the
|
||||
/// display. Admin endpoint can force-refresh.
|
||||
/// </summary>
|
||||
public interface ILatestVersionsService
|
||||
{
|
||||
@@ -33,13 +39,19 @@ namespace AutopilotMonitor.Functions.Services
|
||||
// it could silently serve a stale version while the release pipeline is green.
|
||||
public const string VersionJsonUrl = Constants.AgentDownloadBaseUrl + "/" + Constants.AgentVersionFileName;
|
||||
private const string CacheKey = "latest-versions";
|
||||
private static readonly TimeSpan CacheDuration = TimeSpan.FromHours(12);
|
||||
private static readonly TimeSpan FailureCacheDuration = TimeSpan.FromMinutes(5);
|
||||
private static readonly TimeSpan CacheDuration = TimeSpan.FromMinutes(5);
|
||||
private static readonly TimeSpan FailureCacheDuration = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly IMemoryCache _cache;
|
||||
private readonly ILogger<LatestVersionsService> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Survives cache expiry: served when the blob read fails so a transient hiccup
|
||||
/// hides the version line for at most one request instead of a full failure TTL.
|
||||
/// </summary>
|
||||
private volatile LatestVersions? _lastGood;
|
||||
|
||||
public LatestVersionsService(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
IMemoryCache cache,
|
||||
@@ -85,15 +97,22 @@ namespace AutopilotMonitor.Functions.Services
|
||||
FromCache: false);
|
||||
|
||||
_cache.Set(CacheKey, result, CacheDuration);
|
||||
_lastGood = result;
|
||||
_logger.LogInformation("LatestVersions refreshed: agent={AgentVersion}, bootstrap={BootstrapVersion}", version, bootstrapVersion);
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to fetch {Url}; caching null for {Minutes}m", VersionJsonUrl, FailureCacheDuration.TotalMinutes);
|
||||
// Cache failure briefly to avoid hammering blob on repeated calls
|
||||
_cache.Set(CacheKey, (LatestVersions?)null, FailureCacheDuration);
|
||||
return null;
|
||||
var lastGood = _lastGood;
|
||||
_logger.LogWarning(
|
||||
ex,
|
||||
"Failed to fetch {Url}; serving {Fallback} for {Minutes}m",
|
||||
VersionJsonUrl,
|
||||
lastGood == null ? "nothing" : $"the value fetched at {lastGood.FetchedAtUtc:O}",
|
||||
FailureCacheDuration.TotalMinutes);
|
||||
// Cache the outcome briefly to avoid hammering the blob on repeated calls.
|
||||
_cache.Set(CacheKey, lastGood, FailureCacheDuration);
|
||||
return lastGood == null ? null : lastGood with { FromCache = true };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,7 +328,12 @@ namespace AutopilotMonitor.Functions.Services
|
||||
// Idempotent, positive-evidence-only; also heals sessions that went
|
||||
// terminal before the resolution seam existed (hadNoRow backfill).
|
||||
if (eventCountMoved || hadNoRow)
|
||||
{
|
||||
await _metricsRepo.ResolveEspBlockingForSessionAsync(session.TenantId, session.SessionId);
|
||||
// Same late-batch reasoning: an app row opened after the agent's
|
||||
// shutdown batch was never closed — the sweep is its self-heal.
|
||||
await _metricsRepo.CloseOpenAppInstallsForSessionAsync(session.TenantId, session.SessionId);
|
||||
}
|
||||
}
|
||||
|
||||
if (breakdown == null)
|
||||
@@ -1045,6 +1050,20 @@ namespace AutopilotMonitor.Functions.Services
|
||||
_logger.LogWarning(ex, "Failed to cleanup old tenant notifications");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Closed community rule submissions: withdrawn 30d, declined 90d (RuleSubmissionRetention);
|
||||
// pending/approved/published rows are never swept.
|
||||
var deleted = await _ruleSubmissionRepo.DeleteExpiredAsync(now);
|
||||
if (deleted > 0)
|
||||
_logger.LogInformation("Rule submissions cleanup: deleted {Count} closed rows (withdrawn {WithdrawnDays}d / declined {DeclinedDays}d)",
|
||||
deleted, RuleSubmissionRetention.WithdrawnDays, RuleSubmissionRetention.DeclinedDays);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to cleanup closed rule submissions");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var deleted = await _hardwareRejectionTracker.DeleteOlderThanAsync(now.AddDays(-hardwareRejectionRetentionDays));
|
||||
|
||||
@@ -41,6 +41,7 @@ namespace AutopilotMonitor.Functions.Services
|
||||
private readonly INotificationRepository _notificationRepo;
|
||||
private readonly ITenantNotificationRepository _tenantNotificationRepo;
|
||||
private readonly IHardwareRejectionNotificationTracker _hardwareRejectionTracker;
|
||||
private readonly IRuleSubmissionRepository _ruleSubmissionRepo;
|
||||
private readonly IDelegationInvitationRepository _delegationInvitationRepo;
|
||||
private readonly DataAccess.TableStorage.BackupJobsRepository _backupJobsRepo;
|
||||
private readonly OpsEventService _opsEventService;
|
||||
@@ -75,6 +76,7 @@ namespace AutopilotMonitor.Functions.Services
|
||||
INotificationRepository notificationRepo,
|
||||
ITenantNotificationRepository tenantNotificationRepo,
|
||||
IHardwareRejectionNotificationTracker hardwareRejectionTracker,
|
||||
IRuleSubmissionRepository ruleSubmissionRepo,
|
||||
IDelegationInvitationRepository delegationInvitationRepo,
|
||||
DataAccess.TableStorage.BackupJobsRepository backupJobsRepo,
|
||||
OpsEventService opsEventService,
|
||||
@@ -103,6 +105,7 @@ namespace AutopilotMonitor.Functions.Services
|
||||
_opsEventRepo = opsEventRepo;
|
||||
_notificationRepo = notificationRepo;
|
||||
_tenantNotificationRepo = tenantNotificationRepo;
|
||||
_ruleSubmissionRepo = ruleSubmissionRepo;
|
||||
_hardwareRejectionTracker = hardwareRejectionTracker;
|
||||
_delegationInvitationRepo = delegationInvitationRepo;
|
||||
_backupJobsRepo = backupJobsRepo;
|
||||
|
||||
+102
@@ -4,6 +4,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Models.Notifications;
|
||||
using AutopilotMonitor.Shared.Models.WhatsNew;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Services.Notifications
|
||||
{
|
||||
@@ -465,5 +466,106 @@ namespace AutopilotMonitor.Functions.Services.Notifications
|
||||
var result = string.Join(" ", Array.FindAll(parts, p => p != null));
|
||||
return string.IsNullOrEmpty(result) ? "\u2013" : result;
|
||||
}
|
||||
|
||||
// ── What's new digest ─────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Entries rendered in full; the rest is folded into a "+N more" line.</summary>
|
||||
public const int WhatsNewMaxSections = 6;
|
||||
private const int WhatsNewMaxBodyLength = 280;
|
||||
|
||||
/// <summary>
|
||||
/// Builds the "What's new" digest sent to channels with <c>NotifyOnWhatsNew</c>: one
|
||||
/// message per batch of newly published changelog entries (newest first), one section per
|
||||
/// entry. Entry text is inline markdown authored for the docs; renderers disagree on
|
||||
/// markdown dialects (Adaptive Card vs. Slack mrkdwn vs. Discord), so it is flattened to
|
||||
/// plain text here and the links live in the action buttons instead.
|
||||
/// </summary>
|
||||
public static NotificationAlert BuildWhatsNewAlert(
|
||||
IReadOnlyList<WhatsNewFeedEntry> newEntries,
|
||||
IReadOnlyDictionary<string, string>? docsUrls,
|
||||
string portalWhatsNewUrl)
|
||||
{
|
||||
if (newEntries == null) throw new ArgumentNullException(nameof(newEntries));
|
||||
if (newEntries.Count == 0) throw new ArgumentException("At least one entry is required.", nameof(newEntries));
|
||||
|
||||
var ordered = newEntries.OrderByDescending(e => e.AddedUtc).ToList();
|
||||
var platformCount = ordered.Count(e => e.Channel == WhatsNewFeed.PlatformChannel);
|
||||
var agentCount = ordered.Count - platformCount;
|
||||
|
||||
var alert = new NotificationAlert
|
||||
{
|
||||
EventType = "whats_new",
|
||||
Title = "\ud83c\udd95 What's new in Autopilot Monitor",
|
||||
Summary = BuildWhatsNewSummary(ordered.Count, platformCount, agentCount),
|
||||
Severity = NotificationSeverity.Info,
|
||||
ThemeColor = "0078D4",
|
||||
};
|
||||
|
||||
foreach (var entry in ordered.Take(WhatsNewMaxSections))
|
||||
{
|
||||
var channelLabel = entry.Channel == WhatsNewFeed.AgentChannel ? "Agent" : "Platform";
|
||||
var heading = $"{channelLabel} \u00b7 {entry.AddedUtc:MMM d, yyyy}";
|
||||
var title = StripInlineMarkdown(entry.Title);
|
||||
if (!string.IsNullOrEmpty(title))
|
||||
heading += $" \u2014 {title}";
|
||||
|
||||
alert.Sections.Add(new NotificationSection
|
||||
{
|
||||
Title = heading,
|
||||
Text = Truncate(StripInlineMarkdown(entry.Body), WhatsNewMaxBodyLength),
|
||||
});
|
||||
}
|
||||
|
||||
var remaining = ordered.Count - WhatsNewMaxSections;
|
||||
if (remaining > 0)
|
||||
{
|
||||
alert.Sections.Add(new NotificationSection
|
||||
{
|
||||
Title = string.Empty,
|
||||
Text = $"+ {remaining} more update{(remaining == 1 ? "" : "s")} \u2014 see the full changelog.",
|
||||
});
|
||||
}
|
||||
|
||||
alert.Actions.Add(new NotificationAction { Type = "openUrl", Title = "Open What's new", Url = portalWhatsNewUrl });
|
||||
|
||||
// Changelog button for the channel with the most new entries (platform on a tie).
|
||||
var primaryChannel = agentCount > platformCount ? WhatsNewFeed.AgentChannel : WhatsNewFeed.PlatformChannel;
|
||||
if (docsUrls != null && docsUrls.TryGetValue(primaryChannel, out var docsUrl) && !string.IsNullOrWhiteSpace(docsUrl))
|
||||
alert.Actions.Add(new NotificationAction { Type = "openUrl", Title = "Full changelog", Url = docsUrl });
|
||||
|
||||
return alert;
|
||||
}
|
||||
|
||||
private static string BuildWhatsNewSummary(int total, int platformCount, int agentCount)
|
||||
{
|
||||
var parts = new List<string>(2);
|
||||
if (platformCount > 0) parts.Add($"{platformCount} platform");
|
||||
if (agentCount > 0) parts.Add($"{agentCount} agent");
|
||||
var breakdown = parts.Count == 2 ? $" ({string.Join(", ", parts)})" : string.Empty;
|
||||
return $"{total} new update{(total == 1 ? "" : "s")}{breakdown} just went live in the portal.";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flattens the docs' inline markdown: <c>[label](url)</c> → label, <c>**x**</c>/<c>__x__</c> → x,
|
||||
/// <c>`x`</c> → x, <c>*x*</c>/<c>_x_</c> → x. Null-safe; whitespace is collapsed.
|
||||
/// </summary>
|
||||
internal static string StripInlineMarkdown(string? markdown)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(markdown))
|
||||
return string.Empty;
|
||||
|
||||
var text = markdown!;
|
||||
text = System.Text.RegularExpressions.Regex.Replace(text, @"\[([^\]]+)\]\([^)]*\)", "$1");
|
||||
text = System.Text.RegularExpressions.Regex.Replace(text, @"\*\*(.+?)\*\*", "$1");
|
||||
text = System.Text.RegularExpressions.Regex.Replace(text, @"__(.+?)__", "$1");
|
||||
text = System.Text.RegularExpressions.Regex.Replace(text, @"`([^`]*)`", "$1");
|
||||
text = System.Text.RegularExpressions.Regex.Replace(text, @"(?<![\w*])\*(?!\s)(.+?)(?<!\s)\*(?![\w*])", "$1");
|
||||
text = System.Text.RegularExpressions.Regex.Replace(text, @"(?<![\w_])_(?!\s)(.+?)(?<!\s)_(?![\w_])", "$1");
|
||||
text = System.Text.RegularExpressions.Regex.Replace(text, @"\s+", " ");
|
||||
return text.Trim();
|
||||
}
|
||||
|
||||
private static string Truncate(string text, int maxLength)
|
||||
=> text.Length <= maxLength ? text : text[..(maxLength - 1)].TrimEnd() + "\u2026";
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -141,6 +141,7 @@ namespace AutopilotMonitor.Functions.Services.Offboarding
|
||||
{
|
||||
(Constants.TableNames.BootstrapSessions, "CodeLookup"),
|
||||
(Constants.TableNames.SessionReports, "reports"),
|
||||
(Constants.TableNames.RuleSubmissions, "submissions"),
|
||||
};
|
||||
|
||||
// Plan §6.3.2 — Variant C (TenantId property only).
|
||||
|
||||
@@ -127,6 +127,18 @@ namespace AutopilotMonitor.Functions.Services
|
||||
});
|
||||
}
|
||||
|
||||
// Field-absence gate: not_exists WITH a dataField matches when no event of the type
|
||||
// carries a non-empty value at that field — including when the type is absent — the
|
||||
// same semantics as the precondition gate. Must run before the "no matching events"
|
||||
// veto and the per-event loop below, whose null short-circuit could never express
|
||||
// "the field is missing" (session 683f1eff: "esp_failure_settle_started.errorCode
|
||||
// not_exists" was silently dead).
|
||||
if (!string.IsNullOrEmpty(condition.DataField)
|
||||
&& string.Equals(condition.Operator, "not_exists", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return EvaluateFieldAbsence(condition, matchingEvents);
|
||||
}
|
||||
|
||||
if (!matchingEvents.Any())
|
||||
return (false, "no matching events");
|
||||
|
||||
@@ -206,6 +218,11 @@ namespace AutopilotMonitor.Functions.Services
|
||||
{
|
||||
var matchingEvents = ApplyValueFilter(condition, events.Where(e => MatchesEventType(e, condition.EventType)).ToList());
|
||||
|
||||
// Field-absence gate — see EvaluateEventTypeCondition; here it applies to the
|
||||
// filtered event set, so "no event with filterField=x carries dataField" is expressible.
|
||||
if (string.Equals(condition.Operator, "not_exists", StringComparison.OrdinalIgnoreCase))
|
||||
return EvaluateFieldAbsence(condition, matchingEvents);
|
||||
|
||||
foreach (var evt in matchingEvents)
|
||||
{
|
||||
var fieldValue = GetDataFieldValue(evt, condition.DataField);
|
||||
@@ -227,6 +244,26 @@ namespace AutopilotMonitor.Functions.Services
|
||||
return (false, "no matching data");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>not_exists</c> with a dataField: true when none of <paramref name="matchingEvents"/>
|
||||
/// carries a non-empty value at the field (an empty set counts as absent). A single
|
||||
/// non-empty value disproves it. Evidence names the type, the field and how many events
|
||||
/// of the type were inspected, so a finding can say "0 esp_failure_settle_started events
|
||||
/// carried errorCode" rather than pointing at one event.
|
||||
/// </summary>
|
||||
private static (bool matched, object evidence) EvaluateFieldAbsence(RuleCondition condition, List<EnrollmentEvent> matchingEvents)
|
||||
{
|
||||
if (matchingEvents.Any(e => !string.IsNullOrEmpty(GetDataFieldValue(e, condition.DataField))))
|
||||
return (false, "data field present");
|
||||
|
||||
return (true, new Dictionary<string, object>
|
||||
{
|
||||
["eventType"] = condition.EventType,
|
||||
["field"] = condition.DataField,
|
||||
["count"] = matchingEvents.Count
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evidence values feed the finding UI and {{token}} interpolation, both of which
|
||||
/// render via ToString() — a raw List would surface as its .NET type name
|
||||
|
||||
@@ -0,0 +1,559 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Functions.Rules;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Pagination;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Community rule submissions: freezes a tenant's custom rule at submit time, records the
|
||||
/// pre-flight findings and fire telemetry, and carries the review through to the repo file.
|
||||
/// Publishing itself is a repository commit plus reseed — this service never writes the
|
||||
/// global rule partition; <c>published</c> is derived from the catalog on every read.
|
||||
/// </summary>
|
||||
public class RuleSubmissionService
|
||||
{
|
||||
public const int MaxRuleJsonLength = 32_000;
|
||||
public const int MaxSubmissionsPerTenantPerDay = 10;
|
||||
public const int FireStatsDays = 30;
|
||||
|
||||
/// <summary>The credit text is published in the repo, so it is a name and nothing else.</summary>
|
||||
private static readonly Regex AttributionNameShape = new(@"^[\p{L}\p{N} .,'&()\-]{1,64}$", RegexOptions.CultureInvariant);
|
||||
|
||||
/// <summary>Rule fields that belong to the server or the tenant, never to a frozen or published rule.</summary>
|
||||
private static readonly string[] StrippedFields =
|
||||
{
|
||||
"isBuiltIn", "provenance", "createdAt", "updatedAt",
|
||||
"markSessionAsFailed", "notifyDefault", "notify", "notifyChannelIds",
|
||||
};
|
||||
|
||||
private static readonly JsonSerializerOptions RepoFileOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
};
|
||||
|
||||
// The dominant convention per kind in rules/ (ANALYZE-APP vs GATHER-APPS …); an unmapped
|
||||
// category falls back to its upper-cased name, which the reviewer can overrule.
|
||||
private static readonly Dictionary<string, string> AnalyzeCategoryCodes = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["apps"] = "APP", ["device"] = "DEV", ["enrollment"] = "ENRL", ["esp"] = "ESP",
|
||||
["identity"] = "ID", ["network"] = "NET", ["security"] = "SEC",
|
||||
};
|
||||
private static readonly Dictionary<string, string> GatherCategoryCodes = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["apps"] = "APPS", ["device"] = "DEVICE", ["enrollment"] = "ENROLL", ["esp"] = "ESP",
|
||||
["identity"] = "ID", ["network"] = "NET",
|
||||
};
|
||||
|
||||
private readonly IRuleSubmissionRepository _submissions;
|
||||
private readonly IRuleRepository _ruleRepo;
|
||||
private readonly IMetricsRepository _metricsRepo;
|
||||
private readonly TenantConfigurationService _configService;
|
||||
private readonly ILogger<RuleSubmissionService> _logger;
|
||||
|
||||
public RuleSubmissionService(
|
||||
IRuleSubmissionRepository submissions,
|
||||
IRuleRepository ruleRepo,
|
||||
IMetricsRepository metricsRepo,
|
||||
TenantConfigurationService configService,
|
||||
ILogger<RuleSubmissionService> logger)
|
||||
{
|
||||
_submissions = submissions;
|
||||
_ruleRepo = ruleRepo;
|
||||
_metricsRepo = metricsRepo;
|
||||
_configService = configService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
// ── Submit ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Freezes and stores every referenced rule. All-or-nothing: a pre-flight error on any
|
||||
/// item rejects the whole batch (<see cref="ArgumentException"/>), so a tenant never ends
|
||||
/// up with half a submission. <see cref="InvalidOperationException"/> = conflict (open
|
||||
/// duplicate, daily cap).
|
||||
/// </summary>
|
||||
public async Task<List<RuleSubmission>> SubmitAsync(
|
||||
string tenantId, SubmitRuleSubmissionsRequest request, string submittedBy, string submittedByName)
|
||||
{
|
||||
if (request.Items == null || request.Items.Count == 0)
|
||||
throw new ArgumentException("At least one rule is required.");
|
||||
if (request.Items.Count > SubmitRuleSubmissionsRequest.MaxItems)
|
||||
throw new ArgumentException($"At most {SubmitRuleSubmissionsRequest.MaxItems} rules per submission.");
|
||||
if (request.Comment != null && request.Comment.Length > SubmitRuleSubmissionsRequest.MaxCommentLength)
|
||||
throw new ArgumentException($"Comment exceeds {SubmitRuleSubmissionsRequest.MaxCommentLength} characters.");
|
||||
|
||||
var attributionName = await ResolveAttributionNameAsync(tenantId, request.AttributionMode, request.AttributionName);
|
||||
var contactEmail = NormalizeEmail(request.Email);
|
||||
|
||||
var distinct = request.Items
|
||||
.Select(i => (Kind: i.Kind?.Trim().ToLowerInvariant() ?? string.Empty, RuleId: i.RuleId?.Trim() ?? string.Empty))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
foreach (var (kind, ruleId) in distinct)
|
||||
{
|
||||
if (!RuleSubmissionKinds.IsKnown(kind))
|
||||
throw new ArgumentException($"Unknown rule kind '{kind}'.");
|
||||
if (string.IsNullOrEmpty(ruleId))
|
||||
throw new ArgumentException("ruleId is required for every item.");
|
||||
}
|
||||
|
||||
var existing = await _submissions.GetForTenantAsync(tenantId);
|
||||
var since = DateTime.UtcNow.AddDays(-1);
|
||||
if (existing.Count(s => s.SubmittedAt >= since) + distinct.Count > MaxSubmissionsPerTenantPerDay)
|
||||
throw new InvalidOperationException($"At most {MaxSubmissionsPerTenantPerDay} rule submissions per tenant and day.");
|
||||
|
||||
var analyzeRules = distinct.Any(d => d.Kind == RuleSubmissionKinds.Analyze)
|
||||
? await _ruleRepo.GetAnalyzeRulesAsync(tenantId) : new List<AnalyzeRule>();
|
||||
var gatherRules = distinct.Any(d => d.Kind == RuleSubmissionKinds.Gather)
|
||||
? await _ruleRepo.GetGatherRulesAsync(tenantId) : new List<GatherRule>();
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
var batchId = NewId();
|
||||
var prepared = new List<RuleSubmission>(distinct.Count);
|
||||
var errors = new List<string>();
|
||||
|
||||
foreach (var (kind, ruleId) in distinct)
|
||||
{
|
||||
if (existing.Any(s => s.Status == RuleSubmissionStatuses.Pending
|
||||
&& s.RuleKind == kind
|
||||
&& string.Equals(s.SourceRuleId, ruleId, StringComparison.OrdinalIgnoreCase)))
|
||||
throw new InvalidOperationException($"Rule '{ruleId}' already has a pending submission.");
|
||||
|
||||
var submission = new RuleSubmission
|
||||
{
|
||||
SubmissionId = NewId(),
|
||||
BatchId = batchId,
|
||||
TenantId = tenantId,
|
||||
RuleKind = kind,
|
||||
SourceRuleId = ruleId,
|
||||
Comment = string.IsNullOrWhiteSpace(request.Comment) ? null : request.Comment!.Trim(),
|
||||
SubmittedBy = submittedBy,
|
||||
SubmittedByName = submittedByName,
|
||||
ContactEmail = contactEmail,
|
||||
AttributionMode = request.AttributionMode,
|
||||
AttributionName = attributionName,
|
||||
SubmittedAt = now,
|
||||
Status = RuleSubmissionStatuses.Pending,
|
||||
};
|
||||
|
||||
var findings = new List<RuleSubmissionFinding>();
|
||||
if (kind == RuleSubmissionKinds.Analyze)
|
||||
{
|
||||
var rule = analyzeRules.FirstOrDefault(r => string.Equals(r.RuleId, ruleId, StringComparison.OrdinalIgnoreCase)
|
||||
&& !r.IsBuiltIn && !r.IsCommunity);
|
||||
if (rule == null) { errors.Add($"{ruleId}: not a custom analyze rule of this tenant."); continue; }
|
||||
|
||||
submission.Title = rule.Title ?? string.Empty;
|
||||
submission.Category = rule.Category ?? string.Empty;
|
||||
submission.DerivedFromTemplateRuleId = rule.DerivedFromTemplateRuleId;
|
||||
submission.RuleJson = FreezeRule(rule);
|
||||
foreach (var e in DryRunAnalyzeRuleFunction.ValidateDraftRule(rule))
|
||||
findings.Add(new RuleSubmissionFinding { Level = "error", Message = e });
|
||||
if (!string.IsNullOrEmpty(rule.DerivedFromTemplateRuleId))
|
||||
findings.Add(new RuleSubmissionFinding { Level = "info", Message = $"Derived from template {rule.DerivedFromTemplateRuleId} — usually a filled-in copy rather than a new detection." });
|
||||
}
|
||||
else
|
||||
{
|
||||
var rule = gatherRules.FirstOrDefault(r => string.Equals(r.RuleId, ruleId, StringComparison.OrdinalIgnoreCase)
|
||||
&& !r.IsBuiltIn && !r.IsCommunity);
|
||||
if (rule == null) { errors.Add($"{ruleId}: not a custom gather rule of this tenant."); continue; }
|
||||
|
||||
submission.Title = rule.Title ?? string.Empty;
|
||||
submission.Category = rule.Category ?? string.Empty;
|
||||
submission.RuleJson = FreezeRule(rule);
|
||||
if (string.IsNullOrWhiteSpace(rule.CollectorType)) findings.Add(new RuleSubmissionFinding { Level = "error", Message = "collectorType is required" });
|
||||
if (string.IsNullOrWhiteSpace(rule.Target)) findings.Add(new RuleSubmissionFinding { Level = "error", Message = "target is required" });
|
||||
if (string.IsNullOrWhiteSpace(rule.Trigger)) findings.Add(new RuleSubmissionFinding { Level = "error", Message = "trigger is required" });
|
||||
if (string.IsNullOrWhiteSpace(rule.OutputEventType)) findings.Add(new RuleSubmissionFinding { Level = "error", Message = "outputEventType is required" });
|
||||
var scopeError = GatherRulesFunction.ValidateScopeAndEmitMode(rule);
|
||||
if (scopeError != null) findings.Add(new RuleSubmissionFinding { Level = "error", Message = scopeError });
|
||||
findings.Add(new RuleSubmissionFinding { Level = "info", Message = "Collector guardrails are enforced on the device; the full allowlist check runs in the MCP validate_rule tool." });
|
||||
}
|
||||
|
||||
if (submission.RuleJson.Length > MaxRuleJsonLength)
|
||||
findings.Add(new RuleSubmissionFinding { Level = "error", Message = $"rule document exceeds {MaxRuleJsonLength} characters" });
|
||||
|
||||
var itemErrors = findings.Where(f => f.Level == "error").Select(f => $"{ruleId}: {f.Message}").ToList();
|
||||
if (itemErrors.Count > 0) { errors.AddRange(itemErrors); continue; }
|
||||
|
||||
submission.ValidationFindings = findings;
|
||||
submission.SourceFireStats = await GetFireStatsAsync(tenantId, kind, ruleId);
|
||||
prepared.Add(submission);
|
||||
}
|
||||
|
||||
if (errors.Count > 0)
|
||||
throw new ArgumentException("Submission rejected: " + string.Join(" | ", errors));
|
||||
|
||||
foreach (var submission in prepared)
|
||||
{
|
||||
if (!await _submissions.AddAsync(submission))
|
||||
throw new InvalidOperationException("Failed to store the submission.");
|
||||
}
|
||||
|
||||
return prepared;
|
||||
}
|
||||
|
||||
private async Task<string> ResolveAttributionNameAsync(string tenantId, string? mode, string? requestedName)
|
||||
{
|
||||
switch (mode)
|
||||
{
|
||||
case RuleAttributionModes.Anonymous:
|
||||
return RuleAttributionModes.AnonymousAuthor;
|
||||
case RuleAttributionModes.Organization:
|
||||
{
|
||||
var config = await _configService.GetConfigurationIfExistsAsync(tenantId);
|
||||
var name = config?.CompanyName;
|
||||
if (string.IsNullOrWhiteSpace(name)) name = config?.DomainName;
|
||||
if (string.IsNullOrWhiteSpace(name))
|
||||
throw new ArgumentException("No organization name is known for this tenant — set the company name in the tenant settings or choose another attribution.");
|
||||
return ValidateAttributionName(name!.Trim());
|
||||
}
|
||||
case RuleAttributionModes.Person:
|
||||
if (string.IsNullOrWhiteSpace(requestedName))
|
||||
throw new ArgumentException("attributionName is required for the person attribution.");
|
||||
return ValidateAttributionName(requestedName!.Trim());
|
||||
default:
|
||||
throw new ArgumentException($"attributionMode must be one of: {string.Join(", ", RuleAttributionModes.All)}.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Trimmed, or null when empty; the shape check is deliberately loose (exactly one @ with something on both sides, no whitespace, at most 254 characters).</summary>
|
||||
internal static string? NormalizeEmail(string? email)
|
||||
{
|
||||
var trimmed = email?.Trim();
|
||||
if (string.IsNullOrEmpty(trimmed)) return null;
|
||||
var at = trimmed!.IndexOf('@');
|
||||
if (trimmed.Length > SubmitRuleSubmissionsRequest.MaxEmailLength
|
||||
|| at <= 0
|
||||
|| at != trimmed.LastIndexOf('@')
|
||||
|| at == trimmed.Length - 1
|
||||
|| trimmed.Any(char.IsWhiteSpace))
|
||||
throw new ArgumentException("email is not a valid address.");
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
internal static string ValidateAttributionName(string name)
|
||||
{
|
||||
if (!AttributionNameShape.IsMatch(name))
|
||||
throw new ArgumentException("attributionName may only contain letters, digits, spaces and . , ' & ( ) - (1–64 characters).");
|
||||
return name;
|
||||
}
|
||||
|
||||
/// <summary>Wire JSON of the rule minus server and tenant fields — what the reviewer sees and what ships.</summary>
|
||||
internal static string FreezeRule<T>(T rule)
|
||||
{
|
||||
var node = JsonSerializer.SerializeToNode(rule, ApiJsonOptions.Create()) as JsonObject
|
||||
?? throw new InvalidOperationException("Rule did not serialize to an object.");
|
||||
foreach (var field in StrippedFields) node.Remove(field);
|
||||
return node.ToJsonString();
|
||||
}
|
||||
|
||||
private async Task<RuleSubmissionFireStats?> GetFireStatsAsync(string tenantId, string kind, string ruleId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var end = DateTime.UtcNow;
|
||||
var start = end.AddDays(-FireStatsDays);
|
||||
var entries = await _metricsRepo.GetRuleStatsAsync(
|
||||
tenantId, start.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
end.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), kind);
|
||||
var mine = entries.Where(e => string.Equals(e.RuleId, ruleId, StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
return new RuleSubmissionFireStats
|
||||
{
|
||||
Days = FireStatsDays,
|
||||
FireCount = mine.Sum(e => e.FireCount),
|
||||
SessionsEvaluated = mine.Sum(e => e.SessionsEvaluated),
|
||||
EvaluationCount = mine.Sum(e => e.EvaluationCount),
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Fire stats unavailable for {RuleId} (tenant {TenantId})", ruleId, tenantId);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Read ────────────────────────────────────────────────────────────────
|
||||
|
||||
public Task<RuleSubmission?> GetAsync(string submissionId) => _submissions.GetAsync(submissionId);
|
||||
|
||||
public Task<List<RuleSubmission>> GetForTenantAsync(string tenantId) => _submissions.GetForTenantAsync(tenantId);
|
||||
|
||||
public Task<RawPage<RuleSubmission>> GetPageAsync(string? tenantId, string? status, int pageSize, string? continuation)
|
||||
=> _submissions.GetPageAsync(tenantId, status, pageSize, continuation);
|
||||
|
||||
/// <summary>Projects rows to the wire shape with the effective status (<c>published</c> derived from the catalog).</summary>
|
||||
public async Task<List<RuleSubmissionItem>> ToItemsAsync(IEnumerable<RuleSubmission> rows)
|
||||
{
|
||||
var list = rows.ToList();
|
||||
HashSet<string>? globalAnalyze = null, globalGather = null;
|
||||
if (list.Any(s => s.Status == RuleSubmissionStatuses.Approved && !string.IsNullOrEmpty(s.PublishedRuleId)))
|
||||
{
|
||||
globalAnalyze = (await _ruleRepo.GetAnalyzeRulesAsync("global")).Select(r => r.RuleId).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
globalGather = (await _ruleRepo.GetGatherRulesAsync("global")).Select(r => r.RuleId).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
return list.Select(s => ToItem(s, IsPublished(s, globalAnalyze, globalGather))).ToList();
|
||||
}
|
||||
|
||||
private static bool IsPublished(RuleSubmission s, HashSet<string>? globalAnalyze, HashSet<string>? globalGather)
|
||||
{
|
||||
if (s.Status != RuleSubmissionStatuses.Approved || string.IsNullOrEmpty(s.PublishedRuleId)) return false;
|
||||
var set = s.RuleKind == RuleSubmissionKinds.Analyze ? globalAnalyze : globalGather;
|
||||
return set != null && set.Contains(s.PublishedRuleId!);
|
||||
}
|
||||
|
||||
internal static RuleSubmissionItem ToItem(RuleSubmission s, bool published) => new()
|
||||
{
|
||||
SubmissionId = s.SubmissionId,
|
||||
BatchId = s.BatchId,
|
||||
TenantId = s.TenantId,
|
||||
RuleKind = s.RuleKind,
|
||||
SourceRuleId = s.SourceRuleId,
|
||||
Title = s.Title,
|
||||
Category = s.Category,
|
||||
Comment = s.Comment,
|
||||
SubmittedBy = s.SubmittedBy,
|
||||
SubmittedByName = s.SubmittedByName,
|
||||
ContactEmail = s.ContactEmail,
|
||||
AttributionMode = s.AttributionMode,
|
||||
AttributionName = s.AttributionName,
|
||||
SubmittedAt = s.SubmittedAt,
|
||||
Status = published ? RuleSubmissionStatuses.Published : s.Status,
|
||||
ValidationFindings = s.ValidationFindings,
|
||||
SourceFireStats = s.SourceFireStats,
|
||||
ReviewedBy = s.ReviewedBy,
|
||||
ReviewedAt = s.ReviewedAt,
|
||||
ReviewComment = s.ReviewComment,
|
||||
WillBeAdapted = s.WillBeAdapted,
|
||||
PublishedRuleId = s.PublishedRuleId,
|
||||
DerivedFromTemplateRuleId = s.DerivedFromTemplateRuleId,
|
||||
};
|
||||
|
||||
/// <summary>Everything the reviewer (human or AI) needs for one submission.</summary>
|
||||
public async Task<RuleSubmissionDetailResponse?> GetDetailAsync(string submissionId)
|
||||
{
|
||||
var s = await _submissions.GetAsync(submissionId);
|
||||
if (s == null) return null;
|
||||
|
||||
var item = (await ToItemsAsync(new[] { s }))[0];
|
||||
var response = new RuleSubmissionDetailResponse { Success = true, Submission = item };
|
||||
|
||||
if (s.RuleKind == RuleSubmissionKinds.Analyze)
|
||||
{
|
||||
var rule = JsonSerializer.Deserialize<AnalyzeRule>(s.RuleJson, ApiJsonOptions.Read);
|
||||
if (rule != null) { rule.IsBuiltIn = false; rule.IsCommunity = false; }
|
||||
response.AnalyzeRule = rule;
|
||||
}
|
||||
else
|
||||
{
|
||||
var rule = JsonSerializer.Deserialize<GatherRule>(s.RuleJson, ApiJsonOptions.Read);
|
||||
if (rule != null) { rule.IsBuiltIn = false; rule.IsCommunity = false; }
|
||||
response.GatherRule = rule;
|
||||
}
|
||||
|
||||
response.LiveFireStats = await GetFireStatsAsync(s.TenantId, s.RuleKind, s.SourceRuleId);
|
||||
response.SuggestedPublishedRuleId = s.PublishedRuleId ?? await SuggestPublishedRuleIdAsync(s.RuleKind, s.Category);
|
||||
var fileId = s.PublishedRuleId ?? response.SuggestedPublishedRuleId;
|
||||
if (!string.IsNullOrEmpty(fileId))
|
||||
response.RepoFile = BuildRepoFile(s, fileId!);
|
||||
return response;
|
||||
}
|
||||
|
||||
// ── Review ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Applies a reviewer decision. Transitions: pending → approved | declined; approved → declined
|
||||
/// while not yet published. <see cref="KeyNotFoundException"/> = unknown id,
|
||||
/// <see cref="ArgumentException"/> = bad input, <see cref="InvalidOperationException"/> = conflict.
|
||||
/// </summary>
|
||||
public async Task<RuleSubmission> ReviewAsync(string submissionId, ReviewRuleSubmissionRequest request, string reviewedBy)
|
||||
{
|
||||
var s = await _submissions.GetAsync(submissionId) ?? throw new KeyNotFoundException("Submission not found.");
|
||||
var comment = string.IsNullOrWhiteSpace(request.ReviewComment) ? null : request.ReviewComment!.Trim();
|
||||
if (comment != null && comment.Length > ReviewRuleSubmissionRequest.MaxReviewCommentLength)
|
||||
throw new ArgumentException($"reviewComment exceeds {ReviewRuleSubmissionRequest.MaxReviewCommentLength} characters.");
|
||||
|
||||
var published = (await ToItemsAsync(new[] { s }))[0].Status == RuleSubmissionStatuses.Published;
|
||||
if (published)
|
||||
throw new InvalidOperationException("The rule is already published; the submission is final.");
|
||||
if (s.Status == RuleSubmissionStatuses.Withdrawn)
|
||||
throw new InvalidOperationException("The submitter withdrew this submission.");
|
||||
|
||||
switch (request.Decision)
|
||||
{
|
||||
case RuleSubmissionDecisions.Approve:
|
||||
{
|
||||
if (s.Status != RuleSubmissionStatuses.Pending)
|
||||
throw new InvalidOperationException($"Only a pending submission can be approved (status: {s.Status}).");
|
||||
var publishedRuleId = request.PublishedRuleId?.Trim();
|
||||
if (string.IsNullOrEmpty(publishedRuleId))
|
||||
throw new ArgumentException("publishedRuleId is required to approve.");
|
||||
await ValidatePublishedRuleIdAsync(s, publishedRuleId!);
|
||||
s.Status = RuleSubmissionStatuses.Approved;
|
||||
s.PublishedRuleId = publishedRuleId;
|
||||
s.WillBeAdapted = request.WillBeAdapted ?? false;
|
||||
break;
|
||||
}
|
||||
case RuleSubmissionDecisions.Decline:
|
||||
{
|
||||
if (s.Status != RuleSubmissionStatuses.Pending && s.Status != RuleSubmissionStatuses.Approved)
|
||||
throw new InvalidOperationException($"Cannot decline a submission in status {s.Status}.");
|
||||
if (comment == null)
|
||||
throw new ArgumentException("reviewComment is required to decline — the submitter sees it.");
|
||||
s.Status = RuleSubmissionStatuses.Declined;
|
||||
s.PublishedRuleId = null;
|
||||
s.WillBeAdapted = false;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new ArgumentException($"decision must be one of: {string.Join(", ", RuleSubmissionDecisions.All)}.");
|
||||
}
|
||||
|
||||
s.ReviewComment = comment;
|
||||
s.ReviewedBy = reviewedBy;
|
||||
s.ReviewedAt = DateTime.UtcNow;
|
||||
|
||||
if (!await _submissions.UpdateAsync(s))
|
||||
throw new InvalidOperationException("The submission changed underneath this review; reload and retry.");
|
||||
return s;
|
||||
}
|
||||
|
||||
private async Task ValidatePublishedRuleIdAsync(RuleSubmission s, string publishedRuleId)
|
||||
{
|
||||
var kindPrefix = s.RuleKind == RuleSubmissionKinds.Analyze ? "ANALYZE-" : "GATHER-";
|
||||
if (!RuleIdPolicy.IsReservedBuiltInId(publishedRuleId)
|
||||
|| !publishedRuleId.StartsWith(kindPrefix, StringComparison.OrdinalIgnoreCase)
|
||||
|| !Regex.IsMatch(publishedRuleId, @"^[A-Z]+-[A-Z]+-\d{3}$"))
|
||||
throw new ArgumentException($"publishedRuleId must be {kindPrefix}<CATEGORY>-<NNN> in the reserved built-in namespace (upper case, three digits).");
|
||||
|
||||
var taken = await GetTakenIdsAsync(s.RuleKind);
|
||||
if (taken.Contains(publishedRuleId))
|
||||
throw new InvalidOperationException($"Rule id '{publishedRuleId}' is already taken (catalog, global partition or another approved submission).");
|
||||
}
|
||||
|
||||
/// <summary>Tenant-side withdrawal; only while pending. False when there is nothing to withdraw.</summary>
|
||||
public async Task<bool> WithdrawAsync(string tenantId, string submissionId, bool crossTenantAllowed)
|
||||
{
|
||||
var s = await _submissions.GetAsync(submissionId);
|
||||
if (s == null) return false;
|
||||
if (!crossTenantAllowed && !string.Equals(s.TenantId, tenantId, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (s.Status != RuleSubmissionStatuses.Pending)
|
||||
throw new InvalidOperationException($"Only a pending submission can be withdrawn (status: {s.Status}).");
|
||||
s.Status = RuleSubmissionStatuses.Withdrawn;
|
||||
return await _submissions.UpdateAsync(s);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Operator hard delete — the row disappears from the operator list and the tenant's list
|
||||
/// alike. Not part of normal operations: for test and demo submissions, or on a tenant's request.
|
||||
/// </summary>
|
||||
public Task<bool> DeleteAsync(string submissionId) => _submissions.DeleteAsync(submissionId);
|
||||
|
||||
/// <summary>Daily retention sweep of closed submissions (see <see cref="RuleSubmissionRetention"/>).</summary>
|
||||
public Task<int> SweepExpiredAsync(DateTime nowUtc) => _submissions.DeleteExpiredAsync(nowUtc);
|
||||
|
||||
// ── Id suggestion + repo file ───────────────────────────────────────────
|
||||
|
||||
private async Task<HashSet<string>> GetTakenIdsAsync(string kind)
|
||||
{
|
||||
var taken = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (kind == RuleSubmissionKinds.Analyze)
|
||||
{
|
||||
foreach (var r in BuiltInAnalyzeRules.GetAll()) taken.Add(r.RuleId);
|
||||
foreach (var r in await _ruleRepo.GetAnalyzeRulesAsync("global")) taken.Add(r.RuleId);
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var r in BuiltInGatherRules.GetAll()) taken.Add(r.RuleId);
|
||||
foreach (var r in await _ruleRepo.GetGatherRulesAsync("global")) taken.Add(r.RuleId);
|
||||
}
|
||||
foreach (var id in await _submissions.GetReservedPublishedRuleIdsAsync()) taken.Add(id);
|
||||
return taken;
|
||||
}
|
||||
|
||||
public async Task<string> SuggestPublishedRuleIdAsync(string kind, string category)
|
||||
=> SuggestPublishedRuleId(kind, category, await GetTakenIdsAsync(kind));
|
||||
|
||||
/// <summary>
|
||||
/// Max + 1 within <c>{KIND}-{CODE}-</c> over every taken id. Gaps are retired ids that may
|
||||
/// return (RuleIdPolicy) and are never reused.
|
||||
/// </summary>
|
||||
internal static string SuggestPublishedRuleId(string kind, string category, IEnumerable<string> takenIds)
|
||||
{
|
||||
var codes = kind == RuleSubmissionKinds.Analyze ? AnalyzeCategoryCodes : GatherCategoryCodes;
|
||||
var code = codes.TryGetValue(category ?? string.Empty, out var mapped)
|
||||
? mapped
|
||||
: Regex.Replace((category ?? "MISC").ToUpperInvariant(), "[^A-Z]", "");
|
||||
if (code.Length == 0) code = "MISC";
|
||||
var prefix = (kind == RuleSubmissionKinds.Analyze ? "ANALYZE-" : "GATHER-") + code + "-";
|
||||
|
||||
var max = 0;
|
||||
foreach (var id in takenIds)
|
||||
{
|
||||
if (!id.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
if (int.TryParse(id.Substring(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out var n) && n > max)
|
||||
max = n;
|
||||
}
|
||||
return prefix + (max + 1).ToString("D3", CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The file that ships the rule: schema pointer first, the assigned id, the chosen credit,
|
||||
/// <c>isCommunity</c>, and <c>enabled</c> after the built-in convention (analyze rules ship
|
||||
/// on, gather rules opt-in because they cost device work). Lineage to the tenant's template
|
||||
/// copy is dropped.
|
||||
/// </summary>
|
||||
internal static RuleSubmissionRepoFile BuildRepoFile(RuleSubmission s, string publishedRuleId)
|
||||
{
|
||||
var frozen = JsonNode.Parse(s.RuleJson) as JsonObject
|
||||
?? throw new InvalidOperationException("Frozen rule is not an object.");
|
||||
var isAnalyze = s.RuleKind == RuleSubmissionKinds.Analyze;
|
||||
|
||||
var ordered = new JsonObject
|
||||
{
|
||||
["$schema"] = isAnalyze ? "../schema/analyze-rule.schema.json" : "../schema/gather-rule.schema.json",
|
||||
["ruleId"] = publishedRuleId,
|
||||
};
|
||||
foreach (var head in isAnalyze
|
||||
? new[] { "title", "description", "severity", "category", "version" }
|
||||
: new[] { "title", "description", "category", "version" })
|
||||
{
|
||||
if (frozen.TryGetPropertyValue(head, out var value)) ordered[head] = value?.DeepClone();
|
||||
}
|
||||
ordered["author"] = s.AttributionName;
|
||||
ordered["enabled"] = isAnalyze;
|
||||
ordered["isCommunity"] = true;
|
||||
|
||||
foreach (var kv in frozen)
|
||||
{
|
||||
if (ordered.ContainsKey(kv.Key)) continue;
|
||||
if (kv.Key == "derivedFromTemplateRuleId") continue;
|
||||
if (Array.IndexOf(StrippedFields, kv.Key) >= 0) continue;
|
||||
ordered[kv.Key] = kv.Value?.DeepClone();
|
||||
}
|
||||
|
||||
var folder = isAnalyze ? "analyze" : "gather";
|
||||
return new RuleSubmissionRepoFile
|
||||
{
|
||||
Path = $"rules/{folder}/{publishedRuleId}.json",
|
||||
Content = ordered.ToJsonString(RepoFileOptions) + "\n",
|
||||
};
|
||||
}
|
||||
|
||||
private static string NewId() => Guid.NewGuid().ToString("N").Substring(0, 12);
|
||||
}
|
||||
}
|
||||
@@ -253,9 +253,11 @@ namespace AutopilotMonitor.Functions.Services
|
||||
// Status "InProgress" — a real (non-sentinel) value that Merge-mode would
|
||||
// happily write over a row the terminal batch already closed. Only another
|
||||
// terminal observation may change a terminal status (Failed→Succeeded on a
|
||||
// successful retry stays legal).
|
||||
// successful retry stays legal). Incomplete (observation-end close step) is
|
||||
// terminal for the same purpose: a straggling progress-only batch must not
|
||||
// reopen it, while a real terminal observation still wins.
|
||||
var existingStatus = existing.GetString("Status");
|
||||
if ((existingStatus == "Succeeded" || existingStatus == "Failed") &&
|
||||
if ((existingStatus == "Succeeded" || existingStatus == "Failed" || existingStatus == "Incomplete") &&
|
||||
summary.Status != "Succeeded" && summary.Status != "Failed")
|
||||
{
|
||||
summary.Status = existingStatus;
|
||||
@@ -525,6 +527,66 @@ namespace AutopilotMonitor.Functions.Services
|
||||
return sets.Contains(appId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the session's app rows that never reached a terminal state: Status
|
||||
/// "InProgress" (or missing) with no CompletedAt becomes "Incomplete" — terminal,
|
||||
/// non-failure, outcome unknown. Runs at the terminal seam, again after the batch that
|
||||
/// carries the agent's shutdown (rows opened after the verdict), and from the 30-day
|
||||
/// sweep. Idempotent + fail-soft; a real terminal arriving later still wins through the
|
||||
/// sticky-status reconcile. Returns the number of rows closed.
|
||||
/// </summary>
|
||||
public async Task<int> CloseOpenAppInstallsForSessionAsync(string tenantId, string sessionId)
|
||||
{
|
||||
try
|
||||
{
|
||||
SecurityValidator.EnsureValidGuid(tenantId, nameof(tenantId));
|
||||
SecurityValidator.EnsureValidGuid(sessionId, nameof(sessionId));
|
||||
|
||||
var tableClient = _tableServiceClient.GetTableClient(Constants.TableNames.AppInstallSummaries);
|
||||
var filter = $"PartitionKey eq '{tenantId}' and RowKey ge '{sessionId}_' and RowKey lt '{sessionId}`'";
|
||||
var query = tableClient.QueryAsync<TableEntity>(
|
||||
filter: filter,
|
||||
select: new[] { "PartitionKey", "RowKey", "Status", "CompletedAt" });
|
||||
|
||||
var closed = 0;
|
||||
await foreach (var row in query)
|
||||
{
|
||||
if (!ShouldCloseAsIncomplete(row)) continue;
|
||||
|
||||
var update = new TableEntity(row.PartitionKey, row.RowKey)
|
||||
{
|
||||
["Status"] = "Incomplete"
|
||||
};
|
||||
await tableClient.UpsertEntityAsync(update, TableUpdateMode.Merge);
|
||||
closed++;
|
||||
}
|
||||
|
||||
if (closed > 0)
|
||||
_logger.LogInformation(
|
||||
"Session {SessionId}: closed {Count} app rows as Incomplete (no terminal state when observation ended)",
|
||||
sessionId, closed);
|
||||
return closed;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Closing open app rows failed for session {SessionId} (fail-soft)", sessionId);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pure per-row predicate behind <see cref="CloseOpenAppInstallsForSessionAsync"/> —
|
||||
/// internal static so the contract is pinned by unit tests: only a row that is still
|
||||
/// open (Status missing, empty or "InProgress", no CompletedAt) closes; every terminal
|
||||
/// row, including an already-closed Incomplete one, is left alone (idempotency).
|
||||
/// </summary>
|
||||
internal static bool ShouldCloseAsIncomplete(TableEntity row)
|
||||
{
|
||||
if (row.GetDateTimeOffset("CompletedAt").HasValue) return false;
|
||||
var status = row.GetString("Status");
|
||||
return string.IsNullOrEmpty(status) || status == "InProgress";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets app install summaries for a tenant (fleet-level metrics). When <paramref name="sinceUtc"/>
|
||||
/// is supplied, a server-side <c>StartedAt ge</c> filter is applied so a windowed view (e.g. the
|
||||
|
||||
@@ -104,6 +104,42 @@ namespace AutopilotMonitor.Functions.Services
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a Telegram notification when a tenant admin submits a custom rule for the
|
||||
/// community pool. The submission id comes first — it is the handle for the review.
|
||||
/// Best-effort — silently no-ops if the webhook URL is not configured.
|
||||
/// </summary>
|
||||
public async Task SendRuleSubmissionAsync(string submissionId, string tenantId, string submittedBy, string ruleKind, string ruleId, string title, string comment)
|
||||
{
|
||||
try
|
||||
{
|
||||
var webhookUrl = await GetWebhookUrlAsync();
|
||||
if (string.IsNullOrWhiteSpace(webhookUrl))
|
||||
{
|
||||
_logger.LogDebug("Telegram webhook URL not configured — skipping rule submission notification");
|
||||
return;
|
||||
}
|
||||
|
||||
var commentLine = string.IsNullOrWhiteSpace(comment) ? "" : $"\nComment: {comment}";
|
||||
var payload = new
|
||||
{
|
||||
chat_id = "-1003632442830",
|
||||
text = $"New Rule Submission {submissionId}\nRule: {ruleId} \"{title}\" ({ruleKind})\nTenantID: {tenantId}\nBy: {submittedBy}{commentLine}"
|
||||
};
|
||||
|
||||
var json = JsonConvert.SerializeObject(payload);
|
||||
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
var response = await _http.PostAsync(webhookUrl, content);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
_logger.LogInformation("Telegram rule submission notification sent for {SubmissionId}", submissionId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to send Telegram rule submission notification for {SubmissionId}", submissionId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a Telegram notification when a tenant admin submits a diag-files-only report
|
||||
/// (no session context). Best-effort — silently no-ops if the webhook URL is not configured.
|
||||
@@ -281,7 +317,8 @@ namespace AutopilotMonitor.Functions.Services
|
||||
/// <summary>
|
||||
/// Flattens an alert into the plain-text form Telegram accepts. Telegram has no card
|
||||
/// format, so facts become "Name: Value" lines — that is also what carries an ops event's
|
||||
/// structured payload into the message.
|
||||
/// structured payload into the message. Sections (rule explanations, What's new entries)
|
||||
/// follow as title + text blocks, and openUrl actions as trailing "Title: url" lines.
|
||||
/// </summary>
|
||||
internal static string RenderAlertText(NotificationAlert alert)
|
||||
{
|
||||
@@ -300,6 +337,25 @@ namespace AutopilotMonitor.Functions.Services
|
||||
foreach (var fact in alert.Facts)
|
||||
sb.AppendLine($"{fact.Name}: {fact.Value}");
|
||||
|
||||
foreach (var section in alert.Sections)
|
||||
{
|
||||
if (string.IsNullOrEmpty(section.Title) && string.IsNullOrEmpty(section.Text))
|
||||
continue;
|
||||
sb.AppendLine();
|
||||
if (!string.IsNullOrEmpty(section.Title))
|
||||
sb.AppendLine(section.Title);
|
||||
if (!string.IsNullOrEmpty(section.Text))
|
||||
sb.AppendLine(section.Text);
|
||||
}
|
||||
|
||||
var links = alert.Actions.Where(a => a.Type == "openUrl" && !string.IsNullOrEmpty(a.Url)).ToList();
|
||||
if (links.Count > 0)
|
||||
{
|
||||
sb.AppendLine();
|
||||
foreach (var action in links)
|
||||
sb.AppendLine($"{action.Title}: {action.Url}");
|
||||
}
|
||||
|
||||
return sb.ToString().TrimEnd();
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,8 @@ public static class TenantNotificationAudienceCatalog
|
||||
["rule_frequency_regression"] = NotificationAudience.Admin,
|
||||
// App-version duration regression radar: packaging/rollout is an admin concern.
|
||||
["app_version_duration_regression"] = NotificationAudience.Admin,
|
||||
// Community rule submission decided (approved/declined): only admins submit, only admins act.
|
||||
["rule_submission_decided"] = NotificationAudience.Admin,
|
||||
};
|
||||
|
||||
public static NotificationAudience Resolve(string? type)
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models.WhatsNew;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Services.WhatsNew
|
||||
{
|
||||
/// <summary>Reads the live What's new payload the portal serves.</summary>
|
||||
public interface IWhatsNewFeedClient
|
||||
{
|
||||
/// <summary>The parsed payload, or null when it could not be fetched or is off-shape.</summary>
|
||||
Task<WhatsNewFeed?> GetAsync(CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fetches <c>{PortalBaseUrl}/whats-new.json</c> — the static file the web deploy generates from
|
||||
/// the docs changelogs. Reading the portal's own copy (rather than the docs repo) keeps the
|
||||
/// notifier in lockstep with what the panel shows: an entry is announced when it becomes visible
|
||||
/// to users, not when it is committed to the docs.
|
||||
/// </summary>
|
||||
public sealed class WhatsNewFeedClient : IWhatsNewFeedClient
|
||||
{
|
||||
public const string FeedUrl = Constants.PortalBaseUrl + "/whats-new.json";
|
||||
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly ILogger<WhatsNewFeedClient> _logger;
|
||||
|
||||
public WhatsNewFeedClient(HttpClient httpClient, ILogger<WhatsNewFeedClient> logger)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<WhatsNewFeed?> GetAsync(CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, FeedUrl);
|
||||
request.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue { NoCache = true };
|
||||
using var response = await _httpClient.SendAsync(request, ct);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogWarning("What's new feed returned HTTP {Status}", (int)response.StatusCode);
|
||||
return null;
|
||||
}
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync(ct);
|
||||
var feed = WhatsNewFeed.Parse(json);
|
||||
if (feed == null)
|
||||
_logger.LogWarning("What's new feed at {Url} has an unexpected shape — skipping", FeedUrl);
|
||||
return feed;
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException || ex is TaskCanceledException)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to fetch What's new feed from {Url}", FeedUrl);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Services.Notifications;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models.Notifications;
|
||||
using AutopilotMonitor.Shared.Models.WhatsNew;
|
||||
using Microsoft.ApplicationInsights;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Services.WhatsNew
|
||||
{
|
||||
/// <summary>
|
||||
/// Announces newly published What's new entries to every tenant channel that opted in
|
||||
/// (<see cref="NotificationChannel.NotifyOnWhatsNew"/>).
|
||||
/// <para>
|
||||
/// "New" means: present in the live <c>/whats-new.json</c> but absent from the platform-wide
|
||||
/// watermark (<see cref="WhatsNewNotificationState.KnownEntryKeys"/>) — i.e. the entry became
|
||||
/// visible in the portal since the last run. Diffing on ids rather than dates matters because
|
||||
/// the payload is regenerated only on web deploys: a bullet's docs commit date can be days
|
||||
/// older than the moment it actually appears. All new entries of a run go out as ONE digest
|
||||
/// per channel, so a release that adds five bullets is one message, not five.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Ordering is claim-then-send: the watermark is advanced with an ETag compare-and-swap
|
||||
/// BEFORE any channel is contacted. A lost race means another run owns this batch and this
|
||||
/// one exits without sending; a crash after the claim loses the batch rather than
|
||||
/// double-announcing it (at-most-once, like every other channel notification here).
|
||||
/// The very first run — no state row, or an empty known set — only baselines and never
|
||||
/// announces: a fresh deployment must not blast the entire changelog at every tenant.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public class WhatsNewNotificationService
|
||||
{
|
||||
/// <summary>Portal deep link that opens the panel on load (WhatsNewPanelHost reads <c>?whats-new=</c>).</summary>
|
||||
internal static string PortalWhatsNewUrl(string channel)
|
||||
=> $"{Constants.PortalBaseUrl}/dashboard?whats-new={Uri.EscapeDataString(channel)}";
|
||||
|
||||
private readonly IWhatsNewFeedClient _feedClient;
|
||||
private readonly IWhatsNewNotificationStateRepository _stateRepo;
|
||||
private readonly IConfigRepository _configRepo;
|
||||
private readonly NotificationChannelDispatcher _channelDispatcher;
|
||||
private readonly TelemetryClient _telemetryClient;
|
||||
private readonly ILogger<WhatsNewNotificationService> _logger;
|
||||
private readonly Func<DateTime> _nowProvider;
|
||||
|
||||
public WhatsNewNotificationService(
|
||||
IWhatsNewFeedClient feedClient,
|
||||
IWhatsNewNotificationStateRepository stateRepo,
|
||||
IConfigRepository configRepo,
|
||||
NotificationChannelDispatcher channelDispatcher,
|
||||
TelemetryClient telemetryClient,
|
||||
ILogger<WhatsNewNotificationService> logger,
|
||||
Func<DateTime>? nowProvider = null)
|
||||
{
|
||||
_feedClient = feedClient;
|
||||
_stateRepo = stateRepo;
|
||||
_configRepo = configRepo;
|
||||
_channelDispatcher = channelDispatcher;
|
||||
_telemetryClient = telemetryClient;
|
||||
_logger = logger;
|
||||
_nowProvider = nowProvider ?? (() => DateTime.UtcNow);
|
||||
}
|
||||
|
||||
public sealed class RunResult
|
||||
{
|
||||
public bool FeedUnavailable { get; init; }
|
||||
public bool Baselined { get; init; }
|
||||
public bool LostRace { get; init; }
|
||||
public int NewEntries { get; init; }
|
||||
public int TenantsNotified { get; init; }
|
||||
public int ChannelsNotified { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Timer entry point. Never throws for expected conditions (feed down, nothing new, lost race).</summary>
|
||||
public async Task<RunResult> RunAsync(CancellationToken ct = default)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
|
||||
var feed = await _feedClient.GetAsync(ct);
|
||||
if (feed == null)
|
||||
{
|
||||
_logger.LogWarning("What's new notifier: feed unavailable — skipping run");
|
||||
return new RunResult { FeedUnavailable = true };
|
||||
}
|
||||
|
||||
var (state, etag) = await _stateRepo.GetWithETagAsync();
|
||||
var now = _nowProvider();
|
||||
var currentKeys = new HashSet<string>(feed.Entries.Select(e => e.Key), StringComparer.Ordinal);
|
||||
|
||||
var next = new WhatsNewNotificationState
|
||||
{
|
||||
KnownEntryKeys = currentKeys,
|
||||
LastDocsCommit = feed.DocsCommit,
|
||||
LastRunUtc = now,
|
||||
LastNotifiedUtc = state?.LastNotifiedUtc,
|
||||
LastNotifiedEntryCount = state?.LastNotifiedEntryCount ?? 0,
|
||||
};
|
||||
|
||||
// First run (or a wiped/malformed watermark): record what is live, announce nothing.
|
||||
if (state == null || state.KnownEntryKeys.Count == 0)
|
||||
{
|
||||
var stored = await _stateRepo.TryUpsertAsync(next, etag);
|
||||
_logger.LogInformation("What's new notifier: baselined {Count} entries (docs @ {Commit}), stored={Stored}",
|
||||
currentKeys.Count, feed.DocsCommit ?? "unknown", stored);
|
||||
return new RunResult { Baselined = true };
|
||||
}
|
||||
|
||||
var newEntries = feed.Entries.Where(e => !state.KnownEntryKeys.Contains(e.Key)).ToList();
|
||||
if (newEntries.Count == 0)
|
||||
{
|
||||
// Only touch storage when the payload actually changed (entries rolled out of the window).
|
||||
if (!currentKeys.SetEquals(state.KnownEntryKeys))
|
||||
await _stateRepo.TryUpsertAsync(next, etag);
|
||||
_logger.LogDebug("What's new notifier: nothing new ({Count} entries live)", currentKeys.Count);
|
||||
return new RunResult();
|
||||
}
|
||||
|
||||
next.LastNotifiedUtc = now;
|
||||
next.LastNotifiedEntryCount = newEntries.Count;
|
||||
|
||||
if (!await _stateRepo.TryUpsertAsync(next, etag))
|
||||
{
|
||||
_logger.LogInformation("What's new notifier: watermark changed underneath this run — another run owns the batch");
|
||||
return new RunResult { LostRace = true, NewEntries = newEntries.Count };
|
||||
}
|
||||
|
||||
var (tenantsNotified, channelsNotified) = await DispatchAsync(feed, newEntries, ct);
|
||||
|
||||
_logger.LogInformation(
|
||||
"What's new notifier: announced {New} new entries to {Channels} channels across {Tenants} tenants in {ElapsedMs}ms",
|
||||
newEntries.Count, channelsNotified, tenantsNotified, sw.ElapsedMilliseconds);
|
||||
|
||||
_telemetryClient.TrackEvent("WhatsNewNotificationSent", new Dictionary<string, string>
|
||||
{
|
||||
{ "NewEntries", newEntries.Count.ToString() },
|
||||
{ "PlatformEntries", newEntries.Count(e => e.Channel == WhatsNewFeed.PlatformChannel).ToString() },
|
||||
{ "AgentEntries", newEntries.Count(e => e.Channel == WhatsNewFeed.AgentChannel).ToString() },
|
||||
{ "Tenants", tenantsNotified.ToString() },
|
||||
{ "Channels", channelsNotified.ToString() },
|
||||
{ "DocsCommit", feed.DocsCommit ?? "unknown" },
|
||||
});
|
||||
|
||||
return new RunResult
|
||||
{
|
||||
NewEntries = newEntries.Count,
|
||||
TenantsNotified = tenantsNotified,
|
||||
ChannelsNotified = channelsNotified,
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<(int Tenants, int Channels)> DispatchAsync(
|
||||
WhatsNewFeed feed, List<WhatsNewFeedEntry> newEntries, CancellationToken ct)
|
||||
{
|
||||
var platformCount = newEntries.Count(e => e.Channel == WhatsNewFeed.PlatformChannel);
|
||||
var primaryChannel = newEntries.Count - platformCount > platformCount
|
||||
? WhatsNewFeed.AgentChannel
|
||||
: WhatsNewFeed.PlatformChannel;
|
||||
var alert = NotificationAlertBuilder.BuildWhatsNewAlert(newEntries, feed.DocsUrls, PortalWhatsNewUrl(primaryChannel));
|
||||
|
||||
var configs = await _configRepo.GetAllTenantConfigurationsAsync();
|
||||
int tenants = 0, channels = 0;
|
||||
|
||||
foreach (var config in configs)
|
||||
{
|
||||
if (ct.IsCancellationRequested) break;
|
||||
if (config.IsCurrentlyDisabled()) continue;
|
||||
|
||||
var targets = config.GetNotificationChannels()
|
||||
.Where(c => c.Enabled && c.NotifyOnWhatsNew && !string.IsNullOrEmpty(c.Url))
|
||||
.ToList();
|
||||
if (targets.Count == 0) continue;
|
||||
|
||||
try
|
||||
{
|
||||
await _channelDispatcher.SendToChannelsAsync(targets, alert);
|
||||
tenants++;
|
||||
channels += targets.Count;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "What's new notifier: dispatch failed for tenant {TenantId}", config.TenantId);
|
||||
}
|
||||
}
|
||||
|
||||
return (tenants, channels);
|
||||
}
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Two request-gate contracts (2026-09-10):
|
||||
* - a token the backend refuses (401) is answered 401 + WWW-Authenticate error="invalid_token"
|
||||
* (spec: invalid or expired tokens MUST receive 401), cached like a deny, never 403 "not enabled";
|
||||
* - the caller context carries a cancellation signal that fires when the client closes the request
|
||||
* before the response is written (Streamable HTTP: closing the response stream cancels the request).
|
||||
*/
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import type { Request, Response, NextFunction } from 'express';
|
||||
import { accessGuard } from '../access-guard.js';
|
||||
import { getCallerSignal } from '../client.js';
|
||||
|
||||
function makeToken(claims: Record<string, unknown>): string {
|
||||
const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url');
|
||||
const payload = Buffer.from(JSON.stringify(claims)).toString('base64url');
|
||||
return `${header}.${payload}.sig`;
|
||||
}
|
||||
|
||||
let seed = 0;
|
||||
/** A fresh, unexpired token per call — the guard caches verdicts per UPN+token. */
|
||||
function request(): Request {
|
||||
seed += 1;
|
||||
const token = makeToken({ upn: `user${seed}@contoso.com`, exp: Math.floor(Date.now() / 1000) + 3600 });
|
||||
return {
|
||||
headers: { host: 'mcp.example.com', authorization: `Bearer ${token}` },
|
||||
protocol: 'https',
|
||||
body: { jsonrpc: '2.0', method: 'tools/list', id: 1 },
|
||||
} as unknown as Request;
|
||||
}
|
||||
|
||||
interface Outcome {
|
||||
nextCalled: boolean;
|
||||
status: number | null;
|
||||
body: unknown;
|
||||
headers: Record<string, string>;
|
||||
/** The caller context's signal, read INSIDE next(). */
|
||||
signal?: AbortSignal;
|
||||
res: { writableFinished: boolean };
|
||||
/** Emits the response's 'close' event the way Node does when the socket goes away. */
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
function run(req: Request): Promise<Outcome> {
|
||||
return new Promise((resolve) => {
|
||||
const headers: Record<string, string> = {};
|
||||
const closeHandlers: Array<() => void> = [];
|
||||
let status: number | null = null;
|
||||
let settled = false;
|
||||
const state = { writableFinished: false };
|
||||
const close = () => closeHandlers.forEach((h) => h());
|
||||
const finish = (o: Omit<Outcome, 'res' | 'close'>) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve({ ...o, res: state, close });
|
||||
};
|
||||
const res = {
|
||||
get writableFinished() { return state.writableFinished; },
|
||||
setHeader(name: string, value: string) { headers[name] = String(value); return this; },
|
||||
status(code: number) { status = code; return this; },
|
||||
json(payload: unknown) { finish({ nextCalled: false, status, body: payload, headers }); return this; },
|
||||
on(event: string, handler: () => void) { if (event === 'close') closeHandlers.push(handler); return this; },
|
||||
} as unknown as Response;
|
||||
const next: NextFunction = () => finish({ nextCalled: true, status, body: undefined, headers, signal: getCallerSignal() });
|
||||
accessGuard(req, res, next);
|
||||
setTimeout(() => finish({ nextCalled: false, status, body: undefined, headers }), 2_000);
|
||||
});
|
||||
}
|
||||
|
||||
function stubBackend(status: number, body: unknown) {
|
||||
const fn = vi.fn(async () => ({ status, text: async () => JSON.stringify(body) } as unknown as Response));
|
||||
vi.stubGlobal('fetch', fn);
|
||||
return fn;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('accessGuard — a backend 401 becomes 401 + challenge', () => {
|
||||
it('answers 401 with error="invalid_token" and the backend reason, not 403', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
stubBackend(401, { error: 'Token signature is invalid', code: 'unauthorized' });
|
||||
const out = await run(request());
|
||||
expect(out.nextCalled).toBe(false);
|
||||
expect(out.status).toBe(401);
|
||||
expect(out.headers['WWW-Authenticate']).toContain('error="invalid_token"');
|
||||
expect(out.headers['WWW-Authenticate']).toContain('oauth-protected-resource/mcp');
|
||||
expect(out.body).toMatchObject({ error: 'Invalid token', reason: 'Token signature is invalid' });
|
||||
});
|
||||
|
||||
it('caches the rejection per token: a replay costs no second backend call and stays 401', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
const fetchMock = stubBackend(401, { error: 'Token expired' });
|
||||
const req = request();
|
||||
const first = await run(req);
|
||||
const second = await run(req);
|
||||
expect(first.status).toBe(401);
|
||||
expect(second.status).toBe(401);
|
||||
expect(second.headers['WWW-Authenticate']).toContain('error="invalid_token"');
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps a 401 without an envelope body at 401 with a generic reason', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
stubBackend(401, 'Unauthorized');
|
||||
const out = await run(request());
|
||||
expect(out.status).toBe(401);
|
||||
expect(out.body).toMatchObject({ reason: 'The backend rejected the token' });
|
||||
});
|
||||
|
||||
it('keeps a genuine authorization deny (200, allowed:false) at 403 without a challenge', async () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
stubBackend(200, { allowed: false, upn: 'x', accessGrant: '', reason: 'not on the MCP allowlist' });
|
||||
const out = await run(request());
|
||||
expect(out.status).toBe(403);
|
||||
expect(out.headers['WWW-Authenticate']).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('accessGuard — cancellation signal', () => {
|
||||
it('hands the caller context a signal that fires when the client closes the request early', async () => {
|
||||
stubBackend(200, { allowed: true, upn: 'x', accessGrant: 'ok' });
|
||||
const out = await run(request());
|
||||
expect(out.nextCalled).toBe(true);
|
||||
expect(out.signal).toBeInstanceOf(AbortSignal);
|
||||
expect(out.signal?.aborted).toBe(false);
|
||||
out.close();
|
||||
expect(out.signal?.aborted).toBe(true);
|
||||
});
|
||||
|
||||
it('does not fire when the response completed normally before the socket closed', async () => {
|
||||
stubBackend(200, { allowed: true, upn: 'x', accessGrant: 'ok' });
|
||||
const out = await run(request());
|
||||
out.res.writableFinished = true;
|
||||
out.close();
|
||||
expect(out.signal?.aborted).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -45,6 +45,7 @@ function runGuard(req: Request): Promise<Outcome> {
|
||||
setHeader() { return this as Response; },
|
||||
status(code: number) { statusCode = code; return this as Response; },
|
||||
json() { done({ nextCalled: false, status: statusCode }); return this as Response; },
|
||||
on() { return this as Response; },
|
||||
};
|
||||
const next: NextFunction = () => done({ nextCalled: true, status: statusCode });
|
||||
accessGuard(req, res as Response, next);
|
||||
|
||||
@@ -68,6 +68,10 @@ function mockRes(): CapturedRes {
|
||||
captured.body = payload;
|
||||
return this as Response;
|
||||
},
|
||||
// The guard subscribes to 'close' for the cancellation signal; nothing here ever emits it.
|
||||
on() {
|
||||
return this as Response;
|
||||
},
|
||||
};
|
||||
captured.res = res as Response;
|
||||
return captured;
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Client cancellation reaches the backend: the caller context's signal (aborted by the access
|
||||
* guard when the client closes the request) is folded into every apiFetch attempt and into the
|
||||
* automatic 429/503 retry wait, so an abandoned tool call stops its backend work at once.
|
||||
*/
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { apiFetch, runWithCaller } from '../client.js';
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
function caller(signal: AbortSignal) {
|
||||
return { token: 'test-token', isGlobalAdmin: true, isGlobalReader: false, signal };
|
||||
}
|
||||
|
||||
describe('apiFetch — caller cancellation', () => {
|
||||
it("aborts the in-flight backend fetch when the caller's signal fires", async () => {
|
||||
let seen: AbortSignal | undefined;
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation((_url, init) => new Promise<Response>((_resolve, reject) => {
|
||||
seen = init?.signal ?? undefined;
|
||||
seen?.addEventListener('abort', () => reject(seen?.reason), { once: true });
|
||||
}));
|
||||
const controller = new AbortController();
|
||||
const pending = runWithCaller(caller(controller.signal), () => apiFetch<unknown>('/api/sessions'));
|
||||
|
||||
expect(seen).toBeDefined();
|
||||
expect(seen?.aborted).toBe(false);
|
||||
controller.abort();
|
||||
await expect(pending).rejects.toMatchObject({ name: 'AbortError' });
|
||||
expect(seen?.aborted).toBe(true);
|
||||
});
|
||||
|
||||
it('ends the automatic retry wait at once on cancellation instead of sleeping out Retry-After', async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
ok: false,
|
||||
status: 429,
|
||||
headers: { get: (name: string) => (name.toLowerCase() === 'retry-after' ? '5' : null) },
|
||||
text: async () => '',
|
||||
} as unknown as Response);
|
||||
const controller = new AbortController();
|
||||
const started = Date.now();
|
||||
const pending = runWithCaller(caller(controller.signal), () => apiFetch<unknown>('/api/sessions'));
|
||||
setTimeout(() => controller.abort(), 20);
|
||||
|
||||
await expect(pending).rejects.toMatchObject({ name: 'AbortError' });
|
||||
expect(Date.now() - started).toBeLessThan(2000);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps the plain per-attempt timeout when the caller context carries no signal', async () => {
|
||||
let seen: AbortSignal | undefined;
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
|
||||
seen = init?.signal ?? undefined;
|
||||
return { ok: true, status: 200, headers: { get: () => null }, text: async () => '{"ok":true}' } as unknown as Response;
|
||||
});
|
||||
await runWithCaller({ token: 'test-token', isGlobalAdmin: true }, () => apiFetch<unknown>('/api/sessions'));
|
||||
expect(seen).toBeDefined();
|
||||
expect(seen?.aborted).toBe(false);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user