Compare commits

...

121 Commits

Author SHA1 Message Date
Oliver Kieselbach f1457d823d chore: bump .claude/commands gitlink 2026-09-09 12:02:05 +02:00
Oliver Kieselbach 12e66299e6 feat(rules): allow-list folders under the signed-in user's profile (D-228, D-229)
Gather rules and admin-configured diagnostics paths could never reach a
folder below a user profile. The %LOGGED_ON_USER_PROFILE% token lifts the
C:\Users hard block for AppData\Local and AppData\Roaming, but lifting is
not admitting: the path then fell into filePrefixes, which is matched
literally against the already-expanded path, and the profile name is not
known when that list is authored. The exception only ever worked in
unrestricted mode, and no agent test passed a non-null userProfilePath.

D-228 introduces userProfileFilePrefixes, holding entries relative to the
profile root (AppData\Local\RealmJoin). Both guards resolve them against
the detected profile and match segment-bounded; entries that are rooted,
contain "..", or sit outside AppData\Local / AppData\Roaming are dropped at
load, so configuration can only narrow the hard block's exception, never
widen it. The allowlist is anchored to the detected profile, so a rule
cannot reach another user's AppData. The AppData subdirectory list existed
in both guard classes with the GatherRuleGuards copy unused; it is now one
list and DiagnosticsPathGuards delegates. filePrefixes additionally gains
C:\ProgramData\RealmJoin\choco\logs.

D-229 fixes the pre-flight validators, which must only ever reject what the
agent rejects:
- the portal returned "allowed" on the lifted hard block without consulting
  the allowlist, so a rule the agent refuses passed the enable gate and then
  failed silently on the device with a security_warning;
- the MCP validator offered logparser the diagnosticsPathPrefixes list that
  no collector consults (four paths reported allowed that the agent blocks);
- the MCP validator did not expand environment variables at all, reporting
  %ProgramData% targets as blocked although the device reads them.

Measured before changing the portal: no rule in any tenant used the token,
so nothing that was working gets disabled.

Verified: solution build 0 warnings, agent 2897 tests, web 1257 + tsc +
eslint 0, MCP 779, guardrails.json validates against its schema, rules/dist
regenerates without drift. The six new agent tests were green against the
unchanged guard first, which is what proves the exception was inert.

Takes effect on devices only after an agent release: guardrails.json is an
EmbeddedResource in the agent assembly.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 11:54:36 +02:00
Oliver Kieselbach e9a01de9da chore: bump .claude/commands gitlink
Event reference in /ux-insights completed and live-verified.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 10:06:20 +02:00
Oliver Kieselbach 5f793ea01a chore: bump .claude/commands gitlink
Marker-catalog rows for the What's new panel events and the digest timer.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 09:58:50 +02:00
Oliver Kieselbach e86f7efed3 feat(bootstrap): verify the publisher of the extracted agent binaries before --install (D-227)
The SHA-256 check proves the ZIP is the one version.json names, but that
manifest lives in the same container as the ZIP: it 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 is publisher-anchored
end to end.

Install-AutopilotMonitor.ps1 v2.4 -> v2.5:
- Get-UnverifiedAgentBinaries checks every AutopilotMonitor.*.exe/.dll in the
  extracted payload for status Valid and the same subject pin the loader
  carries; the gate runs immediately before --install and throws on any
  rejection, exactly like the hash check.
- Third-party assemblies keep their own publisher's signature and are not
  checked: System.Management.Automation.dll ships unsigned, so a gate over all
  files would refuse the live payload.
- An extracted folder with no binary of ours is a rejection, not a pass.
- The SHA-256 manifest check is unchanged and still runs first: it proves the
  bytes, the signature proves the author.

Verified against the live payload 2.0.1454 (all five of our PEs Valid and
glueckkanja AG, gate passes); appending one byte to AutopilotMonitor.Shared.dll
makes it reject. Pester 55/55.

The portal privacy and about pages carried the pre-signing wording and are
corrected in the same change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 23:11:16 +02:00
Oliver Kieselbach 78bfad0ec6 web: the portal What's new panel names the currently published agent version
A quiet third line in the panel header ("Latest agent version 2.0.1452",
faint, the number monospaced) reads from the existing config/latest-versions
endpoint. The monospaced string is the same one the session list shows in its
"Agent Version" column, so a reader can tell at a glance whether their fleet
runs the latest agent.

Portal and signed-in only: the endpoint is AuthenticatedUser, and the public
site has no session list to compare against. The gate sits on the mount of the
small component, so the landing page never even issues the request; a missing
version renders nothing.
2026-09-08 22:37:29 +02:00
Oliver Kieselbach f5efadfd07 ci: pin every third-party action to a commit SHA, gated and Dependabot-maintained (D-226)
A tag is a mutable pointer owned by the action's publisher. These jobs are not
ordinary CI: they hold the code-signing Key Vault token (D-223), the federated
storage credentials (D-222), and combine-rules.yml holds a contents:write token
that pushes to main. Whoever could repoint v7 would run code with all of that.

azure/login and Azure/functions-action were already pinned; the actions/* and
github/codeql-action references were not, on the usual argument that GitHub owns
them and shares the runner's trust boundary. That argument does not survive the
fact that they run in the same jobs as the signing identity. All seven are now
pinned by SHA with the version in a trailing comment -- the comment is what keeps
the line reviewable, and Dependabot rewrites both together.

action-pins.yml is the guard: pins nobody enforces rot, and no review reliably
catches one @v4 added to a 200-line workflow. It lives in its own workflow because
ci.yml deliberately ignores changes to the other workflow files, so a job placed
there would stay silent for exactly the commits it must inspect. Like CI it reports
rather than blocks -- main is unprotected; making it binding would mean adding it
as a required status check, which is a branch-protection decision.

Verified both directions: 49 references pass against the repo, and a fixture with
@v7, @main and a bare SHA fails with three annotations while the local reusable
workflow refs are skipped.

Two floating tool versions closed while here. wix went from the range 5.* to 5.0.2
-- it writes the bytes of the MSI customers install, where AzureSignTool only signs
them. ajv was the worse one: unpinned, and npm runs lifecycle scripts at install,
so a hijacked release would have executed with the push token before a single rule
was validated; now exact versions with --ignore-scripts.

Line endings: sed -i rewrote the workflow files as LF. Git normalises on commit, so
the content diff is unaffected and indexnow-notify.yml carries no change at all.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 22:14:15 +02:00
Oliver Kieselbach c26eca2f01 chore: bump internal gitlink
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 21:36:42 +02:00
Oliver Kieselbach 9f1879a9f3 fix(agent): raise the captured script output cap from 2K to 8K
The portal showed the two-stage bootstrap output ending in ...[truncated]. That marker
comes from the agent, not from the web view: the stdout is cut at capture time, so no
amount of UI space brings the rest back.

Measured over 1,486 script outputs in the fleet (2026-08-25..09-08): median 39, p90 644,
max 1,501 chars, and the 2,048 cap had never been hit -- the maximum was our own
one-stage bootstrap. The loader preamble of ~460 chars pushed exactly that output over
the edge, i.e. this is a consequence of D-224 and it hit the one output an operator
actually reads.

8,192 covers 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. Other scripts are unaffected in practice: p90 is 644 chars.

Reaches the fleet with the next agent release.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 21:36:15 +02:00
Oliver Kieselbach c24c7bf7ef fix(publish): serve the customer scripts as a download, not as a web page
The blobs carry Content-Type: text/plain and no Content-Disposition, so every browser
renders them inline -- the documented "download the bootstrapper script" step turns into
"select this text and save it yourself", with whatever the editor then does to the line
endings and the signature block.

x-ms-blob-content-disposition makes the link a download in every browser, which is a
server-side fact rather than a per-browser hint in the docs. Command-line clients (the
loader, the MSI runner, curl) ignore the header, so nothing on the device path changes.

Metadata only: the script bytes are untouched, so no version bump and the bump guard
still sees the published copies as current.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 21:07:35 +02:00
Oliver Kieselbach 5fac3d6004 Agent Host changes for agents/whats-new-notification-settings (#153) 2026-09-08 20:51:20 +02:00
Oliver Kieselbach 7605d2e9f5 fix(loader): log the signer CN instead of the whole EV subject
The full subject of an EV certificate is a line of street address and registration
numbers and pushed the useful part of the log line off the screen. The CN answers the
question the log has to answer. The full subject is still logged in the one case where it
is the finding itself: a valid signature from a publisher that is not us.

Loader 1.1 -> 1.2; a Pester case pins the short form. Suite on PS 5.1: 45/45.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 20:49:38 +02:00
Oliver Kieselbach 7bf5412d63 docs(mcp): teach the diag-zip map the loader log
bootstrap-loader.log is new with the two-stage bootstrap and told the diag tooling
nothing so far. Names which channel a device was assigned: the loader logs there when
assigned directly, and to bootstrap-msi.log when it runs from the MDM-LOB MSI.

Takes effect with the next MCP deploy.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 20:47:56 +02:00
Oliver Kieselbach b53ceb1a7c chore: bump internal gitlink (MSI loader consolidation)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 20:47:01 +02:00
Oliver Kieselbach 647581b4ff refactor(msi): the MSI carries the shared stage-1 loader instead of its own downloader
Invoke-BootstrapDownload.ps1 and Start-AutopilotMonitor.ps1 had become the same script:
download the current installer, run it, log, always exit 0. The MSI copy additionally
downloaded and executed WITHOUT verifying what it got, which is exactly the gap the loader
was written to close. The MSI is now packaging only -- it installs and runs the same file
that is assigned directly in Intune, and both delivery channels get publisher verification
from one implementation.

Dropped from the MSI path: its own Deployed-marker check. That guard lives in stage 2 and
runs there anyway, so the only cost is one download on a device that is already deployed.

Kept: the log file name. bootstrap-msi.log is what the diagnostics tooling keys on to tell
the MDM-LOB channel apart from the Intune script channel, so the loader takes -LogFileName
(default bootstrap-loader.log) and the custom action passes bootstrap-msi.log. A Pester
test now pins that contract across the two files -- renaming the parameter on either side
would leave the MSI channel logging under the wrong name.

Package version 1.0.2 -> 1.1.0 so Intune LOB update detection sees the new payload, and a
new component GUID because the key path file changed.

Loader 1.0 -> 1.1. Bootstrap suite on Windows PowerShell 5.1: 44/44.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 20:41:52 +02:00
Oliver Kieselbach db9b1995bc refactor: move the error-code generator from scripts/ to tools/ (D-225)
scripts/ at the repo root is the customer surface: everything under
Bootstrap/ and CustomerSetup/ is published to the download container by
Publish-BootstrapScripts.ps1, Authenticode-signed and version-gated. The
error-code generator is a maintainer tool no workflow runs, so it diluted
that invariant. .github/scripts/ was not the alternative -- it holds only
helpers a workflow step invokes, and unlike guardrails-in-sync and
shared-manifests-in-sync the catalog has no CI drift gate (the generator
needs IME_ENUMS_JSON from operator tooling and live MS Learn fetches).

REPO_ROOT stays ../.. at the new depth, so only the documented path moved:
the generator header and README, the C# and TypeScript comments, the test
summary, and the description header of error-codes.json together with the
generator literal that emits it (the two must stay identical or the next
regeneration diffs). The web sync re-ran clean at 607 entries with no
change to utils/error-codes.json, which drops the header.
2026-09-08 20:35:51 +02:00
Oliver Kieselbach 7563435837 feat(ci): Authenticode-sign the bootstrap MSI and the runner it embeds (D-223)
MSI carries an Authenticode signature like any PE, so the same identity and the same
ordering rules apply: signing identity logs in first and only for the Key Vault token,
the storage login stays last, and no environment: on the job.

The embedded Invoke-BootstrapDownload.ps1 is signed BEFORE wix build -- wix embeds the
file as it finds it, so signing afterwards would leave the copy inside the MSI unsigned,
and a device under an AllSigned policy needs the runner to carry its own signature.

The MSI is signed after the build and before the hash and the upload, then both files are
verified (Valid, timestamped, optional publisher pin) while nothing is published yet.
The provenance attestation now also skips runs that upload nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 20:34:17 +02:00
Oliver Kieselbach e39f2abb61 chore: bump internal gitlink (comment lesson)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 19:21:39 +02:00
Oliver Kieselbach 47dad7143f docs(ci): tighten the code-signing comments in build-agent
Public repo: keep the reasoning that a later change could break -- signing must precede
the release hashes, the job must never carry an environment, the timestamp is not
optional -- and drop the rest. Comments only, no behaviour change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 19:20:39 +02:00
Oliver Kieselbach d81f41dc72 chore: bump internal gitlink (D-223/D-224 plans and decisions)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 18:59:54 +02:00
Oliver Kieselbach cc6be10532 fix(publish): read the signed bytes back as byte[], not as a wrapped Object[]
The ',' operator elsewhere in this file exists because PowerShell unrolls an array
RETURNED from a function; a property assignment does not unroll, so it wrapped the
byte[] in an Object[] of length 1 and the upload failed converting it back. Signing
itself was fine -- run 34253331703 signed all six scripts and uploaded none, so nothing
reached the download alias.

Added the invariant that would have caught it: signed bytes must be longer than the
unsigned form, since a signature only ever adds.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 18:54:36 +02:00
Oliver Kieselbach 0ac548bfce feat(bootstrap): two-stage loader and Authenticode-signed customer scripts (D-224)
Start-AutopilotMonitor.ps1 is the new stage 1 -- the file an administrator assigns in
Intune. It carries no enrollment logic: it downloads the published installer, verifies its
Authenticode signature, and runs it in the same process, passing through every remaining
argument. Assigning the installer directly stays supported and unchanged.

The point of the split is that the customer-held artifact stops changing. Today every
bootstrap change forces customers to replace their Intune copy, so the fleet runs a
distribution of script versions we do not control. It is also what makes script signing
worth doing: signing a file that gets swapped by hand each release is a one-off gain,
signing a loader that never changes is permanent.

The loader is deliberately minimal, because it is the one piece that cannot be fixed
remotely -- every guard placed in it would be frozen for years. All guards stay in stage 2.

Verification pins the certificate SUBJECT, never a thumbprint: certificates get renewed and
a deployed loader cannot be, so a thumbprint pin would strand the fleet at the next
renewal. A hash oracle was rejected for a different reason -- it would have to be fetched
from the same host as the script, so it could not survive a compromise of that host, while
the expected publisher travels inside the loader.

Fail-closed on verification, fail-soft on exit: nothing runs without a valid signature from
us (running unverified code as SYSTEM is the risk being removed here), but the loader still
exits 0, because a device without monitoring is acceptable and a failed enrollment step is
not. The accepted cost is that a device which can never fetch or verify stays silent.

Publisher changes:

- every published script is signed (loader, installer, both -Dev renders,
  Test-ShouldBootstrapAgent, Grant-AutopilotMonitorAddOn), and signing is the LAST
  transformation: it covers exactly the CRLF/UTF-8 bytes Get-PublishBytes produced, so
  nothing may normalise or re-encode them afterwards.
- signing is mandatory for a real publish. Only -DryRun may run unsigned, because the PR
  gate executes the publisher without any Azure login.
- comparisons against a published copy strip the signature block first. A timestamped
  signature differs on every run, so without stripping the version-bump guard and the
  drift check would report a change for every unchanged script.
- the bump guard became Assert-VersionBump and now covers the loader as well.
- version.json gains loaderVersion. Additive, no consumer yet: stage 2 is current by
  construction, so only stage 1's version says anything about a customer's Intune copy.
- -SignedOutputDir writes the exact uploaded bytes for the CI artifact, in a dry run too --
  that is how a signed script gets inspected before it reaches anyone.

publish-scripts.yml logs in with the signing identity first and only to fetch the Key Vault
token (azure/login sets the default az account and the storage login has to be the one that
stays), then publishes and offers the signed scripts as an artifact. build-agent.yml passes
the same parameters on a stable cutover.

Tests: 14 new Pester cases, including that a validly signed script from a FOREIGN publisher
is refused -- that is what an attacker with any code-signing certificate can produce. Full
bootstrap suite on Windows PowerShell 5.1: 43/43.

Not covered: the MSI runner still downloads stage 2 without verifying it, and the customer
docs still describe the direct assignment only.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 18:48:21 +02:00
Oliver Kieselbach 9c1d0586ef ci: skip the provenance attestation on test runs of build-agent
A dispatch with upload_blob=false and create_release=false publishes nothing, so the
Sigstore attestation would write a permanent public transparency-log entry for bytes
nobody ever receives. The step now runs only when the run actually ships something.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 18:34:52 +02:00
Oliver Kieselbach 21ec5e4773 ci: Authenticode-sign the agent binaries before the release hashes are computed (D-223)
Every assembly we author -- AutopilotMonitor.Agent.exe, AutopilotMonitor.SummaryDialog.exe
and the three AutopilotMonitor.*.dll beside them -- is signed with AzureSignTool (pinned
7.0.1) against a certificate in the corporate code-signing Key Vault, SHA-256 file digest
plus an RFC-3161 timestamp. Third-party assemblies keep their own publisher's signature.

The position of the step is load-bearing: signing rewrites the PE file, so it has to run
before the staging copy, the ZIP and every SHA-256 in "Create release artifact". Those
hashes are the bootstrap's integrity oracle (version.json, AdminConfiguration) -- signing
after hashing would publish hashes that no downloaded file can ever match.

The signing identity is a SECOND federated principal in the same tenant and logs in FIRST,
only to fetch a Key Vault token; the storage login of D-222 follows and owns the az context
from there, because azure/login sets the default account and the last login wins. Both
federated credentials carry the subject repo:okieselbach/AutopilotMonitor:ref:refs/heads/main,
so this job must never be given a GitHub 'environment:' -- that rewrites the OIDC subject
claim and would break BOTH logins at once.

No unsigned fallback and no dispatch input to skip signing: a missing repository variable,
a Key Vault failure or a non-zero azuresigntool exit code fails the run before anything is
published. azuresigntool is a native tool, so $LASTEXITCODE is checked explicitly --
PowerShell does not throw on a non-zero exit, and a silently unsigned release is exactly
the outcome signing exists to prevent.

Verification runs against the STAGED bytes, not the build output: every AutopilotMonitor.*
PE in the ZIP must be Valid, must carry a timestamp (without one the signature dies with
the certificate) and all of them must share one signing certificate. Setting the optional
repository variable CODE_SIGN_EXPECTED_SUBJECT additionally pins the publisher, so the gate
proves "signed by us" instead of "signed by someone trusted".

The build provenance attestation now covers the ZIP and both EXEs, so an extracted binary
can be verified without the ZIP. Authenticode and the attestation answer different
questions and both stay: who published this binary (offline, what Windows, SmartScreen and
WDAC evaluate) versus which build produced these exact bytes (gh attestation verify).

Not covered here: the customer bootstrap script (its signature block changes the published
bytes and must follow the dev render; see B-57c, the two-stage loader), the bootstrap MSI,
and the local build.ps1 path, which from now on produces unsigned bits.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 18:20:16 +02:00
Oliver Kieselbach e4a5a6654d ci: workflows authorize Azure Storage with the federated identity, not SAS secrets (D-222)
Every storage write against autopilotmonitoreu -- build-counter CAS, agent ZIP and MSI,
version manifests, customer bootstrap scripts, the AdminConfiguration hash oracle -- now
rides on the existing federated credential (subject repo:.../ref:refs/heads/main) instead
of a long-lived SAS in repo secrets.

The REST calls themselves are unchanged: '?<sas>' became an Authorization header, so the
ETag-CAS of the counters, Content-MD5 and the no-cache contract survive verbatim. That is
also why this is not a rewrite onto 'az storage blob upload' -- it cannot express If-Match,
and two concurrent builds could then mint the same build number.

.github/scripts/Get-StorageAuthHeaders.ps1 is the single place that knows the resource id,
the az invocation and the service version. x-ms-version is mandatory for Entra-authorized
requests (>= 2017-11-09) and for any Table request without a SAS; 2021-08-06 was verified
live against both the blob and the table endpoint of this account.

azure/login added to build-agent, build-msi, publish-scripts (plus id-token: write) and
deploy-web; deploy-backend and deploy-mcp already had it. Publish-BootstrapScripts.ps1
-DryRun acquires NO token: the PR gate runs it without any Azure login, and that must
stay true.

The AdminConfiguration merge lost its "secret not configured" skip branch -- a failure
there now surfaces instead of silently leaving the hash oracle pointing at an older build.

AZURE_BLOB_AGENT_SAS_TOKEN, AZURE_BLOB_VERSIONS_SAS_TOKEN and AZURE_TABLE_ADMIN_SAS_TOKEN
are retired once the first runs are green. AZURE_BLOB_AGENT_LEGACY_SAS_TOKEN stays: that
account lives in the pre-migration tenant, where this principal has no identity -- it dies
with the mirror, not before.

Requires on the SP: Storage Blob Data Contributor on the containers 'agent' and 'versions',
Storage Table Data Contributor on the table 'AdminConfiguration'. Granted 2026-09-08.
2026-09-08 17:38:14 +02:00
Oliver Kieselbach 01bc35aa97 new ordering for What's new section 2026-09-08 15:48:28 +02:00
Oliver Kieselbach e33d85c01d Agent Host changes for agents/gather-rule-exitcode-info-update (#151) 2026-09-08 14:57:30 +02:00
Oliver Kieselbach 4e73ba8900 Agent Host changes for agents/improve-changelog-promotion-ui (#152) 2026-09-08 14:57:11 +02:00
Oliver Kieselbach 4df52b3da9 Agent Host changes for agents/timeline-search-enhancement (#150) 2026-09-08 14:47:30 +02:00
Oliver Kieselbach 844d86410c Agent Host changes for agents/mcp-server-beschreibung-lieferung (#149) 2026-09-08 14:46:15 +02:00
dependabot[bot] 9514e1033d chore(deps): bump the web group (#148)
Bumps the web group in /src/Web/autopilot-monitor-web with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [next](https://github.com/vercel/next.js) | `16.3.3` | `16.3.4` |
| [@next/bundle-analyzer](https://github.com/vercel/next.js/tree/HEAD/packages/next-bundle-analyzer) | `16.3.3` | `16.3.4` |
| [@types/react-dom](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/react-dom) | `19.2.5` | `19.2.7` |
| [autoprefixer](https://github.com/postcss/autoprefixer) | `10.5.4` | `10.5.5` |
| [eslint-config-next](https://github.com/vercel/next.js/tree/HEAD/packages/eslint-config-next) | `16.3.3` | `16.3.4` |


Updates `next` from 16.3.3 to 16.3.4
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/compare/v16.3.3...v16.3.4)

Updates `@next/bundle-analyzer` from 16.3.3 to 16.3.4
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/commits/v16.3.4/packages/next-bundle-analyzer)

Updates `@types/react-dom` from 19.2.5 to 19.2.7
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/react-dom)

Updates `autoprefixer` from 10.5.4 to 10.5.5
- [Release notes](https://github.com/postcss/autoprefixer/releases)
- [Changelog](https://github.com/postcss/autoprefixer/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/autoprefixer/compare/10.5.4...10.5.5)

Updates `eslint-config-next` from 16.3.3 to 16.3.4
- [Release notes](https://github.com/vercel/next.js/releases)
- [Commits](https://github.com/vercel/next.js/commits/v16.3.4/packages/eslint-config-next)

---
updated-dependencies:
- dependency-name: next
  dependency-version: 16.3.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: web
- dependency-name: "@next/bundle-analyzer"
  dependency-version: 16.3.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: web
- dependency-name: "@types/react-dom"
  dependency-version: 19.2.7
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: web
- dependency-name: autoprefixer
  dependency-version: 10.5.5
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: web
- dependency-name: eslint-config-next
  dependency-version: 16.3.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: web
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-08 13:07:51 +02:00
Oliver Kieselbach b2236bf65f web: card and page headers stack below sm so their action buttons stay on screen at phone width
Title and trailing controls shared one non-wrapping flex row with the controls
marked flex-shrink-0. At 440px (iPhone 16 Pro Max) that squeezed the Operational
Events title into an 86px column and pushed the Refresh buttons of Agent Metrics
and the Tenant Config Report past the viewport, scrolling the whole page sideways.
SectionCardHeader now stacks below sm, which covers all 32 cards that use it.

A width sweep over the portal routes at 440px found two more real overflows, fixed
here as well: the audit From/To date pair, and Alert Rules, where the unbreakable
event-type names and a channel-name input without min-w-0 pushed the severity
selects 99px off screen.

Verified: every swept route now measures zero horizontal overflow at 440px, desktop
is unchanged at 1440px. The header test asserted "no trailing group" via the absence
of gap-3, which the wrapper itself now carries; it checks flex-wrap instead and pins
the stacking classes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 01:35:50 +02:00
Oliver Kieselbach 31535b07e0 web+backend: a warming MCP health card says only "Starting instance... (attempt n of 12)" and re-probes for ~60s before it warns (D-220)
The card composed its line from the backend's explanation ("did not answer within
3s - it scales to zero when idle ... ~20-30s"): probe mechanics nobody waiting on a
starting instance needs. It now writes its own one-liner and ignores check.message,
so the server's "warming" and a client-side probe timeout read identically and the
wording does not depend on a backend deploy. The backend message is shortened but
still carries the budget for direct API callers.

The re-poll budget of 8 x 5s (~40s) expired on a real cold start - Container Apps
activation has no upper bound we control - so it is now 12 x 5s (~60s), with a test
pinning that the stated seconds come from cadence x attempts.
2026-09-07 21:27:07 +02:00
Oliver Kieselbach 066b6e6f04 backend+web: the MCP health probe answers a cold container in 3s with status "warming" instead of holding the request for 30s, and the System Health card re-probes until it is up (D-220)
Measured over 14 days, GET health/mcp answered in 4..148ms when warm and timed out at 30s
in 50 of 83 calls — the median call took 27,972ms. A cold start is 20-30s of Container Apps
activation (~98% KEDA plus image mount, ~500ms application), so no UI wait covers it and the
generous timeout only bought a long wall in front of the same answer. The browser's own
budget is the same 30s, so the backend's carefully worded warning never reached the user at
all: they saw a raw DOMException.

Backend: the budget drops to 3s, which sits in the widest observed latency gap
(2347ms..3930ms) so jitter cannot flip the verdict. Our own cancellation now reports the new
status "warming" at Information level (with minReplicas=0 a cold probe is the expected path,
and logging it as a warning poisons the ops signal); HttpRequestException is split out of
that catch and stays a real warning, still without the host in the message. The warm-hit
threshold drops to 750ms — ~5x the warm maximum, deliberately generous because every
measurement comes from a near-idle single-user system and warm latency will rise under
concurrency — and moves into McpReachableMessage so a test can pin the boundary. The XML doc
now describes the probe that exists rather than the wake-signal design the measurements
disproved.

"warming" is a new status value rather than an added DTO boolean because the backend deploys
before the web: an unknown value degrades to a grey card with a clean banner, whereas a
boolean would leave old web showing yellow and "Warnings detected" on every cold start.
HealthCheck.Status now documents the five-value vocabulary, which rides into both generated
TypeScript mirrors as JSDoc.

Web: resolveMcpCardState owns display, banner rating and the poll decision as a pure
function (the suite runs on node, so testable logic cannot live in JSX). A warming server
re-probes every 5s for up to 8 attempts and stays out of the overall banner exactly as
"unknown" already does — scaling from zero is expected behaviour, not a degraded platform —
and only becomes a real warning once the re-polls are spent. The card keeps showing
"warming" while the next probe is in flight so it cannot flicker, carries the blue
in-progress look instead of yellow, and was hoisted out of the healthResult guard: a failing
detailed check would otherwise hide a card that is still polling.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 18:25:56 +02:00
Oliver Kieselbach a1e2b76a9f web: the session Vulnerability Report names its inventory badge "Identification Confidence" (header and legend, Inventory and Delta tab); the Software Inventory analyzer toggle uses the rose accent like the other Agent Analyzer toggles
The column showed high/medium/low under the header "Identification", which reads as a method rather than a rating. The wire field is `confidence` and the tooltip already says "identification confidence"; the header and legend now match. The analyzer toggle and its hover border were still emerald from before the section moved.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 13:13:31 +02:00
Oliver Kieselbach 29e5b8251d web(rules): analyze and gather rule cards get a two-row header on every breakpoint — badge row with fixed-width toggle, severity and rule-id columns on top, the full title below with threshold, sparkline and hit rate right-aligned; gather badges ordered category, type, collector like the analyze card
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 13:11:44 +02:00
Oliver Kieselbach 02168a5c55 chore: bump internal gitlink (geo-statistics-explained plan, D-219, backlog B-fpu/B-csp)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 12:12:12 +02:00
Oliver Kieselbach a6b6661320 web(geo): the Location Performance table states what Avg Duration, P95 and vs Global are computed over (footnote with docs links, header and benchmark tooltips); a location without a succeeded session shows no duration instead of 0 min / -100% in the fastest bucket
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 12:10:25 +02:00
Oliver Kieselbach 0c72666a7a chore: bump skills gitlink (CAS marker row corrected to the pre-fix code path)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 10:35:34 +02:00
Oliver Kieselbach 9023321db9 chore: bump skills gitlink (platform-health KQL fix + 09-07 marker baselines)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 07:48:08 +02:00
Oliver Kieselbach 7ef097529c backend: deleting an owned tenant group stamps the retention grace anchor on every member (conferred Pro ended without ProDowngradedUtc)
The portal hides Delete for owned (msp-{home}) groups, but DELETE global/tenant-groups/{groupId} accepts any id: a Global Admin deleting one ended Pro (MSP) for every member with no grace anchor, so a member that raised its retention under Pro was clamped to the Community cap at the next sweep. DeleteGroupCoreAsync now snapshots the owner and calls ProConferralService.RecordLossAsync(member, owner, "group-deleted") per member, owner excluded, independent of assignees. Two tests in RevokeEnforcementTests; internal docs list the fourth writer.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 00:15:21 +02:00
Oliver Kieselbach e7df69efe4 backend+web: vulnerability summary carries a priority breakdown (act/attend/track); the exposure panel shows Act and Attend tiles and every severity or priority chip filters the top-CVE list (D-218)
Act equals the KEV set by construction (CvePriority: KEV => act), so the KEV tile becomes the Act tile and Attend joins it instead of a duplicate count. The breakdown is counted in the backend over every CVE in the window, like the severity breakdown, because the list is top-N. Both panel consumers read the generated CveExposureSummary type; the MCP tool description names the new block. Wire types regenerated for web and MCP.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 22:30:36 +02:00
Oliver Kieselbach 2c7efa2733 backend: key-safe X-MCP-Tool-Name prefix for the usage row key (CodeQL cs/log-forging #91)
The caller-supplied X-MCP-Tool-Name header went verbatim into the UserUsageLog
row key ({yyyyMMdd}_{tool}:{endpoint}) and from there into the CAS-conflict
warning of TableCasRetry. EndpointNormalizer.ToolNameKey now strips CR/LF and
every other control character or line separator, replaces the characters Table
Storage rejects in keys (/ \ # ?) and caps the length at 64; an empty result
skips the prefix. Real tool names pass through unchanged, so existing usage
rows keep their keys. A header with an illegal key character previously made
every usage increment fail with 400 (fail-soft, counter never advanced).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 22:19:56 +02:00
Oliver Kieselbach 2742549827 chore: bump skills gitlink (platform-health marker baselines + GetBootstrapScript trap)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 22:07:46 +02:00
Oliver Kieselbach 3c45f5cb09 chore: regenerate the shared manifest and wire types for the NtpServer summary text (D-216 follow-up)
The manifest committed with d5d1d7bf carried the types section of the previous HEAD, so
the ntpServer doc string still read "null = use agent default"; SharedManifestParityTests
compares byte-for-byte. Generated output only, no wire change. Bumps the internal gitlink
(plan review addendum).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 22:02:10 +02:00
Oliver Kieselbach d5d1d7bfbd backend+web: one agent-config derivation (AgentConfigResolver) served on agent/config and GET config/{tenantId}/effective-agent-config; wire-type initializer defaults in the shared manifest; the Tenant Config Report reads both (D-216)
The report still carried two hand copies after D-215: a typed map of C#
initializer defaults for the "custom" highlight, and a TypeScript mirror of
GetAgentConfigFunction's resolution rules for the runtime column.

Backend: the derivation moves verbatim into Services/AgentConfigResolver
(Build = pure, ResolveAsync loads tenant + admin config and the two rule
catalogs). GetAgentConfigFunction keeps the kill verdict, the migrate logging
and the device fields on top; ParseAgentMajor, ResolveDiagnosticsUploadEnabled,
MergeDiagnosticsLogPaths and ResolveMigrateTarget move with it (call sites and
tests retargeted; the QueryParams ratchet baseline shrinks by the file). New
GlobalAdminOnly route config/{tenantId}/effective-agent-config returns the same
AgentConfigResponse without a device (optional ?agentVersion=, default the V2
line). AgentConfigResolverTests pin the rules that used to live in the web:
upload 10, Hosted destination without SAS, SAS regardless of mode, unrestricted
only with entitlement + gate + toggle, operator knobs from AdminConfiguration,
analyzer defaults, hash line per major, migrate override and rejection.

Manifest: SharedManifestParityTests emits "defaults" next to "fields" for
TenantConfiguration and AdminConfiguration and an "agentConfig" section with
the AgentConfigResponse / CollectorConfiguration / AnalyzerConfiguration class
defaults (fresh-instance values; nested objects null). TenantConfiguration.
NtpServer gets the initializer "time.windows.com" the table read already
applies, so the manifest default and a stored row agree.

Web: the catalog rows lose value() and default; the runtime column renders
the endpoint's response, the highlight compares against the manifest defaults,
informational rows (reasons, timestamps, identities, secrets) never read as
custom. Previously excluded fields are visible (configVersion, catalog counts,
sealing pattern ids, hash oracle, migrate target); the collector class
defaults sit in a collapsed "Collector Internals" section. Fail-soft: while the
backend is not deployed the runtime column shows a notice.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 21:59:34 +02:00
Oliver Kieselbach f4e2088b69 chore: bump internal gitlink (lessons: shared index) 2026-09-06 21:57:49 +02:00
Oliver Kieselbach 55425058a8 chore: bump internal gitlink (dashboard-search plan review) 2026-09-06 21:57:26 +02:00
Oliver Kieselbach eec0d17607 chore: bump internal + skills gitlinks (D-217 plan/review, lessons, ux-insights marker row) 2026-09-06 21:54:47 +02:00
Oliver Kieselbach 43f5304ba4 web+backend: dashboard search gets field qualifiers (model=, manufacturer=), AND-ed terms and exclusions, parsed identically on both sides; Fleet Health model rows link with that search (D-217)
The "Health by Device Model" link searched "{Manufacturer} {Model}" as one substring; the server's
free-text predicate tested it per field, so once the failed sessions were outside the loaded first
page the sweep returned nothing.

- lib/searchQueryTokens.ts: tokenizer shared by the timeline and the session search (terms, quotes,
  leading minus, key=value / key:value qualifier when the separator precedes any quote)
- app/dashboard/utils/sessionSearchQuery.ts: 15 qualifiers = exactly the fields both sides search,
  matcher over session fields + client-derived extra text, suggestion field lookup, link builder
- useDashboardFilters / SessionTable: filter and suggestions use the grammar; fuzzy only for a
  single free term; session_searched gains a `qualifiers` count
- Helpers/SessionSearchQuery.cs: the same grammar for q= on /api/search/sessions (+ global), parsed
  once per request; MatchesFreeText is a thin wrapper
- utils/session-search-syntax.cases.json: one case file run by vitest and by
  SessionFreeTextSearchTests (parity proof)
- FleetModelHealth/FleetSlowModel/FleetFailingModel: manufacturer + model as stored plus label,
  grouped on the pair; useFleetHealth uses the generated wire types; "Unknown" is not a link
- shared manifest + wire types regenerated for the three DTOs

Backend suite 6158/6159 (the one failure is SharedManifestParityTests against uncommitted WIP of a
parallel task), web vitest 1177/1177, build 0 warnings.
2026-09-06 21:54:10 +02:00
Oliver Kieselbach b21472dd8c web(progress): pre-provisioned device parked after the technician part sits on Account setup instead of a forever-running device apps step
The progress portal placed the active step purely by the stored phase. After
whiteglove_complete the backend caps that phase at Apps (Device), so the end
user saw "Waiting for you to sign in" above a step list that still showed
"Installing apps (device)" as running at 43 % (customer report).

The seal detection the headline already used is now one helper,
isParkedAfterTechnicianPart (pre-provisioned, whiteglove_complete, no resumedAt
and no whiteglove_resumed), and resolveActiveStepIndex places such a session on
the first user step: every device step done, 57 %, Account setup current. A
stale Complete phase on older sessions can no longer push it past the sign-in;
once resumed the placement is phase-driven again.

Vitest 24/24, tsc and eslint clean. Backlog B-ydz carries the post-deploy check.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 21:24:32 +02:00
Oliver Kieselbach e3991d55be web(admin): Tenant Config Report renders from an exhaustive catalog over the generated wire types (D-215)
The report typed its own TenantConfig interface and drifted for five months: 31 stored
fields were missing (payingCustomer, the MSP overrides, three validation gates, the SLA
block, four analyzer flags, app-homing and trial bookkeeping) and three runtime values
were wrong (upload interval 30 instead of 10, diagnostics-enabled without the Hosted
destination, unrestricted mode without the entitlement).

tenantConfigReportCatalog.ts is Record<keyof TenantConfiguration> and
Record<keyof AgentConfigResponse | CollectorConfiguration | AnalyzerConfiguration>:
every key is rendered or excluded with a reason, so a new C# property fails tsc once the
wire type is regenerated. Runtime rows carry the GetAgentConfigFunction rule and a source
tag; entitlement values come from feature-flags, operator knobs from global/config.
A vitest pins the same parity against SHARED_MANIFEST.tenantConfiguration.fields and the
resolution rules (upload 10, Hosted destination, flags-driven unrestricted mode, admin
idle timeout, analyzer defaults). Empty strings count as unset for the custom highlight.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 21:08:03 +02:00
Oliver Kieselbach 864d1ed31e backend: MCP usage counters go through TableCasRetry with an 8-attempt jittered budget instead of three immediate retries (B-c92)
Parallel tool calls of one user hit the same (user, day, endpoint) row in the same instant; without backoff the losers stayed synchronised and 3 of 6 increments were lost. Both increments now use the one CAS helper (merge patch, AddEntity on 404, StorageCasConflict marker) with UsageCounterRetries = 8; the tenant counter's attribution columns travel in the merge patch. Tests pin the budget, the patch shape and the create path.
2026-09-06 19:04:58 +02:00
Oliver Kieselbach 76ef1e53ca chore: bump internal gitlink (final check 2026-09-06: plans released, backlog long-tail rewritten, todo cleared) 2026-09-06 18:48:46 +02:00
Oliver Kieselbach 7dd298f04e chore: bump skills gitlink (session skills: exit-code class, packaging counters, WU symbols)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 18:21:14 +02:00
Oliver Kieselbach 66452621c6 exit-code class per app + reboot rule: IME-EXITCODE-CLASS, ANALYZE-APP-018, exitCode on every terminal app event (D-214)
- IME-EXITCODE-CLASS captures the return-code class of the installer exit code ("lpExitCode is defined as <Success|SoftReboot|HardReboot|Retry|Failed>", verified against the IME string literal) as exitCodeClass on AppPackageState; new action captureExitCodeClass, persisted across the agent restart a reboot causes, last value wins across a Retry loop. IME-EXITCODE-MAPPED-FAILED keeps the error path; both match the same line.
- Adapter: exitCodeClass whenever known, exitCode on every terminal state (Installed/Postponed/Skipped/Error) instead of Error only.
- ANALYZE-APP-018 (warning, apps): app_install_completed.exitCodeClass in SoftReboot,HardReboot; +25 HardReboot, +15 observed system_reboot_detected; never fails the session.
- Web: completed-app exit badge amber (failed stays red), "mapped as SoftReboot/HardReboot/Retry" on timeline and Install Progress.
- Tests: pack end to end (phase, current app, class lines, negatives, restart round trip), adapter payloads, linearity samples, backend rule engine + known actions.
- internal gitlink: plan, D-214, backlog.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 18:08:49 +02:00
Oliver Kieselbach 0b23d93957 updated last modified 2026-09-06 17:49:25 +02:00
Oliver Kieselbach 4281a6d81b chore: bump internal gitlink (rules category groups plan, Paket 3) 2026-09-06 17:39:10 +02:00
Oliver Kieselbach fe919a51aa web rules pages: group analyze and gather rules by category with collapsible headers, counters and Expand/Collapse All (state per tab in localStorage); reveal a rule inside its group from telemetry, template copy and view-copy
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 17:37:44 +02:00
Oliver Kieselbach 0dcf0eb503 Observation coverage in get_session_summary, absence audit with coverage lint, diagnostics packaging counters (D-213)
MCP: coverage block (window, IME tracker, collectors, upload, diagnostics, gaps) built from the
health events the summary already fetches (session-coverage.ts, data.<key> slices); validate_rule
warns on a required not_exists of an IME-log-derived event without the ime_tracker_degraded
precondition; authoring guide 'absence'; instructions and prompts point at coverage.gaps.
Rules: guardrails.json imeLogDerivedEventTypes (schema + combine). Backend: catalog invariant test —
absence rules carry the coverage gate or a documented exception (ANALYZE-ID-004).
Agent: diagnostics_uploaded/_upload_failed carry packaging counters (truncated, includedFiles,
skippedFiles, skippedByReason, problemsByKind) — counts only, never paths.
Also: shared-manifests.json regenerated (was stale at HEAD; McpAccessPolicy doc string) + codegen.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 17:35:52 +02:00
Oliver Kieselbach e2fb99d5d8 mcp access-guard: surface the suspension text from the policy envelope; AdminConfiguration.McpAccessPolicy comment matches the enforced AllMembers semantics; internal gitlink (MCP-Nebenbefunde, B-4s2)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 17:12:19 +02:00
Oliver Kieselbach a3ee613b60 scripts/error-codes: decode entities in one pass and strip tags until none remain (CodeQL 89/90)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 16:33:36 +02:00
Oliver Kieselbach d2197c6a57 error-code catalog v2: generated from primary sources, symbols and families, MCP lookup_error_code (D-211/D-212)
Shared: error-codes.json schemaVersion 2 (607 entries, 50 IME enforcement states) generated
by scripts/error-codes/generate.mjs from MS Learn tables and the IME enums of one build;
ErrorCodeEntry gains symbol/category/imeRetriesDuringEsp, ErrorCodeCatalog gains
TryLookupDetailed (HRESULT_FROM_WIN32 derivation as data), TryLookupBySymbol,
TryLookupEnforcementState. Backend enricher siblings carry symbol/category/derivedFromWin32
plus enforcementStateInfo. Web: validating, minifying sync; formatErrorCodeSource for every
tooltip; windows_update_failed badge; script error codes decoded; bundle budget test.
Agent: WindowsUpdateTracker reads the catalog symbol (WU_E_UNKNOWN sentinel, load failure
never costs an event). MCP: error-code-catalog.ts (lexical-only), lookup_error_code for every
role, search_knowledge merges catalog hits, get_session_summary key events carry
errorCode/errorText, Dockerfile COPY + ERROR_CODES_PATH. ANALYZE-APP-014 1.2.1 corrects the
0x80073cf0 gloss. Gitlinks: internal (D-211/D-212, plan review, backlog), .claude/commands.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 16:24:35 +02:00
Oliver Kieselbach e5997bc50e chore: bump internal gitlink (error-code catalog v2 plan)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 15:25:13 +02:00
Oliver Kieselbach 75138016ce chore: bump internal gitlink (analysis notes revision 2)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 14:46:44 +02:00
Oliver Kieselbach fc4772efb0 chore: bump internal gitlink (analysis notes: detection-coverage ideas)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 14:42:56 +02:00
Oliver Kieselbach 0bde428fa0 web: GA tenant modal — MCP switch and suspension moved down next to offboarding
Order at the end of the modal: MCP Access, Tenant Suspension, Offboard Tenant. Rarely used
levers sit together; the frequently edited plan, contact and limit sections come first.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 14:13:40 +02:00
Oliver Kieselbach 16ca3a059c backend/web/mcp: per-tenant MCP switch as an operator control (D-210)
TenantConfiguration.McpDisabled + McpDisabledReason (GA-only, same deny-list and PUT guard as Disabled).
Front door: McpUserService denies every caller of a closed home tenant below the platform roles.
Per request: PolicyEnforcementMiddleware denies a closed home or target tenant for X-Client-Source: mcp
(403 McpDisabled) and narrows the delegated fleet bound, never to null. ClientSourceHeader is the one
reader of the header. The MCP access guard surfaces the backend reason verbatim. GA tenant modal,
list badge and config report; wire types regenerated; internal doc, health marker, gitlinks bumped.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 14:01:01 +02:00
Oliver Kieselbach 1bfc80e6db chore: bump internal gitlink (release backfill plan RELEASED, D-209)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 13:26:49 +02:00
Oliver Kieselbach fa705a2ef6 updated Readme.md 2026-09-06 13:13:42 +02:00
Oliver Kieselbach 81f807e124 web: modal overlays render through ModalPortal into <body> (D-208)
A fixed overlay still receives its parent's box-model margins: the tenants page's
space-y-8 wrapper gave the edit dialog's backdrop a 32 px margin-top, leaving the
navbar un-dimmed. All 21 full-screen overlays now portal to document.body.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 12:27:01 +02:00
Oliver Kieselbach a4f7c88785 chore: bump internal gitlink (request-wire-contract RELEASED, live verify) 2026-09-06 12:02:36 +02:00
Oliver Kieselbach 54259f070f chore: bump internal gitlink (request-wire-contract GEBAUT, D-207, B-r95/B-cme) 2026-09-06 11:42:37 +02:00
Oliver Kieselbach 26cef3ab06 web: request bodies as jsonBody<T> against the generated wire types (D-207)
Every request body in app/, components/, contexts/, hooks/ and lib/ is encoded
as jsonBody<SomeRequest>(…) from lib/apiClient.ts; the apiClient ratchet gains
the `body[:=] JSON.stringify(` pattern (74 → 10 sites) and refuses a bare
jsonBody(. The hand-written RestoreRowRequestBody/RestoreRowMode are the
generated RestoreRowRequest/RestoreRowMode now; scriptDisplayNames posts through
fetchJson; the tenant-group and delegation mutate helpers take a pre-encoded body.

What the typing surfaced and fixes here: canManageBootstrapTokens and `all` are
sent explicitly, AdminConfiguration goes back on the wire through
toWireAdminConfiguration (the outbound twin of fromWire…), TenantManagementSection
uses the wire TenantConfiguration instead of a local subset, nameless CPE entries
are filtered before they are sent, the session action posts
QueueSessionActionRequest, create-from-template sends { variables }.

Remaining baseline (with reason): the three rule/pattern pages, whose local rule
types diverge from the wire — B-cme.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 11:42:24 +02:00
Oliver Kieselbach 00ad230ffe mcp: request bodies typed against the generated wire types (jsonBody<T>, D-207)
The eight backend POST/PUT/PATCH bodies name their request DTO through
jsonBody<T> from client.ts — the one place a body is encoded — so a renamed
or retyped backend field fails tsc instead of surfacing as a 400 at runtime.
The apiFetch guard additionally refuses `body: JSON.stringify(` and a bare
`jsonBody(` with an empty baseline.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 11:42:22 +02:00
Oliver Kieselbach 3d920a8113 shared+backend: IApiRequest marker, one RequestBody reader, every request body a Shared wire type (D-207)
Every HTTP request body the web, the MCP or the agent sends is now a flat class in
AutopilotMonitor.Shared implementing IApiRequest — the request twin of IApiResponse.
WireTypeManifestBuilder exports the implementers as a third root, so the request DTOs
reach wire-types.generated.ts on both clients; for request types a nullable property
keeps `| null` (a PATCH may send an explicit null to clear an override).

Functions read a body only through RequestBody.ReadAsync<T>/ReadOptionalAsync<T>
(System.Text.Json, ApiJsonOptions.Read = wire options + case-insensitive; empty or
malformed body = 400 envelope, never a 500) whose generic constrains on IApiRequest.
ReadNewtonsoftAsync<T> stays for the Newtonsoft-bound cluster (tenant/admin config via
the patch service's PopulateObject, rule and pattern documents) as a frozen per-file
baseline. The tenant-plan PATCH keeps its presence-sensitive JsonDocument walk with the
keys derived from PatchTenantPlanRequest by nameof (PlanPatchKeyParityTests).

35 nested request classes, 7 JObject/JsonDocument hand-walks and the anonymous
DeserializeAnonymousType bodies moved to Shared; the two identical TicketRequests are
one DownloadTicketRequest; ServerAction is no longer the request (QueueSessionActionRequest,
the stored row is built server-side); create-from-template takes { "variables": … }
instead of a bare map. Fields the endpoints default server-side are nullable now
(CPE mapping, report attachments, feedback rating on dismissal, upn for applications).

TypedRequestGuardTests: no raw deserializer under Functions/ (named exemptions: agent
routes frozen by D-200, Azure Monitor webhook, upstream/stored-column parses), the
Newtonsoft branch only in its baseline, no request type in the Functions assembly, every
DTO flat and in Shared. RequestBodyTests cover both readers, the cap and the envelope.
QueryParamGuardTests baseline shrinks by 14 (the Content-Length TryParse lives in the reader).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 11:42:03 +02:00
Oliver Kieselbach f6eac1964a chore: bump internal gitlink (both plans RELEASED, live verify, B-fq7 / B-8va)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 04:10:34 +02:00
Oliver Kieselbach e1b5b9d163 backend+web: per-user rate limits split by throttle surface — portal (public client) gets its own global budget, MCP/integrations keep override and floor (D-206)
The surface comes from the signed appidacr/azpacr claim (0 = public client = portal;
secret/certificate, app-only or missing = integration), never from a header: portal SPA,
MCP server and API share one app registration in production, so the client id cannot tell
them apart and any token holder controls headers. New AdminConfiguration field
PortalUserRateLimitRequestsPerMinute (default 600, Global Settings round-trip, wire types
regenerated); the existing user budget is relabelled MCP & integrations and keeps the tenant
override and the Pro floor; buckets are keyed per surface; ThrottleSurface is a request
dimension next to ClientSource so the classification is auditable (platform-health check 2).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 03:45:42 +02:00
Oliver Kieselbach 094833f831 backend: a Graph 401/403 on the first validator attempt invalidates the tenant token and retries fresh; the agent keeps getting 503 for a permission gap (D-205)
A freshly onboarded tenant spent 45 minutes in 503 because a second instance held a
roleless app-only token minted before the consent; InvalidateTenant never reaches other
instances. GraphAuthFailure is the shared step for all five Graph validators: attempt 1
drops the cached token and reports transient so the existing loop re-mints; attempt 2
keeps each validator's semantics (Autopilot/DeviceAssociation transient with Retry-After
120, CorporateIdentifier/CloudPc/IntuneBinding definitive) and logs a stable marker.
SecurityValidator hands the agent the largest Retry-After requested. Platform-health
check 6 and the marker catalog know both markers; the cloudpc concept doc carries the
contract.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 03:35:39 +02:00
Oliver Kieselbach 3579ce0add chore: bump internal gitlink (typed call sites RELEASED, verify) 2026-09-06 02:55:20 +02:00
Oliver Kieselbach 0188860d1c chore: bump internal gitlink (storage-budgets plan RELEASED)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 02:52:23 +02:00
Oliver Kieselbach 871a1ac059 chore: bump internal (typed call sites plan GEBAUT, D-204, envelope doc consumers, B-7sw) and .claude/commands (mcp-telemetry retries) gitlinks 2026-09-06 02:37:21 +02:00
Oliver Kieselbach 298a182fbb shared+web: backup job status and restore-row payloads join the wire contract; the web reads the generated types (audit package 5, stage 4b)
BackupJobStatus, RestoreRowPreviewResponse and RestoreRowCommitResponse were the last response payloads the
portal typed by hand: the C# classes existed in Shared but were not marked [WireContract], so the manifest
never carried them. The attribute pulls them and their enums (BackupJobKind/State, BackupOutcome,
RestoreRowDiffKind, RestoreRowCommitOutcome) into shared-manifests.json and both generated wire-type files;
the three backup pages import those and lib/api.ts drops eleven hand-written mirrors. Attribute only: no
runtime behaviour changes, no backend deploy needed.

Still hand-written in lib/api.ts, with reason: BackupManifest/BackupTableEntry (a blob passed through by
GET global/backups/{id}), BackupTriggerResponse (the 202 body of global/backups/trigger is an anonymous
object outside the typed regime) and the RestoreRow request body.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 02:34:11 +02:00
Oliver Kieselbach e71223507c web: customs archive reads the generated types, annotations page follows nextLink through the typed builder, dead PaginatedResponse removed (audit package 5, stage 4a)
The five hand-written customs-archive response types in lib/api.ts duplicated CustomsArchiveRunListResponse,
CustomsArchiveEntryListResponse, CustomsArchiveRunSummary, CustomsArchiveEntrySummary and
TenantOffboardingCustomsArchiveEntry from the manifest; the two pages import those. The annotations page
built its next-page URL from API_BASE_URL + nextLink instead of the scoped builder plus extractContinuation.
PaginatedResponse<T> had no importer. types/diagnostics.ts states why it stays hand-written (no wire DTO
for GET diagnostics/paths).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 02:28:08 +02:00
Oliver Kieselbach 02187f0f3c web: the last raw API call sites join the call layer; ratchet baseline for authenticatedFetch reaches zero (audit package 5, stage 3d)
Rules pages, apps tabs, audit, delegations, diagnosis, fleet health, geographic, health check, SLA, usage
metrics, the notification and SignalR contexts, the feedback bubble, global search and the shared hooks
now call fetchJson/fetchOk; the activation page's hand-rolled Bearer fetch (no 401 retry, no
telemetry) joins the layer too. The SignalR join/leave paths keep their visible-refusal semantics through
ApiError, the delegation acceptance explains refusals by code, the health check keeps its 403 wording,
and the local mirrors of SlaMetricsResponse and PlatformUsageMetrics give way to the generated types.

No page, component, hook or context calls authenticatedFetch directly any more. What stays is
documented per file in the baseline's PERMANENT map: the auth/me bootstrap, the SWA's own version.json,
the public stats manifest, the delete-cascade classifier's 202 body, and seven TokenExpiredError
branches where the UI must act differently from showing the message (route, rethrow, batch, retry flag).

Ratchet baseline: 39 → 0 raw fetches, 40 → 7 parses, 25 → 8 token checks (from 228 / 221 / 140).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 02:21:25 +02:00
Oliver Kieselbach 3e2f62daeb backend: host.json holds Azure.Identity, Microsoft.AspNetCore and Microsoft.Hosting.Lifetime at Warning
About 12 MB/day of severityLevel-1 traces without diagnostic value (MSAL verbose, StatusCodeResult,
CORS success, Application started). Application logs were Warning+ already via Function: Warning.
Measured and documented in internal/docs/backend/telemetry-ingest-shaping.md.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 02:11:44 +02:00
Oliver Kieselbach c8b8a8dbb4 web(sessions/dashboard/progress): every API call through fetchJson/fetchOk/fetchBlob (audit package 5, stage 3c)
The 33 raw authenticatedFetch sites under app/sessions, app/dashboard and app/progress are gone. Hooks
that receive addNotification as a parameter report failures through notifyApiError (same rendering as
notifyError, injected notifier); fail-soft reads that used to check res.ok read through
.catch(nullOnApiError). The delete-cascade classifier accepts the ApiError of a refused DELETE next to
the 202 Response, so the 409/503/404 branches keep their wording; the polling probe reads the status
from either. Session and event reads name their wire types (GetSessionResponse, GetSessionEventsResponse,
SearchSessionsResponse, SessionStatsResponse, the progress and rule-stats responses); the legacy
list-shaped fallbacks on the single-session read are gone. SessionTimeBreakdownDto is the generated type.

Ratchet baseline: 72 → 39 raw fetches, 67 → 40 parses, 36 → 25 token checks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 02:09:51 +02:00
Oliver Kieselbach 9e4c5f11c5 chore: bump internal gitlink (plan verify line, trace-noise backlog idea)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 02:00:11 +02:00
Oliver Kieselbach b16e72c10e web(settings): every API call through fetchJson/fetchOk, errors through apiErrorText (audit package 5, stage 3b)
The 46 raw authenticatedFetch sites under app/settings are gone: 20 by the transformer, the rest by hand.
The tenant config load keeps its 403 fallback to the feature-flags view through ApiError; the access
check treats a backend refusal as an outcome and only a failed round trip as transient; delegated
access, MCP users and the offboarding flows read their specialised envelopes through ApiError.code
and ApiError.body. Twenty 'Session Expired toast / else inline' catch dialects collapse to the inline
message apiErrorText already renders; local mirrors of McpUserEntry, PlanTierDefinition,
HardwareRejectedResponse and DeviceNotRegisteredResponse give way to the generated types.

Ratchet baseline: 115 → 72 raw fetches, 111 → 67 parses, 59 → 36 token checks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 01:56:53 +02:00
Oliver Kieselbach 5cb9b0b30b backend: storage SDK budgets under the agent timeout, ingest 503 on an exhausted budget, request-token fan-outs, single-flight factory budget, ProcessStall monitor (audit F09, D-203)
- StorageClientOptions: Table/Queue 8 s per attempt × 3 attempts + capped backoffs = 25.8 s < the
  agent's 30 s upload timeout (pinned by test); Blob 60 s × 4. Every production client takes its
  options from there. No Polly over the SDK.
- StorageErrors.IsTransient(Exception): OperationCanceled / IO / HttpRequest / Aggregate-of-those
  / RequestFailed status 0; the ingest answers 503 + Retry-After instead of 500.
- The ingest still takes no caller cancellation (a batch is a unit). GetAllSessionsPageAsync
  carries the request token down to BoundedFanOut (Global Admin list); SingleFlightCache hands its
  factory a 30 s budget token and evicts on timeout (tenant ids, app-summary snapshot, session stats).
- ProcessStallMonitor: 1 s tick drift ≥ 1 s ⇒ ProcessStall event (sampling bypass) + metric with
  cause gc / threadpool / unknown from GC.GetTotalPauseDuration and thread-pool counters;
  GcPauseMs on request rows ≥ 100 ms. Measures the instance-local 5–10 s pauses seen in production.
- Gitlinks: internal (plan, D-203, concept doc, B-9hf, lesson), .claude/commands (marker rows).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 01:51:02 +02:00
Oliver Kieselbach c925001a8a web(admin): every API call through fetchJson/fetchOk/fetchBlob, errors through apiErrorText (audit package 5, stage 3a)
The 113 raw authenticatedFetch sites under app/admin are gone: 73 by the transformer (fetch + ok-check
+ json parse become one typed call), the rest by hand — 404-as-empty lists read through
.catch(nullOn404), the app-homing, offboard, delegated-admin and tenant-group flows read the
specialised envelope through the new ApiError.body, downloads use fetchBlob, action calls fetchOk.
Session-expired branches that only logged or set the same message are gone; apiErrorText renders
every failure with the reference.

Typing the responses surfaced eight local mirrors that had drifted from the wire types (required
fields the backend leaves optional): BlockedDevice, FeedbackEntry, DistressReport, OpsEvent,
SessionReport, IdentityBinding, UnmatchedSoftwareEntry, DailySummary and the whole
SectionPlatformUsage metric set are now aliases of the generated types, with the optional fields
handled where they render. AdminConfiguration keeps its literal-union narrowing through
fromWireAdminConfiguration instead of an unchecked parse.

Ratchet baseline: 228 → 115 raw fetches, 221 → 111 parses, 140 → 59 token checks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 01:41:19 +02:00
Oliver Kieselbach e494334720 mcp: apiFetch<T> at every call site, one retry on 429/503 within Retry-After, typed error envelope (audit package 5, stage 2)
apiFetch takes a mandatory wire type (60 call sites name their generated DTO; the 28 as-casts
and 31 unknown results are gone) and refuses an empty or malformed 2xx body. It retries once on
429 (never the MCP quota) or 503 when Retry-After is at most 10 s — GET only, never with a
caller-supplied signal, opt-in via retry:true otherwise — and counts the retry on the tool-call
context, which withToolTelemetry writes as `retries` on the tool_call line. ApiError.parsed is
the generated ApiErrorResponse plus domain fields and carries retryAfterSeconds; toolError
renders it in the 503, envelope and rate-limit branches. The lean-projection default lives in
one helper (leanFieldSelection) instead of two copies.

apifetch-typed.guard.test.ts refuses a bare apiFetch( or apiFetch<unknown>; apifetch-retry.test.ts
pins the retry, the opt-outs and the body contract. tools-delegated fakes now answer text() with
the body they claim (the client parses text, not json).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 01:13:20 +02:00
Oliver Kieselbach 1554540431 web: one API call layer (fetchJson/fetchOk/fetchBlob), notifyError, ratchets with the full baseline (audit package 5, stage 1)
lib/scopedFetch.ts becomes lib/apiClient.ts: ApiError carries retryAfterSeconds (body first,
Retry-After header second), fetchJson<T> refuses empty and malformed 2xx bodies instead of
handing back undefined, sets Content-Type for string bodies, fetchOk covers action calls and
fetchBlob downloads. describeApiError renders 429/503 with the server's retry advice;
apiErrorText is the one-string form for inline error slots; apiErrorNotification folds the
"Session Expired" dialect into one place and NotificationContext.notifyError uses it.
useAuthenticatedFetch throws ApiError (correlation id preserved), drops the dead 204 branch
and onTokenExpired. dedupedFetchJson<T> for the three feature-flag readers.

lib/__tests__/apiClient.guard.test.ts ratchets raw authenticatedFetch(/dedupedAuthFetch(/
.json()/instanceof TokenExpiredError per file against a baseline that may only shrink
(a count above fails as a new site, below as a stale entry); fetchJson without a type
argument is a violation. Baseline today: 228 raw fetches, 221 parses, 140 token checks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 01:01:41 +02:00
Oliver Kieselbach fef09690d2 web: coalesce live timeline refetches per burst instead of per SignalR signal
Agent uploads arrive as bursts of batches ~0.3 s apart with seconds of silence in
between, and every batch raises a SignalR signal. The 300 ms trailing debounce on the
session page either refetched once per batch or hid a tight burst until it paused;
session 46096bcd produced 155 full first-page reads for 261 batches in 13 minutes.

lib/burstScheduler: leading edge + trailing debounce + max wait. The first signal after
a quiet period refetches at once, later signals of a burst refetch once after the
burst's last signal, and a burst that never pauses still refetches every max-wait
(spool replay after reconnect/reboot). Fetch semantics are unchanged: every run reads
the full first page, the server stays the single source of truth, no incremental path.

Session page: trailing 300 ms, max wait 1 s. Progress portal (same pattern, two
requests per refresh): trailing 500 ms, max wait 1.5 s. scheduleFetchEvents loses its
delayMs parameter; the scheduler is created lazily on the first signal so refs stay
out of render (react-hooks/refs). Seven fake-timer tests pin the timing rules.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 00:41:13 +02:00
Oliver Kieselbach 3a975fa74f chore: bump internal gitlink (wire-contract plan RELEASED, short-sentence lesson) 2026-09-05 23:47:00 +02:00
Oliver Kieselbach 69c6353fb1 chore: bump internal (plan gebaut, D-200/D-201/D-202, drift-guards) and .claude/commands (platform-health 422 marker) gitlinks 2026-09-05 23:28:16 +02:00
Oliver Kieselbach 2b9bf3cd3f backend: one query-parameter parser (QueryParams) with a lenient and a strict contract, ratcheted (D-202)
Helpers/QueryParams replaces fourteen private days/limit parsers, the three
TryParseUtc copies, eleven identical pageSize blocks and ~50 inline TryParse sites
under Functions/ and Pagination/. Lenient (Int/IntOrNull/UtcInstant): absent, garbage
or below-minimum means the call site's default, above-maximum clamps. Strict
(TryInt/TryPageSize/TryUtcInstant): absent is null, anything else invalid is a 400
with a message that names the parameter. Integers are invariant-culture, instants are
invariant UTC (AssumeUniversal | AdjustToUniversal), whitespace counts as absent.
Defaults and ranges stay arguments at every call site.

Settled differences: the Apps windows clamp above 365 instead of falling back to 30,
days=0 or negative yields the default everywhere, the two global geo endpoints and
the session list cap days at 365, SLA months is capped at SlaMetricsService.MaxMonths
on the HTTP layer, a whitespace date means no filter on every route, the admin batch
sizes reject values above their maximum, and the three culture-dependent
DateTime.TryParse sites parse as UTC.

QueryParamGuardTests ratchets TryParse out of Functions/ and Pagination/ (baseline:
headers, raw cells, the agent version major, the se= of a stored SAS URL);
QueryParamsTests carries the cases the removed copies pinned.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 23:26:21 +02:00
Oliver Kieselbach d99e16314b agent+backend: one telemetry wire class, 422 poison for rejected items, agent responses in the typed regime (D-200/D-201)
TelemetryItemKind moves to Shared; TelemetryItem.ToWire() maps onto TelemetryItemDto
and the uploader serialises the DTO, so both ends share one wire class. The spool line
keeps writing Kind by name (StringEnumConverter registered in TelemetryItemSerializer).

IngestTelemetryFunction.PartitionBatch routes by exact kind name and collects every
item it cannot route or parse; a non-empty rejection list answers the batch with 422 +
TelemetryItemsRejectedResponse (poison, rejectedRowKeys, reason) before anything is
persisted, logs a Warning and writes the new TelemetryItemsRejected ops event. The
agent's existing poison protocol drops exactly the named RowKeys and re-uploads the
rest; before this the ingest skipped the items, answered 200 and the agent cleared
its spool.

Contract tests from both sides: TelemetryWireContractTests (agent) freezes the real
batch body under tests/fixtures/telemetry-wire/ and parses the pinned poison body;
TelemetryWireFixtureTests (backend) dispatches every frozen body with zero rejections,
requires an arm per kind and pins the poison body.

Agent-facing responses implement IApiResponse and go through ResponseHelper, request
types carry [WireContract]; plain ingest refusals use the error envelope, the
register-session and upload-url refusals keep their DTO bodies (the agent reads
ErrorCode/Message). Manifests and generated wire types regenerated (also picks up
four types HEAD had left out of the manifest).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 23:10:25 +02:00
Oliver Kieselbach e4203e0f15 chore: bump .claude/commands (platform-health skill, backend-logs corrections) and internal (marker-catalog rule) gitlinks; drop stale index dual-write mention in the dependency filter comment
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 22:53:14 +02:00
Oliver Kieselbach 2a5366d9c3 chore: bump internal gitlink (D-198/D-199, counters concept doc, storage-hardening plan GEBAUT)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 22:31:33 +02:00
Oliver Kieselbach 9c9cf24ddc backend: platform counters recomputed instead of incremented, RuleStats keyed per scope and day with CAS batches (audit F06, D-198/D-199)
PlatformStats(global,current) took a GET plus a full-row upsert without ETag
from every ingest batch: increments were lost under concurrency and a writer
clobbered fields another writer had just changed. RuleStats put every tenant's
daily rule traffic into one date partition (1,459 rows on 2026-09-04), the
writer issued four serial calls per evaluated rule without ETag, and the
reader was a cross-partition scan whose 10k cap dropped the newest dates.

- D-198: TotalEnrollments / SuccessfulEnrollments / TotalEventsProcessed have
  no hot-path writer; the two-hourly recompute is the only source. Only
  IssuesDetected still increments, through TableCasRetry (ETag + field-only
  merge, AddEntity for a missing row, conflicts as StorageCasConflict). The
  tenant counters share the helper.
- D-199: RuleStats PartitionKey "{scope}_{date}", RowKey ruleId.
  RecordRuleStatsAsync merges a session's increments per rule, reads the
  partition once and writes one transaction (UpdateReplace with ETag / Add),
  retrying on 412/409. Readers are PartitionKey ranges per scope; aggregation
  and the regression radar fan out over the registered tenants; the cleanup
  deletes per scope. RuleStats joins the offboarding composite wipe.
- Legacy rows (PartitionKey = date) are read by an extra query and cleaned by
  a date range that checks every row for a bare-date key, until 2026-12-05.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 22:30:58 +02:00
Oliver Kieselbach ec0d8ad735 backend: blob proxy lifetime and timing, one delegation key per process, shared KEV instance, single-flight config misses (audit F11/F12)
- DiagnosticsBlobStreamer disposes the download result on every exit path
  (it was disposed only on the 413 branch), measures open and transfer
  separately and fires DiagnosticsDownloadProxied after the copy with
  Completed=true/false.
- UserDelegationKeyCache: one user delegation key per process (24 h, re-mint
  under a lock with 2 h margin or when a SAS would outlive it) instead of one
  storage round-trip per download or upload SAS.
- KevDataService is resolved as one singleton over the typed-client handler
  pipeline; the cache warmer used to hydrate a throwaway transient instance
  while the correlation service held a cold one.
- Admin and tenant configuration services single-flight concurrent cache
  misses (Lazy<Task> per key); the MemoryCache and the in-place projection
  semantics stay untouched.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 22:14:56 +02:00
Oliver Kieselbach fc9e9d13e6 backend: keep slow storage successes and count CAS conflicts as a metric (audit F10)
The dependency filter dropped every successful storage call and the expected
412/409 outcomes, so storage-side latency and ETag contention were invisible
until a call failed outright (seven days of App Insights held zero storage
dependency rows).

- StorageDependencyFilterProcessor keeps a successful storage call at or above
  2 s and stamps SlowStorage=true; the operation name is on the row, the table
  name is not (the Azure SDK span carries neither URL nor table).
- StorageMetrics wraps TelemetryClient.GetMetric("StorageCasConflict",
  operation, table, outcome): pre-aggregated per minute, bypasses the worker's
  adaptive sampling, null-tolerant for tests.
- The CAS loops report conflicts: session event count, session counter
  reconcile, session store, tenant stats, MCP user/tenant usage.
- TableStorageService keeps its two-argument constructors (Moq matches by
  exact arity); DI resolves the three-argument overload.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 22:09:08 +02:00
Oliver Kieselbach d0cb7e66f4 backend: byte-aware table transactions and classified storage failures on the ingest (audit F07)
Every entity-group transaction was chunked by count only; 100 payload-heavy rows
(Signals with chunked PayloadJson, Events with 30k-char Message + DataJson) could
exceed the 4 MiB transaction cap, and the failure surfaced as an opaque 500. The
agent halves its batch only on 413 and treats 5xx as "replay later", so such a
batch wedged the device forever.

- TableTransactionBatcher: 100 actions, 3.5 MB per transaction, 1 MB per entity,
  never across partitions; an entity that cannot fit throws
  TableEntityTooLargeException. Used by the event, signal, transition, restore
  and rules writers; delete-only batches keep their count chunking.
- StorageErrors: one classifier for RequestFailedException (transient 408/429/
  5xx, payload-too-large by status or error code, already-exists incl. the
  Azurite 400 shape); the two IsAlreadyExistsStatus copies use it.
- Event writer: per-row fallback only for data-shaped rejections; throttling,
  outages and oversize batches propagate. Single and batched writer share one
  entity builder.
- IngestTelemetryFunction: payload too large -> 413, transient -> 503 with
  Retry-After: 5, anything else 500.
- TableStorageChunking.MaxPropertyChars is the one 30,000-char bound.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 22:03:07 +02:00
Oliver Kieselbach bd66480ccc chore: bump internal gitlink (remove-decision-inspector RELEASED)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 05:05:36 +02:00
Oliver Kieselbach b05f1f6bcf chore: bump internal gitlink (remove-v2-index-tables RELEASED)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 04:51:52 +02:00
Oliver Kieselbach 12ad9c9436 Remove the Decision Inspector: web subpage, three session read endpoints, renderer deps (D-197)
Web: app/sessions/inspector, Inspector button, inspectorUrl, legacy /sessions/{id}/inspector
redirect, SWA rewrites, api.inspector; drops @xyflow/react, dagre, @types/dagre.
Backend/Shared: GetSessionSignals/DecisionGraph/ReducerVerification functions, DecisionGraphBuilder,
ReducerVerifier, their DTOs and tests, the QueryBySessionAsync readers and SignalQueryLimits;
three catalog entries fewer. Signals/DecisionTransitions tables and ingest unchanged; operator
analysis reads them through MCP. Wire manifests regenerated (web + MCP copy).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 04:51:28 +02:00
Oliver Kieselbach c8ce7cdb37 backend: remove the V2 index tables and their dual-write pipeline (D-196)
The five cross-session index tables (SessionsByTerminal, SessionsByStage,
DeadEndsByReason, ClassifierVerdictsByIdLevel, SignalsByKind) were write-only
since M5.d: no endpoint, MCP tool or web page ever read them, while the
dual-write cost a serial queue send per signal/transition on the ingest path,
a 5-13 min full scan of Signals + DecisionTransitions every two hours and five
property-filter scans per session deletion (audit 2026-09-05 F05).

Removed: the tables from TableNames.All (schema hash changes, next cold start
runs a full pass without them), the telemetry-index-reconcile queue name,
producer, envelope, handler, queue function and 2h timer, the cross-partition
Timestamp scans on the signal/transition repositories, the EnableIndexDualWrite
flag (model, config mapping, admin UI, generated wire types), cascade steps
11-15 (later steps renumbered 11-18), the deletion wrappers and the offboarding
wipe entries. DiscriminatorPkProp stays as a step class so manifests written
before this change still resume.

Order of operations: deploy first, then delete the queue pair and the five
tables in the portal (B-88h). Deleting the tables before the deploy 500s every
delete preview/enqueue and poisons offboarding.

Submodules: .claude/commands (import_session.py), internal (D-196, docs, plan).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 04:27:48 +02:00
Oliver Kieselbach 56d4dd8b84 chore: bump internal gitlink (queue-trigger plan RELEASED, live verify)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 03:16:26 +02:00
Oliver Kieselbach 86fdc5aca9 backend: stateless queue consumers become [QueueTrigger] functions; webhooks go through a queue; poll loop receives one message at a time
Audit 2026-09-05 F01/F02. Analyze, VulnerabilityCorrelate, TenantAutoApprove,
IndexReconcile and ImeMsiArchive are now host-managed queue functions under
Functions/Queue bound to the DataStorage connection (identity-based, resolved
by the host): the Flex scale controller wakes an instance for a message, the
host renews the lease and owns the retry/poison ladder. The four cascade
workers with lease/CAS state stay self-polling BackgroundServices; their base
now receives one message per poll so waiting messages can no longer expire
under another worker. Terminal enrollment alerts and hardware-rejection alerts
are enqueued on notification-dispatch (channel ids only, resolved at send
time) instead of fire-and-forget sends the host could drop on scale-in.
Requires the app setting DataStorage__queueServiceUri before deploy.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 02:52:37 +02:00
Oliver Kieselbach 87c5bc59dc chore: bump internal gitlink (error envelope RELEASED)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 01:57:06 +02:00
Oliver Kieselbach 21b30b21c2 chore: bump internal gitlink (lessons rule block)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 01:44:39 +02:00
Oliver Kieselbach f94f1c0c4e chore: bump internal gitlink (lesson: no Front Door for the API)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 01:44:02 +02:00
Oliver Kieselbach a6a9883451 chore: bump internal gitlink (error envelope + correlation docs, D-192/D-193)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 01:37:57 +02:00
Oliver Kieselbach 03116a97d1 mcp: one correlation id per tool call — sent to the backend, logged, shown in every error
withToolTelemetry mints a UUID per tool call and runs the handler in a
ToolCallContext (tool name + correlation id); apiFetch stamps it as
X-Correlation-ID next to X-MCP-Tool-Name, so every backend request of the call
(pagination scans included) and the MCP_TOOL_LOGGING tool_call line carry the
same id — a row-level join between the MCP log and the backend's request rows.
ApiError reads the X-Correlation-ID response header (body correlationId as
fallback), and the error handler names it in every branch — 5xx, quota 429,
structured 4xx and the unstructured 401/403/404/429 texts that had none. The
handler reads the envelope's `code` (errorCode as the pre-envelope fallback),
the quota body's `error`, and the log proxy's `upstreamCode`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 01:33:44 +02:00
Oliver Kieselbach 2abc78ab6d web: send X-Correlation-ID on every API call, read the error envelope, show the reference
authenticatedFetch mints one UUID per logical call (kept across the 401 retry,
where caller headers now survive too), sends it as X-Correlation-ID — the id
the backend echoes, stamps on its request row and writes into every error body
— and tracks api_request_failed {path, method, status, correlationId} for any
final status >= 400. App Insights gets enableCorsCorrelation + W3C
distributedTracingMode scoped to the API host, so portal dependency rows and
backend request rows share an operation_Id.

fetchJson/ApiError read the envelope (error, code, correlationId, hint; the
pre-envelope `message` as fallback), describeApiError renders message +
short reference, addNotification takes an optional reference the bell renders
as "Ref …"; the error boundaries show and track Next's digest. Consumers of
renamed fields follow: delete-session parser (code ?? hint, PascalCase codes),
app-homing (code ?? reason). API_ERROR_CODES comes from the manifest, and
HOME_TENANT_UNRESOLVED plus the cascade codes are `satisfies ApiErrorCode`.
InstallsTab is the first site showing the reference.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 01:29:54 +02:00
Oliver Kieselbach 6e54b52376 backend: migrate the 458 anonymous error bodies to the typed envelope helpers
Every non-2xx body in the Functions project now goes through ResponseHelper
(ErrorAsync / BadRequestAsync / NotFoundAsync / ForbiddenAsync /
UnauthorizedAsync / ConflictAsync / InternalServerErrorAsync): 408 sites by a
pattern-exact rewrite of the CreateResponse + WriteAsJsonAsync + return shape,
50 by hand. The eight private BadRequestAsync shadow helpers are gone; the raw
500 catch blocks use InternalServerErrorAsync (sanitized message, correlation
id, MCP hint). 429s keep Retry-After via retryAfterSeconds.

Specialised error bodies where a consumer reads more than the prefix:
AppHomingDeniedResponse (kebab reason codes now Constants.AppHomingReasonCodes,
probe result), TenantConfigPatchFailedResponse (backupId, drift),
QueryBackendLogsErrorResponse (upstreamCode, statusCode, source, hint,
upstream). Twenty-one message-first 200 bodies that the old error tolerance had
let through are typed too (MessageResponse, PreviewWhitelistActionResponse,
SuccessMessageResponse). New codes: PayloadTooLarge, UpstreamError,
UpstreamTimeout, the three trial-gate codes; the agent security path
(SecurityValidationExtensions) writes the envelope with the retry window.

TypedResponseGuardTests: WriteBaseline is empty again — the anonymous
WriteAsJsonAsync ratchet now covers error bodies with zero tolerated sites.
Manifest and generated TypeScript regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 01:21:01 +02:00
Oliver Kieselbach 7cef2ea361 backend: one typed error envelope (IApiErrorResponse) on every non-2xx body
Every error body now leads with { error, code, correlationId }: the generic
ApiErrorResponse (hint?, retryAfterSeconds?, operation?) plus the specialised
McpQuotaExceededResponse (reordered; `message` became `error`),
DelegatedSlotLimitReachedResponse (+correlationId) and the new
SessionDeletionRejectedResponse (replaces the anonymous delete arms). The
correlation id is stamped by the writers — ResponseHelper.ErrorAsync and the
new ApiErrorWriter for the middleware side (auth 401, policy 403/503, rate
limit 429, MCP quota 429, global exception 500) — never by call sites.
exceptionType and rateLimitInfo leave the wire; Constants.ApiErrorCodes is the
code vocabulary and is exported as the manifest section `apiErrorCodes`
(API_ERROR_CODES for web + MCP). CorrelationIdMiddleware names the readable
headers via Access-Control-Expose-Headers.

Guard: TypedResponseGuardTests no longer tolerates anonymous error shapes;
the 458 legacy sites in 149 files are frozen in WriteBaseline to melt down.
New facts: envelope-prefix reflection, ApiErrorWriter body/header pins,
exact-shape pins for the generic envelope and the changed specialised bodies.

Reverses the "error bodies stay anonymous" clause of D-043 (decision entry
follows with the docs stage).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 00:56:21 +02:00
Oliver Kieselbach 5b5ee0e8fd chore: bump internal gitlink (release verify)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-04 21:43:17 +02:00
Oliver Kieselbach 7bcc4f00b1 chore: bump internal gitlink (release verify 2026-09-04)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-04 21:42:33 +02:00
Oliver Kieselbach 34ec44e3d4 backend: duration evaluators refuse mixed timestamp provenance only
The first cut refused every reader-zone-fallback endpoint. The DeviceSetup line is
written before the agent starts and is backlog on every device, so that silenced
ANALYZE-ESP-001 for all agents without an era anchor (control sessions 2708e6b4 and
18d80f9c came back "not measurable" after the deploy). Two fallback endpoints share the
writer-zone error and cancel it; only a span mixing a fallback endpoint with an anchored
one (or with "now" for an open phase) is unmeasurable — the a7140f98 shape.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-04 21:34:15 +02:00
829 changed files with 37035 additions and 21546 deletions
+4
View File
@@ -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'
}
+263 -67
View File
@@ -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
+8 -11
View File
@@ -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 {
+70
View File
@@ -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."
+1 -1
View File
@@ -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
+177 -24
View File
@@ -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
View File
@@ -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
View File
@@ -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'
+4 -4
View File
@@ -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 }}
+6 -3
View File
@@ -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: |
+6 -6
View File
@@ -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
+6 -6
View File
@@ -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
+40 -9
View File
@@ -35,12 +35,38 @@ 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
- uses: actions/setup-node@v7
# Only the version manifest at the very end needs Azure; logging in here rather than
# next to that step keeps a credential problem from surfacing after a live deploy.
- name: Login to Azure (OIDC)
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
# The customer docs repo is the single source of the "What's new" panel: the prebuild
# step (scripts/whats-new/build-whats-new.js) turns changelog/*.md into
# public/whats-new.json and dates every bullet via git blame — hence the full history.
# Public repo, no token. Editing the docs does NOT update the live panel until this
# workflow runs again (push under src/Web/** or a manual dispatch); versions/web.json
# records which docs commit is live.
- name: Check out documentation bundle
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
repository: autopilotmonitor/autopilotmonitor-docs
path: whats-new-docs
fetch-depth: 0
- name: Resolve docs commit
id: docs
run: echo "sha=$(git -C whats-new-docs rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
with:
node-version: '22'
cache: npm
@@ -51,7 +77,7 @@ jobs:
run: npm ci
# next.config output:'export' -- `next build` writes the static site to out/
# (prebuild: sync-error-codes, generate-lastmod, generate-version).
# (prebuild: sync-error-codes, generate-lastmod, generate-version, whats-new).
- name: Build
working-directory: ${{ env.WEB_DIR }}
env:
@@ -68,9 +94,12 @@ jobs:
# Build stamp for public/version.json (scripts/generate-version.js in prebuild);
# the verify step below polls the deployed file for exactly this commit.
GITHUB_SHA: ${{ github.sha }}
# Docs checkout for public/whats-new.json; the prebuild fails in CI without it.
WHATS_NEW_DOCS_DIR: ${{ github.workspace }}/whats-new-docs
run: |
npm run build
test -f out/version.json || { echo "out/version.json missing - export did not run"; exit 1; }
test -f out/whats-new.json || { echo "out/whats-new.json missing - whats-new prebuild did not run"; exit 1; }
# One archive of the exact bytes that get uploaded, so the attestation has a single subject.
- name: Package export
@@ -85,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 }}
@@ -136,7 +165,8 @@ jobs:
throw "Portal did not serve commit $expectedCommit within 5 minutes -- deployment not verified, version manifest NOT published"
# Cross-component deploy record, written last and only on a verified deploy --
# same contract as versions/backend.json and versions/mcp.json.
# same contract as versions/backend.json and versions/mcp.json. docsCommit says which
# docs revision the live What's new panel was generated from (as for the MCP corpus).
- name: Publish version manifest
shell: pwsh
run: |
@@ -145,11 +175,12 @@ jobs:
commit = '${{ github.sha }}'.Substring(0, 7)
deployedUtc = [DateTime]::UtcNow.ToString('o')
runId = '${{ github.run_id }}'
docsCommit = '${{ steps.docs.outputs.sha }}'.Substring(0, 7)
} | ConvertTo-Json
$sas = '${{ secrets.AZURE_BLOB_VERSIONS_SAS_TOKEN }}'.TrimStart('?')
$url = "${{ env.VERSIONS_CONTAINER }}/web.json?$sas"
$authHeaders = & ./.github/scripts/Get-StorageAuthHeaders.ps1
$url = "${{ env.VERSIONS_CONTAINER }}/web.json"
# no-cache: rotating pointer, must never be served stale by any fronting cache.
Invoke-RestMethod -Uri $url -Method Put -Headers @{ 'x-ms-blob-type' = 'BlockBlob'; 'x-ms-blob-cache-control' = 'no-cache' } -Body $manifest -ContentType 'application/json' | Out-Null
Invoke-RestMethod -Uri $url -Method Put -Headers ($authHeaders + @{ 'x-ms-blob-type' = 'BlockBlob'; 'x-ms-blob-cache-control' = 'no-cache' }) -Body $manifest -ContentType 'application/json' | Out-Null
Write-Host "Published versions/web.json"
Write-Host $manifest
+81 -3
View File
@@ -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
+4
View File
@@ -145,6 +145,10 @@ internal/docs/~$Introduction-AutopilotMonitor.pptx
# changes each run) and served at /version.json from the static export.
src/Web/autopilot-monitor-web/public/version.json
# What's new payload: generated by scripts/whats-new/build-whats-new.js from the docs
# checkout on every build and served at /whats-new.json from the static export.
src/Web/autopilot-monitor-web/public/whats-new.json
# Local IME installer scratch (MSI + extracted payload per version, for grepping
# in binaries). Operator-only, never committed.
+50 -14
View File
@@ -1,33 +1,63 @@
# <img src=".github/assets/logo.svg" height="28" alt="" /> Autopilot Monitor
# <img src=".github/assets/logo.svg" height="28" alt="Autopilot Monitor logo" /> Autopilot Monitor
[![Status](https://img.shields.io/badge/status-live-brightgreen)](https://www.autopilotmonitor.com)
[![License](https://img.shields.io/badge/license-MIT%20%2B%20AGPL--3.0-blue)](LICENSE)
[![Website](https://img.shields.io/badge/website-autopilotmonitor.com-2ea44f)](https://www.autopilotmonitor.com)
Advanced monitoring and troubleshooting solution for Windows Autopilot deployments. Gain full visibility into every enrollment session with a detailed event timeline, fleet health dashboards, and session reporting. Define custom analysis rules to automatically detect issues and gather rules to collect targeted evidence. Retrieve diagnostics packages on demand, configure agent settings like auto-reboot behavior and automatic timezone adjustment — all managed centrally from the web dashboard.
Autopilot Monitor is an open-source, real-time monitoring and troubleshooting platform for **Windows Autopilot** and **Microsoft Intune** enrollment. It records enrollment events, application installations, policies, device state, and diagnostics while provisioning is still running, instead of collecting logs by hand after a failure. Administrators get live enrollment tracking, Enrollment Status Page (ESP) visibility, detailed session timelines, automated issue detection, on-demand diagnostics, fleet health analytics, and AI-assisted troubleshooting through a hosted Model Context Protocol (MCP) server.
The platform supports classic Windows Autopilot and modern Intune provisioning scenarios, including **Windows Autopilot Device Preparation**.
## Availability
Autopilot Monitor is **publicly available** — the Community plan is free. Sign in with your work account at **[autopilotmonitor.com](https://www.autopilotmonitor.com)**; new organizations complete a short activation step after first sign-in.
<p align="center">
<img src=".github/assets/SessionList.png" width="45%" />
<img src=".github/assets/FleetHealth.png" width="45%" />
<img src=".github/assets/SessionList.png" width="45%" alt="Autopilot Monitor dashboard showing live Windows Autopilot and Intune enrollment sessions" />
<img src=".github/assets/FleetHealth.png" width="45%" alt="Autopilot Monitor fleet health dashboard with Windows Autopilot enrollment analytics and success metrics" />
</p>
<p align="center">
<img src=".github/assets/SessionDetails.png" width="45%" />
<img src=".github/assets/SessionTimeline.png" width="45%" />
<img src=".github/assets/SessionDetails.png" width="45%" alt="Autopilot Monitor session details showing device information, diagnostics, apps, policies, and enrollment status" />
<img src=".github/assets/SessionTimeline.png" width="45%" alt="Windows Autopilot enrollment timeline showing ESP phases, application installs, policies, events, and errors" />
</p>
## Overview
## Key Features
Autopilot Monitor provides real-time tracking, intelligent diagnostics, and automated troubleshooting for Windows Autopilot enrollment processes. It consists of:
- **Real-time Windows Autopilot monitoring** — follow device provisioning while enrollment is still running
- **Detailed enrollment timelines** — correlate Autopilot, ESP, Intune Management Extension, apps, policies, device state, and system events
- **Enrollment Status Page visibility** — see which phase, application, or policy is delaying provisioning
- **Automated issue detection** — define custom analysis rules that identify known failure patterns
- **Targeted evidence collection** — gather registry values, event log entries, files, log-parser matches, and allow-listed commands when specific conditions are detected
- **On-demand diagnostics** — request diagnostics packages from enrolled devices remotely
- **Fleet health analytics** — success rates, deployment duration, device models, applications, errors, and recurring issues
- **Session reporting** — inspect and share detailed enrollment information for individual devices
- **Windows Autopilot Device Preparation support** — monitor Device Preparation deployments alongside classic Autopilot scenarios
- **Centralized agent configuration** — control diagnostic behavior, automatic reboots, timezone adjustment, and other monitoring settings from the web dashboard
- **AI-assisted troubleshooting** — query enrollment data through the built-in Model Context Protocol server
- **Bootstrap Script** — PowerShell script deployed via Intune that starts monitoring early in the enrollment process
- **Monitoring Agent** — Lightweight .NET application that collects telemetry and evidence during enrollment
## How it works
Autopilot Monitor consists of several components working together throughout Windows enrollment:
- **Bootstrap Script** — PowerShell script deployed through Microsoft Intune that starts monitoring early in the provisioning process
- **Monitoring Agent** — lightweight .NET application that collects telemetry and evidence during enrollment
- **Backend API** — Azure Functions-based ingestion and processing pipeline
- **Web Dashboard** — Next.js application for real-time monitoring and fleet analytics
- **MCP Server** — Model Context Protocol server that lets AI assistants query and troubleshoot enrollments in natural language
- **Web Dashboard** — Next.js application for real-time monitoring, troubleshooting, and fleet analytics
- **MCP Server** — Model Context Protocol server that lets AI assistants query Autopilot Monitor data in natural language
## Windows Autopilot and Intune Troubleshooting
Autopilot Monitor helps investigate common Windows provisioning and enrollment problems such as:
- Windows Autopilot deployments that fail or appear stuck
- Enrollment Status Page (ESP) delays and unusually long deployment phases
- Win32 application installation failures and slow application downloads
- Intune Management Extension problems
- Microsoft Entra join, Hybrid Join, and device registration issues
- policies that block or delay provisioning
- inconsistent behavior across hardware models and recurring failures affecting multiple devices
Because telemetry is collected during enrollment, many problems can be investigated without reproducing the issue or manually collecting logs from the affected device.
## AI Integration (MCP)
@@ -35,13 +65,19 @@ Autopilot Monitor ships a hosted **[Model Context Protocol](https://modelcontext
- *"Show me all failed enrollments from the last 24 hours and group them by failure reason."*
- *"Why did session X fail, and which app install caused the delay?"*
- *"Which devices had unusually long ESP application phases this week?"*
- *"Which device models have the highest Autopilot failure rate?"*
- *"Which devices in my fleet are affected by CVE-2024-30078?"*
Server URL: `https://mcp.autopilotmonitor.com/mcp` — sign-in runs through your existing work account, access is scoped to your tenant exactly like in the portal, and no credentials are stored. Setup guide: **[AI Integration (MCP)](https://docs.autopilotmonitor.com/integrations/ai-integration-mcp)**.
Server URL: `https://mcp.autopilotmonitor.com/mcp` — sign-in runs through your existing work account, access is scoped to your tenant exactly like in the portal, and the MCP server stores no credentials. Setup guide: **[AI Integration (MCP)](https://docs.autopilotmonitor.com/integrations/ai-integration-mcp)**.
## Documentation
Full admin documentation is available at **[docs.autopilotmonitor.com](https://docs.autopilotmonitor.com)**
Full admin documentation is available at **[docs.autopilotmonitor.com](https://docs.autopilotmonitor.com)** — deployment, configuration, monitoring, diagnostics, troubleshooting, analysis and gather rules, integrations, and AI-assisted troubleshooting.
## Open Source
Autopilot Monitor is developed openly on GitHub. The source is published so that customers and security reviewers can see what runs on their devices and with their data: the repository contains the device agent, shared library, backend, web dashboard, and MCP server.
## Feedback
+1 -1
Submodule infra updated: 2c2687b6ab...55a8eaf929
+2 -2
View File
@@ -5,7 +5,7 @@
"description": "Detects when the Enrollment Status Page failed on the Apps subcategory and the agent's AppX deployment log scan identified a suspected MSIX/Store package. Store/MSIX apps install outside the Win32 pipeline, so the regular per-app tracking sees nothing — this correlation names the likely culprit.",
"severity": "warning",
"category": "apps",
"version": "1.2.0",
"version": "1.2.1",
"enabled": true,
"evaluateOn": [
"enrollment_end",
@@ -93,7 +93,7 @@
"steps": [
"Open Event Viewer → Applications and Services Logs → Microsoft → Windows → AppXDeploymentServer → Operational on the device (or in the diagnostics archive if uploaded)",
"Filter for Error-level events around the ESP failure time and confirm the package name and HRESULT match this finding",
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = invalid/corrupt package, 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = package could not be opened (unsigned, publisher mismatch, or not found), 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
]
},
{
+98
View File
@@ -0,0 +1,98 @@
{
"$schema": "../schema/analyze-rule.schema.json",
"ruleId": "ANALYZE-APP-018",
"title": "App Return Code Requested a Reboot During Enrollment",
"description": "Detects Win32 apps whose installer exit code maps to Soft reboot or Hard reboot in the app's Intune return-code table (the '[Win32App] lpExitCode is defined as ...' line). Hard reboot stops app processing and restarts the device in Device Setup - the mid-enrollment restart and second sign-in; Soft reboot leaves the app pending until the next restart while the ESP moves on. Confidence rises for Hard reboot and when a reboot was actually observed in the session.",
"severity": "warning",
"category": "apps",
"version": "1.0.0",
"author": "Autopilot Monitor",
"enabled": true,
"evaluateOn": [
"enrollment_end",
"whiteglove_sealed"
],
"trigger": "single",
"baseConfidence": 60,
"conditions": [
{
"signal": "reboot_return_code",
"source": "event_data",
"eventType": "app_install_completed",
"dataField": "exitCodeClass",
"operator": "in",
"value": "SoftReboot,HardReboot",
"required": true
},
{
"signal": "hard_reboot_return_code",
"source": "event_data",
"eventType": "app_install_completed",
"dataField": "exitCodeClass",
"operator": "equals",
"value": "HardReboot",
"required": false
},
{
"signal": "reboot_observed",
"source": "event_count",
"eventType": "system_reboot_detected",
"operator": "count_gte",
"value": "1",
"required": false
}
],
"confidenceFactors": [
{
"signal": "hard_reboot_return_code",
"condition": "exists",
"weight": 25
},
{
"signal": "reboot_observed",
"condition": "exists",
"weight": 15
}
],
"confidenceThreshold": 60,
"explanation": "App **{{appName}}** returned exit code **{{exitCode}}**, which its Intune return-code table maps to **{{exitCodeClass}}** - the installer asked for a restart before its work is complete.\n\n- **SoftReboot**: the Intune Management Extension reports the app as *pending reboot*. The Enrollment Status Page treats it as completed and moves on, and Intune only marks the app installed after the next restart re-evaluates the detection rule. Until then the app may be unusable or half-configured, and the user sees a restart notification.\n- **HardReboot**: the Intune Management Extension stops processing further apps and, in Device Setup, restarts the device right away (the restart grace period does not apply during the ESP) - the same mid-enrollment restart and second sign-in that ANALYZE-ESP-005 attributes to reboot-required policies. In Account Setup the extension does not restart the device itself and the app stays pending.\n\nA restart requested by an installer is normal for many MSI packages (exit codes 3010 and 1641), but during Autopilot it lengthens the ESP, can surprise the user with a restart, and hides the app's real state until after the reboot. The return-code class is the app's own configuration in Intune, not a device fault.",
"remediation": [
{
"title": "Check the app's return-code mapping",
"steps": [
"Open the app in the Intune admin center > Properties > Program and review the return codes table: exit code {{exitCode}} is currently mapped to {{exitCodeClass}}",
"If the installer only recommends a restart (MSI 3010 ERROR_SUCCESS_REBOOT_REQUIRED, 1641 ERROR_SUCCESS_REBOOT_INITIATED), map the code to Soft reboot instead of Hard reboot so the next app can install before the restart",
"If the app works without an immediate restart, suppress the installer's own reboot (for MSI: REBOOT=ReallySuppress on the install command) so it returns 0 and the restart happens on your schedule",
"Keep Hard reboot only when the following apps genuinely cannot install before the restart - and then expect the mid-ESP restart in every enrollment"
]
},
{
"title": "Take the app out of the ESP critical path",
"steps": [
"If the app is not needed for first use, remove it from the ESP blocking-app list so the restart happens after the user reaches the desktop",
"If it must stay blocking, order it last in Device Setup (dependencies or install order) so a hard reboot does not interrupt the remaining apps",
"For Soft reboot apps, plan a restart at the end of enrollment or accept that the app finishes on the user's first restart"
]
}
],
"relatedDocs": [
{
"title": "Microsoft Learn: Add a Win32 app - Program step (device restart behavior and return codes)",
"url": "https://learn.microsoft.com/en-us/intune/app-management/deployment/add-win32#step-2-program"
},
{
"title": "Microsoft Learn: Enrollment Status Page tracking",
"url": "https://learn.microsoft.com/en-us/autopilot/enrollment-status"
}
],
"markSessionAsFailedDefault": false,
"tags": [
"apps",
"reboot",
"return-code",
"soft-reboot",
"hard-reboot",
"esp",
"second-sign-in"
]
}
+99 -2
View File
@@ -615,7 +615,7 @@
"description": "Detects when the Enrollment Status Page failed on the Apps subcategory and the agent's AppX deployment log scan identified a suspected MSIX/Store package. Store/MSIX apps install outside the Win32 pipeline, so the regular per-app tracking sees nothing — this correlation names the likely culprit.",
"severity": "warning",
"category": "apps",
"version": "1.2.0",
"version": "1.2.1",
"enabled": true,
"evaluateOn": [
"enrollment_end",
@@ -703,7 +703,7 @@
"steps": [
"Open Event Viewer → Applications and Services Logs → Microsoft → Windows → AppXDeploymentServer → Operational on the device (or in the diagnostics archive if uploaded)",
"Filter for Error-level events around the ESP failure time and confirm the package name and HRESULT match this finding",
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = invalid/corrupt package, 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
"Look up the HRESULT: 0x80073cf9 = generic install failure, 0x80073cf0 = package could not be opened (unsigned, publisher mismatch, or not found), 0x80073cff = sideloading/licensing policy block, 0x80073d02 = blocked because app is in use"
]
},
{
@@ -1034,6 +1034,103 @@
"esp"
]
},
{
"ruleId": "ANALYZE-APP-018",
"title": "App Return Code Requested a Reboot During Enrollment",
"description": "Detects Win32 apps whose installer exit code maps to Soft reboot or Hard reboot in the app's Intune return-code table (the '[Win32App] lpExitCode is defined as ...' line). Hard reboot stops app processing and restarts the device in Device Setup - the mid-enrollment restart and second sign-in; Soft reboot leaves the app pending until the next restart while the ESP moves on. Confidence rises for Hard reboot and when a reboot was actually observed in the session.",
"severity": "warning",
"category": "apps",
"version": "1.0.0",
"author": "Autopilot Monitor",
"enabled": true,
"evaluateOn": [
"enrollment_end",
"whiteglove_sealed"
],
"trigger": "single",
"baseConfidence": 60,
"conditions": [
{
"signal": "reboot_return_code",
"source": "event_data",
"eventType": "app_install_completed",
"dataField": "exitCodeClass",
"operator": "in",
"value": "SoftReboot,HardReboot",
"required": true
},
{
"signal": "hard_reboot_return_code",
"source": "event_data",
"eventType": "app_install_completed",
"dataField": "exitCodeClass",
"operator": "equals",
"value": "HardReboot",
"required": false
},
{
"signal": "reboot_observed",
"source": "event_count",
"eventType": "system_reboot_detected",
"operator": "count_gte",
"value": "1",
"required": false
}
],
"confidenceFactors": [
{
"signal": "hard_reboot_return_code",
"condition": "exists",
"weight": 25
},
{
"signal": "reboot_observed",
"condition": "exists",
"weight": 15
}
],
"confidenceThreshold": 60,
"explanation": "App **{{appName}}** returned exit code **{{exitCode}}**, which its Intune return-code table maps to **{{exitCodeClass}}** - the installer asked for a restart before its work is complete.\n\n- **SoftReboot**: the Intune Management Extension reports the app as *pending reboot*. The Enrollment Status Page treats it as completed and moves on, and Intune only marks the app installed after the next restart re-evaluates the detection rule. Until then the app may be unusable or half-configured, and the user sees a restart notification.\n- **HardReboot**: the Intune Management Extension stops processing further apps and, in Device Setup, restarts the device right away (the restart grace period does not apply during the ESP) - the same mid-enrollment restart and second sign-in that ANALYZE-ESP-005 attributes to reboot-required policies. In Account Setup the extension does not restart the device itself and the app stays pending.\n\nA restart requested by an installer is normal for many MSI packages (exit codes 3010 and 1641), but during Autopilot it lengthens the ESP, can surprise the user with a restart, and hides the app's real state until after the reboot. The return-code class is the app's own configuration in Intune, not a device fault.",
"remediation": [
{
"title": "Check the app's return-code mapping",
"steps": [
"Open the app in the Intune admin center > Properties > Program and review the return codes table: exit code {{exitCode}} is currently mapped to {{exitCodeClass}}",
"If the installer only recommends a restart (MSI 3010 ERROR_SUCCESS_REBOOT_REQUIRED, 1641 ERROR_SUCCESS_REBOOT_INITIATED), map the code to Soft reboot instead of Hard reboot so the next app can install before the restart",
"If the app works without an immediate restart, suppress the installer's own reboot (for MSI: REBOOT=ReallySuppress on the install command) so it returns 0 and the restart happens on your schedule",
"Keep Hard reboot only when the following apps genuinely cannot install before the restart - and then expect the mid-ESP restart in every enrollment"
]
},
{
"title": "Take the app out of the ESP critical path",
"steps": [
"If the app is not needed for first use, remove it from the ESP blocking-app list so the restart happens after the user reaches the desktop",
"If it must stay blocking, order it last in Device Setup (dependencies or install order) so a hard reboot does not interrupt the remaining apps",
"For Soft reboot apps, plan a restart at the end of enrollment or accept that the app finishes on the user's first restart"
]
}
],
"relatedDocs": [
{
"title": "Microsoft Learn: Add a Win32 app - Program step (device restart behavior and return codes)",
"url": "https://learn.microsoft.com/en-us/intune/app-management/deployment/add-win32#step-2-program"
},
{
"title": "Microsoft Learn: Enrollment Status Page tracking",
"url": "https://learn.microsoft.com/en-us/autopilot/enrollment-status"
}
],
"markSessionAsFailedDefault": false,
"tags": [
"apps",
"reboot",
"return-code",
"soft-reboot",
"hard-reboot",
"esp",
"second-sign-in"
]
},
{
"ruleId": "ANALYZE-CORR-003",
"title": "Proxy Configuration Causing Download Failure",
+11
View File
@@ -339,6 +339,17 @@
"description": "Captures the installer exit code (lpExitCode) for the current app.",
"enabled": true
},
{
"patternId": "IME-EXITCODE-CLASS",
"category": "currentPhase",
"pattern": "^\\[Win32App\\] lpExitCode is defined as (?<exitCodeClass>Success|SoftReboot|HardReboot|Retry|Failed)$",
"action": "captureExitCodeClass",
"parameters": {
"useCurrentApp": "true"
},
"description": "Captures the admin-defined return-code class of the installer exit code for the current app ('[Win32App] lpExitCode is defined as <Failed|Success|SoftReboot|HardReboot|Retry>', Win32AppInstaller.cs, enum AppReturnCodeType - literal identical from IME 1.50 through 1.105). Stored as exitCodeClass on the app and emitted on its terminal events; the last value wins, so a Retry loop that ends in Success reports Success. Anchored on both ends on purpose: the no-mapping warning ('... defined as <n>, fall into default now.') and an unparsable numeric type print a raw number and must not match. Companion of IME-EXITCODE (the number, logged just before) and IME-EXITCODE-MAPPED-FAILED (the Failed state transition), which still owns the error path.",
"enabled": true
},
{
"patternId": "IME-EXITCODE-MAPPED-FAILED",
"category": "currentPhase",
+25 -1
View File
@@ -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",
@@ -282,5 +286,25 @@
"log_entry",
"agent_trace",
"stall_probe_check"
],
"imeLogDerivedEventTypes": [
"app_install_started",
"app_install_completed",
"app_install_failed",
"app_install_skipped",
"app_download_started",
"app_tracking_summary",
"download_progress",
"do_telemetry",
"script_started",
"script_completed",
"script_failed",
"script_timeout_suspected",
"esp_phase_changed",
"ime_agent_version",
"ime_token_failure",
"ime_user_session_completed",
"ime_process_exited",
"ime_user_token_acquired"
]
}
@@ -0,0 +1,10 @@
{
"$schema": "../schema/ime-log-pattern.schema.json",
"patternId": "IME-EXITCODE-CLASS",
"category": "currentPhase",
"pattern": "^\\[Win32App\\] lpExitCode is defined as (?<exitCodeClass>Success|SoftReboot|HardReboot|Retry|Failed)$",
"action": "captureExitCodeClass",
"parameters": { "useCurrentApp": "true" },
"description": "Captures the admin-defined return-code class of the installer exit code for the current app ('[Win32App] lpExitCode is defined as <Failed|Success|SoftReboot|HardReboot|Retry>', Win32AppInstaller.cs, enum AppReturnCodeType - literal identical from IME 1.50 through 1.105). Stored as exitCodeClass on the app and emitted on its terminal events; the last value wins, so a Retry loop that ends in Success reports Success. Anchored on both ends on purpose: the no-mapping warning ('... defined as <n>, fall into default now.') and an unparsable numeric type print a raw number and must not match. Companion of IME-EXITCODE (the number, logged just before) and IME-EXITCODE-MAPPED-FAILED (the Failed state transition), which still owns the error path.",
"enabled": true
}
+1 -1
View File
@@ -168,7 +168,7 @@
},
"source": {
"type": "string",
"description": "Source of the signal. phase_duration and app_install_duration never derive a duration from an IME-log timestamp whose sourceOffsetOrigin is reader-zone-fallback (writer timezone unknown to the agent): such a condition evaluates false with evidence timestampProvenance=reader-zone-fallback.",
"description": "Source of the signal. phase_duration and app_install_duration never derive a duration from a span with mixed timestamp provenance (exactly one IME-log endpoint with sourceOffsetOrigin=reader-zone-fallback, i.e. the writer timezone was unknown to the agent for one endpoint only): such a condition evaluates false with evidence timestampProvenance=reader-zone-fallback. Two fallback endpoints share the same error and stay measurable.",
"enum": ["event_type", "event_data", "event_data_array", "phase_duration", "event_count", "app_install_duration", "event_correlation", "clock_skew"]
},
"skewMetric": {
+5
View File
@@ -114,6 +114,11 @@
"description": "Emit behavior: \"always\" (default — emit on every collection) or \"on_change\" (poll on the trigger cadence but emit only when the collected result changes; the first in-scope result always emits).",
"enum": ["always", "on_change"]
},
"enrichErrorCodes": {
"type": "boolean",
"description": "Opt-in: let the backend explain error-code fields in this rule's output (exitCode, errorCode, hresult, ...) with the Windows/MSI/Intune error-code catalog, attaching the same *Info siblings built-in events get. Default false because gather-rule codes usually come from third-party logs or commands (HP Image Assistant, Dell Command Update, custom scripts) with their own exit-code numbering, where the catalog meaning would be wrong. Enable only when the parsed source really uses Windows codes (e.g. an msiexec or IME log).",
"default": false
},
"outputEventType": {
"type": "string",
"description": "EventType for the emitted event (e.g., \"gather_proxy_settings\")."
+11
View File
@@ -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" },
@@ -16,6 +26,7 @@
"blockedFilePrefixes": { "$ref": "#/$defs/stringList" },
"blockedCommandPatterns": { "$ref": "#/$defs/stringList" },
"blockedInterimTriggerEventTypes": { "$ref": "#/$defs/stringList" },
"imeLogDerivedEventTypes": { "$ref": "#/$defs/stringList" },
"maxCommandLength": { "type": "integer", "minimum": 1, "maximum": 100000 }
},
"required": [
+2 -1
View File
@@ -79,7 +79,8 @@
"captureAppTypeWinGet",
"captureAppTypeMsi",
"captureAttemptNumber",
"captureDetectionResult"
"captureDetectionResult",
"captureExitCodeClass"
]
},
"parameters": {
+9
View File
@@ -142,6 +142,7 @@ if (fs.existsSync(guardrailsPath)) {
assertStringList(guardrails[key], key);
}
assertStringList(guardrails.blockedInterimTriggerEventTypes ?? [], 'blockedInterimTriggerEventTypes');
assertStringList(guardrails.imeLogDerivedEventTypes ?? [], 'imeLogDerivedEventTypes');
if (!Number.isInteger(guardrails.maxCommandLength) || guardrails.maxCommandLength < 1) {
fail(`maxCommandLength: expected a positive integer, got ${JSON.stringify(guardrails.maxCommandLength)}`);
}
@@ -207,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}$'
}
}
+78 -3
View File
@@ -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
}
@@ -152,18 +152,6 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests
.Where(p => !p.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}")
&& !p.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}"));
private static string RepoRoot()
{
var dir = AppContext.BaseDirectory;
for (int i = 0; i < 12; i++)
{
if (File.Exists(Path.Combine(dir, "AutopilotMonitor.sln"))) return dir;
var parent = Directory.GetParent(dir)?.FullName;
if (parent == null || parent == dir) break;
dir = parent;
}
throw new DirectoryNotFoundException(
"Could not locate repo root (AutopilotMonitor.sln) from " + AppContext.BaseDirectory);
}
private static string RepoRoot() => Harness.RepoPaths.Root();
}
}
@@ -0,0 +1,27 @@
using System;
using System.IO;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Harness
{
/// <summary>Repository paths for tests that read or write checked-in files (guards, fixtures).</summary>
internal static class RepoPaths
{
/// <summary>Walks up from the test binary to the directory holding <c>AutopilotMonitor.sln</c>.</summary>
public static string Root()
{
var dir = AppContext.BaseDirectory;
for (int i = 0; i < 12; i++)
{
if (File.Exists(Path.Combine(dir, "AutopilotMonitor.sln"))) return dir;
var parent = Directory.GetParent(dir)?.FullName;
if (parent == null || parent == dir) break;
dir = parent;
}
throw new DirectoryNotFoundException(
"Could not locate repo root (AutopilotMonitor.sln) from " + AppContext.BaseDirectory);
}
/// <summary><c>tests/fixtures/&lt;name&gt;</c> under the repo root.</summary>
public static string Fixtures(string name) => Path.Combine(Root(), "tests", "fixtures", name);
}
}
@@ -13,6 +13,7 @@ using AutopilotMonitor.DecisionCore.Classifiers;
using AutopilotMonitor.DecisionCore.Engine;
using AutopilotMonitor.DecisionCore.Signals;
using AutopilotMonitor.DecisionCore.State;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Integration
{
@@ -5,6 +5,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
using AutopilotMonitor.DecisionCore.Classifiers;
using AutopilotMonitor.DecisionCore.State;
using Xunit;
using AutopilotMonitor.Shared.Models;
#pragma warning disable xUnit1031 // SpinWait.SpinUntil for uploader-batch-arrival assertion
@@ -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));
}
}
}
@@ -0,0 +1,111 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using AutopilotMonitor.Agent.V2.Core.Logging;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather;
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using AutopilotMonitor.Shared;
using AutopilotMonitor.Shared.Models;
using Xunit;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
{
/// <summary>
/// <see cref="GatherRule.EnrichErrorCodes"/> is an opt-in the backend honours at response time:
/// the agent stamps <c>enrichErrorCodes: true</c> into the event data of a rule that set it and
/// nothing at all otherwise (the default payload stays as it was).
/// </summary>
[Collection("SerialThreading")] // startup rules execute on the shared ThreadPool
public sealed class GatherRuleExecutorEnrichErrorCodesTests : IDisposable
{
private readonly TempDirectory _tmp = new TempDirectory();
private readonly List<EnrollmentEvent> _events = new List<EnrollmentEvent>();
private readonly object _eventsGate = new object();
private readonly GatherRuleExecutor _executor;
private const string AbsentPath =
"HKLM\\SOFTWARE\\AutopilotMonitorTests\\DefinitelyAbsent_7e3a1f4b-0000-0000-0000-000000000000";
public GatherRuleExecutorEnrichErrorCodesTests()
{
var logger = new AgentLogger(_tmp.Path, AgentLogLevel.Info);
_executor = new GatherRuleExecutor(
"sess", "tenant",
evt => { lock (_eventsGate) _events.Add(evt); },
logger)
{
UnrestrictedMode = true
};
}
public void Dispose()
{
_executor.Dispose();
_tmp.Dispose();
}
private EnrollmentEvent SingleEvent()
{
lock (_eventsGate) return Assert.Single(_events);
}
private bool WaitForEventCount(int count, int timeoutMs = 10000)
{
var sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < timeoutMs)
{
lock (_eventsGate) if (_events.Count >= count) return true;
Thread.Sleep(25);
}
lock (_eventsGate) return _events.Count >= count;
}
private static GatherRule StartupRule(bool enrichErrorCodes) => new GatherRule
{
RuleId = "GATHER-EEC-001",
Title = "enrich test",
CollectorType = "registry",
Target = AbsentPath,
Trigger = "startup",
OutputEventType = "gather_test",
Enabled = true,
EnrichErrorCodes = enrichErrorCodes,
};
[Fact]
public void StampRuleMarkers_AddsMarkerOnlyWhenOptedIn()
{
var optedIn = new Dictionary<string, object> { ["exitCode"] = "1603" };
GatherRuleExecutor.StampRuleMarkers(StartupRule(enrichErrorCodes: true), optedIn);
Assert.Equal(true, optedIn[Constants.GatherRuleDataKeys.EnrichErrorCodes]);
var defaultRule = new Dictionary<string, object> { ["exitCode"] = "1603" };
GatherRuleExecutor.StampRuleMarkers(StartupRule(enrichErrorCodes: false), defaultRule);
Assert.False(defaultRule.ContainsKey(Constants.GatherRuleDataKeys.EnrichErrorCodes));
Assert.Single(defaultRule);
}
[Fact]
public void ExecuteRule_StampsMarker_WhenRuleOptsIn()
{
_executor.UpdateRules(new List<GatherRule> { StartupRule(enrichErrorCodes: true) });
Assert.True(_executor.WaitForStartupRules(30));
Assert.True(WaitForEventCount(1));
var evt = SingleEvent();
Assert.Equal(GatherRuleExecutor.SourceName, evt.Source);
Assert.Equal(true, evt.Data[Constants.GatherRuleDataKeys.EnrichErrorCodes]);
}
[Fact]
public void ExecuteRule_LeavesPayloadUnchanged_ByDefault()
{
_executor.UpdateRules(new List<GatherRule> { StartupRule(enrichErrorCodes: false) });
Assert.True(_executor.WaitForStartupRules(30));
Assert.True(WaitForEventCount(1));
Assert.False(SingleEvent().Data.ContainsKey(Constants.GatherRuleDataKeys.EnrichErrorCodes));
}
}
}
@@ -311,6 +311,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
"[Win32App] Admin did NOT set mapping for lpExitCode: 1603 of app: " + Guid1,
new[] { "exitCode=1603", "id=" + Guid1 }
};
// Win32AppInstaller.cs "[Win32App] lpExitCode is defined as {0}", enum AppReturnCodeType
// (identical 1.50–1.105).
yield return new object[]
{
"IME-EXITCODE-CLASS",
"[Win32App] lpExitCode is defined as SoftReboot",
new[] { "exitCodeClass=SoftReboot" }
};
yield return new object[]
{
"IME-GRS-SKIP",
@@ -361,6 +369,31 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
}
}
[Theory]
[InlineData("Success")]
[InlineData("SoftReboot")]
[InlineData("HardReboot")]
[InlineData("Retry")]
[InlineData("Failed")]
public void IME_EXITCODE_CLASS_captures_every_AppReturnCodeType_member(string member)
{
var m = Compile(Get("IME-EXITCODE-CLASS")).Match("[Win32App] lpExitCode is defined as " + member);
Assert.True(m.Success);
Assert.Equal(member, m.Groups["exitCodeClass"].Value);
}
[Fact]
public void IME_EXITCODE_CLASS_ignores_the_no_mapping_warning_and_raw_numeric_types()
{
// The default branch logs "... defined as {0}, fall into default now." and an admin
// type outside the enum prints as a raw number; neither is a class the app carries.
var regex = Compile(Get("IME-EXITCODE-CLASS"));
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode is defined as 5, fall into default now.");
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode is defined as SoftReboot, fall into default now.");
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode is defined as 5");
Assert.DoesNotMatch(regex, "[Win32App] lpExitCode 3010");
}
[Fact]
public void PS_SCRIPT_CONTEXT_no_longer_fires_on_Win32App_detection_script_lines()
{
@@ -0,0 +1,248 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutopilotMonitor.Agent.V2.Core.Logging;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using AutopilotMonitor.Shared.Models;
using Newtonsoft.Json;
using Xunit;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
{
/// <summary>
/// Return-code class of the installer exit code (IME "[Win32App] lpExitCode is defined as
/// {AppReturnCodeType}"): captured by the shipped IME-EXITCODE-CLASS pattern into
/// <see cref="AppPackageState.ExitCodeClass"/>, last value wins across a Retry loop, the
/// no-mapping/default-branch variants are ignored, and the value survives the agent
/// restart that a SoftReboot/HardReboot app causes (persistence round trip).
/// </summary>
public sealed class ImeLogTrackerExitCodeClassTests
{
private const string AppId = "5c95bf94-1cf4-4629-88d1-3f616e7a405c";
// ---------------------------------------------------------------- AppPackageState
[Fact]
public void UpdateExitCodeClass_last_value_wins_and_ignores_empty()
{
var pkg = new AppPackageState(AppId, 0);
Assert.Null(pkg.ExitCodeClass);
Assert.True(pkg.UpdateExitCodeClass("Retry"));
Assert.True(pkg.UpdateExitCodeClass(" Success "));
Assert.Equal("Success", pkg.ExitCodeClass);
Assert.False(pkg.UpdateExitCodeClass("Success"));
Assert.False(pkg.UpdateExitCodeClass(""));
Assert.False(pkg.UpdateExitCodeClass(null));
Assert.Equal("Success", pkg.ExitCodeClass);
}
[Fact]
public void ToEventData_carries_the_class_only_when_known()
{
var pkg = new AppPackageState(AppId, 0);
Assert.False(pkg.ToEventData().ContainsKey("exitCodeClass"));
pkg.UpdateExitCode("3010");
pkg.UpdateExitCodeClass("SoftReboot");
var data = pkg.ToEventData();
Assert.Equal("3010", data["exitCode"]);
Assert.Equal("SoftReboot", data["exitCodeClass"]);
}
[Fact]
public void Restore_round_trips_the_class()
{
var pkg = AppPackageState.Restore(
AppId, 0, "Contoso VPN",
AppRunAs.System, AppIntent.Install, AppTargeted.Device,
new HashSet<string>(),
AppInstallationState.Installed, true, 100, 0, 0,
exitCode: "3010", exitCodeClass: "SoftReboot");
Assert.Equal("SoftReboot", pkg.ExitCodeClass);
}
// ---------------------------------------------------------------- shipped pack, end to end
private static string FindRulesPatternDir()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir != null)
{
var candidate = Path.Combine(dir.FullName, "rules", "ime-log-patterns");
if (Directory.Exists(candidate)) return candidate;
dir = dir.Parent;
}
throw new DirectoryNotFoundException($"Could not locate rules/ime-log-patterns walking up from {AppContext.BaseDirectory}");
}
/// <summary>The shipped pack, exactly as combine.js embeds it (sorted by file name).</summary>
private static List<ImeLogPattern> ShippedPack()
=> Directory.GetFiles(FindRulesPatternDir(), "*.json")
.OrderBy(f => f, StringComparer.Ordinal)
.Select(f => JsonConvert.DeserializeObject<ImeLogPattern>(File.ReadAllText(f))!)
.ToList();
private static string Entry(string message, DateTime utcInstant)
{
// CMTrace line with a zero writer offset: the tracker reads the local time and
// resolves it against the reader zone; only freshness (< 24 h) matters here.
return $"<![LOG[{message}]LOG]!><time=\"{utcInstant:HH:mm:ss.fffffff}\" date=\"{utcInstant:M-d-yyyy}\" " +
"component=\"IntuneManagementExtension\" context=\"\" type=\"1\" thread=\"1\" file=\"\">";
}
private sealed class Harness : IDisposable
{
private readonly TempDirectory _tmp = new TempDirectory();
public ImeLogTracker Tracker { get; }
public string StateDir { get; }
public DateTime Now { get; } = new DateTime(2026, 9, 6, 12, 0, 0, DateTimeKind.Utc);
public Harness()
{
StateDir = Path.Combine(_tmp.Path, "State");
Tracker = Build();
}
public ImeLogTracker Build()
{
var tracker = new ImeLogTracker(
logFolder: _tmp.Path,
patterns: ShippedPack(),
logger: new AgentLogger(_tmp.Path, AgentLogLevel.Info),
stateDirectory: StateDir);
// The historic-replay guard skips app-mutating actions for lines older than 24 h
// relative to "now": pin both so the CMTrace entries below are always fresh.
tracker.UtcNowProvider = () => Now;
return tracker;
}
public void Append(params string[] messages)
{
var lines = messages.Select((m, i) => Entry(m, Now.AddSeconds(-60 + i)));
File.AppendAllText(Path.Combine(_tmp.Path, "IntuneManagementExtension.log"),
string.Join(Environment.NewLine, lines) + Environment.NewLine);
}
public Task Pass() => Tracker.CheckLogFilesAsync(CancellationToken.None);
public void Dispose()
{
Tracker.Dispose();
_tmp.Dispose();
}
}
private static string PhaseLine => "[Win32App] In EspPhase: DeviceSetup.";
private static string CurrentAppLine => @"[Win32App] SetCurrentDirectory: C:\Windows\IMECache\" + AppId + "_1";
[Fact]
public async Task Shipped_pattern_captures_the_class_for_the_current_app()
{
using var h = new Harness();
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
h.Append(
PhaseLine, // activates the currentPhase pack (IME-EXITCODE, IME-EXITCODE-CLASS)
CurrentAppLine, // IME-SET-CURRENT-4 → current app
"[Win32App] lpExitCode 3010",
"[Win32App] lpExitCode is defined as SoftReboot");
await h.Pass();
var pkg = h.Tracker.PackageStates.GetPackage(AppId);
Assert.NotNull(pkg);
Assert.Equal("3010", pkg!.ExitCode);
Assert.Equal("SoftReboot", pkg.ExitCodeClass);
Assert.NotEqual(AppInstallationState.Error, pkg.InstallationState);
}
[Fact]
public async Task Retry_loop_that_ends_in_success_reports_the_last_class()
{
using var h = new Harness();
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
h.Append(
PhaseLine, CurrentAppLine,
"[Win32App] lpExitCode 1618",
"[Win32App] lpExitCode is defined as Retry",
"[Win32App] lpExitCode 1618",
"[Win32App] lpExitCode is defined as Retry",
"[Win32App] lpExitCode 0",
"[Win32App] lpExitCode is defined as Success");
await h.Pass();
var pkg = h.Tracker.PackageStates.GetPackage(AppId)!;
Assert.Equal("0", pkg.ExitCode);
Assert.Equal("Success", pkg.ExitCodeClass);
}
[Fact]
public async Task Failed_class_still_drives_the_error_transition_and_carries_the_class()
{
// IME-EXITCODE-CLASS and IME-EXITCODE-MAPPED-FAILED both match the Failed line: the
// class is captured and the existing error path stays intact.
using var h = new Harness();
var pkg = new AppPackageState(AppId, 0);
pkg.UpdateState(AppInstallationState.Installing);
h.Tracker.PackageStates.Add(pkg);
h.Append(
PhaseLine, CurrentAppLine,
"[Win32App] lpExitCode 1603",
"[Win32App] lpExitCode is defined as Failed");
await h.Pass();
Assert.Equal(AppInstallationState.Error, pkg.InstallationState);
Assert.Equal("Failed", pkg.ExitCodeClass);
Assert.Equal("IME-EXITCODE-MAPPED-FAILED", pkg.ErrorPatternId);
}
[Fact]
public async Task Default_branch_and_raw_numeric_types_leave_the_class_unset()
{
using var h = new Harness();
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
h.Append(
PhaseLine, CurrentAppLine,
"[Win32App] lpExitCode 5",
"[Win32App] lpExitCode is defined as 5",
"[Win32App] lpExitCode is defined as 5, fall into default now.",
"[Win32App] Setting enforcementState as: Error with lpExitCode: 5 without mapping");
await h.Pass();
var pkg = h.Tracker.PackageStates.GetPackage(AppId)!;
Assert.Equal("5", pkg.ExitCode);
Assert.Null(pkg.ExitCodeClass);
}
[Fact]
public async Task Class_survives_the_state_round_trip_of_an_agent_restart()
{
// A SoftReboot/HardReboot app completes only after the reboot; the restarted agent
// must still know the class when the post-reboot Success line arrives.
using var h = new Harness();
h.Tracker.PackageStates.Add(new AppPackageState(AppId, 0));
h.Append(
PhaseLine, CurrentAppLine,
"[Win32App] lpExitCode 1641",
"[Win32App] lpExitCode is defined as HardReboot");
await h.Pass();
h.Tracker.SaveStateForTest();
using var restarted = h.Build();
restarted.LoadStateForTest();
var pkg = restarted.GetAllKnownPackageStates().Single(p => p.Id == AppId);
Assert.Equal("1641", pkg.ExitCode);
Assert.Equal("HardReboot", pkg.ExitCodeClass);
}
}
}
@@ -903,5 +903,87 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Runtime
NtfsLinks.RemoveLink(link);
}
}
// ============================================================= packaging counters
[Fact]
public void BuildArchiveBytes_records_packaging_counters_by_reason_and_kind_without_paths()
{
using var rig = new Rig();
File.WriteAllText(Path.Combine(rig.StateFolder, "small.json"), "{}");
File.WriteAllText(Path.Combine(rig.StateFolder, "big-1.json"), new string('x', 64));
File.WriteAllText(Path.Combine(rig.StateFolder, "big-2.json"), new string('y', 64));
var blockedPath = @"C:\Windows\System32\config\SYSTEM";
var service = rig.Build(cfg => cfg.DiagnosticsLogPaths.Add(
new AutopilotMonitor.Shared.Models.DiagnosticsLogPath { Path = blockedPath }));
service.Budget = new DiagnosticsBudget { MaxSingleFileBytes = 16, MaxTotalUncompressedBytes = 1L << 30, MaxFileCount = 5000 };
Assert.Null(service.LastPackaging);
var bytes = service.BuildArchiveBytes(enrollmentSucceeded: true);
var stats = service.LastPackaging;
Assert.NotNull(stats);
Assert.True(stats!.Truncated);
Assert.Equal(2, stats.SkippedFiles);
Assert.Equal(2, stats.SkippedByReason["size"]);
Assert.Single(stats.SkippedByReason);
Assert.Equal(1, stats.ProblemsByKind["path-guard"]);
Assert.Single(stats.ProblemsByKind);
Assert.True(stats.IncludedFiles >= 1, "the small file must have been included");
Assert.True(stats.IncludedBytes >= 2);
// The ZIP still carries the per-file list; the counters never do.
Assert.NotNull(ReadZipEntryText(bytes, "_TRUNCATED.txt"));
foreach (var key in stats.SkippedByReason.Keys.Concat(stats.ProblemsByKind.Keys))
{
Assert.DoesNotContain("\\", key);
Assert.DoesNotContain(":", key);
Assert.DoesNotContain("/", key);
}
}
[Fact]
public void BuildArchiveBytes_reports_a_clean_build_as_not_truncated_with_empty_maps()
{
using var rig = new Rig();
File.WriteAllText(Path.Combine(rig.StateFolder, "snapshot.json"), "{}");
var service = rig.Build();
service.BuildArchiveBytes(enrollmentSucceeded: true);
var stats = service.LastPackaging;
Assert.NotNull(stats);
Assert.False(stats!.Truncated);
Assert.Equal(0, stats.SkippedFiles);
Assert.Empty(stats.SkippedByReason);
Assert.Empty(stats.ProblemsByKind);
Assert.True(stats.IncludedFiles >= 1);
}
[Fact]
public void BuildArchiveBytes_counts_a_rejected_source_folder_as_a_problem()
{
using var rig = new Rig();
using var outside = new TempDirectory();
File.WriteAllText(Path.Combine(outside.Path, "snapshot.json"), "{}");
var link = Path.Combine(rig.Tmp.Path, "StateLink");
NtfsLinks.CreateJunction(link, outside.Path);
try
{
var service = rig.Build(sectionFolderOverrides: new Dictionary<string, string> { ["AgentState"] = link });
service.BuildArchiveBytes(enrollmentSucceeded: true);
// The section is walked once per search pattern (11 patterns) but the folder
// failed once — the counter says so.
Assert.Equal(1, service.LastPackaging!.ProblemsByKind["folder-rejected"]);
Assert.False(service.LastPackaging.Truncated);
}
finally
{
NtfsLinks.RemoveLink(link);
}
}
}
}
@@ -243,12 +243,23 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
}
[Fact]
public void DecodeHResult_KnownAndUnknown()
public void ResolveHResultSymbol_ReadsTheSharedCatalog()
{
Assert.Equal("WU_E_ALL_UPDATES_FAILED", WindowsUpdateTracker.DecodeHResult(0x80240022));
Assert.Equal("CBS_E_INSTALLERS_FAILED", WindowsUpdateTracker.DecodeHResult(0x800F0922));
Assert.Equal("S_OK", WindowsUpdateTracker.DecodeHResult(0x00000000));
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.DecodeHResult(0x8888DEAD));
Assert.Equal("WU_E_ALL_UPDATES_FAILED", WindowsUpdateTracker.ResolveHResultSymbol(0x80240022));
Assert.Equal("CBS_E_INSTALLERS_FAILED", WindowsUpdateTracker.ResolveHResultSymbol(0x800F0922));
Assert.Equal("ERROR_TIMEOUT", WindowsUpdateTracker.ResolveHResultSymbol(0x800705B4));
Assert.Equal("S_OK", WindowsUpdateTracker.ResolveHResultSymbol(0x00000000));
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.ResolveHResultSymbol(0x8888DEAD));
}
[Fact]
public void ResolveHResultSymbol_FallsBackWhenTheCatalogHasNoSymbolOrThrows()
{
// An entry without a symbol (IME/Intune paraphrases) still yields the sentinel.
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.ResolveHResultSymbol(0x87D1041C));
// A catalog load failure is decoration lost, never an event lost.
Assert.Equal("WU_E_UNKNOWN", WindowsUpdateTracker.ResolveHResultSymbol(0x80240022, _ => throw new InvalidOperationException("catalog")));
Assert.Equal("S_OK", WindowsUpdateTracker.ResolveHResultSymbol(0, _ => throw new InvalidOperationException("catalog")));
}
// ---------------------------------------------------------------------------
@@ -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()
{
@@ -11,6 +11,7 @@ using AutopilotMonitor.DecisionCore.Engine;
using AutopilotMonitor.DecisionCore.Signals;
using AutopilotMonitor.DecisionCore.State;
using Xunit;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
{
@@ -8,6 +8,7 @@ using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using AutopilotMonitor.DecisionCore.Signals;
using AutopilotMonitor.DecisionCore.State;
using Xunit;
using AutopilotMonitor.Shared.Models;
#pragma warning disable xUnit1031
@@ -42,7 +43,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
// items must be a whiteglove_resumed event.
Assert.DoesNotContain(
rig.Uploader.Received.SelectMany(b => b),
item => item.Kind == AutopilotMonitor.Agent.V2.Core.Transport.Telemetry.TelemetryItemKind.Event &&
item => item.Kind == TelemetryItemKind.Event &&
item.PayloadJson != null &&
item.PayloadJson.Contains("\"whiteglove_resumed\""));
}
@@ -75,7 +76,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
var resumedEvents = rig.Uploader.Received
.SelectMany(b => b)
.Where(item =>
item.Kind == AutopilotMonitor.Agent.V2.Core.Transport.Telemetry.TelemetryItemKind.Event &&
item.Kind == TelemetryItemKind.Event &&
item.PayloadJson != null &&
item.PayloadJson.Contains("\"whiteglove_resumed\""))
.ToList();
@@ -15,6 +15,7 @@ using AutopilotMonitor.DecisionCore.Engine;
using AutopilotMonitor.DecisionCore.Signals;
using AutopilotMonitor.DecisionCore.State;
using Xunit;
using AutopilotMonitor.Shared.Models;
#pragma warning disable xUnit1031
@@ -9,6 +9,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
using AutopilotMonitor.DecisionCore.Engine;
using AutopilotMonitor.DecisionCore.Signals;
using Xunit;
using AutopilotMonitor.Shared.Models;
#pragma warning disable xUnit1031
@@ -282,8 +282,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
errorPatternId: null,
errorDetail: null,
errorCode: null,
exitCode: null,
exitCode: "0",
hresultFromWin32: null,
exitCodeClass: "Success",
appVersion: "11.2.1787.0",
appType: "WinGet",
attemptNumber: 1,
@@ -293,6 +294,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
var info = Assert.Single(f.InfoEvents(SharedEventTypes.AppInstallComplete));
Assert.Equal("app-xyz", info.Payload!["appId"]);
// Installer outcome surfaces on the terminal event even when the app succeeded: the
// return-code class is the only evidence of a SoftReboot/HardReboot mapping and the
// number says which code was mapped (IME-EXITCODE-CLASS, ANALYZE-APP-018).
Assert.Equal("Success", info.Payload["exitCodeClass"]);
Assert.Equal("0", info.Payload["exitCode"]);
Assert.Equal("Company Portal", info.Payload["appName"]);
Assert.Equal("Installed", info.Payload["state"]);
Assert.Equal("Install", info.Payload["intent"]);
@@ -331,6 +337,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
errorCode: "60001",
exitCode: "60001",
hresultFromWin32: "-2146964895",
exitCodeClass: "Failed",
attemptNumber: 1,
detectionResult: "NotDetected");
@@ -340,6 +347,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
Assert.Equal("true", info.Payload!["isError"]);
Assert.Equal("IME-ERROR-UNMAPPED-EXIT", info.Payload["errorPatternId"]);
Assert.Equal("60001", info.Payload["errorCode"]);
Assert.Equal("60001", info.Payload["exitCode"]);
Assert.Equal("Failed", info.Payload["exitCodeClass"]);
Assert.Equal("-2146964895", info.Payload["hresultFromWin32"]);
Assert.Equal(EventSeverity.Error.ToString(), info.Payload[SignalPayloadKeys.Severity]);
// Codex review follow-up (P1): an unrelated ErrorPatternId (here a regular
@@ -5,6 +5,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
using AutopilotMonitor.DecisionCore.Signals;
using Newtonsoft.Json.Linq;
using Xunit;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Telemetry.Signals
{
@@ -8,6 +8,7 @@ using AutopilotMonitor.DecisionCore.Engine;
using AutopilotMonitor.DecisionCore.State;
using Newtonsoft.Json.Linq;
using Xunit;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Telemetry.Transitions
{
@@ -1701,5 +1701,86 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Termination
rig.PromotionCalls[0].failureType);
Assert.Null(rig.PromotionCalls[0].errorCode);
}
// ============================================================= packaging counters on the diag events
[Fact]
public void Handle_diagnostics_uploaded_carries_packaging_counters_when_the_packager_reported_them()
{
using var rig = new Rig();
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Completed }.Build();
rig.DiagnosticsResult = new DiagnosticsUploadResult
{
BlobName = "diag-blob.zip",
Packaging = new DiagnosticsPackagingStats
{
IncludedFiles = 412,
IncludedBytes = 123456,
SkippedFiles = 3,
SkippedByReason = new Dictionary<string, int> { ["size"] = 2, ["total"] = 1 },
ProblemsByKind = new Dictionary<string, int> { ["copy"] = 1 },
},
};
var cfg = rig.BuildConfig(diagEnabled: true, diagMode: "Always", selfDestruct: false);
rig.Build(cfg).Handle(sender: null!,
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Succeeded, SessionStage.Completed));
var uploaded = rig.DataOf("diagnostics_uploaded");
Assert.NotNull(uploaded);
Assert.Equal(true, uploaded!["truncated"]);
Assert.Equal(412, uploaded["includedFiles"]);
Assert.Equal(123456L, uploaded["includedBytes"]);
Assert.Equal(3, uploaded["skippedFiles"]);
var byReason = Assert.IsType<Dictionary<string, int>>(uploaded["skippedByReason"]);
Assert.Equal(2, byReason["size"]);
Assert.Equal(1, byReason["total"]);
var problems = Assert.IsType<Dictionary<string, int>>(uploaded["problemsByKind"]);
Assert.Equal(1, problems["copy"]);
// Counters only — no key or value carries a file path.
foreach (var kv in uploaded)
Assert.False(kv.Value is string s && (s.Contains("\\") || s.Contains("/")) && kv.Key != "sasUrlPrefix",
$"payload key {kv.Key} looks like a path: {kv.Value}");
}
[Fact]
public void Handle_diagnostics_upload_failed_after_a_build_carries_the_counters_too()
{
using var rig = new Rig();
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Failed }.Build();
rig.DiagnosticsResult = new DiagnosticsUploadResult
{
ErrorCode = "upload_5xx",
Packaging = new DiagnosticsPackagingStats { IncludedFiles = 40, IncludedBytes = 1000 },
};
var cfg = rig.BuildConfig(diagEnabled: true, diagMode: "Always", selfDestruct: false);
rig.Build(cfg).Handle(sender: null!,
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Failed, SessionStage.Failed));
var failed = rig.DataOf("diagnostics_upload_failed");
Assert.NotNull(failed);
Assert.Equal("upload_5xx", (string)failed!["errorCode"]);
Assert.Equal(false, failed["truncated"]);
Assert.Equal(40, failed["includedFiles"]);
Assert.Empty(Assert.IsType<Dictionary<string, int>>(failed["skippedByReason"]));
}
[Fact]
public void Handle_diagnostics_events_omit_the_counters_when_no_package_was_built()
{
using var rig = new Rig();
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Completed }.Build();
rig.DiagnosticsResult = new DiagnosticsUploadResult { BlobName = "diag-blob.zip" };
var cfg = rig.BuildConfig(diagEnabled: true, diagMode: "Always", selfDestruct: false);
rig.Build(cfg).Handle(sender: null!,
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Succeeded, SessionStage.Completed));
var uploaded = rig.DataOf("diagnostics_uploaded");
Assert.NotNull(uploaded);
Assert.False(uploaded!.ContainsKey("truncated"));
Assert.False(uploaded.ContainsKey("skippedByReason"));
}
}
}
@@ -6,6 +6,7 @@ using System.Net.Http;
using System.Threading;
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
using Xunit;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
{
@@ -8,6 +8,7 @@ using AutopilotMonitor.Agent.V2.Core.Logging;
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
using Xunit;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
{
@@ -7,6 +7,7 @@ using System.Threading.Tasks;
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
using Newtonsoft.Json.Linq;
using Xunit;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
{
@@ -4,6 +4,7 @@ using System.Text;
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
using Xunit;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
{
@@ -4,6 +4,7 @@ using System.Threading.Tasks;
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
using Xunit;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
{
@@ -0,0 +1,250 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AutopilotMonitor.Agent.V2.Core.Telemetry.Events;
using AutopilotMonitor.Agent.V2.Core.Telemetry.Signals;
using AutopilotMonitor.Agent.V2.Core.Telemetry.Transitions;
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using AutopilotMonitor.Agent.V2.Core.Tests.Telemetry.Events;
using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
using AutopilotMonitor.DecisionCore.Engine;
using AutopilotMonitor.DecisionCore.Signals;
using AutopilotMonitor.DecisionCore.State;
using AutopilotMonitor.Shared;
using AutopilotMonitor.Shared.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
{
/// <summary>
/// The agent → backend wire contract of <c>POST /api/agent/telemetry</c>, proven from the
/// WRITER side. <see cref="TelemetryItemDto"/> (Shared) is the one class both ends serialise;
/// <see cref="TelemetryItem.ToWire"/> is the only mapping onto it.
/// <list type="bullet">
/// <item>Round trip + reflection: every DTO property is populated by <c>ToWire()</c> and
/// survives Newtonsoft defaults — a DTO field added without a mapping fails here.</item>
/// <item>Frozen body: the real batch serialiser's output for one item per
/// <see cref="TelemetryItemKind"/> is pinned under <c>tests/fixtures/telemetry-wire/</c>.
/// The backend's <c>TelemetryWireFixtureTests</c> reads the same files and demands zero
/// rejections, so a rename on either side breaks a test until both sides and the fixture
/// agree. Regenerate with <c>AM_WRITE_WIRE_FIXTURES=1</c>.</item>
/// <item>Poison body: the exact 422 shape the backend writes (pinned there by
/// <c>TelemetryWireFixtureTests</c>) is parsed as an item-level poison signal here.</item>
/// </list>
/// </summary>
public sealed class TelemetryWireContractTests
{
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
private const string SessionId = "b2c3d4e5-f6a7-8901-bcde-f12345678901";
private const string FixtureFile = "agent-v2.json";
private static readonly DateTime At = new DateTime(2026, 4, 20, 10, 0, 0, DateTimeKind.Utc);
private static TelemetryItem FullyPopulatedItem() =>
new TelemetryItem(
kind: TelemetryItemKind.DecisionTransition,
partitionKey: $"{TenantId}_{SessionId}",
rowKey: "0000000007",
telemetryItemId: 42,
sessionTraceOrdinal: 7,
payloadJson: "{\"StepIndex\":7}",
requiresImmediateFlush: true,
enqueuedAtUtc: At,
retryCount: 3);
// ============================================================ ToWire mapping
[Fact]
public void ToWire_round_trips_every_property_through_Newtonsoft_defaults()
{
var item = FullyPopulatedItem();
var json = JsonConvert.SerializeObject(item.ToWire());
var dto = JsonConvert.DeserializeObject<TelemetryItemDto>(json)!;
Assert.Equal("DecisionTransition", dto.Kind);
Assert.Equal(item.PartitionKey, dto.PartitionKey);
Assert.Equal(item.RowKey, dto.RowKey);
Assert.Equal(item.TelemetryItemId, dto.TelemetryItemId);
Assert.Equal(item.SessionTraceOrdinal, dto.SessionTraceOrdinal);
Assert.Equal(item.PayloadJson, dto.PayloadJson);
Assert.Equal(item.RequiresImmediateFlush, dto.RequiresImmediateFlush);
Assert.Equal(item.EnqueuedAtUtc, dto.EnqueuedAtUtc);
Assert.Equal(DateTimeKind.Utc, dto.EnqueuedAtUtc.Kind);
Assert.Equal(item.RetryCount, dto.RetryCount);
}
[Fact]
public void ToWire_populates_every_TelemetryItemDto_property()
{
// A DTO property that ToWire() does not set keeps its default — this catches a field
// added to the wire type without a mapping (the backend would read the default forever).
var dto = FullyPopulatedItem().ToWire();
var unset = typeof(TelemetryItemDto)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => IsDefault(p.GetValue(dto), p.PropertyType))
.Select(p => p.Name)
.ToList();
Assert.True(unset.Count == 0,
"TelemetryItem.ToWire() leaves these TelemetryItemDto properties at their default: " + string.Join(", ", unset));
}
[Fact]
public void TelemetryItemDto_properties_mirror_TelemetryItem()
{
var itemProps = typeof(TelemetryItem).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.ToDictionary(p => p.Name, p => p.PropertyType);
foreach (var dtoProp in typeof(TelemetryItemDto).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
Assert.True(itemProps.TryGetValue(dtoProp.Name, out var itemType),
$"TelemetryItemDto.{dtoProp.Name} has no counterpart on TelemetryItem");
var expected = dtoProp.Name == nameof(TelemetryItemDto.Kind) ? typeof(TelemetryItemKind) : dtoProp.PropertyType;
Assert.True(itemType == expected,
$"TelemetryItemDto.{dtoProp.Name} is {dtoProp.PropertyType.Name}, TelemetryItem.{dtoProp.Name} is {itemType.Name}");
}
}
[Fact]
public void Every_kind_serialises_by_name_on_the_wire_and_on_the_spool_line()
{
foreach (var kind in TelemetryItemKinds.All)
{
var item = new TelemetryItem(kind, "T_S", "rk", 1, 1, "{}", false, At);
var wire = JObject.Parse(JsonConvert.SerializeObject(item.ToWire()));
Assert.Equal(kind.ToString(), (string?)wire["Kind"]);
// The spool line (TelemetryItemSerializer) has always written the NAME too; the enum's
// move to Shared must not turn it into an ordinal (a crash-restart rehydrates it).
var spool = JObject.Parse(TelemetryItemSerializer.Serialize(item));
Assert.Equal(kind.ToString(), (string?)spool["Kind"]);
Assert.Equal(kind, TelemetryItemSerializer.Deserialize(spool.ToString(Formatting.None)).Kind);
Assert.True(TelemetryItemKinds.TryParse(kind.ToString(), out var parsed));
Assert.Equal(kind, parsed);
}
}
// ============================================================ Frozen wire body
[Fact]
public void Frozen_wire_body_matches_the_current_serializer()
{
var items = OneItemPerKind();
Assert.Equal(TelemetryItemKinds.All.OrderBy(k => k), items.Select(i => i.Kind).Distinct().OrderBy(k => k));
var body = BackendTelemetryUploader.SerializeBatch(items);
var path = Path.Combine(RepoPaths.Fixtures("telemetry-wire"), FixtureFile);
if (Environment.GetEnvironmentVariable("AM_WRITE_WIRE_FIXTURES") == "1")
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, body + "\n", new UTF8Encoding(false));
}
Assert.True(File.Exists(path), "Missing wire fixture " + path + " — run this test with AM_WRITE_WIRE_FIXTURES=1 to create it.");
var frozen = File.ReadAllText(path).TrimEnd('\r', '\n');
Assert.True(string.Equals(frozen, body, StringComparison.Ordinal),
"The agent's telemetry wire body changed. If the change is intended, update the backend ingest " +
"(TelemetryWireFixtureTests must still dispatch every frozen body) and regenerate with " +
"AM_WRITE_WIRE_FIXTURES=1.\nExpected: " + frozen + "\nActual: " + body);
}
/// <summary>
/// One item per kind through the REAL emitters (payload shapes are theirs, not hand-typed),
/// re-based onto fixed transport fields so the body is byte-stable.
/// </summary>
private static IReadOnlyList<TelemetryItem> OneItemPerKind()
{
using var tmp = new TempDirectory();
var transport = new FakeTelemetryTransport();
var counter = new EventSequenceCounter(new EventSequencePersistence(tmp.File("seq.json")));
new TelemetryEventEmitter(transport, counter, SessionId, TenantId).Emit(new EnrollmentEvent
{
EventId = "00000000-0000-4000-8000-000000000001",
EventType = Constants.EventTypes.AgentStarted,
Severity = EventSeverity.Info,
Source = "Agent",
Timestamp = At,
Phase = EnrollmentPhase.Unknown,
Message = "Agent started",
Data = new Dictionary<string, object> { ["agentVersion"] = "2.0.0" },
});
new TelemetrySignalEmitter(transport, SessionId, TenantId).Emit(new DecisionSignal(
sessionSignalOrdinal: 1,
sessionTraceOrdinal: 1,
kind: DecisionSignalKind.SessionStarted,
kindSchemaVersion: 1,
occurredAtUtc: At,
sourceOrigin: "Fixture",
evidence: new Evidence(EvidenceKind.Raw, "raw-1", "session start")));
new TelemetryTransitionEmitter(transport, SessionId, TenantId).Emit(new DecisionTransition(
stepIndex: 1,
sessionTraceOrdinal: 2,
signalOrdinalRef: 1,
occurredAtUtc: At,
trigger: "SessionStarted",
fromStage: SessionStage.Unknown,
toStage: SessionStage.AwaitingEspPhaseChange,
taken: true,
deadEndReason: null,
reducerVersion: "1.0.0"));
return transport.Enqueued
.Select(e => new TelemetryItem(e.Kind, e.PartitionKey, e.RowKey, e.TelemetryItemId, e.SessionTraceOrdinal,
e.PayloadJson, e.RequiresImmediateFlush, At))
.ToList();
}
// ============================================================ Poison body
/// <summary>
/// The exact 422 body the backend writes for rejected items (pinned byte-for-byte in the
/// backend's TelemetryWireFixtureTests). camelCase because the backend serialises with
/// its wire options; the agent's parser accepts both casings.
/// </summary>
internal const string BackendPoisonBody =
"{\"error\":\"2 of 3 telemetry item(s) cannot be ingested (unknown Kind or unusable payload); they were not stored.\"," +
"\"code\":\"TelemetryItemsRejected\",\"correlationId\":\"cid-1\",\"poison\":true,\"rejectedRowKeys\":[\"rk-1\",\"rk-3\"]," +
"\"reason\":\"unknown_kind=1;unparseable=1\",\"received\":3,\"rejected\":2}";
[Fact]
public async Task Backend_422_poison_body_is_parsed_as_item_level_poison()
{
using var handler = new RecordingHttpMessageHandler().QueueStatus((HttpStatusCode)422, BackendPoisonBody);
using var http = new HttpClient(handler);
var sut = new BackendTelemetryUploader(http, baseUrl: "https://backend.example.invalid", tenantId: TenantId, agentVersion: "2.0.0");
var result = await sut.UploadBatchAsync(new[] { FullyPopulatedItem() }, CancellationToken.None);
Assert.False(result.Success);
Assert.True(result.IsPoison);
Assert.Equal(new[] { "rk-1", "rk-3" }, result.PoisonRowKeys);
Assert.Equal("unknown_kind=1;unparseable=1", result.ErrorReason);
}
private static bool IsDefault(object? value, Type type)
{
if (value == null) return true;
if (type == typeof(string)) return ((string)value).Length == 0;
var underlying = Nullable.GetUnderlyingType(type) ?? type;
return underlying.IsValueType && value.Equals(Activator.CreateInstance(underlying));
}
}
}
@@ -99,6 +99,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
// Installer result codes (captured from lpExitCode / hResultFromWin32 log lines)
public string ExitCode { get; private set; }
public string HResultFromWin32 { get; private set; }
/// <summary>
/// Admin-defined return-code class of the last installer exit code: Success, SoftReboot,
/// HardReboot, Retry or Failed (IME's AppReturnCodeType, captured from the
/// "lpExitCode is defined as X" line by IME-EXITCODE-CLASS). Last value wins, so a Retry
/// loop that ends in Success reports Success.
/// </summary>
public string ExitCodeClass { get; private set; }
// App metadata (captured from IME log patterns — used by App Dashboard / reports)
/// <summary>Product version detected after install (e.g. "11.2.1787.0"). From ReportingManager DetectedIdentityVersion.</summary>
@@ -167,6 +174,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
int? progressPercent, long bytesDownloaded, long bytesTotal,
string errorPatternId = null, string errorDetail = null, string errorCode = null,
string exitCode = null, string hresultFromWin32 = null,
string exitCodeClass = null,
long doFileSize = 0, long doTotalBytesDownloaded = 0,
long doBytesFromPeers = 0, int doPercentPeerCaching = 0,
long doBytesFromLanPeers = 0, long doBytesFromGroupPeers = 0,
@@ -195,6 +203,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
ErrorCode = errorCode,
ExitCode = exitCode,
HResultFromWin32 = hresultFromWin32,
ExitCodeClass = exitCodeClass,
InstallationStateLastChangedTicks = Stopwatch.GetTimestamp(),
DoFileSize = doFileSize,
DoTotalBytesDownloaded = doTotalBytesDownloaded,
@@ -302,6 +311,19 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
HResultFromWin32 = code;
}
/// <summary>
/// Captures the return-code class (Success/SoftReboot/HardReboot/Retry/Failed) IME assigned
/// to the last exit code. Last value wins; empty values are ignored.
/// </summary>
public bool UpdateExitCodeClass(string exitCodeClass)
{
if (string.IsNullOrWhiteSpace(exitCodeClass)) return false;
var trimmed = exitCodeClass.Trim();
if (ExitCodeClass == trimmed) return false;
ExitCodeClass = trimmed;
return true;
}
/// <summary>
/// Updates the product version detected for this app (e.g. "11.2.1787.0").
/// Only applies non-empty values so a later detection without version cannot wipe it.
@@ -547,6 +569,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
data["exitCode"] = ExitCode;
if (!string.IsNullOrEmpty(HResultFromWin32))
data["hresultFromWin32"] = HResultFromWin32;
if (!string.IsNullOrEmpty(ExitCodeClass))
data["exitCodeClass"] = ExitCodeClass;
// App metadata fields (emitted whenever available so ingest can merge them).
if (!string.IsNullOrEmpty(AppVersion))
@@ -491,7 +491,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
"imeshutdown", "espphasedetected", "setcurrentapp",
"updatestateinstalled", "updatestatedownloading", "updatestateinstalling",
"updatestateskipped", "updatestateerror", "updatestatepostponed",
"captureexitcode", "capturehresult", "captureappversion",
"captureexitcode", "capturehresult", "captureexitcodeclass", "captureappversion",
"captureapptypewinget", "captureapptypemsi", "captureattemptnumber",
"capturedetectionresult", "esptrackstatus", "policiesdiscovered",
"ignorecompletedapp", "updatename", "updatewin32appstate",
@@ -715,6 +715,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
_packageStates.GetPackage(_packageStates.CurrentPackageId)?.UpdateHResult(hresultVal);
break;
case "captureexitcodeclass":
// Return-code class of the exit code captured just before (IME logs the
// number, then "lpExitCode is defined as <class>"). Same current-app
// addressing as captureExitCode; last value wins across a Retry loop.
var exitCodeClassVal = match.Groups["exitCodeClass"]?.Value;
if (!string.IsNullOrEmpty(exitCodeClassVal) && !string.IsNullOrEmpty(_packageStates.CurrentPackageId))
_packageStates.GetPackage(_packageStates.CurrentPackageId)?.UpdateExitCodeClass(exitCodeClassVal);
break;
case "captureappversion":
var appVersionVal = match.Groups["appVersion"]?.Value;
if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(appVersionVal))
@@ -223,7 +223,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
return true;
}
private const int MaxScriptOutputLength = 2048;
// Script stdout kept per event. Measured over 1,486 script outputs in the fleet
// (2026-08-25..09-08): median 39, p90 644, max 1,501 chars -- the maximum being our own
// one-stage bootstrap, and nothing ever hit the previous 2,048 cap. The two-stage
// bootstrap then added a ~460-char loader preamble to that maximum and started
// truncating the one output an operator actually reads. 8,192 leaves room for the
// realistic worst case (download retries plus relax logging, ~2,700) and stays 4x below
// the 32K-char Table Storage property limit that bounds the event downstream. Growth
// driver is the number of log lines the bootstrap chain writes, so re-measure before
// adding a chatty step rather than raising this again.
private const int MaxScriptOutputLength = 8192;
private const int MaxMultiLineBufferLines = 100;
// Size cap for ONE entry — a single physical line (enforced by BoundedLineReader before
// the line is materialized) and an assembled multiline entry alike. Any process able to
@@ -1241,6 +1250,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
ErrorCode = p.ErrorCode,
ExitCode = p.ExitCode,
HResultFromWin32 = p.HResultFromWin32,
ExitCodeClass = p.ExitCodeClass,
DoFileSize = p.DoFileSize,
DoTotalBytesDownloaded = p.DoTotalBytesDownloaded,
DoBytesFromPeers = p.DoBytesFromPeers,
@@ -1270,6 +1280,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
p.ProgressPercent, p.BytesDownloaded, p.BytesTotal,
errorPatternId: p.ErrorPatternId, errorDetail: p.ErrorDetail, errorCode: p.ErrorCode,
exitCode: p.ExitCode, hresultFromWin32: p.HResultFromWin32,
exitCodeClass: p.ExitCodeClass,
doFileSize: p.DoFileSize, doTotalBytesDownloaded: p.DoTotalBytesDownloaded,
doBytesFromPeers: p.DoBytesFromPeers, doPercentPeerCaching: p.DoPercentPeerCaching,
doBytesFromLanPeers: p.DoBytesFromLanPeers, doBytesFromGroupPeers: p.DoBytesFromGroupPeers,
@@ -190,6 +190,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
// Installer result codes
public string ExitCode { get; set; }
public string HResultFromWin32 { get; set; }
// Return-code class of the last exit code (null on state files written before the field
// existed) - must survive the reboot a SoftReboot/HardReboot app asks for.
public string ExitCodeClass { get; set; }
// Delivery Optimization telemetry
public long DoFileSize { get; set; }
@@ -9,6 +9,7 @@ using AutopilotMonitor.Agent.V2.Core.Logging;
using AutopilotMonitor.Agent.V2.Core.Orchestration;
using AutopilotMonitor.Shared;
using AutopilotMonitor.Shared.Models;
using AutopilotMonitor.Shared.Services;
using Newtonsoft.Json;
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
@@ -303,7 +304,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
if (TryNormalizeHResult(errorCode, out var hresultValue, out hresultHex))
{
data["hresult"] = hresultHex;
data["hresultSymbol"] = DecodeHResult(hresultValue);
data["hresultSymbol"] = ResolveHResultSymbol(hresultValue);
}
var title = string.IsNullOrEmpty(updateTitle) ? "(unknown update)" : updateTitle;
@@ -462,36 +463,25 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
}
/// <summary>
/// Maps common Windows Update HRESULTs to their symbolic name. Not exhaustive — the full
/// catalog lives at
/// https://learn.microsoft.com/windows/deployment/update/windows-update-error-reference.
/// Unknown codes return "WU_E_UNKNOWN" so the raw <c>hresult</c> hex still carries the value.
/// Symbolic name of a WU HRESULT from the shared error-code catalog (WU, CBS, Win32 and
/// COM families). <c>S_OK</c> for zero, <c>WU_E_UNKNOWN</c> when the catalog has no symbol,
/// so the raw <c>hresult</c> hex still carries the value. A catalog load failure is
/// swallowed the same way: decoding is decoration and must never cost the event.
/// </summary>
internal static string DecodeHResult(uint hresult)
internal static string ResolveHResultSymbol(uint hresult)
=> ResolveHResultSymbol(hresult, code => ErrorCodeCatalog.TryLookup(code));
internal static string ResolveHResultSymbol(uint hresult, Func<string, ErrorCodeEntry> lookup)
{
switch (hresult)
if (hresult == 0) return "S_OK";
try
{
case 0x00000000: return "S_OK";
// WU agent codes (0x8024xxxx)
case 0x80240022: return "WU_E_ALL_UPDATES_FAILED";
case 0x8024200B: return "WU_E_UH_INSTALLERFAILURE";
case 0x80240020: return "WU_E_NO_INTERACTIVE_USER";
case 0x80240016: return "WU_E_INSTALL_NOT_ALLOWED";
case 0x8024000B: return "WU_E_CALL_CANCELLED";
case 0x8024000C: return "WU_E_NOOP";
case 0x80240FFF: return "WU_E_UNEXPECTED";
case 0x80248007: return "WU_E_DS_NODATA";
case 0x8024402C: return "WU_E_PT_WINHTTP_NAME_NOT_RESOLVED";
// Generic Win32 / HRESULT
case 0x80070005: return "E_ACCESSDENIED";
case 0x80070002: return "ERROR_FILE_NOT_FOUND";
case 0x80070003: return "ERROR_PATH_NOT_FOUND";
case 0x800705B4: return "ERROR_TIMEOUT";
// CBS / servicing (LCU install failures)
case 0x800F0831: return "CBS_E_STORE_CORRUPTION";
case 0x800F0922: return "CBS_E_INSTALLERS_FAILED";
case 0x800F0991: return "PSFX_E_MISSING_PAYLOAD_FILE";
default: return "WU_E_UNKNOWN";
var symbol = lookup("0x" + hresult.ToString("x8", CultureInfo.InvariantCulture))?.Symbol;
return string.IsNullOrEmpty(symbol) ? "WU_E_UNKNOWN" : symbol;
}
catch
{
return "WU_E_UNKNOWN";
}
}
@@ -65,6 +65,44 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
public static DiagnosticsUploadResult SkippedBy(string gate) =>
new DiagnosticsUploadResult { Skipped = true, ErrorCode = gate };
/// <summary>
/// Counters of the archive build that produced (or preceded) this result; null when no
/// package was built (configuration gate, build exception). Surfaced into the
/// <c>diagnostics_uploaded</c> / <c>diagnostics_upload_failed</c> events so a truncated or
/// partially failed package is visible without opening the ZIP.
/// </summary>
public DiagnosticsPackagingStats Packaging { get; set; }
}
/// <summary>
/// What the packager included, skipped and failed on — as bounded counters only. File paths
/// stay inside the ZIP (<c>package-manifest.txt</c>, <c>_TRUNCATED.txt</c>): they can carry
/// user names, and a skip list has no upper bound while this payload must stay small no
/// matter how many files a cap rejected.
/// </summary>
public sealed class DiagnosticsPackagingStats
{
private static readonly IReadOnlyDictionary<string, int> Empty = new Dictionary<string, int>();
public int IncludedFiles { get; set; }
public long IncludedBytes { get; set; }
/// <summary>Files rejected by a cap or a reparse-point check (the <c>_TRUNCATED.txt</c> list).</summary>
public int SkippedFiles { get; set; }
/// <summary>True when at least one file was skipped — the same condition that writes <c>_TRUNCATED.txt</c>.</summary>
public bool Truncated => SkippedFiles > 0;
/// <summary>Skip count per reason: <c>size</c>, <c>count</c>, <c>total</c>, <c>reparse</c>, <c>resolved-outside-folder</c>.</summary>
public IReadOnlyDictionary<string, int> SkippedByReason { get; set; } = Empty;
/// <summary>
/// Packaging problems that are not cap skips, per kind: <c>path-guard</c> (configured path
/// refused), <c>no-user-session</c> (user-profile token without a signed-in user),
/// <c>folder-rejected</c>, <c>enumerate</c>, <c>open</c>, <c>copy</c>.
/// </summary>
public IReadOnlyDictionary<string, int> ProblemsByKind { get; set; } = Empty;
}
/// <summary>
@@ -134,6 +172,41 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
Skipped.Add(new SkipRecord(path, reason, size));
public bool HasSkips => Skipped.Count > 0;
// Non-cap problems (guard refusals, enumeration/open/copy failures) by kind — the
// manifest names the files, the event carries only these counts.
public Dictionary<string, int> Problems { get; } = new Dictionary<string, int>(StringComparer.Ordinal);
private readonly HashSet<string> _problemKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Counts one problem of <paramref name="kind"/>. A section is walked once per search
/// pattern, so a folder-level failure would otherwise be counted once per pattern —
/// pass the folder as <paramref name="dedupeKey"/> to count it once.
/// </summary>
public void RecordProblem(string kind, string dedupeKey = null)
{
if (dedupeKey != null && !_problemKeys.Add(kind + "|" + dedupeKey)) return;
Problems.TryGetValue(kind, out var n);
Problems[kind] = n + 1;
}
public DiagnosticsPackagingStats ToStats()
{
var byReason = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var s in Skipped)
{
byReason.TryGetValue(s.Reason, out var n);
byReason[s.Reason] = n + 1;
}
return new DiagnosticsPackagingStats
{
IncludedFiles = FileCount,
IncludedBytes = TotalBytes,
SkippedFiles = Skipped.Count,
SkippedByReason = byReason,
ProblemsByKind = new Dictionary<string, int>(Problems, StringComparer.Ordinal),
};
}
}
private readonly struct SkipRecord
@@ -262,6 +335,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
var zipFileName = $"AgentDiagnostics-{_configuration.SessionId}-{timestamp}{suffix}.zip";
var zipBytes = BuildArchiveBytes(enrollmentSucceeded);
var packaging = LastPackaging;
_logger.Info($"Diagnostics package created: {zipFileName} ({zipBytes.Length / 1024} KB)");
@@ -276,7 +350,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
{
var errorCode = uploadUrlResponse?.Message ?? "Failed to get diagnostics upload URL from backend";
_logger.Warning($"Failed to get diagnostics upload URL from backend — skipping upload: {errorCode}");
return new DiagnosticsUploadResult { ErrorCode = errorCode };
return new DiagnosticsUploadResult { ErrorCode = errorCode, Packaging = packaging };
}
var sasUrlPrefix = BuildSasUrlPrefix(uploadUrlResponse.UploadUrl);
@@ -305,6 +379,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
BlobName = persistedBlobName,
Destination = uploadUrlResponse.Destination,
SasUrlPrefix = sasUrlPrefix,
Packaging = packaging,
};
}
@@ -313,6 +388,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
Destination = uploadUrlResponse.Destination,
SasUrlPrefix = sasUrlPrefix,
ErrorCode = uploadErrorCode,
Packaging = packaging,
};
}
catch (Exception ex)
@@ -351,6 +427,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
// INSIDE the ZIP (field case: sessions a11102f4 / 3ae7528b, missing evtx undiagnosable).
private StringBuilder _manifest;
/// <summary>Counters of the most recent <see cref="BuildArchiveBytes"/>; null before the first build.</summary>
internal DiagnosticsPackagingStats LastPackaging { get; private set; }
private void ManifestLine(string text)
{
_manifest?.AppendLine($"[{DateTime.UtcNow:HH:mm:ss.fff}Z] {text}");
@@ -391,6 +470,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
{
_logger.Warning($"Diagnostics path blocked by guard: {entry.Path}");
ManifestLine($"BLOCKED (path guard): {entry.Path}");
tracker.RecordProblem("path-guard");
continue;
}
var expandedPath = UserProfileResolver.ExpandCustomTokens(entry.Path);
@@ -398,6 +478,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
{
_logger.Warning($"Diagnostics path skipped (no user session for token): {entry.Path}");
ManifestLine($"SKIPPED (no user session for token): {entry.Path}");
tracker.RecordProblem("no-user-session");
continue;
}
var folder = Path.GetDirectoryName(expandedPath);
@@ -427,6 +508,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
WriteTruncatedMarker(archive, tracker);
}
LastPackaging = tracker.ToStats();
return ms.ToArray();
}
}
@@ -498,6 +580,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
{
_logger.Warning($"Built-in diagnostics section skipped (no user session for token): {section.Id}");
ManifestLine($"BUILT-IN SKIPPED (no user session for token): {section.Id} '{section.SourceFolder}'");
tracker.RecordProblem("no-user-session");
return;
}
@@ -584,6 +667,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
{
_logger.Warning($"Diagnostics source folder rejected ({folderRejection}): {sourceFolder}");
ManifestLine($"FOLDER REJECTED ({folderRejection}): {sourceFolder} (pattern '{searchPattern}')");
tracker.RecordProblem("folder-rejected", sourceFolder);
}
return;
}
@@ -597,6 +681,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
{
_logger.Warning($"Failed to enumerate log files in {sourceFolder}: {ex.Message}");
ManifestLine($"ENUMERATION FAILED: {sourceFolder} (pattern '{searchPattern}'): {ex.Message}");
tracker.RecordProblem("enumerate", sourceFolder);
return;
}
@@ -681,6 +766,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
{
_logger.Warning($"Failed to add log file to diagnostics package: {file} - {ex.Message}");
ManifestLine($"FAILED (copy): {file}: {ex.Message}");
tracker.RecordProblem("copy");
}
finally
{
@@ -720,6 +806,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
default:
_logger.Warning($"Failed to open {file}: {rejection}");
ManifestLine($"FAILED (open): {file}: {rejection}");
tracker.RecordProblem("open");
break;
}
return null;
@@ -278,6 +278,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
data["logFile"] = Path.GetFileName(filePath);
data["ruleId"] = rule.RuleId;
data["ruleTitle"] = rule.Title;
GatherRuleExecutor.StampRuleMarkers(rule, data);
var eventType = !string.IsNullOrEmpty(rule.OutputEventType)
? rule.OutputEventType
@@ -347,6 +348,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather.Collectors
data["logFile"] = Path.GetFileName(filePath);
data["ruleId"] = rule.RuleId;
data["ruleTitle"] = rule.Title;
GatherRuleExecutor.StampRuleMarkers(rule, data);
var eventType = !string.IsNullOrEmpty(rule.OutputEventType)
? rule.OutputEventType
@@ -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.
@@ -26,7 +26,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
/// emits (executor, context guard events, collectors). The timeline feed uses it to keep
/// gather output from re-triggering on_event rules.
/// </summary>
public const string SourceName = "GatherRuleExecutor";
public const string SourceName = Constants.EventSources.GatherRuleExecutor;
/// <summary>
/// Upper bound on on_event executions per rule and session. on_event has no natural
@@ -496,6 +496,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
result["ruleId"] = rule.RuleId;
result["ruleTitle"] = rule.Title;
StampRuleMarkers(rule, result);
var eventType = !string.IsNullOrEmpty(rule.OutputEventType) ? rule.OutputEventType : Constants.EventTypes.GatherResult;
@@ -537,6 +538,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
// ===== Phase scope (ActivePhases / ActiveFromPhase) =====
/// <summary>
/// Injects the per-rule opt-in markers the backend reads at response time. Called after
/// the on_change hash is taken (the markers are rule config, not collected data) by the
/// executor and by collectors that emit directly (logparser).
/// </summary>
internal static void StampRuleMarkers(GatherRule rule, Dictionary<string, object> data)
{
if (rule.EnrichErrorCodes)
data[Constants.GatherRuleDataKeys.EnrichErrorCodes] = true;
}
private static bool HasPhaseScope(GatherRule rule)
{
return (rule.ActivePhases != null && rule.ActivePhases.Count > 0)
@@ -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
/// &lt;profile&gt;\&lt;relativePrefix&gt;. 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>
@@ -1628,6 +1628,15 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
if (app.AttemptNumber > 0) data["attemptNumber"] = app.AttemptNumber.ToString(culture);
if (!string.IsNullOrEmpty(app.DetectionResult)) data["detectionResult"] = app.DetectionResult!;
// Installer outcome of the last attempt (IME-EXITCODE + IME-EXITCODE-CLASS). The class
// is the admin's return-code mapping (Success/SoftReboot/HardReboot/Retry/Failed) and
// the only evidence that an app asked for a reboot; the number says which code was
// mapped (3010 vs 1641 vs custom). Both are known from the terminal lpExitCode lines
// only, so they surface on the terminal events - completed, postponed, skipped and
// failed alike - never on progress events.
if (!string.IsNullOrEmpty(app.ExitCodeClass)) data["exitCodeClass"] = app.ExitCodeClass!;
if (IsCompletedState(newState) && !string.IsNullOrEmpty(app.ExitCode)) data["exitCode"] = app.ExitCode!;
// Plan §5 Fix 4c — per-app install-lifecycle timing. StartedAt appears on the
// first Downloading/Installing/InProgress event; CompletedAt + DurationSeconds
// light up on the terminal event. Values are omitted when not yet known so the
@@ -1644,7 +1653,6 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
if (!string.IsNullOrEmpty(app.ErrorPatternId)) data["errorPatternId"] = app.ErrorPatternId!;
if (!string.IsNullOrEmpty(app.ErrorDetail)) data["errorDetail"] = app.ErrorDetail!;
if (!string.IsNullOrEmpty(app.ErrorCode)) data["errorCode"] = app.ErrorCode!;
if (!string.IsNullOrEmpty(app.ExitCode)) data["exitCode"] = app.ExitCode!;
if (!string.IsNullOrEmpty(app.HResultFromWin32)) data["hresultFromWin32"] = app.HResultFromWin32!;
// Likely-stuck / detection-failure / install-failure classification: when the
@@ -4,6 +4,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
using AutopilotMonitor.DecisionCore.Signals;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Agent.V2.Core.Telemetry.Signals
{
@@ -4,6 +4,7 @@ using AutopilotMonitor.Agent.V2.Core.Transport.Telemetry;
using AutopilotMonitor.DecisionCore.Engine;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Agent.V2.Core.Telemetry.Transitions
{
@@ -1007,6 +1007,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
if (result != null && result.Success)
{
_logger.Info($"EnrollmentTerminationHandler: diagnostics uploaded (blob={result.BlobName}).");
var data = new Dictionary<string, object>
{
{ "blobName", result.BlobName ?? string.Empty },
// Tells the backend which storage the blob landed in so it can
// stamp Session.DiagnosticsBlobDestination and route downloads
// even after a future tenant destination switch. Empty when the
// backend predates the field (agent falls through harmlessly).
{ "destination", result.Destination ?? string.Empty },
{ "sasUrlPrefix", result.SasUrlPrefix ?? string.Empty },
};
AppendPackagingStats(data, result.Packaging);
EmitEventSafe(new EnrollmentEvent
{
SessionId = _configuration.SessionId,
@@ -1015,17 +1026,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
Severity = EventSeverity.Info,
Source = "EnrollmentTerminationHandler",
Phase = EnrollmentPhase.Unknown,
Message = $"Diagnostics package uploaded ({result.BlobName}).",
Data = new Dictionary<string, object>
{
{ "blobName", result.BlobName ?? string.Empty },
// Tells the backend which storage the blob landed in so it can
// stamp Session.DiagnosticsBlobDestination and route downloads
// even after a future tenant destination switch. Empty when the
// backend predates the field (agent falls through harmlessly).
{ "destination", result.Destination ?? string.Empty },
{ "sasUrlPrefix", result.SasUrlPrefix ?? string.Empty },
},
Message = $"Diagnostics package uploaded ({result.BlobName})."
+ (result.Packaging != null && result.Packaging.Truncated
? $" Truncated: {result.Packaging.SkippedFiles} file(s) skipped by the packaging caps."
: string.Empty),
Data = data,
ImmediateUpload = true,
});
}
@@ -1033,6 +1038,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
{
var errorCode = result?.ErrorCode ?? "null-result";
_logger.Warning($"EnrollmentTerminationHandler: diagnostics upload failed: {errorCode}.");
var data = new Dictionary<string, object>
{
{ "errorCode", errorCode },
{ "blobName", result?.BlobName ?? string.Empty },
{ "destination", result?.Destination ?? string.Empty },
};
AppendPackagingStats(data, result?.Packaging);
EmitEventSafe(new EnrollmentEvent
{
SessionId = _configuration.SessionId,
@@ -1042,17 +1054,30 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
Source = "EnrollmentTerminationHandler",
Phase = EnrollmentPhase.Unknown,
Message = $"Diagnostics upload failed: {errorCode}.",
Data = new Dictionary<string, object>
{
{ "errorCode", errorCode },
{ "blobName", result?.BlobName ?? string.Empty },
{ "destination", result?.Destination ?? string.Empty },
},
Data = data,
ImmediateUpload = true,
});
}
}
/// <summary>
/// Adds the packager's counters to a diagnostics event payload — counts only, never a
/// file path (paths live in the ZIP's manifest and may carry user names). Absent when no
/// package was built, so consumers treat the keys as optional.
/// </summary>
private static void AppendPackagingStats(Dictionary<string, object> data, DiagnosticsPackagingStats packaging)
{
if (packaging == null) return;
data["truncated"] = packaging.Truncated;
data["includedFiles"] = packaging.IncludedFiles;
data["includedBytes"] = packaging.IncludedBytes;
data["skippedFiles"] = packaging.SkippedFiles;
data["skippedByReason"] = new Dictionary<string, int>(
(IDictionary<string, int>)packaging.SkippedByReason ?? new Dictionary<string, int>(), StringComparer.Ordinal);
data["problemsByKind"] = new Dictionary<string, int>(
(IDictionary<string, int>)packaging.ProblemsByKind ?? new Dictionary<string, int>(), StringComparer.Ordinal);
}
private void WriteEnrollmentCompleteMarker(EnrollmentTerminatedEventArgs args)
{
// On WhiteGlove Part 1 exit we keep the session alive for Part 2 — DO NOT write the
@@ -395,12 +395,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
}
}
private static string SerializeBatch(IReadOnlyList<TelemetryItem> items)
/// <summary>
/// The batch body: a JSON array of <see cref="TelemetryItemDto"/> — the Shared class the
/// ingest deserialises — with Newtonsoft defaults (PascalCase, ISO-8601 UTC, Kind by name).
/// Internal so <c>TelemetryWireContractTests</c> can freeze the real output as a fixture.
/// </summary>
internal static string SerializeBatch(IReadOnlyList<TelemetryItem> items)
{
// Newtonsoft PascalCase default + TelemetryItemKind carries [StringEnumConverter] →
// Backend routes by string "Event"/"Signal"/"DecisionTransition". Wire-format
// matches Plan §4.x M5 contract (PascalCase, StringEnum, ISO-8601 UTC).
return JsonConvert.SerializeObject(items, Formatting.None);
var wire = new TelemetryItemDto[items.Count];
for (var i = 0; i < items.Count; i++) wire[i] = items[i].ToWire();
return JsonConvert.SerializeObject(wire, Formatting.None);
}
private static byte[] CompressWithGzip(string text)
@@ -1,5 +1,6 @@
#nullable enable
using System;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
{
@@ -106,6 +107,26 @@ namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
/// <summary>Anzahl der bisher fehlgeschlagenen Upload-Versuche. Wird vom Orchestrator incrementiert.</summary>
public int RetryCount { get; }
/// <summary>
/// The wire shape of this item. <see cref="TelemetryItemDto"/> (Shared) is the ONE class both
/// ends serialise; this mapping is the only place the agent's validated model meets it.
/// <c>TelemetryWireContractTests</c> proves every DTO property is populated here and
/// freezes the resulting body under <c>tests/fixtures/telemetry-wire/</c> for the backend.
/// </summary>
public TelemetryItemDto ToWire() =>
new TelemetryItemDto
{
Kind = Kind.ToString(),
PartitionKey = PartitionKey,
RowKey = RowKey,
TelemetryItemId = TelemetryItemId,
SessionTraceOrdinal = SessionTraceOrdinal,
PayloadJson = PayloadJson,
RequiresImmediateFlush = RequiresImmediateFlush,
EnqueuedAtUtc = EnqueuedAtUtc,
RetryCount = RetryCount,
};
/// <summary>Copy-with-incremented <see cref="RetryCount"/>. Immutable-Erhalt (§2.3 L.3).</summary>
public TelemetryItem WithRetryIncremented() =>
new TelemetryItem(
@@ -1,5 +1,6 @@
#nullable enable
using System;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
{
@@ -1,29 +0,0 @@
#nullable enable
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
{
/// <summary>
/// Typ eines <see cref="TelemetryItem"/>. Plan §2.7a / L.10.
/// <para>
/// Drei getrennte Backend-Tabellen:
/// <see cref="Event"/> → <c>Events</c>,
/// <see cref="Signal"/> → <c>Signals</c>,
/// <see cref="DecisionTransition"/> → <c>DecisionTransitions</c>.
/// Der generische Transport routet auf Backend-Seite nach <c>Kind</c>.
/// </para>
/// <para>
/// String-serialisiert via <see cref="StringEnumConverter"/> — Backend-Routing darf
/// nicht von Integer-Ordering abhängen, das bei zukünftigen Erweiterungen bricht
/// (L.14 forward-compat).
/// </para>
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum TelemetryItemKind
{
Event = 0,
Signal,
DecisionTransition,
}
}
@@ -2,6 +2,7 @@
using System;
using AutopilotMonitor.DecisionCore.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
{
@@ -16,10 +17,25 @@ namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
/// </summary>
public static class TelemetryItemSerializer
{
/// <summary>
/// DecisionCore settings plus a <see cref="StringEnumConverter"/>: <see cref="TelemetryItem.Kind"/>
/// is the only enum on a spool line and has always been written by NAME (<c>"Event"</c>),
/// which is also what the wire carries. The enum lives in Shared (no Newtonsoft there), so
/// the converter is registered here instead of as an attribute on the type.
/// </summary>
private static readonly JsonSerializerSettings SpoolSettings = CreateSpoolSettings();
private static JsonSerializerSettings CreateSpoolSettings()
{
var settings = DecisionCoreJsonSettings.Create();
settings.Converters.Add(new StringEnumConverter());
return settings;
}
public static string Serialize(TelemetryItem item)
{
if (item == null) throw new ArgumentNullException(nameof(item));
return JsonConvert.SerializeObject(item, DecisionCoreJsonSettings.Shared);
return JsonConvert.SerializeObject(item, SpoolSettings);
}
public static TelemetryItem Deserialize(string line)
@@ -28,7 +44,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Transport.Telemetry
try
{
var result = JsonConvert.DeserializeObject<TelemetryItem>(line, DecisionCoreJsonSettings.Shared);
var result = JsonConvert.DeserializeObject<TelemetryItem>(line, SpoolSettings);
if (result == null)
{
throw new JsonSerializationException($"TelemetryItem deserialization produced null: {line}");
@@ -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="&quot;[System64Folder]WindowsPowerShell\v1.0\powershell.exe&quot; -NoProfile -ExecutionPolicy Bypass -File &quot;[INSTALLFOLDER]Invoke-BootstrapDownload.ps1&quot;"
ExeCommand="&quot;[System64Folder]WindowsPowerShell\v1.0\powershell.exe&quot; -NoProfile -ExecutionPolicy Bypass -File &quot;[INSTALLFOLDER]Start-AutopilotMonitor.ps1&quot; -LogFileName bootstrap-msi.log"
Execute="deferred"
Impersonate="no"
Return="ignore" />
@@ -11,9 +11,8 @@ namespace AutopilotMonitor.DecisionCore.Tests.State
{
/// <summary>
/// Every payload-derived string that lands in <see cref="DecisionState"/> is bounded by
/// <see cref="FactStringBounds"/> at the reducer boundary. The server-side semantic replay
/// (<c>ReducerVerifier</c>) folds device-uploaded payloads through the same engine, so an
/// unbounded string there is a per-request memory/CPU amplifier. These tests pin that the
/// <see cref="FactStringBounds"/> at the reducer boundary — an unbounded string there is a
/// per-signal memory/CPU amplifier in every snapshot persist. These tests pin that the
/// bound is applied BEFORE any dedupe comparison (so a forged multi-hundred-KB key neither
/// costs a full-length compare nor lands in state) and that real-sized values pass through
/// unchanged.
@@ -1,34 +0,0 @@
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// Default-value + round-trip tests for <see cref="AdminConfiguration.EnableIndexDualWrite"/>
/// (Plan §M5.d). The flag gates the index-table dual-write rollout — defaulting to false
/// keeps pre-M5.d behaviour bit-exact and lets operators flip it on deliberately.
/// </summary>
public class AdminConfigurationEnableIndexDualWriteTests
{
[Fact]
public void EnableIndexDualWrite_defaults_to_false_on_new_config()
{
var cfg = new AdminConfiguration();
Assert.False(cfg.EnableIndexDualWrite);
}
[Fact]
public void EnableIndexDualWrite_defaults_to_false_on_CreateDefault()
{
// CreateDefault() is called when no admin-config row exists yet — if it somehow
// enabled dual-write it would break the "default-off" contract immediately.
var cfg = AdminConfiguration.CreateDefault();
Assert.False(cfg.EnableIndexDualWrite);
}
[Fact]
public void EnableIndexDualWrite_true_persists_on_the_config()
{
var cfg = new AdminConfiguration { EnableIndexDualWrite = true };
Assert.True(cfg.EnableIndexDualWrite);
}
}
@@ -0,0 +1,189 @@
using System;
using System.Collections.Generic;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.Models;
using Xunit;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// Pins the derivation shared by the agent channel (GET agent/config) and the Global-Admin
/// report route (GET config/{tenantId}/effective-agent-config): every rule the Tenant Config
/// Report used to re-implement in the web now has exactly one implementation, and these
/// facts are its contract.
/// </summary>
public class AgentConfigResolverTests
{
private const string TenantId = "11111111-2222-3333-4444-555555555555";
private static readonly DateTime Now = new(2026, 9, 6, 12, 0, 0, DateTimeKind.Utc);
private static TenantConfiguration Tenant(Action<TenantConfiguration>? mutate = null)
{
var c = new TenantConfiguration { TenantId = TenantId, DomainName = "contoso.example", UpdatedBy = "ga@operator.example" };
mutate?.Invoke(c);
return c;
}
private static AdminConfiguration Admin(Action<AdminConfiguration>? mutate = null)
{
var a = new AdminConfiguration();
mutate?.Invoke(a);
return a;
}
private static AgentConfigResponse Build(TenantConfiguration tenant, AdminConfiguration? admin = null, int agentMajor = AgentConfigResolver.CurrentAgentMajor)
=> AgentConfigResolver.Build(tenant, admin ?? Admin(), new List<GatherRule>(), new List<ImeLogPattern>(), agentMajor, Now).Response;
[Fact]
public void Fresh_tenant_gets_the_agent_defaults()
{
var r = Build(Tenant());
Assert.Equal(AgentConfigResolver.ConfigVersion, r.ConfigVersion);
Assert.Equal(AutopilotMonitor.Shared.Constants.DefaultUploadIntervalSeconds, r.UploadIntervalSeconds);
Assert.Equal(10, r.UploadIntervalSeconds); // the report showed 30 for a month — pinned
Assert.True(r.SelfDestructOnComplete);
Assert.False(r.KeepLogFile);
Assert.True(r.EnableGeoLocation);
Assert.Equal(5, r.MaxAuthFailures);
Assert.Equal(0, r.AuthFailureTimeoutMinutes);
Assert.Equal("Info", r.LogLevel);
Assert.Equal(10, r.RebootDelaySeconds);
Assert.Equal(60, r.EnrollmentSummaryTimeoutSeconds);
Assert.Equal(120, r.EnrollmentSummaryLaunchRetrySeconds);
Assert.Equal(100, r.MaxBatchSize);
Assert.Equal("time.windows.com", r.NtpServer);
Assert.Equal("Off", r.DiagnosticsUploadMode);
Assert.False(r.DiagnosticsUploadEnabled);
Assert.False(r.UnrestrictedMode);
Assert.False(r.DeviceBlocked);
Assert.False(r.DeviceKillSignal);
Assert.Null(r.UnblockAt);
Assert.Null(r.MigrateToApiBaseUrl);
Assert.Equal(360, r.Collectors.AgentMaxLifetimeMinutes);
Assert.Equal(15, r.Collectors.CollectorIdleTimeoutMinutes);
Assert.Equal(10, r.Collectors.DesktopDetectorNoCandidateTimeoutMinutes);
Assert.Equal(new[] { 100, 1005, 1010 }, r.Collectors.ModernDeploymentHarmlessEventIds);
Assert.True(r.Analyzers.EnableLocalAdminAnalyzer);
Assert.Empty(r.Analyzers.LocalAdminAllowedAccounts);
Assert.False(r.Analyzers.EnableSoftwareInventoryAnalyzer);
Assert.True(r.Analyzers.EnableIntegrityBypassAnalyzer);
Assert.False(r.Analyzers.EnableRealmJoinWatcher);
Assert.False(r.Analyzers.KeepAwakeDuringUserEsp);
Assert.True(r.Analyzers.EnableConsoleBypassDetection);
}
[Theory]
[InlineData(null, "CustomerSas", "Off", false)]
[InlineData(null, "Hosted", "Off", true)] // hosted destination needs no SAS
[InlineData("https://acct.blob.core.windows.net/c?sv=1", "CustomerSas", "Off", true)] // SAS enables regardless of mode
public void Diagnostics_upload_enabled_follows_sas_or_hosted_not_the_mode(string? sas, string destination, string mode, bool expected)
{
var r = Build(Tenant(t =>
{
t.DiagnosticsBlobSasUrl = sas!;
t.DiagnosticsUploadDestination = destination;
t.DiagnosticsUploadMode = mode;
}));
Assert.Equal(expected, r.DiagnosticsUploadEnabled);
}
[Theory]
[InlineData("free", true, true, false)] // Community: entitlement missing
[InlineData("pro", false, true, false)] // GA gate off
[InlineData("pro", true, false, false)] // tenant toggle off
[InlineData("pro", true, true, true)]
public void Unrestricted_mode_needs_entitlement_and_gate_and_toggle(string planTier, bool gaGate, bool toggle, bool expected)
{
var r = Build(Tenant(t =>
{
t.PlanTier = planTier;
t.UnrestrictedModeEnabled = gaGate;
t.UnrestrictedMode = toggle;
}));
Assert.Equal(expected, r.UnrestrictedMode);
}
[Fact]
public void Operator_knobs_come_from_the_admin_configuration()
{
var admin = Admin(a =>
{
a.CollectorIdleTimeoutMinutes = 25;
a.DesktopDetectorNoCandidateTimeoutMinutes = 7;
a.AllowAgentDowngrade = true;
a.ModernDeploymentHarmlessEventIdsJson = "[100, 42]";
a.LatestAgentV2Sha256 = "zip-v2";
a.LatestAgentV2ExeSha256 = "exe-v2";
});
var r = Build(Tenant(), admin);
Assert.Equal(25, r.Collectors.CollectorIdleTimeoutMinutes);
Assert.Equal(7, r.Collectors.DesktopDetectorNoCandidateTimeoutMinutes);
Assert.True(r.AllowAgentDowngrade);
Assert.Equal(new[] { 100, 42 }, r.Collectors.ModernDeploymentHarmlessEventIds);
Assert.Equal("zip-v2", r.LatestAgentSha256);
Assert.Equal("exe-v2", r.LatestAgentExeSha256);
}
[Fact]
public void Legacy_major_gets_empty_hashes_the_current_major_gets_v2()
{
var admin = Admin(a => { a.LatestAgentV2Sha256 = "zip-v2"; a.LatestAgentV2ExeSha256 = "exe-v2"; });
var legacy = Build(Tenant(), admin, agentMajor: 1);
Assert.Equal(string.Empty, legacy.LatestAgentSha256);
var current = Build(Tenant(), admin, agentMajor: AgentConfigResolver.CurrentAgentMajor);
Assert.Equal("zip-v2", current.LatestAgentSha256);
}
[Fact]
public void Tenant_overrides_win_over_defaults()
{
var r = Build(Tenant(t =>
{
t.MaxBatchSize = 25;
t.LogLevel = "Debug";
t.NtpServer = "";
t.LocalAdminAllowedAccountsJson = "[\"Admin\",\"Helpdesk\"]";
t.AgentMaxLifetimeMinutes = 120;
t.EnableConsoleBypassDetection = false;
}));
Assert.Equal(25, r.MaxBatchSize);
Assert.Equal("Debug", r.LogLevel);
Assert.Equal("time.windows.com", r.NtpServer); // empty string falls back like null
Assert.Equal(new[] { "Admin", "Helpdesk" }, r.Analyzers.LocalAdminAllowedAccounts);
Assert.Equal(120, r.Collectors.AgentMaxLifetimeMinutes);
Assert.False(r.Analyzers.EnableConsoleBypassDetection);
}
[Fact]
public void Migration_target_is_served_when_valid_and_reported_when_rejected()
{
const string Us = "https://autopilotmonitor-api-us.azurewebsites.net";
var served = AgentConfigResolver.Build(Tenant(), Admin(a => a.AgentMigrateApiBaseUrl = Us),
new List<GatherRule>(), new List<ImeLogPattern>(), AgentConfigResolver.CurrentAgentMajor, Now);
Assert.Equal(Us, served.Response.MigrateToApiBaseUrl);
Assert.Null(served.RejectedMigrateCandidate);
var rejected = AgentConfigResolver.Build(Tenant(), Admin(a => a.AgentMigrateApiBaseUrl = "https://evil.example"),
new List<GatherRule>(), new List<ImeLogPattern>(), AgentConfigResolver.CurrentAgentMajor, Now);
Assert.Null(rejected.Response.MigrateToApiBaseUrl);
Assert.Equal("https://evil.example", rejected.RejectedMigrateCandidate);
}
[Fact]
public void Catalogs_pass_through_unchanged()
{
var rules = new List<GatherRule> { new() { RuleId = "GATHER-TEST-001" } };
var patterns = new List<ImeLogPattern> { new() { PatternId = "IME-TEST-001" } };
var r = AgentConfigResolver.Build(Tenant(), Admin(), rules, patterns, AgentConfigResolver.CurrentAgentMajor, Now).Response;
Assert.Same(rules, r.GatherRules);
Assert.Same(patterns, r.ImeLogPatterns);
}
}
@@ -4,6 +4,7 @@ using AutopilotMonitor.Shared.Models;
using AutopilotMonitor.Shared.Pagination;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using System.Threading;
namespace AutopilotMonitor.Functions.Tests;
@@ -21,7 +22,7 @@ public class AgentEfficiencyMetricsServiceTests
{
var repo = new Mock<ISessionRepository>();
repo
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new RawPage<SessionSummary>(new List<SessionSummary>(), null));
repo
.Setup(r => r.GetSessionEventsByTypesAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IReadOnlyCollection<string>>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<int>()))
@@ -67,7 +68,7 @@ public class AgentEfficiencyMetricsServiceTests
private static void SetupSessions(Mock<ISessionRepository> repo, List<SessionSummary> sessions)
{
repo
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new RawPage<SessionSummary>(sessions, null));
}
@@ -201,8 +202,8 @@ public class AgentEfficiencyMetricsServiceTests
string? capturedTenant = null;
IEnumerable<string>? capturedSelect = null;
repo
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?>((t, _, _, _, _, sel) => { capturedTenant = t; capturedSelect = sel; })
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
.Callback<string?, int?, int, string?, IReadOnlyCollection<string>?, IEnumerable<string>?, CancellationToken>((t, _, _, _, _, sel, _) => { capturedTenant = t; capturedSelect = sel; })
.ReturnsAsync(new RawPage<SessionSummary>(new List<SessionSummary>(), null));
var result = await service.ComputeAsync(days: 45, limit: 100, tenantId: Tenant);
@@ -220,7 +221,7 @@ public class AgentEfficiencyMetricsServiceTests
var (service, repo) = CreateService();
int callCount = 0;
repo
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>()))
.Setup(r => r.GetAllSessionsPageAsync(It.IsAny<string?>(), It.IsAny<int?>(), It.IsAny<int>(), It.IsAny<string?>(), It.IsAny<IReadOnlyCollection<string>?>(), It.IsAny<IEnumerable<string>?>(), It.IsAny<CancellationToken>()))
.Callback(() => callCount++)
.ReturnsAsync(new RawPage<SessionSummary>(new List<SessionSummary>(), null));
@@ -1,4 +1,4 @@
using AutopilotMonitor.Functions.Functions.Config;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.Models;
using AutopilotMonitor.Shared.Services;
using Xunit;
@@ -8,7 +8,7 @@ namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// Pins the endpoint-migration serving contract: the shared allowlist rules
/// (<see cref="AgentEndpointMigrationRules"/>, used verbatim by the agent too) and the
/// backend-side per-tenant resolution (<see cref="GetAgentConfigFunction.ResolveMigrateTarget"/> —
/// backend-side per-tenant resolution (<see cref="AgentConfigResolver.ResolveMigrateTarget"/> —
/// tenant override wins, empty override pins, invalid values are never served).
/// </summary>
public class AgentEndpointMigrationTests
@@ -75,7 +75,7 @@ public class AgentEndpointMigrationTests
{
var config = new AdminConfiguration();
Assert.Null(GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out var rejected));
Assert.Null(AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out var rejected));
Assert.Null(rejected);
}
@@ -84,8 +84,8 @@ public class AgentEndpointMigrationTests
{
var config = new AdminConfiguration { AgentMigrateApiBaseUrl = UsUrl };
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantB, out _));
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantB, out _));
}
[Fact]
@@ -97,8 +97,8 @@ public class AgentEndpointMigrationTests
AgentMigrateTenantOverridesJson = $"{{\"{TenantA}\": \"{EuUrl}\"}}"
};
Assert.Equal(EuUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantB, out _));
Assert.Equal(EuUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantB, out _));
}
[Fact]
@@ -110,9 +110,9 @@ public class AgentEndpointMigrationTests
AgentMigrateTenantOverridesJson = $"{{\"{TenantA}\": \"\"}}"
};
Assert.Null(GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out var rejected));
Assert.Null(AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out var rejected));
Assert.Null(rejected); // pinned, not rejected
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantB, out _));
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantB, out _));
}
[Fact]
@@ -123,7 +123,7 @@ public class AgentEndpointMigrationTests
AgentMigrateTenantOverridesJson = $"{{\"{TenantA.ToUpperInvariant()}\": \"{UsUrl}\"}}"
};
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
}
[Fact]
@@ -131,7 +131,7 @@ public class AgentEndpointMigrationTests
{
var config = new AdminConfiguration { AgentMigrateApiBaseUrl = "https://attacker.example.com" };
Assert.Null(GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out var rejected));
Assert.Null(AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out var rejected));
Assert.Equal("https://attacker.example.com", rejected);
}
@@ -144,7 +144,7 @@ public class AgentEndpointMigrationTests
AgentMigrateTenantOverridesJson = "{not json"
};
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
}
[Fact]
@@ -155,6 +155,6 @@ public class AgentEndpointMigrationTests
AgentMigrateApiBaseUrl = "https://AutopilotMonitor-API-US.azurewebsites.net/"
};
Assert.Equal(UsUrl, GetAgentConfigFunction.ResolveMigrateTarget(config, TenantA, out _));
Assert.Equal(UsUrl, AgentConfigResolver.ResolveMigrateTarget(config, TenantA, out _));
}
}
@@ -6,7 +6,7 @@ namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// JSON round-trip tests for <see cref="AnalyzeOnEnrollmentEndEnvelope"/>. The producer
/// (<c>AzureQueueAnalyzeOnEnrollmentEndProducer</c>) serializes with Newtonsoft and the
/// queue worker (<c>AnalyzeOnEnrollmentEndQueueWorker</c>) deserializes the same shape —
/// queue worker (<c>AnalyzeOnEnrollmentEndQueueFunction</c>) deserializes the same shape —
/// pinning the contract here keeps the queue from silently breaking when fields are added.
/// </summary>
public class AnalyzeOnEnrollmentEndEnvelopeSerializationTests
@@ -0,0 +1,103 @@
using System.Net;
using System.Text.Json;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Shared;
using AutopilotMonitor.Shared.Models;
using Microsoft.AspNetCore.Http;
using Xunit;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// The middleware-side error-envelope writer: status, content type, Retry-After and the exact body
/// (production wire options — camelCase, absent-when-null) for the generic envelope and for a
/// specialised <see cref="IApiErrorResponse"/>. Whatever the authentication, policy, rate-limit and
/// quota middlewares write flows through here, so this is the one place their body shape is pinned.
/// </summary>
public class ApiErrorWriterTests
{
[Fact]
public async Task Generic_envelope_writes_status_content_type_and_the_three_prefix_keys()
{
var ctx = NewContext();
await ApiErrorWriter.WriteAsync(ctx, "cid-42", HttpStatusCode.Unauthorized,
Constants.ApiErrorCodes.AuthenticationRequired, "Authentication required.");
Assert.Equal(401, ctx.Response.StatusCode);
Assert.StartsWith("application/json", ctx.Response.ContentType);
Assert.False(ctx.Response.Headers.ContainsKey("Retry-After"));
Assert.Equal(
"{\"error\":\"Authentication required.\",\"code\":\"AuthenticationRequired\",\"correlationId\":\"cid-42\"}",
Body(ctx));
}
[Fact]
public async Task Generic_envelope_with_retry_window_sets_the_header_and_mirrors_it_in_the_body()
{
var ctx = NewContext();
await ApiErrorWriter.WriteAsync(ctx, "cid-7", HttpStatusCode.TooManyRequests,
Constants.ApiErrorCodes.RateLimited, "Rate limit exceeded: 60 requests per minute",
retryAfterSeconds: 23);
Assert.Equal(429, ctx.Response.StatusCode);
Assert.Equal("23", ctx.Response.Headers["Retry-After"]);
Assert.Equal(
"{\"error\":\"Rate limit exceeded: 60 requests per minute\",\"code\":\"RateLimited\",\"correlationId\":\"cid-7\",\"retryAfterSeconds\":23}",
Body(ctx));
}
[Fact]
public async Task Generic_envelope_carries_hint_and_operation_only_when_given()
{
var ctx = NewContext();
await ApiErrorWriter.WriteAsync(ctx, "cid-9", HttpStatusCode.InternalServerError,
Constants.ApiErrorCodes.InternalError, "QueryTable failed.",
hint: "Retry with a narrower filter.", operation: "QueryTable");
Assert.Equal(
"{\"error\":\"QueryTable failed.\",\"code\":\"InternalError\",\"correlationId\":\"cid-9\"," +
"\"hint\":\"Retry with a narrower filter.\",\"operation\":\"QueryTable\"}",
Body(ctx));
}
[Fact]
public async Task Specialised_body_is_stamped_with_the_correlation_id_and_serialized_as_its_runtime_type()
{
var ctx = NewContext();
var body = new DelegatedSlotLimitReachedResponse
{
Error = "Slot limit reached.",
HomeTenantId = "7aa20c11-0002-4b7c-a1d2-52f3aaaa0001",
Used = 2,
Limit = 2,
Required = 1,
};
await ApiErrorWriter.WriteAsync(ctx, "cid-slot", HttpStatusCode.Conflict, body);
Assert.Equal(409, ctx.Response.StatusCode);
Assert.Equal("cid-slot", body.CorrelationId);
var json = JsonDocument.Parse(Body(ctx)).RootElement;
// Envelope prefix first, then the specialised fields — and nothing of the marker interface.
var keys = json.EnumerateObject().Select(p => p.Name).ToArray();
Assert.Equal(new[] { "error", "code", "correlationId", "homeTenantId", "used", "limit", "required" }, keys);
Assert.Equal("DelegatedSlotLimitReached", json.GetProperty("code").GetString());
}
private static DefaultHttpContext NewContext()
{
var ctx = new DefaultHttpContext();
ctx.Response.Body = new MemoryStream();
return ctx;
}
private static string Body(HttpContext ctx)
{
ctx.Response.Body.Position = 0;
using var reader = new StreamReader(ctx.Response.Body);
return reader.ReadToEnd();
}
}
@@ -1,5 +1,6 @@
using System.Text.Json;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Shared;
using AutopilotMonitor.Shared.Models;
using Xunit;
@@ -29,6 +30,33 @@ public class ApiResponseWireParityTests
Assert.Equal(expected, actual);
}
// ---- Error envelope (2026-09, deliberate wire change) ----------------------------------
// Non-2xx bodies used to be ~10 anonymous shapes ({ success = false, message }, { error },
// { error, message }, { error, code }, …). They are ONE typed envelope now, so these pins fix
// the NEW shape exactly rather than proving parity with any single legacy literal.
[Fact]
public void ApiErrorResponse_pins_the_minimal_envelope_shape()
{
var body = ApiErrorWriter.Build("cid-1", Constants.ApiErrorCodes.NotFound, "Session not found.");
Assert.Equal(
"{\"error\":\"Session not found.\",\"code\":\"NotFound\",\"correlationId\":\"cid-1\"}",
JsonSerializer.Serialize(body, WireOptions));
}
[Fact]
public void ApiErrorResponse_pins_the_full_envelope_shape_and_key_order()
{
var body = ApiErrorWriter.Build("cid-2", Constants.ApiErrorCodes.ServiceUnavailable,
"Authorization service temporarily unavailable.", hint: "Retry.", retryAfterSeconds: 5, operation: "PolicyEnforcement");
Assert.Equal(
"{\"error\":\"Authorization service temporarily unavailable.\",\"code\":\"ServiceUnavailable\"," +
"\"correlationId\":\"cid-2\",\"hint\":\"Retry.\",\"retryAfterSeconds\":5,\"operation\":\"PolicyEnforcement\"}",
JsonSerializer.Serialize(body, WireOptions));
}
[Fact]
public void SuccessMessageResponse_matches_the_canonical_anonymous_shape()
{
@@ -356,7 +356,8 @@ public class ApplicationPrincipalTests
var members = new StubTenantMemberRoleResolver();
var sut = new McpUserService(
adminRepo.Object, bindings, cache, NullLogger<McpUserService>.Instance,
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, members);
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, members,
new TenantConfigurationService(Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache));
return (sut, members);
}
}
@@ -83,7 +83,7 @@ public class AuthFunctionSideEffectTests
var mcpUserMock = new Mock<McpUserService>(
adminRepo, new StubAdminIdentityBindingService(bound: true), cache, Mock.Of<ILogger<McpUserService>>(),
globalAdminMock.Object, delegatedAdminMock.Object, adminConfigService.Object,
new TenantMemberRoleResolver(_tenantAdminsMock.Object, _tenantConfigMock.Object))
new TenantMemberRoleResolver(_tenantAdminsMock.Object, _tenantConfigMock.Object), _tenantConfigMock.Object)
{ CallBase = false };
_metricsRepoMock = new Mock<IMetricsRepository>();
@@ -55,6 +55,76 @@ public class AuthFunctionTests
Assert.True((bool)body.hasMcpAccess);
}
[Fact]
public void HappyPath_SurfacesWhatsNewSeenMarks()
{
var platformSeen = new DateTime(2026, 9, 8, 10, 0, 0, DateTimeKind.Utc);
var agentSeen = new DateTime(2026, 9, 8, 10, 5, 0, DateTimeKind.Utc);
var result = AuthFunction.BuildAuthResult(
DefaultConfig(), isGlobalAdmin: false, isGlobalReader: false, isPreviewApproved: true,
memberRole: AdminRole(), mcpCheck: McpAllowed(),
hasTenantAdmins: true,
TenantId, Upn, DisplayName, ObjectId,
whatsNewSeenPlatformUtc: platformSeen,
whatsNewSeenAgentUtc: agentSeen);
Assert.True(result.IsSuccess);
var body = ToDynamic(result.Body);
Assert.Equal(platformSeen, (DateTime)body.whatsNewSeenPlatformUtc);
Assert.Equal(agentSeen, (DateTime)body.whatsNewSeenAgentUtc);
}
[Theory]
[InlineData("platform", "platform")]
[InlineData("Platform", "platform")]
[InlineData("agent", "agent")]
public void TryNormalizeWhatsNewSeen_AcceptsKnownChannels(string input, string expected)
{
var seen = new DateTime(2026, 9, 8, 10, 0, 0, DateTimeKind.Utc);
var ok = AuthFunction.TryNormalizeWhatsNewSeen(
new WhatsNewSeenRequest { Channel = input, SeenUtc = seen },
seen.AddMinutes(1),
out var channel,
out var seenUtc,
out var error);
Assert.True(ok, error);
Assert.Equal(expected, channel);
Assert.Equal(seen, seenUtc);
}
[Fact]
public void TryNormalizeWhatsNewSeen_RejectsUnknownChannel()
{
var ok = AuthFunction.TryNormalizeWhatsNewSeen(
new WhatsNewSeenRequest { Channel = "other", SeenUtc = DateTime.UtcNow },
DateTime.UtcNow,
out _,
out _,
out var error);
Assert.False(ok);
Assert.Equal("channel must be 'platform' or 'agent'", error);
}
[Fact]
public void TryNormalizeWhatsNewSeen_ClampsFarFutureTimestamp()
{
var now = new DateTime(2026, 9, 8, 10, 0, 0, DateTimeKind.Utc);
var ok = AuthFunction.TryNormalizeWhatsNewSeen(
new WhatsNewSeenRequest { Channel = "agent", SeenUtc = now.AddMinutes(6) },
now,
out _,
out var seenUtc,
out var error);
Assert.True(ok, error);
Assert.Equal(now, seenUtc);
}
[Fact]
public void HappyPath_OperatorUser_ReturnsCorrectRole()
{
@@ -47,6 +47,12 @@ public class AutopilotDeviceValidatorTests
new(status) { Content = new StringContent(body) };
private static (AutopilotDeviceValidator Sut, DelayingHandler Handler, MemoryCache Cache) BuildSut(params HttpResponseMessage?[] responses)
{
var built = BuildSutWithTokens(responses);
return (built.Sut, built.Handler, built.Cache);
}
private static (AutopilotDeviceValidator Sut, DelayingHandler Handler, MemoryCache Cache, Mock<GraphTokenService> Tokens) BuildSutWithTokens(params HttpResponseMessage?[] responses)
{
var handler = new DelayingHandler(responses);
var factory = new Mock<IHttpClientFactory>();
@@ -71,10 +77,52 @@ public class AutopilotDeviceValidatorTests
var sut = new AutopilotDeviceValidator(
NullLogger<AutopilotDeviceValidator>.Instance, factory.Object, cache, tokenService.Object);
return (sut, handler, cache);
return (sut, handler, cache, tokenService);
}
private const string FoundBody = "{\"value\":[{\"id\":\"ap-1\",\"serialNumber\":\"PF3XKQ7\"}]}";
private const string ForbiddenBody = "{\"error\":{\"code\":\"Authorization_RequestDenied\",\"message\":\"Application is not authorized to perform this operation.\"}}";
[Fact]
public async Task StaleTokenForbidden_ThenSuccess_InvalidatesOnce_AndValidatesWithTheFreshToken()
{
// Field case 2026-09-02: a second instance held a roleless app-only token minted before the
// tenant's consent; Graph answered 403 for 45 minutes. Attempt 1 must drop that token and
// attempt 2 must succeed with the re-minted one — no 503 loop, no cached negative.
var (sut, handler, cache, tokens) = BuildSutWithTokens(
Json(ForbiddenBody, HttpStatusCode.Forbidden),
Json(FoundBody));
var result = await sut.ValidateAutopilotDeviceAsync(TenantId, Serial, null, CancellationToken.None);
Assert.True(result.IsValid);
Assert.Equal("ap-1", result.AutopilotDeviceId);
Assert.Equal(2, handler.Requests.Count);
tokens.Verify(t => t.InvalidateTenant(TenantId), Times.Once);
tokens.Verify(t => t.GetAccessTokenAsync(TenantId, It.IsAny<CancellationToken>()), Times.Exactly(2));
Assert.True(cache.TryGetValue($"autopilot-device-validation:{TenantId}:{Serial}", out _));
}
[Fact]
public async Task ForbiddenWithFreshToken_StaysTransient_WithLongerRetryAfter_NotCached()
{
// Consent genuinely missing (or not yet propagated): the agent must keep getting 503 (a 403
// would make it shut down as "device not registered"), but with the permission-gap
// Retry-After and nothing cached so a granted consent takes effect on the next call.
var (sut, handler, cache, tokens) = BuildSutWithTokens(
Json(ForbiddenBody, HttpStatusCode.Forbidden),
Json(ForbiddenBody, HttpStatusCode.Forbidden));
var result = await sut.ValidateAutopilotDeviceAsync(TenantId, Serial, null, CancellationToken.None);
Assert.False(result.IsValid);
Assert.True(result.IsTransient);
Assert.Equal(GraphAuthFailure.PermissionMissingRetryAfterSeconds, result.RetryAfterSeconds);
Assert.Contains("permission missing", result.ErrorMessage);
Assert.Equal(2, handler.Requests.Count);
tokens.Verify(t => t.InvalidateTenant(TenantId), Times.Once);
Assert.False(cache.TryGetValue($"autopilot-device-validation:{TenantId}:{Serial}", out _));
}
[Fact]
public async Task Budget_defaults_sit_inside_the_agents_30s_client_timeout()
@@ -61,7 +61,8 @@ public class AzureQueueImeMsiArchiveProducerTests
public async Task EnqueueAsync_send_failure_is_swallowed()
{
var (producer, queue, _) = BuildSut();
queue.Setup(q => q.SendMessageAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
queue.Setup(q => q.SendMessageAsync(
It.IsAny<string>(), It.IsAny<TimeSpan?>(), It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new RequestFailedException(503, "queue busy"));
// Fire-and-forget continuation on the ingest path — must never throw.
@@ -107,8 +108,9 @@ public class AzureQueueImeMsiArchiveProducerTests
queue.Setup(q => q.CreateIfNotExistsAsync(
It.IsAny<IDictionary<string, string>>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((Response?)null);
queue.Setup(q => q.SendMessageAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns<string, CancellationToken>((body, _) =>
queue.Setup(q => q.SendMessageAsync(
It.IsAny<string>(), It.IsAny<TimeSpan?>(), It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>()))
.Returns<string, TimeSpan?, TimeSpan?, CancellationToken>((body, _, _, _) =>
{
sentBodies.Add(body);
var receipt = QueuesModelFactory.SendReceipt(
@@ -53,4 +53,94 @@ public class BuiltInRuleCatalogPolicyTests
Assert.True(duplicates.Count == 0,
$"Duplicate built-in gather rule IDs: {string.Join(", ", duplicates)}");
}
/// <summary>
/// Built-in rules that assert an ABSENCE (required not_exists) of an event the agent derives
/// from the IME logs, and deliberately do NOT carry the ime_tracker_degraded coverage gate.
/// Every entry is a decision with a reason; adding one here is the way to ship such a rule.
/// </summary>
private static readonly IReadOnlyDictionary<string, string> AbsenceWithoutCoverageGate =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["ANALYZE-ID-004"] =
"A hybrid session whose user never obtained an Entra token must not lose its finding because " +
"the tracker skipped the remaining patterns on one line; the tracker state is shown next to " +
"the finding in get_session_summary (coverage) instead (plan session-coverage-and-absence-audit).",
};
[Fact]
public void Required_not_exists_on_ime_derived_events_is_coverage_gated_or_documented()
{
// "Absence proves nothing": a required not_exists on an IME-log-derived event evaluates
// to true both when the event never happened and when the IME log tracker skipped the
// line that carried it (ime_tracker_degraded). A built-in rule that asserts such an
// absence either suppresses itself on degraded sessions (precondition
// ime_tracker_degraded not_exists) or is listed above with the reason it does not.
// The IME-derived list is the guardrails.json mirror the MCP validate_rule lint reads,
// so catalog and pre-flight judge by one list.
var guardrailsPath = Path.Combine(FindRepoRoot(), "rules", "guardrails.json");
var json = Newtonsoft.Json.Linq.JObject.Parse(File.ReadAllText(guardrailsPath));
var imeDerived = new HashSet<string>(
json["imeLogDerivedEventTypes"]!.ToObject<string[]>()!, StringComparer.OrdinalIgnoreCase);
Assert.Contains("ime_user_token_acquired", imeDerived);
var offenders = new List<string>();
foreach (var rule in BuiltInAnalyzeRules.GetAll())
{
var assertsImeAbsence = rule.Conditions.Any(c =>
c.Required
&& string.Equals(c.Operator, "not_exists", StringComparison.OrdinalIgnoreCase)
&& string.IsNullOrEmpty(c.DataField)
&& !string.IsNullOrEmpty(c.EventType)
&& imeDerived.Contains(c.EventType));
if (!assertsImeAbsence) continue;
var gated = rule.Preconditions.Any(p =>
string.Equals(p.EventType, "ime_tracker_degraded", StringComparison.OrdinalIgnoreCase)
&& string.Equals(p.Operator, "not_exists", StringComparison.OrdinalIgnoreCase)
&& string.IsNullOrEmpty(p.DataField));
if (gated || AbsenceWithoutCoverageGate.ContainsKey(rule.RuleId)) continue;
offenders.Add(rule.RuleId);
}
Assert.True(offenders.Count == 0,
"Built-in rules assert the absence of an IME-log-derived event without the " +
"ime_tracker_degraded coverage precondition and without a documented exception: " +
string.Join(", ", offenders));
// The exception list must not outlive the rules it excuses.
var catalogIds = new HashSet<string>(BuiltInAnalyzeRules.GetAll().Select(r => r.RuleId), StringComparer.OrdinalIgnoreCase);
foreach (var excused in AbsenceWithoutCoverageGate.Keys)
Assert.True(catalogIds.Contains(excused), $"Exception list names a rule that is not in the catalog: {excused}");
}
[Fact]
public void Ime_derived_list_names_only_real_event_types_and_the_tracker_event_exists()
{
var guardrailsPath = Path.Combine(FindRepoRoot(), "rules", "guardrails.json");
var json = Newtonsoft.Json.Linq.JObject.Parse(File.ReadAllText(guardrailsPath));
var imeDerived = json["imeLogDerivedEventTypes"]!.ToObject<string[]>()!;
var known = new HashSet<string>(
typeof(AutopilotMonitor.Shared.Constants.EventTypes)
.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)
.Where(f => f.IsLiteral && f.FieldType == typeof(string))
.Select(f => (string)f.GetRawConstantValue()!),
StringComparer.Ordinal);
var phantom = imeDerived.Where(t => !known.Contains(t)).ToList();
Assert.True(phantom.Count == 0, $"imeLogDerivedEventTypes lists unknown event types: {string.Join(", ", phantom)}");
Assert.Contains(AutopilotMonitor.Shared.Constants.EventTypes.ImeTrackerDegraded, known);
}
private static string FindRepoRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir != null && !File.Exists(Path.Combine(dir.FullName, "AutopilotMonitor.sln")))
{
dir = dir.Parent;
}
Assert.NotNull(dir);
return dir!.FullName;
}
}
@@ -179,7 +179,7 @@ public class BuiltInRulesTests
"healthScriptResult", "healthScriptDetectionResult",
"captureExitCode", "captureHResult",
"captureAppVersion", "captureAppTypeWinGet", "captureAppTypeMsi",
"captureAttemptNumber", "captureDetectionResult"
"captureAttemptNumber", "captureDetectionResult", "captureExitCodeClass"
};
var patterns = BuiltInImeLogPatterns.GetAll();
@@ -0,0 +1,83 @@
using System.Linq;
using System.Threading.Tasks;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.DataAccess;
using AutopilotMonitor.Shared.Models;
using AutopilotMonitor.Shared.Models.Config;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// Concurrent cache misses on the two configuration services share one repository read
/// (audit 2026-09-05 F12). The MemoryCache stays: the hit path and the in-place projection
/// semantics are untouched, only the miss path is single-flighted.
/// </summary>
public class ConfigurationServiceSingleFlightTests
{
[Fact]
public async Task Admin_config_concurrent_misses_issue_one_repository_read()
{
var gate = new TaskCompletionSource<AdminConfiguration?>();
var repo = new Mock<IConfigRepository>();
repo.Setup(r => r.GetAdminConfigurationAsync()).Returns(gate.Task);
var sut = new AdminConfigurationService(repo.Object, NullLogger<AdminConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
var calls = Enumerable.Range(0, 10).Select(_ => sut.GetConfigurationAsync()).ToArray();
gate.SetResult(AdminConfiguration.CreateDefault());
var results = await Task.WhenAll(calls);
repo.Verify(r => r.GetAdminConfigurationAsync(), Times.Once);
Assert.All(results, r => Assert.Same(results[0], r));
}
[Fact]
public async Task Admin_config_after_completion_the_next_miss_reads_again()
{
var repo = new Mock<IConfigRepository>();
repo.Setup(r => r.GetAdminConfigurationAsync()).ReturnsAsync(AdminConfiguration.CreateDefault());
var sut = new AdminConfigurationService(repo.Object, NullLogger<AdminConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
await sut.GetConfigurationAsync();
sut.InvalidateCache();
await sut.GetConfigurationAsync();
repo.Verify(r => r.GetAdminConfigurationAsync(), Times.Exactly(2));
}
[Fact]
public async Task Tenant_config_concurrent_misses_for_one_tenant_issue_one_repository_read()
{
const string tenantId = "11111111-1111-1111-1111-111111111111";
var gate = new TaskCompletionSource<TenantConfiguration?>();
var repo = new Mock<IConfigRepository>();
repo.Setup(r => r.GetTenantConfigurationAsync(tenantId)).Returns(gate.Task);
var sut = new TenantConfigurationService(repo.Object, NullLogger<TenantConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
var calls = Enumerable.Range(0, 10).Select(_ => sut.GetConfigurationAsync(tenantId)).ToArray();
gate.SetResult(TenantConfiguration.CreateDefault(tenantId));
var results = await Task.WhenAll(calls);
repo.Verify(r => r.GetTenantConfigurationAsync(tenantId), Times.Once);
Assert.All(results, r => Assert.Same(results[0], r));
}
[Fact]
public async Task Tenant_config_different_tenants_do_not_share_a_flight()
{
const string a = "11111111-1111-1111-1111-111111111111";
const string b = "22222222-2222-2222-2222-222222222222";
var repo = new Mock<IConfigRepository>();
repo.Setup(r => r.GetTenantConfigurationAsync(It.IsAny<string>()))
.Returns<string>(id => Task.FromResult<TenantConfiguration?>(TenantConfiguration.CreateDefault(id)));
var sut = new TenantConfigurationService(repo.Object, NullLogger<TenantConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
await Task.WhenAll(sut.GetConfigurationAsync(a), sut.GetConfigurationAsync(b));
repo.Verify(r => r.GetTenantConfigurationAsync(a), Times.Once);
repo.Verify(r => r.GetTenantConfigurationAsync(b), Times.Once);
}
}
@@ -224,17 +224,36 @@ public class CorporateIdentifierValidatorTests
}
[Fact]
public async Task ValidateAsync_graphPermissionDenied_isCached_notRetried()
public async Task ValidateAsync_graphPermissionDenied_isCached_afterOneFreshTokenRetry()
{
// Definitive permission failures are negative-cached so an agent retry storm does not
// hammer Graph while consent is being fixed; the in-call retry loop must not fire either.
// hammer Graph while consent is being fixed. Attempt 1 may have used a token minted before
// the consent (GraphAuthFailure), so exactly ONE retry with a fresh token precedes the
// verdict; the cached verdict then answers the next call without Graph.
var (sut, handler) = BuildSut(Json("""{"error":{"code":"Forbidden"}}""", HttpStatusCode.Forbidden));
await sut.ValidateAsync(TenantId, "Microsoft Corporation", "Virtual Machine", Serial);
var first = await sut.ValidateAsync(TenantId, "Microsoft Corporation", "Virtual Machine", Serial);
var second = await sut.ValidateAsync(TenantId, "Microsoft Corporation", "Virtual Machine", Serial);
Assert.False(first.IsTransient);
Assert.False(second.IsValid);
Assert.Single(handler.Requests);
Assert.Equal(2, handler.Requests.Count);
}
[Fact]
public async Task ValidateAsync_staleTokenForbidden_thenFound_validatesWithTheFreshToken()
{
// Field case 2026-09-02 in this validator's shape: a stale roleless token gets 403, the
// fresh one finds the identifier. Without the retry the stale token would have been cached
// as "not permitted" for 5 minutes, every 5 minutes, until its 55-minute TTL.
var (sut, handler) = BuildSut(
Json("""{"error":{"code":"Forbidden"}}""", HttpStatusCode.Forbidden),
Json($$"""{"value":[{"importedDeviceIdentityType":"manufacturerModelSerial","importedDeviceIdentifier":"{{StoredIdentifier}}"}]}"""));
var result = await sut.ValidateAsync(TenantId, "Microsoft Corporation", "Virtual Machine", Serial);
Assert.True(result.IsValid);
Assert.Equal(2, handler.Requests.Count);
}
[Fact]
@@ -182,6 +182,7 @@ public class CrossTenantAccessTests
[Theory]
[InlineData("PATCH", "/api/config/{0}/plan")]
[InlineData("GET", "/api/config/{0}/effective-agent-config")]
[InlineData("POST", "/api/preview/whitelist/{0}")]
[InlineData("DELETE", "/api/preview/whitelist/{0}")]
[InlineData("POST", "/api/preview/send-welcome-email/{0}")]
@@ -1,179 +0,0 @@
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// Tests for <see cref="DecisionGraphBuilder"/> — pure projection, zero IO. Covers node
/// de-duplication, terminal classification, dead-end preservation, visit-count semantics, and
/// empty / out-of-order inputs.
/// </summary>
public class DecisionGraphBuilderTests
{
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
private const string SessionId = "b2c3d4e5-f6a7-8901-bcde-f12345678901";
private static DecisionTransitionRecord Transition(
int step, string from, string to, bool taken = true, string? deadEnd = null, string trigger = "t",
string reducer = "1.0.0")
=> new DecisionTransitionRecord
{
TenantId = TenantId,
SessionId = SessionId,
StepIndex = step,
FromStage = from,
ToStage = to,
Taken = taken,
DeadEndReason = deadEnd,
Trigger = trigger,
ReducerVersion = reducer,
IsTerminal = DecisionGraphBuilder.IsTerminalStage(to),
OccurredAtUtc = new DateTime(2026, 4, 21, 10, step, 0, DateTimeKind.Utc),
};
// ============================================================ Empty input
[Fact]
public void Build_returns_empty_projection_when_no_transitions()
{
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, Array.Empty<DecisionTransitionRecord>());
Assert.Equal(TenantId, graph.TenantId);
Assert.Equal(SessionId, graph.SessionId);
Assert.Empty(graph.Nodes);
Assert.Empty(graph.Edges);
Assert.Equal(string.Empty, graph.ReducerVersion);
}
// ============================================================ Node de-duplication
[Fact]
public void Build_deduplicates_stages_into_unique_nodes()
{
// Same stage visited twice through different paths — appears once in Nodes.
var transitions = new[]
{
Transition(0, "SessionStarted", "EspInProgress"),
Transition(1, "EspInProgress", "AccountSetup"),
Transition(2, "AccountSetup", "EspInProgress"), // back-edge (hypothetical)
Transition(3, "EspInProgress", "Completed"),
};
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
// Unique stages: SessionStarted, EspInProgress, AccountSetup, Completed = 4 nodes.
Assert.Equal(4, graph.Nodes.Count);
Assert.Contains(graph.Nodes, n => n.Id == "SessionStarted");
Assert.Contains(graph.Nodes, n => n.Id == "EspInProgress");
Assert.Contains(graph.Nodes, n => n.Id == "AccountSetup");
Assert.Contains(graph.Nodes, n => n.Id == "Completed");
}
// ============================================================ Terminal classification
[Theory]
[InlineData("Completed", "Succeeded")]
[InlineData("Failed", "Failed")]
[InlineData("WhiteGloveSealed", "PausedForPart2")]
public void Build_marks_terminal_stages_and_derives_outcome(string terminalStage, string expectedOutcome)
{
var transitions = new[]
{
Transition(0, "Start", terminalStage),
};
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
var node = graph.Nodes.Single(n => n.Id == terminalStage);
Assert.True(node.IsTerminal);
Assert.Equal(expectedOutcome, node.TerminalOutcome);
}
[Fact]
public void Build_leaves_non_terminal_nodes_unmarked()
{
var transitions = new[] { Transition(0, "SessionStarted", "EspInProgress") };
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
Assert.All(graph.Nodes, n =>
{
Assert.False(n.IsTerminal);
Assert.Null(n.TerminalOutcome);
});
}
// ============================================================ Edges
[Fact]
public void Build_preserves_all_edges_including_dead_ends()
{
var transitions = new[]
{
Transition(0, "EspInProgress", "Completed", taken: true),
Transition(1, "EspInProgress", "EspInProgress", taken: false,
deadEnd: "hybrid_reboot_gate_blocking", trigger: "EspExiting"),
};
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
Assert.Equal(2, graph.Edges.Count);
Assert.Contains(graph.Edges, e => e.Taken && e.ToStage == "Completed");
var deadEnd = graph.Edges.Single(e => !e.Taken);
Assert.Equal("hybrid_reboot_gate_blocking", deadEnd.DeadEndReason);
Assert.Equal("EspExiting", deadEnd.Trigger);
}
[Fact]
public void Build_orders_edges_by_StepIndex_even_if_input_is_shuffled()
{
// Repository sorts, but defend anyway — the builder is used directly in tests and
// could be fed arbitrary lists.
var transitions = new[]
{
Transition(2, "AccountSetup", "Completed"),
Transition(0, "SessionStarted", "EspInProgress"),
Transition(1, "EspInProgress", "AccountSetup"),
};
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
Assert.Equal(new[] { 0, 1, 2 }, graph.Edges.Select(e => e.StepIndex));
}
// ============================================================ VisitCount
[Fact]
public void Build_counts_only_taken_transitions_toward_VisitCount()
{
var transitions = new[]
{
Transition(0, "Start", "EspInProgress", taken: true),
Transition(1, "EspInProgress", "EspInProgress", taken: false, deadEnd: "blocked"),
Transition(2, "EspInProgress", "Completed", taken: true),
Transition(3, "Start", "EspInProgress", taken: true), // hypothetical retry
};
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
var esp = graph.Nodes.Single(n => n.Id == "EspInProgress");
Assert.Equal(2, esp.VisitCount); // two taken → EspInProgress; the dead-end does not count
var completed = graph.Nodes.Single(n => n.Id == "Completed");
Assert.Equal(1, completed.VisitCount);
}
[Fact]
public void Build_exposes_ReducerVersion_from_first_row()
{
var transitions = new[]
{
Transition(0, "Start", "EspInProgress", reducer: "1.4.2"),
Transition(1, "EspInProgress", "Completed", reducer: "1.4.2"),
};
var graph = DecisionGraphBuilder.Build(TenantId, SessionId, transitions);
Assert.Equal("1.4.2", graph.ReducerVersion);
}
}

Some files were not shown because too many files have changed in this diff Show More