Compare commits

..

99 Commits

Author SHA1 Message Date
Oliver Kieselbach 8cb5d42edc Seal pre-provisioning despite IME's AccountSetup line; report why a session never registered
WhiteGlove seal: IME reports "EspPhase: AccountSetup" from the device session
as soon as the device apps are done when the user ESP is enabled. The sealing
classifier counted that as user activity (-40) and left pre-provisioning Part 1
unsealed, so no whiteglove.complete marker was written and the Part-2 boot hit
the 48-hour emergency break. The excluder now also needs the ESP registry to
show AccountSetup progress: the adapter stamps accountSetupProgress on
WhiteGloveShellCoreSuccess, only after the tracker has actually read the
AccountSetup subcategories (unread is never "untouched"). The new excluder is a
subset of the old one, so a verdict can only rise; signals without the key
score as before. WhiteGloveShellCoreSuccess v1 gets its replay fixture.

The Part-1 exit writes whiteglove.complete as its first step instead of after
analyzers, diagnostics upload, grace and drain, where a reseal could kill the
process before it.

Registration failures: a run that exits because register-session failed
records outcome, last error, network link at start and end, the wall-clock
attempt window and the config-fetch outcome in registration-failure.json. The
emergency break sends the record as AgentErrorReport.PriorRegistrationFailure
(null for older agents); the backend bounds it and adds it to the ops details,
the App Insights dimensions and the timeline data. Retry behaviour is unchanged.

The raw registry trigger whiteglove_signal_* is renamed save_result_step_*: the
step exists in every 25H2 enrollment and the old name read as a
pre-provisioning signal.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 01:38:45 +02:00
Oliver Kieselbach fa637369e1 bump pointer: internal (emergency break session age live)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 00:05:44 +02:00
Oliver Kieselbach edf30d35e0 Emergency break reports the session age; a break without a session row is Info
The agent measured the session age at its 48 h break but never sent it.
AgentErrorReport now carries SessionAgeHours (optional, null for older
agents), and the backend puts it into the ops details, the timeline data and
the App Insights dimension. It is information only: the backend cannot derive
it (no row, or a row registered seconds before the break after a hibernate
resume), and it never feeds the severity.

The backend now reads the Sessions row once for the owner binding and the
break verdict. A report for a session without a row (in practice one that
never registered) is Info and writes no timeline event and no EventType index
row: nothing can close or open that session, and the orphan sweep deleted the
event a day later with a Warning of its own. A row under cascade delete gets
nothing written past the lock. Terminal stays Info with lateCleanup; an open
status or a failed read stays Warning with the historical write. Break
materialization now requires GUID ids.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 23:40:36 +02:00
Oliver Kieselbach 3b4228e3a1 bump pointer: internal (session-owner binding stage 2 live)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 23:38:45 +02:00
Oliver Kieselbach a029d69d5e Session-owner binding stage 2: refuse sessions bound to another device
Each Sessions row is bound to the device identity that registered it. The
binding ran in shadow; it now refuses every foreign-identity outcome:
register-session answers 403 with session_owner_mismatch before anything is
written, agent telemetry 403 in the error envelope (SessionOwnerMismatch),
the hosted diagnostics upload URL 403. The error channel stays 200 and only
skips its write into the named session. An evaluation defect fails open.

The agent already rotates its session id on the 403 at registration; it now
does the same for the coded 409 (session id claimed by another tenant) instead
of retrying six times and exiting, and fails without retry on any other coded
409 (BackendRefusalException, never an auth failure). A snapshot restored
after a rotation adopts the current session id.

A guard test pins the four call sites and fails when a site observes the
binding without acting on the refusal. Privacy page: session binding under
how data is protected.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 23:12:18 +02:00
Oliver Kieselbach daae1ce1fa bump pointer: internal (paged cross-partition merge released)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 21:02:35 +02:00
Oliver Kieselbach d90cf24508 bump pointer: internal (D-294/D-295 paged cross-partition merge)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 20:53:35 +02:00
Oliver Kieselbach 32f1fd4132 Click-next lists change page only after the page loaded
The audit log, ops events, rule submissions and session reports each
carried a copy of the same paging state. Next bumped the page number and
cursor stack before the request and kept them when it failed, so a failed
request showed "Page 3" over the rows of page 1.

useCursorPager (pure transitions in lib/cursorPager) owns rows, cursors
and the stack; the page number is derived from the stack. A move commits
only after its page loaded, and only the latest move commits. The fetch is
read through useLatest, which retires the per-page workarounds for the
token getter's changing identity.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 20:53:35 +02:00
Oliver Kieselbach ffb09e60fa Global audit and ops-event pages continue from one RowKey watermark
The cross-partition pages (audit log over all tenants, ops events over
all categories) kept one continuation entry per partition that still had
rows. On the tenant fan-out the nextLink outgrew the host's URL limit:
the follow-up request was rejected with HTTP 414 before the function ran,
so Next never loaded a second page for a Global Admin.

The continuation is now the (RowKey, Partition) of the last returned row.
Every page reads each partition through BoundedFanOut (pageSize + 1 rows
after the watermark) and merges by (RowKey, Partition), which is the
display order in both tables. Partitions after the watermark's partition
continue with `RowKey ge`, the others with `RowKey gt`, so equal ops
RowKeys across categories survive a page cut. The merge no longer sorts
by the resolved OccurredUtc while advancing by RowKey, which could skip
rows where the two disagree.

The fan-out was unbounded (Task.WhenAll over every tenant); it now runs
with the shared cross-tenant concurrency ceiling like the session list.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 20:53:35 +02:00
Oliver Kieselbach f920b6228e fix(web): suspended and offboarded tenants get their page again (#164) 2026-09-28 18:23:28 +02:00
Oliver Kieselbach 1765773116 bump pointer: internal (RealmJoin app install rows released)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 18:21:38 +02:00
Oliver Kieselbach 5c7295019b bump pointer: internal (D-292/D-293 RealmJoin app install rows)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 10:19:18 +02:00
Oliver Kieselbach a0ad769231 RealmJoin packages count as app installs next to Intune apps
App install rows now carry their install channel. The ingest folds the RealmJoin
watcher's package started/completed events into AppInstallSummaries rows (channel
"realmjoin", keyed by scope + package id; duration = completion minus the observed
start). IME rows keep their key and have no channel column, so they read as before.

Every per-app aggregate groups on (channel, name): apps list, app analytics and
sessions (new ?source=, default ime), metrics/app, SLA top failing apps and the
version-regression radar (tracker key, episode key, bell link, ops event). The app
install SLA rate includes RealmJoin packages. The ESP-blocking stamp stays IME-only.
RealmJoin packages do not feed the software inventory or CVE correlation.

Web: a RealmJoin pill and an All / Intune / RealmJoin filter on Software > Installs,
the pill on app detail, Fleet Health and SLA, source-aware app links and PDF meta
line, and a hint in the empty Inventory tab. The pill moves out of InstallProgress
into a shared component. MCP: get_app_install_metrics names the source field.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 10:19:18 +02:00
Oliver Kieselbach 64da9f850b bump pointer: internal (D-291 chain build without downloads)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 09:07:10 +02:00
Oliver Kieselbach 5dae21968b Client-certificate chain building never downloads an issuer
The platform forwards whatever certificate the TLS client presented, so an
unauthenticated caller can hand in a leaf signed by a CA it made up. The
chain engine then fetched the leaf's AIA caIssuers URL before rejecting it:
an attacker-directed GET from the backend, and a worker blocked for the
10 s retrieval timeout. Every legitimate issuer is embedded and Intune
certificates carry no AIA, so downloads are now disabled and the unused
retrieval timeout is gone.

The regression test signs a leaf with a CA that is neither embedded nor
sent and asserts that the listener behind its AIA URL sees no connection;
a self-signed leaf never reaches that path.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 09:06:09 +02:00
Oliver Kieselbach 59897dfbd8 bump pointer: internal (B-g9t editor verify)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 20:33:30 +02:00
Oliver Kieselbach f4551ea1ed bump pointer: internal (D-288/D-289/D-290 live)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 20:21:58 +02:00
Oliver Kieselbach e816c92b88 Tenant configuration has one conditional write path; the full-model PUT is gone
A tenant configuration row is never written blind any more (D-290). Three writers saved
from the 5-minute instance cache and four wrote a fresh read without an ETag: auto-re-enable
could lift a suspension a Global Admin had just renewed, the PUT could write the cached
Disabled=false over the offboarding tombstone during the drain barrier, and a concurrent
first login could overwrite the write-once OnboardedBy.

- TenantConfigurationService.CreateOrUpdateAsync next to UpdateAsync (shared core): fresh
  read with ETag, tombstone refused, mutation decides, conditional replace, conditional
  insert for a missing row, re-read and re-decide on a lost race.
- SaveConfigurationAsync and IConfigRepository.SaveTenantConfigurationAsync deleted; new
  TryCreateTenantConfigurationAsync. The default row of GetConfigurationAsync is a
  conditional insert.
- Converted: first-login seed (writes only while the stored row has no domain; only the
  winning login fires the signup side effects), auto-re-enable (decided on the fresh row),
  auth client-id tracking, app-homing flip, conferred-Pro grace stamp, offboarding tombstone.
- PUT/POST config/{tenantId} removed (function, catalog entries, response DTO). The Global
  Admin tenant editor sends only its changed fields to the field PATCH; the Collect Logs
  quick-config PATCHes its two diagnostics fields with ?intent=collect-logs, which keeps
  the CollectLogsQuickConfigEnabled ops event. Shared diff helper lib/tenantConfigSave.ts.
- Tests: create-or-update and default-row races, concurrent first login, renewed
  suspension, tombstone paths; repository and service doubles in ConfigRepoMockExtensions.
  Regenerated shared manifest and wire types (web, MCP).

Deploy order: backend, then web right after (the old web's editor save and quick-config
use the removed PUT).

Bumps internal (D-290, plan, docs).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 20:11:56 +02:00
Oliver Kieselbach a16a70fba5 Self-service trial stays once per tenant across offboarding; plan writers decide on the fresh row
Offboarding deletes the tenant configuration, and the returning tenant's first login recreated
it with TrialConsumed=false, so the one-time 30-day Pro trial could be chained by offboarding
and re-onboarding.

- The offboard click reads the configuration fail-loud and ORs TrialConsumed into the
  OffboardingByTenantPointer (sticky across rounds, same ETag CAS as OffboardCount).
- The first-login write (HandleNewTenantDomainAsync, the one write that sets OnboardedBy)
  carries it onto the new row; an unreadable pointer means no write, retried next login.
  Re-onboarding itself is unchanged, auto-approve included.
- TenantConfigurationService.UpdateAsync: fresh projected row with ETag, offboarding
  tombstone refused (403 TenantSuspended), mutation may decline, conditional replace with
  the ordinary pre-write backup, re-read and re-decide on a lost race (409 after 3).
  SetTenantPlanTier and StartTrial use it, so a warm instance's cached row is never saved
  (it could lift the tombstone during the drain barrier) and two concurrent trial starts
  cannot both pass.
- Tests: TenantConfigUpdateTests (service + both endpoints), pointer stickiness and the
  offboard endpoint in TenantOffboardFunctionTests, first-login carry-over in
  AuthFunctionSideEffectTests; shared EndpointHarness.

Bumps internal (D-288, D-289, plan, docs).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 19:08:34 +02:00
Oliver Kieselbach 1b2bdd8f35 bump pointer: internal (SSRF gate released)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 13:43:22 +02:00
Oliver Kieselbach 942bd86238 bump pointer: internal (SSRF gate live-verify)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 13:08:24 +02:00
Oliver Kieselbach 7a920049ca bump pointer: internal (D-287 Node/Next version plan)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 12:48:30 +02:00
Oliver Kieselbach 2eeb4da950 bump pointer: internal (B-h4m CodeQL note)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 12:38:08 +02:00
Oliver Kieselbach 20a80cbdc6 bump pointer: internal (SSRF address gate D-286, B-h4m)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 12:37:03 +02:00
Oliver Kieselbach c59e65ee0a fix(backend): webhook SSRF gate moves onto the connection
SsrfGuard.ValidateDestinationAsync resolved the webhook host and checked
it, then HttpClient resolved it again for the POST, so a DNS-rebinding
host could pass the check and be connected to an internal address.

The webhook client's SocketsHttpHandler now connects through
SsrfGuard.ConnectToPublicAddress: it resolves once per connection,
refuses the connection if any address is blocked, enforces HTTPS and
connects the socket only to the checked addresses; TLS still runs against
the request host. The pre-flight check is removed, the registration moves
to AddWebhookNotificationHttpClient so a test can prove the wiring, the
notification retry policy no longer retries a refused destination, and
the test endpoint reports the refusal with the same message as before.

IsBlockedAddress follows the same model as the MCP server: all IANA
special-purpose space, IPv6 only 2000::/3, zone ids and IPv4-mapped
addresses refused (IPNetwork.Contains judges a mapped address by its
IPv4 form, so those are refused first).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 12:36:06 +02:00
Oliver Kieselbach 89aa9e1f10 fix(mcp): CIMD fetch checks the address inside the socket's own DNS lookup
The SSRF gate resolved the client_id host, checked the answer and then
handed the hostname to fetch(), which resolved it again at connect time.
A DNS-rebinding host could pass the check with a public answer and be
connected to an internal one.

The metadata fetch now runs through a dedicated undici dispatcher whose
connect.lookup is the gate: one resolution per connection, every address
must be public, the socket connects only to those addresses. The global
fetch is untouched.

The address classifier now refuses every IANA special-purpose block
(IPv4), allows only global unicast 2000::/3 minus its special-purpose
blocks (IPv6), and refuses zone ids and IPv4-mapped addresses. The tests
enumerate the unedited IANA registries (tests/fixtures/
iana-special-purpose-addresses) and prove on loopback sockets that a
refused host opens no socket and that an allowed one is connected to
exactly the address the gate returned.

Adds undici ^8.11.2 (engines >=22.19.0).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 12:35:56 +02:00
Oliver Kieselbach 2d3700cfaf bump pointer: internal (B-5p4 release state)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 17:16:02 +02:00
Oliver Kieselbach 5a182f3f16 bump pointer: internal (B-5p4 DO-geo deploy/verify)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 17:10:32 +02:00
Oliver Kieselbach 889b843d6d feat(agent): Delivery Optimization geo endpoint as last-resort geolocation provider
When ipinfo.io (plus retry) and ifconfig.co both fail, the agent now asks
geo.prod.do.dsp.mp.microsoft.com/geo. It returns only CountryCode and
ExternalIpAddress, but it belongs to the DO/Windows Update endpoint set Autopilot
needs anyway, so it stays reachable where public geo services are blocked.
The session then gets a country-only device_location (source "do-geo", no
timezone, so timezone auto-set stays pending) instead of none.

- GeoLocationService: the three providers share one TryProvider skeleton;
  response parsers are internal and unit-tested; GeoLocationResult.Describe()
  skips missing parts ("DE" instead of ", , DE") in the event message and log.
- Failure trace carries doGeoError + lastResortProvider.
- Backend: geographic location keys skip empty region/city, so country-only
  sessions group as "DE" rather than ", DE"; drilldown still round-trips.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 17:08:56 +02:00
Oliver Kieselbach 9b91119239 bump pointer: internal (way 3 docs live)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 14:58:33 +02:00
Oliver Kieselbach 1e74d67da9 fix(web): service-principal member form names both uses — automation (access_as_application) and an app sending its users' tokens (delegated access_as_user, users read-only)
The ClientAppNotRegistered refusal (D-279, now enforced) sends Tenant Admins
to this form; its hint required access_as_application, which an app acting
on behalf of users does not need.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 14:51:52 +02:00
Oliver Kieselbach ed013bbdda bump pointers: internal (hash repair via v2.0.1466), .claude/commands (platform-health repair note)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 14:51:37 +02:00
Oliver Kieselbach 4b40619d1d bump pointer: internal (client-app binding enforced, way 3 documented)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 14:48:21 +02:00
Oliver Kieselbach 3ce1f2b036 bump pointer: internal (D-285 plan live)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 14:06:30 +02:00
Oliver Kieselbach 673f045212 fix(web): platform settings saves send only the changed fields via PATCH global/config (D-285)
Each save handler still builds the edited configuration but now sends changedAdminConfigFields(loaded, edited) through lib/adminConfigSave.ts, and nothing at all when nothing changed. This covers the Global Settings, the diagnostics paths, the ops alerts and the vulnerability section. The MCP access policy patches its single field without reading first. A page loaded before another writer (the agent release pipeline, a second operator, a sync job) can no longer revert that writer's fields. Deployed after the backend that serves PATCH global/config.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 13:55:43 +02:00
Oliver Kieselbach df640e3684 fix(backend): admin configuration is written only in its changed columns; PATCH global/config replaces the full-model PUT (D-285)
On 2026-09-25 a Global Settings save from a page loaded before an agent release wrote the whole configuration back and reverted the release's LatestAgentV2* hashes. After that, every 2.0.1465 agent reported IntegrityCheckFailed. The flaw was structural: every writer (portal PUT, plan tiers, three vulnerability-sync stamp paths) replaced the whole row from the copy it held, usually the 5-minute cache.

- IConfigRepository.UpdateAdminConfigurationAsync(mutate, updatedBy) is the one write path. It reads the row fresh with its ETag and applies the mutation to a copy materialized from that read. It computes the changed columns from the converter projections and writes only those onto the freshly read raw entity; a null value drops the column. The replace is conditional, and a conflict triggers a re-read and retry. A no-op writes nothing. Pipeline-owned and unknown columns survive. The full-model SaveAdminConfigurationAsync / SaveConfigurationAsync are removed, and the first row is created with AddEntity.
- PATCH global/config with { fields } (PatchAdminConfigurationRequest) replaces PUT/POST. Its field gate is derived from the persisted columns and rejects server stamps, LatestAgentV2* / LatestBootstrapV2ScriptVersion, PlanTierDefinitionsJson, the sync stamps and redacted placeholders. The route catalog lists PATCH.
- Plan tiers, TriggerMsrcSync, TriggerVulnerabilityDataSync, VulnerabilityDataSyncFunction and VulnerabilityCacheRefreshService.StampAsync each hand in a mutation.
- Tests: AdminConfigurationChangedFieldsTests (stale-page toggle keeps the release hashes, concurrent pipeline write re-read and kept, no-op, rejection, null drop, first row, gate); existing tests adapted; the request guard allows the admin field map.
- Regenerated shared manifest and wire types (web utils + MCP). The web still sends PUT until the web commit that follows the backend deploy.
- The internal pointer is bumped to D-285.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 13:51:53 +02:00
Oliver Kieselbach 59bea9d888 bump pointers: internal (plan envelope live), .claude/commands (platform-health markers)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 13:11:39 +02:00
Oliver Kieselbach e2c91afda2 feat(mcp): seal refresh tokens of registered self-hosted clients so that deleting the registration also ends copies (D-283)
A portal-registered client (amc_) now receives its Entra refresh token only as a compact JWE (RFC 7516, dir + A256GCM, kid amc-rt-v1). The key is derived from OAuthStateSigningKey. At refresh, the registration comes from the envelope, never from the client_id parameter. Before, a copy of the token redeemed without client_id went to the organizations authority and skipped the registration check.

A raw refresh token presented with an amc_ client id is accepted and returned sealed, so these clients migrate on their next refresh. All other clients are unchanged. jose becomes a production dependency; it was a dev-only transitive dependency before. The internal pointer is bumped to D-283/D-284.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 13:00:42 +02:00
Oliver Kieselbach eb47c4d69a bump pointer
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 12:32:14 +02:00
Oliver Kieselbach 91d56f2bbb bump pointer
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 11:58:20 +02:00
Oliver Kieselbach 12b847360c feat(web): Intune Enrollment Validation in the tenant settings; banners follow any device validation (D-282)
The option is a regular tenant-admin toggle in its own "Without pre-registration" block, with the
add-on permission state read from the existing graph-permissions status endpoint. The dashboard
banner and the admin Ready badge key on "any validation method enabled" (feature flag
deviceValidationEnabled, manifest-driven validate* fields) instead of Autopilot alone, so a
device-preparation tenant that validates by device association is no longer told that agent
ingestion is blocked. Stale "shadow mode" wording for Device Association is gone, the
Not-registered report names every method, sessions show "Intune Enrollment", and the privacy
page and FAQ list the new method. Grant script help describes the IntuneDeviceBinding feature
as Intune Enrollment Validation.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 11:57:42 +02:00
Oliver Kieselbach 2e736f40ad feat(backend,shared): Intune Enrollment Validation admits enrolled devices without pre-registration (D-282)
The certificate's Intune managedDevice id is looked up in the tenant's Intune. With the tenant
switch ValidateIntuneDeviceBinding on, that lookup is the last accepting link of the validator
chain: an enrolled device that is not being retired, wiped or deleted is admitted as
ValidatorType.IntuneEnrollment. A 404 for a certificate younger than 60 minutes is
NotFoundRecentEnrollment (503, never cached); a missing grant is 503 with 120 s.

For devices another validator admitted, the lookup only observes: in the background, never
admitting or rejecting, and only when the app token carries
DeviceManagementManagedDevices.Read.All, so a tenant without the add-on costs no Graph call.
Outcomes ride on the request row (CertDeviceBinding, role, serial match, owner and enrollment
type).

TenantConfiguration.HasAnyDeviceValidation() is the single gate precondition; the feature flags
expose it as deviceValidationEnabled (replaces validateAutopilotDevice).

The agent parses ValidatorType strictly: release the agent before this backend.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 11:57:26 +02:00
Oliver Kieselbach 9c3e5ecb30 Merge branch 'main' of https://github.com/okieselbach/AutopilotMonitor 2026-09-25 06:55:36 +02:00
Oliver Kieselbach 27ce316206 bump pointer 2026-09-25 06:55:25 +02:00
Oliver Kieselbach 7280b61d28 fix(web): self-hosted AI clients are ones the organization hosts itself (#163)
"Runs on its own servers" read as on-premises only and collided with the
MCP server. The criterion is who hosts the client (on premises or in the
cloud), matching the customer docs.


Claude-Session: https://claude.ai/code/session_012P3YpD3CSsR8Sy1Ubg4pUw

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-25 05:43:05 +02:00
Oliver Kieselbach 79f1ecd378 Tenant Config Report: show self-hosted AI client registrations (#162)
The registrations (name, callback URL, client id) live in their own table,
not in TenantConfiguration, so the report only showed the limit. Fetch
GET tenants/{tenantId}/mcp-client-registrations fail-soft alongside the
other side views and render them in the Tenant Status section, plus the
platform switch. The limit row is relabelled to say it is a limit.


Claude-Session: https://claude.ai/code/session_01DbRs7NCppizQ7wWFjN7n3M

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-24 20:54:10 +02:00
Oliver Kieselbach b6791d37e0 ci(codeql): exclude js/missing-rate-limiting; a test pins every OAuth route to its limiter (D-281)
The query recognizes only npm limiter packages, never oauthRateLimit /
oauthTokenRateLimit, and flags a handler as soon as it calls a function
named like *auth*, *login* or *verify*. All six alerts it ever raised were
on throttled OAuth routes (the last two came from tenantAuthority()).

What it stood in for is now a test: every route of the OAuth router must
run a per-IP limiter first unless it is one of the three named discovery
documents, /oauth/token must carry the strict budget, and a router.use()
middleware fails the check. Verified by mutation: removing the limiter
from /oauth/authorize fails the test with the route name.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 18:58:08 +02:00
Oliver Kieselbach 4f1b4f8c03 fix(mcp): URL-encode the registration id in the tenant-client lookup path
The registration lookup put a client_id-derived value into the backend URL
path unencoded. The amc_ regex already limits it to 32 hex characters, so
nothing changes at runtime, but every other request-derived path segment in
the MCP server goes through encodeURIComponent, and CodeQL counts only that
(or a ?/# prefix) as a request-forgery barrier - a regex capture group is
not one. Closes code-scanning alert js/request-forgery on oauth.ts.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 18:33:32 +02:00
Oliver Kieselbach 869580c9df feat(web): progress portal deep link /progress?serial=
A ?serial= parameter (serial number or exact device name) runs one lookup
as soon as sign-in has resolved the tenant, so organisations can send users
a link to follow their own device. Every hit writes the found session's
serial back into the URL for reload, bookmark and copying. Authorization is
unchanged: sign-in stays mandatory and roleless callers still need the exact
serial server-side. The query survives the login redirect because
ProtectedRoute keeps pathname + search. progress_serial_submitted carries
source form | link.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 17:14:39 +02:00
Oliver Kieselbach 1a96cd20da feat(web,backend): AI Integration settings page; one self-hosted client per tenant, raisable by a Global Admin
- Settings > Tenant > AI Integration (between SLA Targets and Bootstrap
  Sessions) explains the normal connection first - server URL for Claude,
  ChatGPT, VS Code and other hosted assistants, nothing to register - and
  shows the self-hosted client registration below it (Tenant Admin, platform
  switch on). The page is visible to admins, platform scopes and anyone with
  MCP access. The self-hosted example text is neutral.
- A tenant may hold one self-hosted client registration. The GA-only
  TenantConfiguration.McpClientRegistrationLimit (1-10) raises it on request:
  reverted for non-GA callers on PUT, refused on PATCH, edited in the Global
  Admin tenant dialog. MCP_SERVER_URL joins the portal URL registry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 15:00:15 +02:00
Oliver Kieselbach 8e637cf86a feat(web): docs link of the self-hosted AI clients section points at its own docs section
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 14:47:47 +02:00
Oliver Kieselbach 93c6e1facb feat(mcp): tenant-bound registrations for self-hosted MCP clients (D-280)
A self-hosted AI client redirects to its own domain, which the vendor
redirect allowlist never admits, so it could not use the browser sign-in.
Tenant Admins can now register the client's exact OAuth callback in the
portal and configure the client with client id amc_<registrationId>.

- MCP OAuth proxy: an amc_ id is resolved through the backend; its
  registration is the redirect allowlist entry for that exact callback.
  Authorize and token run at the registering tenant's Entra authority, and
  the token endpoint discards a token of any other tenant (code and
  refresh). Lookups are cached for 60 s, a failed lookup fails closed. Every
  other client keeps the allowlist check before its resolution.
- Backend: table McpClientRegistrations, TenantAdminOrGA routes
  tenants/{tenantId}/mcp-client-registrations (list, create, delete; at
  most three, https or loopback http, exact URI, audited) and the anonymous,
  per-IP rate-limited lookup auth/mcp/client-registrations/{id} (under
  /api/auth for the client-certificate exclusion list).
- AdminConfiguration.McpClientRegistrationEnabled (default off) is the
  platform switch: off hides the portal section and makes every lookup 404.
  auth/me carries it for the sidebar.
- Portal: Settings > Tenant > Self-hosted AI clients (Tenant Admin / Global
  Admin), and the switch in Admin > Settings > Global.
- Tests: MCP tenant-client flow (authority, tid check, revocation, cache,
  allowlist), backend round trip, wire parity, validation, cap, switch,
  audit; nav visibility. Manifests and wire types regenerated.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 14:10:13 +02:00
Oliver Kieselbach 4a4bbc056a fix(mcp): the OAuth proxy advertises and returns token auth method none
The proxy issues no client secrets, but its authorization server metadata
named no token_endpoint_auth_methods_supported (RFC 8414 then implies
client_secret_basic) and /oauth/register echoed a requested secret-based
method. A client following that default registered with client_secret_basic
and then failed the token exchange ("client_secret_basic authentication
requires a client_secret"), reproduced with the SDK calls a self-hosted chat
client makes. The metadata now lists ["none"] and registration always answers
none (RFC 7591 lets the server replace a requested value).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 13:35:47 +02:00
Oliver Kieselbach c59b366560 feat(auth): client-app binding for delegated tokens - measured always, enforced behind a switch (D-279)
A user token obtained by an application other than the platform's own
registrations (for example a self-hosted AI client using on-behalf-of) was
accepted with the user's full role; only audience, issuer, signature and
lifetime were checked. Such tokens are now classified on every request.

- ClientAppBindingMiddleware (after authentication, before policy enforcement)
  records the request dimensions ClientAppBinding (registered | unregistered |
  unidentified) and ClientAppId, plus a throttled Warning.
- AdminConfiguration.EnforceClientAppBinding (default off; Admin > Settings >
  Global): when on, a foreign client is refused with 403 ClientAppNotRegistered
  unless the application is an enabled member of the caller's tenant (the
  app:<client-id> row a service principal uses). An admitted caller keeps their
  identity but gets the application caps: at most Viewer, no platform role,
  DelegatedReader on managed tenants, roleless tiers closed except auth/mcp.
- AdminIdentity.IsCapped (application or admitted foreign client) is what the
  global, delegated and member-role resolvers switch on; RequestContext carries it.
- Own clients = the audience trust set plus EntraId:TrustedClientAppIds, a
  client-only trust for the local development registration that never widens
  the accepted audiences.
- Tests: classification, unforgeable cap marker, middleware in both modes, caps
  through the real policy middleware, pipeline order; manifests and wire types
  regenerated.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 13:28:21 +02:00
Oliver Kieselbach d0aded5401 chore: bump internal (D-278, MCP client plan draft)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-24 12:41:21 +02:00
Oliver Kieselbach 8f9c683b7c chore: bump infra (redirect-allowlist parameter description)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 09:45:42 +02:00
Oliver Kieselbach e82878af57 feat(mcp): name the rejected token's aud/azp/tid and the rejected redirect targets in the auth log lines
A backend 401 on `initialize` logged only the UPN, and the backend's own trace
("IDX10214 audience validation failed") never names the token; a registration
rejection logged only a count of redirect_uris. Diagnosing a self-hosted client
(LibreChat) that first failed DCR on its own callback host and then presented
tokens minted for another resource took a customer round trip.

- access-guard: `invalid-token-claims` and `backend-rejected-token` carry
  `aud=... azp=... tid=...` (unverified claims; control characters stripped, capped)
- oauth/register: the rejection names origin + path of up to three rejected
  redirect_uris (never the query); the error_description names the actual
  defaults (VS Code, not Google)
- tests for both lines; skill catalog in .claude/commands (mcp-telemetry) updated

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 09:44:20 +02:00
Oliver Kieselbach d60e858e95 chore: bump internal (signature-check lesson)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 14:27:04 +02:00
Oliver Kieselbach f6ce9ae0a0 chore: bump internal (web perf audit released, first RUM comparison)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 13:38:15 +02:00
Oliver Kieselbach b4f26401f5 perf(web): stop recording own-origin non-API fetches as dependencies (D-277)
Route payloads (__next.*.txt, index.txt), static JSON and the router's HEAD
self-requests were 20k of 62k dependency rows per week and nobody reads them.
lib/webTelemetryExclusions.ts builds the patterns (own origins minus /api/,
plus relative non-API URLs) for two layers: excludeRequestFromAutoTracking-
Patterns for string fetches, and a dependency initializer that drops the
finished item by its absolute target - the SDK's own check sees an empty URL
for the URL objects Next's router passes to fetch (verified against the ingest
batch: 11 such fetches, 0 shipped; API, SignalR and token rows still shipped).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 12:42:00 +02:00
Oliver Kieselbach 2b5004fb33 perf(web): web perf audit 2026-09-23 - cache headers, intent prefetch, seeds, SignalR refcount, lazy telemetry
P1 - full loads
- staticwebapp.config.json: /_next/static/* immutable, /landing/* max-age=86400
  (SWA default was max-age=30 for hashed assets); guard test pins it
- components/NavLink.tsx: prefetch on hover/focus/touch for the portal chrome
  (prefetch={false} also disabled the hover prefetch); landing links stay off
- app/layout.tsx: preconnect to the API origin
- lib/dashboardSeed.ts + lib/prefetchSeeds.ts: the dashboard's first list and
  stats requests start with auth/me and are handed to the hooks as one-shot
  seeds (the own-tenant list URL carries no tenantId; the backend reads the JWT)
- lib/msalConfig.ts: the login request carries the API scope, so one token
  redemption serves the first API call; Graph consent via extraScopesToConsent

P2 - chatter per navigation
- lib/signalrGroupRegistry.ts + contexts/SignalRContext.tsx: group membership
  is reference-counted with a 2 s grace leave; reconnect rejoins run in
  parallel; on/off/invoke and the context value are memoised; the dashboard's
  unconditional leave no longer drops the notification bell's global-admins
  membership; consumers pair every join with a cleanup leave
- app/sessions/hooks: both group joins in parallel, the join catch-up is
  dropped while the initial walk is in flight, identical session deltas skip
  the state update
- lib/cachedAuthFetch.ts: TTL cache for feature flags, tenant list and latest
  versions with invalidation on every write path; FeedbackBubble defers its
  status call

P3 - pure derivations only (D-274): memoised filter arrays, one-pass phase
  summary, status counts, useDeferredValue on both search inputs

P4 - landing
- lib/authHint.ts + AuthGate + globals.css: the loading overlay is applied by
  an inline head script only when the site root is opened by a browser with an
  auth hint; the prerendered HTML carries no overlay; CSS lifts it after 8 s
- hero as WebP srcset (81 KB instead of a 180 KB PNG), dead landing-v1 CSS
  removed, terminal demo pauses off-screen, duplicate twitter image dropped

Telemetry (D-276)
- lib/appInsightsRuntime.ts: the SDK is its own chunk, deferred until idle on
  the public host, remote config fetch off (blkCdnCfg), initial trackPageView
  on both hosts, Web Vitals as web_vital_* custom metrics

Verified: tsc, eslint --max-warnings 0, vitest 127 files / 1442 tests, next
build, Playwright click-through of every portal route, settings section,
session views and public pages on the production bundle against the live API.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 12:10:11 +02:00
Oliver Kieselbach 00f4cb1f26 fix(agent,web): a script run duration is judged from both lines' provenance; an offset-error span is omitted, never shown (D-273)
A platform script that ran 10 s was shown as "1h 00m" (session 4377911b): its
start line was self-anchored (+120 min) while its result line, re-read after an
overwrite rewind and therefore never fresh, fell back to the agent's cached zone
(+60 min), was rejected as ahead of the clock, and the duration was taken from
the raw pair. The same shape fired script_timeout_suspected daily in one tenant
on 2-9 s scripts read as 17 h. Fleet 2026-09-20..23: about 1 % of script
durations, 28 of 28 inflated ones carrying derivedTimestamp.

Agent: ScriptExecutionState binds the provenance of its start, result and exit
lines (CmTraceLineProvenance, persisted); EmitScriptCompleted judges the pair -
verified (both measured, or both assumed with the same offset from the same
file), unverified, or suppressed with durationSuppressedReason
(rejected-endpoint | offset-grid, CmTraceOffsetCalibrator.IsOnOffsetGrid) - and
always emits durationProvenance plus startSourceOffset*. A held completion's
sourceOffset* tags now describe its own result line; script_timeout_suspected
only judges a measurable duration; the emitted-run marker is capped at the
clock so a future-shifted result no longer swallows the next run's start.

Web: the reducer applies the same rule to stored events from older agents,
pairing a final with the latest script_started of its policy, and the panel
shows "n/a" with the explanation where the run time would be.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 09:50:49 +02:00
Oliver Kieselbach e091e50862 chore: bump internal (plan and backlog on the commit state)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 09:47:29 +02:00
Oliver Kieselbach 27ce07b111 chore: bump internal and .claude/commands (IME wait states D-271, ime-diffs note D-272)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 09:46:10 +02:00
Oliver Kieselbach f06fe5afc0 feat(agent): registry observer surfaces IME install-deadline waits and app-in-use deferrals (D-271)
ImeRegistryAppStateObserver reads a fourth IME registry surface,
Win32Apps\OperationalState\<userGuid>\<appGuid>: the install deadline a
downloaded app waits for (ExecutionDeadlineTime, IME 1.106) and the
app-in-use deferral counters (DeferralsUsed, DeferUntilTime,
DeferralMaxDeferrals, DeferralAutoDeferred, IME 1.105). Both travel on the
existing registry_app_state event as data (installDeadlineUtc, deferralsUsed,
deferralMaxDeferrals, deferUntilUtc, deferralAutoDeferred) with the change
triggers installDeadline / deferralsUsed / deferUntil, and the message says
the state in words ("downloaded, install deadline ... UTC", "deferred by user
1/3 until ... UTC", "auto-deferred ..."). No new event type.

ClassifyStatusServiceStatus maps IME's legacy AppInstallStatus explicitly:
1000/1002/1004 installed, 1001/1003 installing, 2000 band notApplicable,
3000 failed, anything else unjudged. The 1000 band was treated as installed,
but IME maps every InProgress enforcement state to 1001, so a running app
counted as terminal success on the registry rail (observability only).

Tests: explicit status mapping, both registry timestamp shapes, the new
change triggers, the wait-state text, and the tick flow for a deadline and a
deferral event. Mutation proof: classifier and trigger broken on purpose
turn exactly the five expected tests red.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 09:46:07 +02:00
Oliver Kieselbach 37e920237c chore: bump internal (Web-Performance-Audit 2026-09-23)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 09:30:14 +02:00
Oliver Kieselbach 7279650772 Merge branch 'main' of https://github.com/okieselbach/AutopilotMonitor 2026-09-23 08:32:03 +02:00
Oliver Kieselbach d8ab70b166 chore(rules): override fast-json-patch to 3.1.1 (Dependabot #103)
ajv-cli 5.0.0 is the latest release and still declares fast-json-patch ^2.0.0,
so neither Dependabot nor npm audit fix can move past CVE-2021-4279. An npm
override forces 3.1.1 into the lockfile; the 3.x API is backward compatible and
the validate command used in combine-rules.yml never touches the package.
Verified: npm ci from the lockfile plus all four ajv validate steps pass locally.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-23 08:29:58 +02:00
dependabot[bot] fb8703a4c6 chore(deps): bump the actions group with 3 updates (#160)
Bumps the actions group with 3 updates: [azure/login](https://github.com/azure/login), [github/codeql-action/init](https://github.com/github/codeql-action) and [github/codeql-action/analyze](https://github.com/github/codeql-action).


Updates `azure/login` from 3.0.2 to 3.1.0
- [Release notes](https://github.com/azure/login/releases)
- [Commits](https://github.com/azure/login/compare/7ddb5af1ef8758cf1353cf3b42f940aee27ba21c...a641126d1b8aa4d1fa005f4f92df94a3a4c4c906)

Updates `github/codeql-action/init` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/cdf488f595d80d6e07e03d4674febd5ab45fa938...b96794f015dfd88f77b49b1c93e0fa7110f94c63)

Updates `github/codeql-action/analyze` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/cdf488f595d80d6e07e03d4674febd5ab45fa938...b96794f015dfd88f77b49b1c93e0fa7110f94c63)

---
updated-dependencies:
- dependency-name: azure/login
  dependency-version: 3.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: github/codeql-action/init
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
- dependency-name: github/codeql-action/analyze
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-23 08:18:43 +02:00
Oliver Kieselbach ac3fa8b2b6 chore: bump internal (B-2am deployed)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 21:29:42 +02:00
Oliver Kieselbach efcb4f9ca1 fix(offboarding): farewell feedback reaches the backend again; farewell mail leaves an ops event; suspended page instead of alert
The offboard endpoint tombstones the tenant (Disabled=true, "Offboarding in
progress") before it answers 202, so the departing admin submits the farewell
feedback from an already-suspended tenant. Since the suspension gate moved onto
the shared authorization path (43ddc601, 2026-08-29) every feedback POST was
403 TenantSuspended — invisible, because nobody clicked and the two stored
feedbacks predate the gate (D-270).

- Endpoint catalog: `AllowedDuringOffboarding` on exactly
  POST tenants/{tenantId}/offboard/feedback; the middleware ignores the
  offboarding tombstone for that route only. An operator suspension still
  denies; policy tier, cross-tenant check and the function's active-marker
  check are untouched. Middleware tests for all four cases plus a catalog
  ratchet pinning the flag to the one route.
- Farewell mail: IOffboardFarewellEmailSender.SendAsync returns whether the
  provider accepted; the offboarding worker records FarewellEmailSent /
  FarewellEmailSkipped / FarewellEmailFailed like the welcome mail — the
  send's own success log is Information and never reaches Application
  Insights. Missing Email:ApiKey logs Warning. Handler tests per outcome;
  OpsAlertRules catalog and the generated manifests (Web + MCP vocabulary)
  carry the three types.
- Web: auth/me 403 TenantSuspended no longer shows alert() and forces a
  logout. AuthContext keeps the user signed in with claims-only info and
  ProtectedRoute renders a suspended page: for the offboarding tombstone
  "Your organization is being offboarded" with the farewell feedback form
  (a reload during the 6-minute preparation window keeps the form), for any
  other suspension the reason text plus contact links; both with sign-out.
  The feedback widget moved from OffboardingSection into
  components/OffboardingFeedbackForm.tsx.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 21:18:44 +02:00
Oliver Kieselbach 7a7a31e8e3 chore: bump internal (B-z9d root cause)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 20:26:59 +02:00
Oliver Kieselbach 3fdcbabd48 chore: bump internal (backlog B-az5, B-z9d)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 20:11:31 +02:00
Oliver Kieselbach b2e8c7627f chore: bump internal and .claude/commands (context diet)
internal: operations facts as reference doc, leaner CLAUDE.md, context-diet plan. .claude/commands: shorter skill descriptions.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 20:02:27 +02:00
Oliver Kieselbach bd08d13011 chore: bump internal (mcp catalog sight check in Claude Code done)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 19:55:11 +02:00
Oliver Kieselbach 10c69f592e chore: bump internal (mcp-catalog-context-audit released)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 18:41:06 +02:00
Oliver Kieselbach fe0b2dc7fe refactor(mcp): catalog diet — shared argument texts, scope-first instructions, $schema stripped (D-269)
Every tool description and both role instructions now fit the 2048-char host cap
(Claude Code truncated the Global Admin instructions and two descriptions silently).
Pagination, projection and scope mechanics are said once in the instructions and
the shared pageSize/continuation/tenantId/days texts; role markers left tools only
that role can see; get_resource lists its sections on the argument. The SDK $schema
URL is stripped from tools/list.

Measured (compact tools/list): Global Admin 111.4 KB -> 89.1 KB, Reader 94.7 -> 74.3,
tenant user 64.5 -> 51.3, delegated 75.1 -> 55.6 KB. catalog-budget.test.ts pins the
new ceilings, the variant counts and the empty over-cap list.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 18:14:52 +02:00
Oliver Kieselbach a0f007fd43 fix(mcp): synthetic tenant examples, catalog budget test and audit script (D-269)
list_tenants named a real customer domain as its example; the filterTenantList test
carried three real tenants. Both now use synthetic names and GUIDs.

catalog-budget.test.ts pins the per-role wire catalog as a ratchet (size, repeated
argument texts, no foreign domains or GUIDs, the 2048-char host truncation cap with
the four known over-cap texts listed). scripts/audit-catalog.ts dumps and sizes the
catalog per role for before/after measurements.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 14:02:35 +02:00
Oliver Kieselbach 1b27babd17 ci: zizmor gate for the workflow files plus a clean baseline (D-268)
zizmor (static analysis for GitHub Actions) now runs twice: locally before a
workflow commit (hard rule in .claude/CLAUDE.md) and as the `zizmor` job next to
the pin gate in action-pins.yml (zizmorcore/zizmor-action pinned by SHA, zizmor
1.30.1 pinned, SARIF into Code scanning, severity low and above). Like the pin
gate it reports and does not block. zizmor.yml holds the single reasoned ignore.

Baseline fixes so the gate starts green:
- persist-credentials: false on every checkout except combine-rules.yml, the one
  job that pushes with the checkout credentials (ignored in zizmor.yml, with reason)
- publish-scripts.yml: id-token: write moves from the workflow to the publish job;
  indexnow-notify.yml: permissions: {}
- deploy-mcp.yml: env values referenced as shell variables inside bash steps
  instead of template expansion
- pester.yml / publish-scripts.yml: reusable workflow via the self-repository form
  $/ (GitHub changelog 2026-07-30); the pin gate treats $/ like ./
- combine-rules.yml: ajv-cli installed with npm ci from rules/scripts/package-lock.json
  (no ts-node peer, no lifecycle scripts) instead of an ad-hoc global install;
  Dependabot watches /rules/scripts
- azure/login pin comment corrected to the tag the SHA actually is (v3.0.2; v3
  moved on to v3.1.0), no runtime change
- Dependabot: 7-day cooldown on every ecosystem (security updates are exempt)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 12:56:03 +02:00
Oliver Kieselbach 100d2242fa chore: regenerate shared manifest and wire types (TenantManagerItem.Name doc)
The XML summary added on TenantManagerItem.Name in ef280b7b rides into
shared-manifests.json as the field's doc; CI run 35701895623 caught the drift.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 10:02:11 +02:00
Oliver Kieselbach 089b1b38fd Merge branch 'main' of https://github.com/okieselbach/AutopilotMonitor 2026-09-22 09:53:24 +02:00
Oliver Kieselbach ac465839a5 chore: bump internal (backlog B-umq for D-267)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 09:52:35 +02:00
Oliver Kieselbach ef280b7bb5 fix(backend): managed tenants see operator-provisioned access as "Platform support"
GET delegations/managers no longer exposes the name of an operator-created
Tenant Group to the customer; both operator shapes (groups and direct grants)
carry the neutral label. Assignees, reader count and source stay visible.
Web badge reads "Provisioned by operators". D-267.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 09:52:00 +02:00
dependabot[bot] 233737f333 chore(deps-dev): bump the web group (#159)
Bumps the web group in /src/Web/autopilot-monitor-web with 2 updates: [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) and [autoprefixer](https://github.com/postcss/autoprefixer).


Updates `@types/node` from 22.20.2 to 22.20.4
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `autoprefixer` from 10.5.6 to 10.6.1
- [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.6...10.6.1)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 22.20.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: web
- dependency-name: autoprefixer
  dependency-version: 10.6.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  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-22 09:29:05 +02:00
dependabot[bot] 909904e928 chore(deps): bump the mcp group (#158)
Bumps the mcp group in /src/McpServer/autopilot-monitor-mcp with 2 updates: [zod](https://github.com/colinhacks/zod) and [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node).


Updates `zod` from 4.6.2 to 4.6.5
- [Release notes](https://github.com/colinhacks/zod/releases)
- [Commits](https://github.com/colinhacks/zod/compare/v4.6.2...v4.6.5)

Updates `@types/node` from 22.20.2 to 22.20.4
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: zod
  dependency-version: 4.6.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: mcp
- dependency-name: "@types/node"
  dependency-version: 22.20.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: mcp
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-22 09:28:50 +02:00
Oliver Kieselbach 59ab47de8c chore: bump internal (D-266 network link changes are not activity)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 00:48:51 +02:00
Oliver Kieselbach f252a0709f fix(agent): network link changes no longer count as enrollment activity
network_state_change and network_connectivity_check join the non-activity
list next to power_state_change. A flapping dock or access point kept the
idle-stopped periodic collectors running for the whole episode and reset
the stall clock of the enrollment it was stalling. The events are emitted
unchanged; the device-info network snapshots stay activity.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 00:48:50 +02:00
Oliver Kieselbach d6d9638981 chore: bump internal (D-265 recurring health-script runs, backlog B-c6h)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 00:38:55 +02:00
Oliver Kieselbach 020248fbda feat(agent): collapse recurring health-script runs into one summary per policy
IME re-runs remediation policies on its own schedule for as long as the
device is up, so an enrollment that waits for its user reported every run
of every policy. The tracker now emits a policy's first run and every run
whose result differs from the last reported one (compliance, exit code,
stderr, remediation status, error code); repeats are counted and surface
as one script_recurrence_summary per policy when the tracker stops.

The start signal of a known policy is held until its result is known,
because the running indicators pair a start with a later result; a start
without any result is still emitted after a grace. The counters live in
the tracker state file next to the file positions, so a hard kill rolls
both back together. Platform scripts are untouched. The summary does not
count as enrollment activity.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 00:38:00 +02:00
Oliver Kieselbach a06a0dbfff chore: bump internal (D-264 emergency break stays a start-time check, backlog B-drn)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 00:08:22 +02:00
Oliver Kieselbach 96c24e0688 chore: bump internal (D-263 excessive-events recount, backlog B-7wp)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 23:46:03 +02:00
Oliver Kieselbach c156350183 fix(backend): excessive-events sweep warns and blocks on recounted rows
The stored EventCount doubles on replayed upload batches and was only
corrected at terminal transitions, so the sweep judged running sessions on
an inflated number. It now recounts a candidate before it records the ops
event or blocks the device, skips candidates it cannot verify, and limits
the recount to candidates with a pending action. The warn text no longer
claims an agent loop bug.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 23:45:11 +02:00
Oliver Kieselbach 15b25ff509 chore: bump internal (D-261 typed wrapper bodies, D-262 req.Query, backlog B-t5z)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 22:31:15 +02:00
Oliver Kieselbach 5163d7d6a0 refactor(backend): read the request query through req.Query only
73 sites in 68 files built the query collection with
HttpUtility.ParseQueryString(req.Url.Query), 15 files used req.Query and five mixed
both. HttpRequestData.Query is that same call, cached per request, and the ASP.NET
Core request type does not override it, so the change is behaviour-neutral.

- QueryParamGuardTests: ParseQueryString in the Functions project is limited to a
  named baseline of three sites that parse something other than the request query.
- A fact pins req.Query against HttpUtility.ParseQueryString (repeated keys, encoded
  values, caching) so a worker update that changes the implementation fails a test.
- Test mocks that set Url answer Query through CallBase; a loose mock returns null.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 22:28:11 +02:00
Oliver Kieselbach 9fd343d328 fix(backend): typed bodies and error envelope for backup, session-restore and delegation wrappers
Six functions wrote their responses through a private wrapper taking the body as
object, which no typed-response guard could see. Their error bodies carried the code
in the error slot, no correlation id, and RestoreRow returned the raw exception text
on a 500.

- Backup job status, row restore and backup trigger answer through ResponseHelper:
  errors are the envelope, the 500 is sanitized, the 202 body is BackupTriggerResponse.
- Same for the session-deletion maintenance trigger, RestoreSession's three error
  sites and the delegation acknowledgements (MessageResponse).
- Backup codes are constants (Constants.BackupErrorCodes) and part of apiErrorCodes;
  RunAlreadyActive and EnqueueFailed join ApiErrorCodes.
- TypedResponseGuardTests gains guard F: no HttpResponseData-returning method with an
  object parameter. BackupWireParityTests pins that the move from the backup
  serializer options to the worker pipeline leaves the wire unchanged.
- Web reads BackupTriggerResponse from the generated wire types.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 22:19:38 +02:00
Oliver Kieselbach aef88f3337 chore: bump internal (IME archiver pre-walk check doc, backlog B-ryg)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 20:59:13 +02:00
Oliver Kieselbach 12af1d6c76 fix(backend): IME archiver accepts an existing archive entry before walking the hosts
A version whose installer was already in the archive could only turn
Archived through the 409 on the write-once upload, which needs a
distribution host that still serves the build. For a version no host
serves any more the row stayed Failed:VersionMismatch next to its own
blob and re-walked every host once a day.

The archiver now checks the archive first: an entry whose ProductVersion
is the observed version ends the job as Archived with the hash and size
of the archived bytes and no download; a missing provenance sidecar is
written without a source URL. An entry holding another build, or an
unreadable one, is not accepted and the walk runs as before.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 20:58:49 +02:00
Oliver Kieselbach 5433bff3db chore: bump internal (navbar profile photo plan and backlog)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 17:40:00 +02:00
Oliver Kieselbach 355509aa7c feat(web): show the signed-in user's profile photo in the navbar avatar
The browser loads the photo straight from Microsoft Graph with the User.Read
scope already consented at sign-in; it never reaches the backend. Any failure
(no photo, token, network) falls back to the initials. One request per account
and tab, cached in sessionStorage including the no-photo answer.

The four copied avatar blocks in the navbar become one UserAvatar component.
Graph host added to the URL registry and to connect-src in both CSPs; the
privacy page states where the photo comes from and that it is not stored.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-21 17:39:41 +02:00
519 changed files with 20213 additions and 4829 deletions
+1
View File
@@ -30,6 +30,7 @@
- Stage explicit file lists; never `git add -A` or a directory. Pushing is the user's call.
- New API responses need a typed DTO plus the parity fact. MCP vocabularies are generated from the wire types, never retyped.
- Every route belongs in the route policy catalog; every new event type goes into the MCP resource catalog.
- Workflow files under `.github/` go through zizmor before they are committed (`zizmor .` from the repository root, findings from severity low on): fix every finding or ignore it in `zizmor.yml` with a reason. The `zizmor` job in `action-pins.yml` runs the same check on every push.
- The about, terms and privacy pages under `src/Web/autopilot-monitor-web/app/` state facts customers rely on: verify every claim against the code before writing it and update them in the same change as the fact they describe.
## Code Quality
+18 -6
View File
@@ -1,8 +1,8 @@
# CodeQL configuration.
#
# The default query suites stay active — this file only filters out two C# queries
# that fire structurally on this codebase, where the flagged behavior is the feature,
# not a defect:
# The default query suites stay active — this file only filters out queries that
# fire structurally on this codebase, where the flagged behavior is the feature
# or the protection exists in a form the query cannot see:
#
# cs/exposure-of-sensitive-information
# Audit and operational logs record WHO performed an action (actor UPN / email)
@@ -15,10 +15,20 @@
# key. The IP is an identifier for throttling, not a secret at rest; storing it in
# the in-memory / table rate-limit key is by design.
#
# js/missing-rate-limiting
# Only the MCP server has Express routes. Every one that does work is throttled by
# our own limiters (oauthRateLimit / oauthTokenRateLimit on /oauth/*, accessGuard
# on /mcp); /health and the OAuth discovery documents return static JSON.
# The query only recognizes limiters from npm packages (express-rate-limit and
# similar) and flags a route handler as soon as it calls a function named
# like *auth*, *login* or *verify*. So it reports throttled and unthrottled
# routes the same way, and every alert it ever raised was a false positive. The
# coverage check it stood in for is a test: every OAuth router route must carry
# a limiter or be named as exempt (MCP oauth-rate-limit.test.ts).
#
# Genuine one-off false positives from OTHER queries (e.g. an open-redirect the taint
# model can't see is allow-listed, a rate-limited route it doesn't recognize) are
# dismissed individually in the Security tab so those queries stay sharp — they are
# NOT suppressed here.
# model can't see is allow-listed) are dismissed individually in the Security tab so
# those queries stay sharp — they are NOT suppressed here.
#
# Log-injection (cs/log-forging) is deliberately NOT filtered: user-controlled values
# are sanitized at the sink via Helpers/LogSanitizer, so the query stays useful for
@@ -29,3 +39,5 @@ query-filters:
id: cs/exposure-of-sensitive-information
- exclude:
id: cs/cleartext-storage-of-sensitive-information
- exclude:
id: js/missing-rate-limiting
+28
View File
@@ -1,5 +1,9 @@
version: 2
# Cooldown: a version is proposed only once it has been public for 7 days, so a
# release that is yanked or found malicious within its first week never reaches a
# PR. Security updates are exempt from the cooldown by Dependabot's own rules.
#
# Grouping: every ecosystem gets one batched PR for minor/patch version
# updates and one batched PR for security updates. Groups apply to version
# updates only by default, so the security-updates groups are declared
@@ -10,6 +14,8 @@ updates:
directory: /
schedule:
interval: weekly
cooldown:
default-days: 7
open-pull-requests-limit: 5
groups:
dotnet:
@@ -23,6 +29,8 @@ updates:
directory: /src/Web/autopilot-monitor-web
schedule:
interval: weekly
cooldown:
default-days: 7
open-pull-requests-limit: 5
groups:
web:
@@ -41,6 +49,8 @@ updates:
directory: /src/McpServer/autopilot-monitor-mcp
schedule:
interval: weekly
cooldown:
default-days: 7
open-pull-requests-limit: 5
groups:
mcp:
@@ -55,6 +65,22 @@ updates:
- dependency-name: '*'
update-types: ['version-update:semver-major']
# Validator tooling for rules/ (ajv-cli); combine-rules.yml installs it from this
# lockfile with contents:write in hand, so the pins must not go stale.
- package-ecosystem: npm
directory: /rules/scripts
schedule:
interval: weekly
cooldown:
default-days: 7
open-pull-requests-limit: 5
groups:
rules-tooling:
patterns: ['*']
rules-tooling-security:
applies-to: security-updates
patterns: ['*']
# 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
@@ -63,6 +89,8 @@ updates:
directory: /
schedule:
interval: monthly
cooldown:
default-days: 7
groups:
actions:
patterns: ['*']
+40 -7
View File
@@ -1,5 +1,13 @@
name: Action Pin Gate
name: Workflow gates
# Two checks over the workflow files themselves:
# * verify-pins -- every third-party action is referenced by a full commit SHA plus a
# version comment (stricter than zizmor's unpinned-uses audit).
# * zizmor -- static analysis of every workflow (permissions, credential
# persistence, template injection, ...). Configuration and the
# reasoned ignores live in zizmor.yml at the repository root; the
# same run is expected locally before a workflow change is committed.
#
# 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
@@ -8,7 +16,8 @@ name: Action Pin Gate
#
# 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.
# commits it needs to inspect. Dependabot's action-pin PRs are the main customer: they
# rewrite workflow files without anyone running zizmor locally.
#
# 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
@@ -22,10 +31,10 @@ name: Action Pin Gate
on:
push:
branches: [main]
paths: ['.github/workflows/**']
paths: ['.github/workflows/**', '.github/dependabot.yml', 'zizmor.yml']
pull_request:
branches: [main]
paths: ['.github/workflows/**']
paths: ['.github/workflows/**', '.github/dependabot.yml', 'zizmor.yml']
workflow_dispatch:
permissions:
@@ -37,15 +46,18 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- 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
# Reusable workflows from this repository (workspace-relative ./ or the
# self-repository form $/) 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"
@@ -68,3 +80,24 @@ jobs:
exit 1
fi
echo "All action references are pinned to commit SHAs."
zizmor:
name: zizmor audit
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write # SARIF upload: findings land in the Code scanning tab next to CodeQL
actions: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
# zizmor itself is version-pinned like every other tool here; bump it together with
# the local install so the gate and the pre-commit run agree on the finding set.
# Informational findings (template expansion of our own step outputs in pwsh) are
# visible locally but do not fail the gate.
- uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4
with:
version: 1.30.1
min-severity: low
@@ -19,6 +19,8 @@ jobs:
runs-on: windows-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- name: Install Pester 5+
shell: powershell
+4 -2
View File
@@ -73,6 +73,8 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
# Every released build is signed; a missing variable stops the run before a build
# number is burnt.
@@ -91,7 +93,7 @@ jobs:
# 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
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
with:
client-id: ${{ env.CODE_SIGN_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
@@ -114,7 +116,7 @@ jobs:
# 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
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
+4 -2
View File
@@ -41,6 +41,8 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
# 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.
@@ -86,7 +88,7 @@ jobs:
# 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
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
with:
client-id: ${{ env.CODE_SIGN_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
@@ -105,7 +107,7 @@ jobs:
# The blob upload below is authorized by this federated identity, not by a SAS.
- name: Login to Azure (OIDC)
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
+12
View File
@@ -24,6 +24,7 @@ on:
- 'infra/**'
- '.claude/**'
- '.gitmodules'
- 'zizmor.yml'
- '**/*.md'
- 'LICENSE'
- '.github/ISSUE_TEMPLATE/**'
@@ -57,6 +58,7 @@ on:
- 'infra/**'
- '.claude/**'
- '.gitmodules'
- 'zizmor.yml'
- '**/*.md'
- 'LICENSE'
- '.github/ISSUE_TEMPLATE/**'
@@ -97,6 +99,8 @@ jobs:
runs-on: windows-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6
with:
@@ -128,6 +132,8 @@ jobs:
working-directory: src/Web/autopilot-monitor-web
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
with:
@@ -162,6 +168,8 @@ jobs:
working-directory: src/McpServer/autopilot-monitor-mcp
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
with:
@@ -196,6 +204,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
with:
@@ -217,6 +227,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
with:
+6 -2
View File
@@ -17,6 +17,7 @@ on:
- 'infra/**'
- '.claude/**'
- '.gitmodules'
- 'zizmor.yml'
- '**/*.md'
- 'LICENSE'
- '.github/ISSUE_TEMPLATE/**'
@@ -48,6 +49,7 @@ on:
- 'infra/**'
- '.claude/**'
- '.gitmodules'
- 'zizmor.yml'
- '**/*.md'
- 'LICENSE'
- '.github/ISSUE_TEMPLATE/**'
@@ -103,6 +105,8 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6
if: matrix.language == 'csharp'
@@ -110,7 +114,7 @@ jobs:
dotnet-version: '10.0.x'
- name: Initialize CodeQL
uses: github/codeql-action/init@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9
uses: github/codeql-action/init@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
@@ -121,6 +125,6 @@ jobs:
run: dotnet build AutopilotMonitor.sln --configuration Release
- name: Analyze
uses: github/codeql-action/analyze@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4.37.9
uses: github/codeql-action/analyze@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
with:
category: /language:${{ matrix.language }}
+9 -4
View File
@@ -30,11 +30,16 @@ jobs:
with:
node-version: '22'
# Exact versions and no lifecycle scripts: this job holds contents:write and pushes to
# Lockfile 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 --ignore-scripts ajv-cli@5.0.0 ajv-formats@3.0.1
# can rewrite the repository. rules/scripts/package-lock.json pins ajv-cli, ajv-formats
# and every transitive package (Dependabot keeps it current); ajv is pure JS and
# needs no install hooks.
- name: Install ajv-cli from the lockfile
working-directory: rules/scripts
run: |
npm ci --ignore-scripts
echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH"
- name: Validate Gather Rules
run: |
+3 -1
View File
@@ -20,9 +20,11 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- name: Login to Azure (OIDC)
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
+11 -8
View File
@@ -27,6 +27,8 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
# 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
@@ -38,6 +40,7 @@ jobs:
- name: Check out documentation bundle
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
repository: autopilotmonitor/autopilotmonitor-docs
path: mcp-docs
@@ -46,7 +49,7 @@ jobs:
run: echo "sha=$(git -C mcp-docs rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- name: Login to Azure (OIDC)
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
@@ -77,7 +80,7 @@ jobs:
"short_sha=$shortSha" >> $env:GITHUB_OUTPUT
- name: Login to ACR
run: az acr login --name ${{ env.ACR_NAME }}
run: az acr login --name "$ACR_NAME"
- name: Build and push container image
run: |
@@ -87,17 +90,17 @@ jobs:
--build-arg BUILD_NUMBER=${{ steps.version.outputs.build_number }} \
--build-arg BUILD_COMMIT=${{ steps.version.outputs.short_sha }} \
--build-arg BUILD_UTC=${{ steps.version.outputs.build_utc }} \
-t ${{ env.ACR_NAME }}.azurecr.io/${{ env.CONTAINER_APP_NAME }}:${{ env.IMAGE_TAG }} \
-t ${{ env.ACR_NAME }}.azurecr.io/${{ env.CONTAINER_APP_NAME }}:latest \
-t "$ACR_NAME.azurecr.io/$CONTAINER_APP_NAME:$IMAGE_TAG" \
-t "$ACR_NAME.azurecr.io/$CONTAINER_APP_NAME:latest" \
.
docker push ${{ env.ACR_NAME }}.azurecr.io/${{ env.CONTAINER_APP_NAME }} --all-tags
docker push "$ACR_NAME.azurecr.io/$CONTAINER_APP_NAME" --all-tags
- name: Deploy to Container App
run: |
az containerapp update \
--name ${{ env.CONTAINER_APP_NAME }} \
--resource-group ${{ env.RESOURCE_GROUP }} \
--image ${{ env.ACR_NAME }}.azurecr.io/${{ env.CONTAINER_APP_NAME }}:${{ env.IMAGE_TAG }}
--name "$CONTAINER_APP_NAME" \
--resource-group "$RESOURCE_GROUP" \
--image "$ACR_NAME.azurecr.io/$CONTAINER_APP_NAME:$IMAGE_TAG"
# `az containerapp update` returns once the revision is provisioned, not once
# it serves traffic — and with minReplicas=0 the first request also pays a cold
+3 -1
View File
@@ -37,13 +37,14 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
lfs: false
fetch-depth: 0 # Full history needed for git-based sitemap lastmod dates
# Only the version manifest at the very end needs Azure; logging in here rather than
# next to that step keeps a credential problem from surfacing after a live deploy.
- name: Login to Azure (OIDC)
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
@@ -58,6 +59,7 @@ jobs:
- name: Check out documentation bundle
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
repository: autopilotmonitor/autopilotmonitor-docs
path: whats-new-docs
fetch-depth: 0
+3
View File
@@ -3,6 +3,9 @@ name: IndexNow Notify (Bing/Yandex)
on:
workflow_dispatch:
# The job only talks to public endpoints; it never needs a repository token.
permissions: {}
jobs:
notify:
runs-on: ubuntu-latest
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
name: Federated login + read check
steps:
- name: Login to Azure (OIDC)
uses: azure/login@7ddb5af1ef8758cf1353cf3b42f940aee27ba21c # v3
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
+2 -1
View File
@@ -25,5 +25,6 @@ concurrency:
cancel-in-progress: true
jobs:
# $/ is the self-repository form: this repository at the running commit.
gates:
uses: ./.github/workflows/bootstrap-script-gates.yml
uses: $/.github/workflows/bootstrap-script-gates.yml
+12 -4
View File
@@ -26,7 +26,6 @@ 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
@@ -46,15 +45,24 @@ env:
CODE_SIGN_TIMESTAMP_URL: http://timestamp.acs.microsoft.com
jobs:
# $/ is the self-repository form: this repository at the running commit, never a
# path some earlier step could have written to the workspace.
gates:
uses: ./.github/workflows/bootstrap-script-gates.yml
uses: $/.github/workflows/bootstrap-script-gates.yml
publish:
name: Publish to the download alias
needs: gates
runs-on: windows-latest
# Job-scoped: only the publish job federates to Azure, the gates job never holds an
# OIDC token it does not need.
permissions:
contents: read
id-token: write # OIDC federated login for the storage writes (secret-less)
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- name: Check code-signing configuration
shell: pwsh
@@ -70,7 +78,7 @@ jobs:
# 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
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
with:
client-id: ${{ env.CODE_SIGN_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
@@ -91,7 +99,7 @@ jobs:
# 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
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
+1 -1
Submodule infra updated: 8a8f8c66dd...be0165a223
+1
View File
@@ -300,6 +300,7 @@
"script_completed",
"script_failed",
"script_timeout_suspected",
"script_recurrence_summary",
"esp_phase_changed",
"ime_agent_version",
"ime_token_failure",
+3
View File
@@ -0,0 +1,3 @@
# ajv-cli declares ts-node as a peer dependency it never needs for JSON schemas; do not
# pull ts-node + typescript into a job that pushes to main.
legacy-peer-deps=true
+315
View File
@@ -0,0 +1,315 @@
{
"name": "autopilot-monitor-rules-tooling",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "autopilot-monitor-rules-tooling",
"devDependencies": {
"ajv-cli": "5.0.0",
"ajv-formats": "3.0.1"
}
},
"node_modules/ajv": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
"dev": true,
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1",
"json-schema-traverse": "^1.0.0",
"require-from-string": "^2.0.2"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/epoberezkin"
}
},
"node_modules/ajv-cli": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/ajv-cli/-/ajv-cli-5.0.0.tgz",
"integrity": "sha512-LY4m6dUv44HTyhV+u2z5uX4EhPYTM38Iv1jdgDJJJCyOOuqB8KtZEGjPZ2T+sh5ZIJrXUfgErYx/j3gLd3+PlQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"ajv": "^8.0.0",
"fast-json-patch": "^2.0.0",
"glob": "^7.1.0",
"js-yaml": "^3.14.0",
"json-schema-migrate": "^2.0.0",
"json5": "^2.1.3",
"minimist": "^1.2.0"
},
"bin": {
"ajv": "dist/index.js"
},
"peerDependencies": {
"ts-node": ">=9.0.0"
},
"peerDependenciesMeta": {
"ts-node": {
"optional": true
}
}
},
"node_modules/ajv-formats": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",
"integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"ajv": "^8.0.0"
},
"peerDependencies": {
"ajv": "^8.0.0"
},
"peerDependenciesMeta": {
"ajv": {
"optional": true
}
}
},
"node_modules/argparse": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
"integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
"dev": true,
"license": "MIT",
"dependencies": {
"sprintf-js": "~1.0.2"
}
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"dev": true,
"license": "MIT"
},
"node_modules/brace-expansion": {
"version": "1.1.21",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz",
"integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
}
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
"dev": true,
"license": "MIT"
},
"node_modules/esprima": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
"integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
"dev": true,
"license": "BSD-2-Clause",
"bin": {
"esparse": "bin/esparse.js",
"esvalidate": "bin/esvalidate.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"dev": true,
"license": "MIT"
},
"node_modules/fast-json-patch": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/fast-json-patch/-/fast-json-patch-3.1.1.tgz",
"integrity": "sha512-vf6IHUX2SBcA+5/+4883dsIjpBTqmfBjmYiWK1savxQmFk4JfBMLa7ynTYOs1Rolp/T1betJxHiGD3g1Mn8lUQ==",
"dev": true,
"license": "MIT"
},
"node_modules/fast-uri": {
"version": "3.1.8",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz",
"integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"license": "BSD-3-Clause"
},
"node_modules/fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
"dev": true,
"license": "ISC"
},
"node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
"dev": true,
"license": "ISC",
"dependencies": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^3.1.1",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
},
"engines": {
"node": "*"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
"integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
"deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.",
"dev": true,
"license": "ISC",
"dependencies": {
"once": "^1.3.0",
"wrappy": "1"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"dev": true,
"license": "ISC"
},
"node_modules/js-yaml": {
"version": "3.15.2",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz",
"integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==",
"dev": true,
"license": "MIT",
"dependencies": {
"argparse": "^1.0.7",
"esprima": "^4.0.0"
},
"bin": {
"js-yaml": "bin/js-yaml.js"
}
},
"node_modules/json-schema-migrate": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/json-schema-migrate/-/json-schema-migrate-2.0.0.tgz",
"integrity": "sha512-r38SVTtojDRp4eD6WsCqiE0eNDt4v1WalBXb9cyZYw9ai5cGtBwzRNWjHzJl38w6TxFkXAIA7h+fyX3tnrAFhQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"ajv": "^8.0.0"
}
},
"node_modules/json-schema-traverse": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"dev": true,
"license": "MIT"
},
"node_modules/json5": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
"integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
"dev": true,
"license": "MIT",
"bin": {
"json5": "lib/cli.js"
},
"engines": {
"node": ">=6"
}
},
"node_modules/minimatch": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz",
"integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==",
"dev": true,
"license": "ISC",
"dependencies": {
"brace-expansion": "^1.1.7"
},
"engines": {
"node": "*"
}
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"dev": true,
"license": "ISC",
"dependencies": {
"wrappy": "1"
}
},
"node_modules/path-is-absolute": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
"integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/sprintf-js": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
"integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"dev": true,
"license": "ISC"
}
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"name": "autopilot-monitor-rules-tooling",
"private": true,
"description": "Validator tooling for rules/ - combine-rules.yml installs from the lockfile so nothing unpinned reaches a job that pushes to main.",
"devDependencies": {
"ajv-cli": "5.0.0",
"ajv-formats": "3.0.1"
},
"overrides": {
"fast-json-patch": "3.1.1"
}
}
@@ -29,10 +29,9 @@
Cloud PCs are never Autopilot-registered, so this enables agent monitoring
of Cloud PC first-connect enrollment)
- IntuneDeviceBinding -> DeviceManagementManagedDevices.Read.All
(cert-to-device binding: verifies that the Intune device id carried in the
agent's client certificate is a device THIS tenant actually enrolled --
currently a Global-Admin-only preview that records telemetry and does not
block enrollment)
(Intune Enrollment Validation: accepts devices enrolled in THIS tenant's
Intune, matched by the Intune device id in the agent's client certificate,
without Autopilot registration, corporate identifier or device association)
- All -> every optional permission above, in one run
(also works with -Revoke to remove all optional grants at once)
@@ -76,15 +75,17 @@
.NOTES
Requires:
- Microsoft.Graph.Authentication PowerShell module (auto-installs if missing).
- Sign-in as Global Administrator OR Privileged Role Administrator OR Cloud Application Administrator.
- Sign-in as Global Administrator OR Privileged Role Administrator (with PIM, activate the
role first). Only these roles may assign Microsoft Graph application permissions;
Application Administrator and Cloud Application Administrator are not enough.
- The Autopilot Monitor app must be admin-consented in your tenant first
(its service principal must exist before grants can be added).
Sign-in behaviour:
In Azure Cloud Shell the script signs in via the ambient identity endpoint (a delegated
token for the already-signed-in user) - no device-code prompt, which Conditional Access
policies commonly block. Outside Cloud Shell it falls back to a normal interactive
Microsoft Graph sign-in. -TenantId only applies to the interactive fallback.
- The Autopilot Monitor app must be admin-consented in your tenant first
(its service principal must exist before grants can be added).
After granting:
The Autopilot Monitor backend may cache an older token for up to ~1 hour. Use the
@@ -140,6 +141,36 @@ if ($PSCmdlet.ParameterSetName -eq 'ByFeatures') {
# ---- Constants ----
$MicrosoftGraphAppId = '00000003-0000-0000-c000-000000000000'
# ---- Graph failure details ----
# Invoke-MgGraphRequest puts only "Response status code does not indicate success: ..." into the
# exception message. Graph's own error (code + message) is the response body in ErrorDetails,
# behind the request line, the status line and the headers. Some headers carry JSON themselves
# (x-ms-ags-diagnostic), so the body is taken from behind the blank line that ends the headers.
function Get-GraphFailure {
param([System.Management.Automation.ErrorRecord]$ErrorRecord)
$status = 0
if ($ErrorRecord.Exception.PSObject.Properties['Response'] -and $ErrorRecord.Exception.Response) {
$status = [int]$ErrorRecord.Exception.Response.StatusCode
}
$text = $ErrorRecord.Exception.Message
if ($ErrorRecord.ErrorDetails -and $ErrorRecord.ErrorDetails.Message) {
$body = ($ErrorRecord.ErrorDetails.Message -split '\r?\n\r?\n', 2)[-1].Trim()
if ($body.StartsWith('{')) {
try {
$graphError = ($body | ConvertFrom-Json).error
if ($graphError.code) { $text = "$($graphError.code): $($graphError.message)" }
}
catch {
# Not a Graph JSON body - keep the exception message.
}
}
}
[pscustomobject]@{ Status = $status; Text = $text }
}
# ---- Pre-flight: module ----
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Authentication)) {
Write-Host "[Setup] Microsoft.Graph.Authentication not installed. Installing for current user..." -ForegroundColor Yellow
@@ -189,7 +220,7 @@ Write-Host "[Auth] Granted scopes: $($ctx.Scopes -join ', ')"
# carries a fixed scope set (incl. Directory.AccessAsUser.All) instead of the requested scopes,
# and its effective rights follow the signed-in user's directory role.
if (-not $identityConnected -and -not ($ctx.Scopes -contains 'AppRoleAssignment.ReadWrite.All')) {
Write-Warning "Scope 'AppRoleAssignment.ReadWrite.All' was NOT granted. The signed-in user likely lacks the required role (Global Admin / Privileged Role Admin / Cloud App Admin)."
Write-Warning "Scope 'AppRoleAssignment.ReadWrite.All' was NOT granted. The signed-in user likely lacks the required role (Global Administrator or Privileged Role Administrator)."
if (-not $VerifyOnly) { return }
}
@@ -263,6 +294,7 @@ $action = if ($Revoke) { 'Revoke' } else { 'Grant' }
Write-Host "[4/4] $action mode - processing $($Permissions.Count) permission(s)..." -ForegroundColor Cyan
$results = @()
$graphForbidden = $false
foreach ($permName in $Permissions) {
$appRole = $graphSp.appRoles | Where-Object {
$_.value -eq $permName -and $_.allowedMemberTypes -contains 'Application'
@@ -289,7 +321,9 @@ foreach ($permName in $Permissions) {
$results += [pscustomobject]@{ Permission = $permName; Status = 'Revoked' }
}
catch {
Write-Warning " [FAIL] '$permName' revoke failed: $($_.Exception.Message)"
$failure = Get-GraphFailure $_
if ($failure.Status -eq 403) { $graphForbidden = $true }
Write-Warning " [FAIL] '$permName' revoke failed: $($failure.Text)"
$results += [pscustomobject]@{ Permission = $permName; Status = 'Failed' }
}
}
@@ -316,7 +350,9 @@ foreach ($permName in $Permissions) {
$results += [pscustomobject]@{ Permission = $permName; Status = 'Granted' }
}
catch {
Write-Warning " [FAIL] '$permName' grant failed: $($_.Exception.Message)"
$failure = Get-GraphFailure $_
if ($failure.Status -eq 403) { $graphForbidden = $true }
Write-Warning " [FAIL] '$permName' grant failed: $($failure.Text)"
$results += [pscustomobject]@{ Permission = $permName; Status = 'Failed' }
}
}
@@ -325,6 +361,9 @@ foreach ($permName in $Permissions) {
Write-Host ""
Write-Host "=========== Summary ===========" -ForegroundColor Cyan
$results | Format-Table -AutoSize | Out-Host
if ($graphForbidden) {
Write-Warning "Microsoft Graph refused the change (403): the signed-in account may not manage Microsoft Graph application permissions. Sign in as Global Administrator or Privileged Role Administrator (with PIM, activate the role first) and run the script again."
}
Write-Host ""
Write-Host "Note: token-cached backends may need up to ~1h to see the new permission set." -ForegroundColor Yellow
Write-Host " Use 'Refresh permission status' in the admin UI to apply changes immediately." -ForegroundColor Yellow
@@ -186,5 +186,20 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
DateTime resolved;
Assert.False(sut.TryResolveUtc(Source, UtcNow, out resolved));
}
[Theory]
[InlineData(3610.39, true, 4)] // session 4377911b: +1 h on a 10 s script
[InlineData(61203.0, true, 68)] // 17 h on a 3 s script
[InlineData(7205.66, true, 8)] // session cbaed57b: +2 h
[InlineData(-3596.0, true, 4)] // the same error on the start end
[InlineData(26.4, false, 0)] // a run time below one grid step
[InlineData(1030.0, false, 1)] // 17 min 10 s: residual past the tolerance
[InlineData(900.0, true, 1)] // exactly one step — a genuine 15-minute run reads the same, the caller needs mixed provenance too
public void A_grid_sized_span_is_the_signature_of_an_offset_error(double seconds, bool onGrid, int expectedSteps)
{
int steps;
Assert.Equal(onGrid, CmTraceOffsetCalibrator.IsOnOffsetGrid(TimeSpan.FromSeconds(seconds), out steps));
if (onGrid) Assert.Equal(expectedSteps, steps);
}
}
}
@@ -304,5 +304,29 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
tracker.HandlePlatformScriptStarted("policyZ");
Assert.Single(started);
}
[Fact]
public void Emitted_marker_is_capped_at_the_clock_so_the_next_run_still_opens_a_slot()
{
// Session 4377911b: the result line was re-read after an overwrite rewind and resolved
// in the reader's zone, one hour ahead of the clock. Stored uncapped, that stamp made
// the genuine second run's start line read as a late line of the first run and its
// result a duplicate.
using var h = new Harness();
h.Start("d94468af", T0.AddSeconds(-10));
h.Result("d94468af", T0.AddHours(1));
h.Exit("d94468af", T0.AddSeconds(-1));
h.Flush();
Assert.Single(h.Completed);
// The second run, two minutes later on the clock — still "before" the uncapped stamp.
h.Now = T0.AddMinutes(2);
h.Start("d94468af", h.Now.AddSeconds(-5));
h.Result("d94468af", h.Now.AddSeconds(-1));
h.Exit("d94468af", h.Now.AddSeconds(-2));
h.Flush();
Assert.Equal(2, h.Completed.Count);
}
}
}
@@ -154,5 +154,45 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Ime
Assert.False(tracker2.TryClaimScriptTimeoutSuspected("policyF")); // cross-restart dedup
Assert.True(tracker2.TryClaimScriptTimeoutSuspected("policyG")); // other policies unaffected
}
[Fact]
public void Line_provenance_of_a_pending_script_survives_restart()
{
using var tmp = new TempDirectory();
var observedAt = new DateTime(2026, 9, 17, 13, 20, 7, DateTimeKind.Utc);
var start = new CmTraceLineProvenance
{
SourceLocalTs = new DateTime(2026, 9, 17, 15, 19, 57, DateTimeKind.Unspecified),
Origin = CmTraceOffsetOrigin.LineAnchored,
OffsetMinutes = 120,
MeasuredWriterOffsetMinutes = 120,
SourceFileName = "IntuneManagementExtension.log",
};
var exit = new CmTraceLineProvenance
{
SourceLocalTs = new DateTime(2026, 9, 17, 15, 20, 7, DateTimeKind.Unspecified),
Origin = CmTraceOffsetOrigin.None,
OffsetMinutes = 60,
SourceFileName = "AgentExecutor.log",
};
var tracker1 = BuildTracker(tmp, out _);
tracker1.SeedPendingPlatformScriptForTesting("policyH", exitCode: 0, exitObservedAtUtc: observedAt,
startedAtUtc: observedAt.AddSeconds(-10), startedAtProvenance: start, exitProvenance: exit);
tracker1.SaveStateForTest();
var tracker2 = BuildTracker(tmp, out var emitted2);
tracker2.LoadStateForTest();
tracker2.FlushPendingPlatformScriptResults(observedAt.AddSeconds(20));
var script = Assert.Single(emitted2);
Assert.Equal(CmTraceOffsetOrigin.LineAnchored, script.StartedAtProvenance.Origin);
Assert.Equal(120, script.StartedAtProvenance.OffsetMinutes);
Assert.Equal(start.SourceLocalTs, script.StartedAtProvenance.SourceLocalTs);
Assert.Equal(DateTimeKind.Unspecified, script.StartedAtProvenance.SourceLocalTs!.Value.Kind); // no zone was ever attached
Assert.Equal("AgentExecutor.log", script.ExitProvenance.SourceFileName);
Assert.Equal(60, script.ExitProvenance.OffsetMinutes);
Assert.Null(script.ResultProvenance);
}
}
}
@@ -0,0 +1,267 @@
using System;
using System.Collections.Generic;
using System.Linq;
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>
/// IME re-runs health-script policies on its own schedule for as long as the device is up.
/// A session that waited days for its user reported every hourly run of every policy
/// (field: 9 policies × 94 runs in one session). The gate emits the first run and every
/// changed result, counts the rest, and keeps the start/result pairing intact that the
/// running indicators rely on.
/// </summary>
public sealed class RecurringScriptGateTests
{
private const string Policy = "11111111-2222-3333-4444-555555555555";
private static readonly DateTime T0 = new DateTime(2026, 9, 16, 20, 0, 0, DateTimeKind.Utc);
private static ScriptExecutionState Early(string compliance, int exit = 0, string? stderr = null) =>
new ScriptExecutionState
{
PolicyId = Policy, ScriptType = "remediation", ScriptPart = "detection",
ComplianceResult = compliance, ExitCode = exit, Stderr = stderr, DurationBasis = "script_runtime",
};
private static ScriptExecutionState Consolidated(string compliance, int exit = 0, int status = 1) =>
new ScriptExecutionState
{
PolicyId = Policy, ScriptType = "remediation", ScriptPart = "detection",
ComplianceResult = compliance, ExitCode = exit, RemediationStatus = status,
DurationBasis = "cycle_including_reporting_latency",
};
[Fact]
public void First_run_emits_start_and_result()
{
var gate = new RecurringScriptGate();
Assert.True(gate.OnStart(Policy, T0, "6", "HS-SCRIPT-START"));
Assert.True(gate.OnResult(Early("True"), T0.AddSeconds(5), out var released));
Assert.Null(released);
}
[Fact]
public void Repeated_result_is_counted_and_its_start_stays_held()
{
var gate = new RecurringScriptGate();
gate.OnStart(Policy, T0, "6", "HS-SCRIPT-START");
gate.OnResult(Early("True"), T0.AddSeconds(5), out _);
Assert.False(gate.OnStart(Policy, T0.AddHours(1), "6", "HS-SCRIPT-START"));
Assert.False(gate.OnResult(Early("True"), T0.AddHours(1).AddSeconds(5), out var released));
Assert.Null(released);
var summary = Assert.Single(gate.TakeSummaries());
Assert.Equal(2, summary.RunsObserved);
Assert.Equal(1, summary.RunsCollapsed);
Assert.Equal(1, summary.CollapsedResults);
Assert.Equal(T0.AddHours(1).AddSeconds(5), summary.LastCollapsedAtUtc);
}
[Fact]
public void Changed_result_releases_the_held_start_with_its_own_timestamp()
{
var gate = new RecurringScriptGate();
gate.OnStart(Policy, T0, "6", "HS-SCRIPT-START");
gate.OnResult(Early("True"), T0.AddSeconds(5), out _);
var secondStart = T0.AddHours(1);
gate.OnStart(Policy, secondStart, "6", "HS-SCRIPT-START");
Assert.True(gate.OnResult(Early("False", exit: 1), secondStart.AddSeconds(5), out var released));
Assert.NotNull(released);
Assert.Equal(Policy, released.PolicyId);
Assert.Equal(secondStart, released.SourceTimestampUtc);
Assert.Equal("HS-SCRIPT-START", released.PatternId);
Assert.Equal("6", released.PolicyType);
Assert.Empty(gate.TakeSummaries());
}
[Fact]
public void New_stderr_counts_as_a_changed_result()
{
var gate = new RecurringScriptGate();
gate.OnStart(Policy, T0, "6", "p");
gate.OnResult(Early("True"), T0, out _);
gate.OnStart(Policy, T0.AddHours(1), "6", "p");
Assert.True(gate.OnResult(Early("True", stderr: "Get-ChildItem : path not found"), T0.AddHours(1), out _));
}
[Fact]
public void Early_signal_and_consolidated_result_do_not_overwrite_each_other()
{
// Both describe the detection phase, but only the consolidated one knows
// RemediationStatus. Sharing one signature slot would make every run look changed.
var gate = new RecurringScriptGate();
gate.OnStart(Policy, T0, "6", "p");
Assert.True(gate.OnResult(Early("True"), T0, out _));
Assert.True(gate.OnResult(Consolidated("True"), T0.AddMinutes(1), out _));
gate.OnStart(Policy, T0.AddHours(1), "6", "p");
Assert.False(gate.OnResult(Early("True"), T0.AddHours(1), out _));
Assert.False(gate.OnResult(Consolidated("True"), T0.AddHours(1).AddMinutes(1), out _));
}
[Fact]
public void Held_start_without_result_is_released_only_after_the_grace()
{
var gate = new RecurringScriptGate();
gate.OnStart(Policy, T0, "6", "p");
gate.OnResult(Early("True"), T0, out _);
var heldAt = T0.AddHours(1);
gate.OnStart(Policy, heldAt, "6", "p");
Assert.Empty(gate.ReleaseStartsWithoutResult(heldAt.AddMinutes(29), TimeSpan.FromMinutes(30)));
var released = Assert.Single(gate.ReleaseStartsWithoutResult(heldAt.AddMinutes(31), TimeSpan.FromMinutes(30)));
Assert.Equal(heldAt, released.SourceTimestampUtc);
Assert.Empty(gate.ReleaseStartsWithoutResult(heldAt.AddHours(2), TimeSpan.FromMinutes(30)));
}
[Fact]
public void Held_start_whose_result_was_collapsed_is_never_released_as_unfinished()
{
var gate = new RecurringScriptGate();
gate.OnStart(Policy, T0, "6", "p");
gate.OnResult(Early("True"), T0, out _);
gate.OnStart(Policy, T0.AddHours(1), "6", "p");
gate.OnResult(Early("True"), T0.AddHours(1), out _);
Assert.Empty(gate.ReleaseStartsWithoutResult(T0.AddDays(1), TimeSpan.FromMinutes(30)));
}
[Fact]
public void Run_superseded_by_the_next_start_counts_as_without_result()
{
var gate = new RecurringScriptGate();
gate.OnStart(Policy, T0, "6", "p");
gate.OnResult(Early("True"), T0, out _);
gate.OnStart(Policy, T0.AddHours(1), "6", "p"); // no result
gate.OnStart(Policy, T0.AddHours(2), "6", "p");
gate.OnResult(Early("True"), T0.AddHours(2), out _);
var summary = Assert.Single(gate.TakeSummaries());
Assert.Equal(3, summary.RunsObserved);
Assert.Equal(1, summary.RunsWithoutResult);
Assert.Equal(1, summary.RunsCollapsed);
}
[Fact]
public void Summary_reports_growth_only()
{
var gate = new RecurringScriptGate();
gate.OnStart(Policy, T0, "6", "p");
gate.OnResult(Early("True"), T0, out _);
gate.OnStart(Policy, T0.AddHours(1), "6", "p");
gate.OnResult(Early("True"), T0.AddHours(1), out _);
Assert.Single(gate.TakeSummaries());
Assert.Empty(gate.TakeSummaries());
gate.OnStart(Policy, T0.AddHours(2), "6", "p");
gate.OnResult(Early("True"), T0.AddHours(2), out _);
Assert.Equal(2, Assert.Single(gate.TakeSummaries()).RunsCollapsed);
}
[Fact]
public void State_round_trips_through_json()
{
var gate = new RecurringScriptGate();
gate.OnStart(Policy, T0, "6", "p");
gate.OnResult(Early("True"), T0, out _);
gate.OnStart(Policy, T0.AddHours(1), "6", "p");
var json = JsonConvert.SerializeObject(gate.ToPersisted());
var restored = new RecurringScriptGate();
restored.Restore(JsonConvert.DeserializeObject<Dictionary<string, RecurringScriptPolicyState>>(json));
// The restored gate still knows the last report and still holds the second start.
Assert.True(restored.OnResult(Early("False", exit: 1), T0.AddHours(1).AddSeconds(5), out var released));
Assert.Equal(T0.AddHours(1), released.SourceTimestampUtc);
}
// ── Through the tracker ───────────────────────────────────────────────────
private sealed class Rig
{
public readonly List<ScriptStartedInfo> Started = new List<ScriptStartedInfo>();
public readonly List<ScriptExecutionState> Completed = new List<ScriptExecutionState>();
public readonly List<ScriptRecurrenceSummary> Summaries = new List<ScriptRecurrenceSummary>();
public readonly ImeLogTracker Tracker;
public Rig(TempDirectory tmp)
{
Tracker = new ImeLogTracker(
logFolder: tmp.Path,
patterns: new List<ImeLogPattern>(),
logger: new AgentLogger(tmp.Path, AgentLogLevel.Info),
stateDirectory: tmp.Path);
Tracker.OnScriptStarted = Started.Add;
Tracker.OnScriptCompleted = Completed.Add;
Tracker.OnScriptRecurrenceSummary = Summaries.Add;
}
public void Run(DateTime startedAtUtc, string compliance)
{
Tracker.HandleHealthScriptStartForTest(Policy, startedAtUtc);
Tracker.HandleHealthScriptDetectionResultForTest(Policy, compliance, "pre", exitCode: compliance == "True" ? 0 : 1);
}
}
[Fact]
public void Tracker_collapses_repeats_across_a_restart_and_reports_them_on_stop()
{
using var tmp = new TempDirectory();
var first = new Rig(tmp);
first.Run(T0, "True");
first.Run(T0.AddHours(1), "True");
Assert.Single(first.Started);
Assert.Single(first.Completed);
first.Tracker.SaveStateForTest();
// Restart (reboot kill, WhiteGlove Part 2): the last report and the counter are back.
var second = new Rig(tmp);
second.Tracker.LoadStateForTest();
second.Run(T0.AddHours(2), "True");
Assert.Empty(second.Started);
Assert.Empty(second.Completed);
second.Run(T0.AddHours(3), "False");
var start = Assert.Single(second.Started);
Assert.Equal(T0.AddHours(3), start.SourceTimestampUtc);
Assert.Equal("False", Assert.Single(second.Completed).ComplianceResult);
second.Tracker.FlushRecurringScripts(T0.AddHours(4), shuttingDown: true);
var summary = Assert.Single(second.Summaries);
Assert.Equal(4, summary.RunsObserved);
Assert.Equal(2, summary.RunsCollapsed);
}
[Fact]
public void Tracker_leaves_platform_scripts_alone()
{
using var tmp = new TempDirectory();
var rig = new Rig(tmp);
var observedAt = T0;
for (var run = 0; run < 2; run++)
{
rig.Tracker.SeedPendingPlatformScriptForTesting("platformA", exitCode: 0, exitObservedAtUtc: observedAt.AddMinutes(run * 10));
rig.Tracker.CompletePlatformScriptFromImeResultForTesting("platformA", "Success", observedAt.AddMinutes(run * 10 + 1));
}
Assert.Equal(2, rig.Completed.Count(s => s.ScriptType == "platform"));
rig.Tracker.FlushRecurringScripts(T0.AddDays(1), shuttingDown: true);
Assert.Empty(rig.Summaries);
}
}
}
@@ -59,9 +59,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
public void ClassifyEnforcementState_bands(int state, string expected)
=> Assert.Equal(expected, ImeRegistryAppStateObserver.ClassifyEnforcementState(state));
// IME AppInstallStatus values (StatusServiceReports\..\Status), stable IME 1.50 .. 1.106.
// 1001/1003 sit inside the 1000 band but are NOT terminal — IME maps every InProgress
// enforcement state to 1001 (verified in the decompiled 1.106 StatusServiceHelpers).
[Theory]
[InlineData(1000, "installed")]
[InlineData(1999, "installed")]
[InlineData(1002, "installed")]
[InlineData(1004, "installed")]
[InlineData(1001, "installing")]
[InlineData(1003, "installing")]
[InlineData(1005, null)]
[InlineData(1999, null)]
[InlineData(3000, "failed")]
[InlineData(2000, "notApplicable")]
[InlineData(2999, "notApplicable")]
@@ -72,6 +80,35 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
public void ClassifyStatusServiceStatus_bands(int status, string? expected)
=> Assert.Equal(expected, ImeRegistryAppStateObserver.ClassifyStatusServiceStatus(status));
[Fact]
public void TryParseRegistryDateTime_reads_both_ime_shapes_as_utc()
{
// ExecutionDeadlineTime: DateTime.ToString(InvariantCulture), UTC without a kind marker.
var deadline = ImeRegistryAppStateObserver.TryParseRegistryDateTime("09/23/2026 18:00:00");
Assert.Equal(new DateTime(2026, 9, 23, 18, 0, 0, DateTimeKind.Utc), deadline);
Assert.Equal(DateTimeKind.Utc, deadline!.Value.Kind);
// DeferUntilTime: round-trip "o" with trailing Z.
var until = ImeRegistryAppStateObserver.TryParseRegistryDateTime("2026-09-23T10:30:00.0000000Z");
Assert.Equal(new DateTime(2026, 9, 23, 10, 30, 0, DateTimeKind.Utc), until);
Assert.Equal(DateTimeKind.Utc, until!.Value.Kind);
Assert.Null(ImeRegistryAppStateObserver.TryParseRegistryDateTime(null));
Assert.Null(ImeRegistryAppStateObserver.TryParseRegistryDateTime(""));
Assert.Null(ImeRegistryAppStateObserver.TryParseRegistryDateTime("not a date"));
Assert.Null(ImeRegistryAppStateObserver.TryParseRegistryDateTime(42));
}
[Fact]
public void TryReadBool_parses_registry_strings_only()
{
Assert.True(ImeRegistryAppStateObserver.TryReadBool("True"));
Assert.False(ImeRegistryAppStateObserver.TryReadBool("false"));
Assert.Null(ImeRegistryAppStateObserver.TryReadBool("yes"));
Assert.Null(ImeRegistryAppStateObserver.TryReadBool(1));
Assert.Null(ImeRegistryAppStateObserver.TryReadBool(null));
}
[Fact]
public void TerminalOutcome_prefers_enforcement_state_then_status_service()
{
@@ -88,6 +125,49 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
Assert.Null(ImeRegistryAppStateObserver.TerminalOutcome(Entry(enforcementState: 3000)));
Assert.Null(ImeRegistryAppStateObserver.TerminalOutcome(Entry(statusServiceStatus: 2500)));
Assert.Null(ImeRegistryAppStateObserver.TerminalOutcome(Entry()));
// Installing (1001) / InstallingPendingReboot (1003) share the 1000 band but are not terminal.
Assert.Null(ImeRegistryAppStateObserver.TerminalOutcome(Entry(statusServiceStatus: 1001)));
Assert.Null(ImeRegistryAppStateObserver.TerminalOutcome(Entry(enforcementState: 2009, statusServiceStatus: 1003)));
}
[Fact]
public void ChangedFields_reports_wait_state_triggers_only()
{
var prev = Entry(enforcementState: 2009);
var next = Entry(enforcementState: 2009,
installDeadlineUtc: T0.AddHours(2),
deferralsUsed: 1, deferralMaxDeferrals: 3, deferUntilUtc: T0.AddMinutes(30), deferralAutoDeferred: false);
Assert.Equal(new[] { "installDeadline", "deferralsUsed", "deferUntil" },
ImeRegistryAppStateObserver.ChangedFields(prev, next));
// MaxDeferrals / AutoDeferred alone are data, not a transition.
var sameCounters = Entry(enforcementState: 2009,
installDeadlineUtc: T0.AddHours(2),
deferralsUsed: 1, deferralMaxDeferrals: 5, deferUntilUtc: T0.AddMinutes(30), deferralAutoDeferred: true);
Assert.Empty(ImeRegistryAppStateObserver.ChangedFields(next, sameCounters));
// A cleared deadline is a transition too (IME clears it when the next download starts).
Assert.Equal(new[] { "installDeadline" },
ImeRegistryAppStateObserver.ChangedFields(
Entry(installDeadlineUtc: T0.AddHours(2)), Entry()));
}
[Fact]
public void DescribeWaitState_texts()
{
Assert.Equal(string.Empty, ImeRegistryAppStateObserver.DescribeWaitState(Entry(enforcementState: 2009)));
Assert.Equal(", downloaded, install deadline 2026-08-18 10:00 UTC",
ImeRegistryAppStateObserver.DescribeWaitState(Entry(installDeadlineUtc: T0.AddHours(2))));
Assert.Equal(", deferred by user 1/3 until 2026-08-18 08:30 UTC",
ImeRegistryAppStateObserver.DescribeWaitState(Entry(
deferralsUsed: 1, deferralMaxDeferrals: 3, deferUntilUtc: T0.AddMinutes(30), deferralAutoDeferred: false)));
Assert.Equal(", auto-deferred 2/3",
ImeRegistryAppStateObserver.DescribeWaitState(Entry(
deferralsUsed: 2, deferralMaxDeferrals: 3, deferralAutoDeferred: true)));
// Zero deferrals used is not a deferral; a missing max falls back to the bare count.
Assert.Equal(string.Empty, ImeRegistryAppStateObserver.DescribeWaitState(Entry(deferralsUsed: 0, deferralMaxDeferrals: 3)));
Assert.Equal(", deferred by user 1", ImeRegistryAppStateObserver.DescribeWaitState(Entry(deferralsUsed: 1)));
}
[Fact]
@@ -184,6 +264,54 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
Assert.Equal("success", evt.Payload["enforcementClass"]);
}
[Fact]
public void Wait_state_changes_emit_state_events_with_data_and_text()
{
var (sink, clock, observer) = CreateObserver(trackerApps: null);
var current = Snapshot((App1, 2009, null));
using (new ImeRegistryAppStateObserver.ScopedSnapshotOverride(() => current))
{
observer.Tick("baseline");
// Download finished, IME parks the app until its install deadline (1.106 ExecutionDeadlineTime).
var withDeadline = Snapshot((App1, 2009, null));
withDeadline.Entries.Values.Single().InstallDeadlineUtc = T0.AddHours(2);
current = withDeadline;
observer.Tick("registry_change");
// A required app hits a running process and the user defers (1.105 app-in-use deferral).
var deferred = Snapshot((App1, 2014, null));
var entry = deferred.Entries.Values.Single();
entry.InstallDeadlineUtc = T0.AddHours(2);
entry.DeferralsUsed = 1;
entry.DeferralMaxDeferrals = 3;
entry.DeferUntilUtc = T0.AddMinutes(30);
entry.DeferralAutoDeferred = false;
current = deferred;
observer.Tick("registry_change");
}
var events = Events(sink, SharedEventTypes.RegistryAppState);
Assert.Equal(2, events.Count);
var deadlineEvent = events[0];
Assert.Equal("installDeadline", deadlineEvent.Payload!["changedFields"]);
Assert.Equal("2026-08-18T10:00:00.0000000Z", deadlineEvent.Payload["installDeadlineUtc"]);
Assert.DoesNotContain("deferralsUsed", deadlineEvent.Payload.Keys);
Assert.Contains("-> inProgress, downloaded, install deadline 2026-08-18 10:00 UTC",
deadlineEvent.Payload[SignalPayloadKeys.Message]);
var deferralEvent = events[1];
Assert.Equal("enforcementState,deferralsUsed,deferUntil", deferralEvent.Payload!["changedFields"]);
Assert.Equal("2014", deferralEvent.Payload["enforcementState"]);
Assert.Equal("1", deferralEvent.Payload["deferralsUsed"]);
Assert.Equal("3", deferralEvent.Payload["deferralMaxDeferrals"]);
Assert.Equal("2026-08-18T08:30:00.0000000Z", deferralEvent.Payload["deferUntilUtc"]);
Assert.Equal("false", deferralEvent.Payload["deferralAutoDeferred"]);
Assert.Contains("deferred by user 1/3 until 2026-08-18 08:30 UTC", deferralEvent.Payload[SignalPayloadKeys.Message]);
}
[Fact]
public void NonEmpty_baseline_emits_one_summary_with_counts()
{
@@ -331,7 +459,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
private static AppRegistryEntry Entry(
int? enforcementState = null, long? errorCode = null, int? exitCode = null,
int? statusServiceStatus = null, bool espTracked = false, string? espPhase = null)
int? statusServiceStatus = null, bool espTracked = false, string? espPhase = null,
DateTime? installDeadlineUtc = null, int? deferralsUsed = null, int? deferralMaxDeferrals = null,
DateTime? deferUntilUtc = null, bool? deferralAutoDeferred = null)
{
var entry = new AppRegistryEntry($"{ImeRegistrySnapshot.DeviceContext}|{App1}", ImeRegistrySnapshot.DeviceContext, App1);
entry.EnforcementState = enforcementState;
@@ -340,6 +470,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
entry.StatusServiceStatus = statusServiceStatus;
entry.EspTracked = espTracked;
entry.EspPhase = espPhase;
entry.InstallDeadlineUtc = installDeadlineUtc;
entry.DeferralsUsed = deferralsUsed;
entry.DeferralMaxDeferrals = deferralMaxDeferrals;
entry.DeferUntilUtc = deferUntilUtc;
entry.DeferralAutoDeferred = deferralAutoDeferred;
return entry;
}
@@ -83,6 +83,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
using var f = new Fixture();
Assert.False(f.Tracker.HasAccountSetupActivity);
Assert.False(f.Tracker.HasAccountSetupProgress);
Assert.Null(f.Tracker.AccountSetupProgressIfRead);
}
[Fact]
@@ -97,6 +98,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
Assert.True(f.Tracker.HasAccountSetupActivity);
Assert.False(f.Tracker.HasAccountSetupProgress);
// Read and untouched — the only state the WhiteGlove sealing gate treats as "false".
Assert.False(f.Tracker.AccountSetupProgressIfRead);
}
[Fact]
@@ -108,6 +111,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
Assert.True(f.Tracker.HasAccountSetupActivity);
Assert.True(f.Tracker.HasAccountSetupProgress);
Assert.True(f.Tracker.AccountSetupProgressIfRead);
}
[Theory]
@@ -138,5 +142,18 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.SystemSignals
Assert.False(f.Tracker.HasAccountSetupProgress);
}
[Fact]
public void OnlyDeviceSetupRead_AccountSetupProgressIsUnknown()
{
// Adversarial for the WhiteGlove sealing gate: the tracker holds DeviceSetup data but
// has not read the AccountSetup category — that must be "unknown", never "untouched".
using var f = new Fixture();
f.Tracker.ProcessCategoryStatusForTest("DeviceSetupCategory.Status",
"{\"categoryState\":\"inProgress\",\"DeviceSetup.AppsSubcategory\":{\"subcategoryState\":\"inProgress\"}}");
Assert.Null(f.Tracker.AccountSetupProgressIfRead);
Assert.False(f.Tracker.HasAccountSetupProgress);
}
}
}
@@ -20,6 +20,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Transport
private sealed class FakeApiClient : BackendApiClient
{
public readonly List<TimeSpan?> Timeouts = new List<TimeSpan?>();
public readonly List<AgentErrorReport> Reports = new List<AgentErrorReport>();
public readonly Queue<bool> Results = new Queue<bool>();
public FakeApiClient() : base(
@@ -40,6 +41,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Transport
public override Task<bool> ReportAgentErrorAsync(AgentErrorReport report, TimeSpan? timeout = null)
{
Timeouts.Add(timeout);
Reports.Add(report);
return Task.FromResult(Results.Count > 0 && Results.Dequeue());
}
}
@@ -139,5 +141,37 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Transport
Assert.Equal(2, client.Calls);
}
[Fact]
public async Task Session_age_is_carried_in_the_report_and_absent_by_default()
{
// One reporter per report: a delivered report starts the 10-minute cooldown.
var client = new FakeApiClient();
client.Results.Enqueue(true);
client.Results.Enqueue(true);
await Reporter(client).TrySendAsync(AgentErrorType.SessionAgeEmergencyBreak, "m", sessionAgeHours: 478.2);
await Reporter(client).TrySendAsync(AgentErrorType.ConfigFetchFailed, "m");
Assert.Equal(2, client.Reports.Count);
Assert.Equal(478.2, client.Reports[0].SessionAgeHours);
Assert.Null(client.Reports[1].SessionAgeHours);
}
[Fact]
public async Task Prior_registration_failure_is_carried_in_the_report_and_absent_by_default()
{
var client = new FakeApiClient();
client.Results.Enqueue(true);
client.Results.Enqueue(true);
var record = new RegistrationFailureSummary { FailedRuns = 2, Outcome = "Failed", NetworkLinkUpAtEnd = false };
await Reporter(client).TrySendAsync(AgentErrorType.SessionAgeEmergencyBreak, "m", priorRegistrationFailure: record);
await Reporter(client).TrySendAsync(AgentErrorType.ConfigFetchFailed, "m");
Assert.Equal(2, client.Reports.Count);
Assert.Same(record, client.Reports[0].PriorRegistrationFailure);
Assert.Null(client.Reports[1].PriorRegistrationFailure);
}
}
}
@@ -0,0 +1,88 @@
using AutopilotMonitor.Agent.V2.Core.Monitoring.Transport;
using Newtonsoft.Json.Linq;
using Xunit;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Transport
{
/// <summary>
/// Response parsers of the geo providers. Addresses come from the RFC 5737 documentation
/// ranges — never real ones.
/// </summary>
public class GeoLocationServiceTests
{
[Fact]
public void ParseDoGeo_maps_country_and_egress_ip_and_ignores_the_do_service_fields()
{
var json = JObject.Parse(@"{
""ExternalIpAddress"": ""203.0.113.7"",
""CountryCode"": ""DE"",
""KeyValue_EndpointFullUri"": ""https://kv601.prod.do.dsp.mp.microsoft.com/all"",
""Version"": ""26A6D4D6994E8DA5"",
""CacheId"": ""7"",
""ContentCert"": false,
""DownloadModeFailSafe"": """"
}");
var result = GeoLocationService.ParseDoGeo(json);
Assert.NotNull(result);
Assert.Equal("DE", result.Country);
Assert.Equal("203.0.113.7", result.Ip);
Assert.Equal("do-geo", result.Source);
Assert.Null(result.Region);
Assert.Null(result.City);
Assert.Null(result.Loc);
Assert.Null(result.Timezone);
}
[Theory]
[InlineData(@"{ ""ExternalIpAddress"": ""203.0.113.7"" }")]
[InlineData(@"{ ""ExternalIpAddress"": ""203.0.113.7"", ""CountryCode"": """" }")]
public void ParseDoGeo_without_country_is_a_failure(string body)
{
Assert.Null(GeoLocationService.ParseDoGeo(JObject.Parse(body)));
}
[Fact]
public void ParseIpInfo_maps_all_fields()
{
var json = JObject.Parse(@"{
""ip"": ""198.51.100.4"", ""city"": ""Stuttgart"", ""region"": ""Baden-Wurttemberg"",
""country"": ""DE"", ""loc"": ""48.7823,9.1770"", ""timezone"": ""Europe/Berlin""
}");
var result = GeoLocationService.ParseIpInfo(json);
Assert.Equal("DE", result.Country);
Assert.Equal("Baden-Wurttemberg", result.Region);
Assert.Equal("Stuttgart", result.City);
Assert.Equal("48.7823,9.1770", result.Loc);
Assert.Equal("Europe/Berlin", result.Timezone);
Assert.Equal("198.51.100.4", result.Ip);
Assert.Equal("ipinfo", result.Source);
}
[Fact]
public void ParseIfConfigCo_joins_coordinates_and_leaves_loc_empty_without_them()
{
var withCoords = GeoLocationService.ParseIfConfigCo(JObject.Parse(@"{
""ip"": ""198.51.100.4"", ""country_iso"": ""DE"", ""region_name"": ""Bavaria"",
""city"": ""Munich"", ""latitude"": 48.13, ""longitude"": 11.58, ""time_zone"": ""Europe/Berlin""
}"));
var withoutCoords = GeoLocationService.ParseIfConfigCo(JObject.Parse(@"{ ""country_iso"": ""DE"" }"));
Assert.Equal("48.13,11.58", withCoords.Loc);
Assert.Equal("DE", withCoords.Country);
Assert.Equal("Bavaria", withCoords.Region);
Assert.Equal("ifconfig.co", withCoords.Source);
Assert.Equal("", withoutCoords.Loc);
}
[Fact]
public void Describe_skips_the_parts_a_provider_did_not_return()
{
Assert.Equal("Stuttgart, BW, DE", new GeoLocationResult { City = "Stuttgart", Region = "BW", Country = "DE" }.Describe());
Assert.Equal("DE", new GeoLocationResult { Country = "DE", Region = "" }.Describe());
}
}
}
@@ -162,6 +162,28 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
Assert.Equal(SessionStage.AwaitingHello, result.InitialState.Stage);
}
[Fact]
public void Clean_snapshot_of_a_rotated_session_adopts_the_current_session_id()
{
// SESSION-OWNER-BINDING: the backend refused the persisted session id at registration,
// the agent rotated, and the snapshot on disk still names the old session. The
// enrollment state carries over; the session id must be the current one.
using var rig = new Rig();
var saved = DecisionState.CreateInitial("S-REFUSED", TenantId)
.ToBuilder()
.WithStage(SessionStage.EspAccountSetup)
.WithStepIndex(7)
.WithLastAppliedSignalOrdinal(6)
.Build();
SeedSnapshot(rig, saved);
var result = rig.Recover();
Assert.Equal(SessionId, result.InitialState.SessionId);
Assert.Equal(SessionStage.EspAccountSetup, result.InitialState.Stage);
Assert.Equal(7, result.InitialState.StepIndex);
}
[Fact]
public void Snapshot_plus_pending_tail_replays_tail_onto_snapshot()
{
@@ -37,6 +37,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
[InlineData("modern_deployment_log")]
// Environment observation — battery drain on an idle device must not reset idle clocks.
[InlineData("power_state_change")]
// A flapping link is environment too: it must neither keep the collectors awake nor
// reset the stall clock of the enrollment it is stalling.
[InlineData("network_state_change")]
[InlineData("network_connectivity_check")]
// Bookkeeping of health-script runs that were deliberately not reported.
[InlineData("script_recurrence_summary")]
// Agent health / control / transport — not device/enrollment progress (P2).
[InlineData("collector_degraded")]
[InlineData("telemetry_upload_poisoned")]
@@ -67,6 +73,18 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
Assert.True(SignalActivityClassifier.IsRealActivity(DecisionSignalKind.InformationalEvent, payload));
}
[Theory]
// Only the link-change pair is exempt. The device-info snapshots are emitted at start
// and at the end, not per flap, and stay activity.
[InlineData("network_interface_info")]
[InlineData("wifi_signal_info")]
[InlineData("network_bandwidth_estimate")]
public void Other_network_events_remain_activity(string eventType)
{
var payload = new Dictionary<string, string> { [SignalPayloadKeys.EventType] = eventType };
Assert.True(SignalActivityClassifier.IsRealActivity(DecisionSignalKind.InformationalEvent, payload));
}
[Theory]
// Genuine ModernDeployment warnings/errors stay real activity — only the Info/Debug
// `modern_deployment_log` forwarding is excluded.
@@ -118,5 +118,88 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Program
Assert.Throws<ArgumentNullException>(
() => BackendSessionRegistration.Register(config, auth, http, "1.0", consoleMode: false, logger: null));
}
// ============================================================ failed-registration record
[Fact]
public void RecordRegistrationRun_records_a_failed_run_with_its_window_and_bounded_error()
{
using var tmp = new TempDirectory();
var persistence = new SessionIdPersistence(tmp.Path);
var started = new DateTime(2026, 8, 20, 9, 0, 0, DateTimeKind.Utc);
BackendSessionRegistration.RecordRegistrationRun(
persistence, SessionRegistrationResult.Failed(new string('e', 1000)),
started, started.AddSeconds(1204.46), linkUpAtStart: false, linkUpAtEnd: true,
configFetchOutcome: "UsedDefaults", logger: NewLogger(tmp.Path));
var record = persistence.LoadRegistrationFailure();
Assert.NotNull(record);
Assert.Equal(1, record!.FailedRuns);
Assert.Equal("Failed", record.Outcome);
Assert.Equal(BackendSessionRegistration.MaxRecordedErrorLength, record.LastError!.Length);
Assert.False(record.NetworkLinkUpAtStart);
Assert.True(record.NetworkLinkUpAtEnd);
Assert.Equal(1204.5, record.AttemptWindowSeconds);
Assert.Equal("UsedDefaults", record.ConfigFetchOutcome);
Assert.Equal(started.AddSeconds(1204.46), record.LastFailedAtUtc);
}
[Fact]
public void RecordRegistrationRun_records_auth_failures_and_clears_on_success()
{
using var tmp = new TempDirectory();
var persistence = new SessionIdPersistence(tmp.Path);
var at = new DateTime(2026, 8, 20, 9, 0, 0, DateTimeKind.Utc);
BackendSessionRegistration.RecordRegistrationRun(
persistence, SessionRegistrationResult.AuthFailed(401, "unauthorized"),
at, at.AddSeconds(3), true, true, "Succeeded", NewLogger(tmp.Path));
Assert.Equal("AuthFailed", persistence.LoadRegistrationFailure()!.Outcome);
BackendSessionRegistration.RecordRegistrationRun(
persistence, SessionRegistrationResult.Succeeded(new RegisterSessionResponse { Success = true }),
at, at.AddSeconds(1), true, true, "Succeeded", NewLogger(tmp.Path));
Assert.Null(persistence.LoadRegistrationFailure());
}
[Fact]
public void RecordRegistrationRun_without_persistence_is_a_no_op()
{
using var tmp = new TempDirectory();
BackendSessionRegistration.RecordRegistrationRun(
null, SessionRegistrationResult.Failed("x"), DateTime.UtcNow, DateTime.UtcNow,
null, null, null, NewLogger(tmp.Path));
}
// ============================================================ emergency-break message
[Fact]
public void Break_message_names_failed_registrations_in_invariant_culture()
{
var previous = System.Threading.Thread.CurrentThread.CurrentCulture;
try
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE");
var record = new RegistrationFailureSummary { FailedRuns = 3, Outcome = "Failed", NetworkLinkUpAtEnd = false };
var message = EmergencyBreakReporter.BuildMessage(478.2, 48, record);
Assert.Contains("session age 478.2h (cap 48h)", message);
Assert.EndsWith(" 3 earlier start(s) failed to register (last: Failed, network link at end: down).", message);
}
finally
{
System.Threading.Thread.CurrentThread.CurrentCulture = previous;
}
}
[Fact]
public void Break_message_without_record_keeps_the_historical_text()
{
Assert.Equal(
"Agent absolute session-age emergency break fired at session age 50.0h (cap 48h) — cleaning up and exiting.",
EmergencyBreakReporter.BuildMessage(50.0, 48, null));
}
}
}
@@ -149,6 +149,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Program
persistence.SaveSessionCreatedAt(DateTime.UtcNow.AddHours(-100));
var stateDir = Path.Combine(tmp.Path, "State");
double? reportedAgeHours = null;
var tripped = AutopilotMonitor.Agent.V2.Program.CheckSessionAgeEmergencyBreak(
dataDirectory: tmp.Path,
@@ -157,9 +158,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Program
selfDestructOnComplete: false,
cleanupServiceFactory: null,
logger: logger,
consoleMode: false);
consoleMode: false,
onBreakFired: ageHours => reportedAgeHours = ageHours);
Assert.True(tripped);
// The measured age reaches the break report (the backend cannot derive it).
Assert.NotNull(reportedAgeHours);
Assert.InRange(reportedAgeHours.Value, 99.9, 100.1);
// Marker must have been written so the next restart exits cleanly.
Assert.True(File.Exists(Path.Combine(stateDir, "enrollment-complete.marker")));
// Session must have been cleared.
@@ -62,6 +62,18 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Runtime
Assert.Equal("ipinfo.io", evt.Data["source"]);
}
[Fact]
public void BuildGeoEvent_country_only_location_has_no_empty_parts_in_message()
{
var loc = new GeoLocationResult { Country = "DE", Source = "do-geo" };
var evt = StartupEnvironmentProbes.BuildGeoEvent(Config(), loc);
Assert.Equal("Device location: DE (via do-geo)", evt.Message);
Assert.Equal("DE", evt.Data["country"]);
Assert.Equal("do-geo", evt.Data["source"]);
}
// ================================================================= Outbound IP
[Fact]
@@ -98,6 +110,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Runtime
PrimaryError = "connection refused",
PrimaryRetryError = "DNS failure",
FallbackError = "timeout",
DoGeoError = "HTTP 403 (Forbidden)",
};
var evt = StartupEnvironmentProbes.BuildGeoFailureEvent(cfg, attempt);
@@ -108,6 +121,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Runtime
Assert.Equal("connection refused", evt.Data["primaryError"]);
Assert.Equal("DNS failure", evt.Data["primaryRetryError"]);
Assert.Equal("timeout", evt.Data["fallbackError"]);
Assert.Equal("HTTP 403 (Forbidden)", evt.Data["doGeoError"]);
Assert.Equal("do-geo", evt.Data["lastResortProvider"]);
}
[Fact]
@@ -119,6 +134,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Runtime
Assert.Equal("unknown", evt.Data["primaryError"]);
Assert.Equal("unknown", evt.Data["primaryRetryError"]);
Assert.Equal("unknown", evt.Data["fallbackError"]);
Assert.Equal("unknown", evt.Data["doGeoError"]);
}
// ================================================================= Timezone
@@ -3,6 +3,7 @@ using System.IO;
using AutopilotMonitor.Agent.V2.Core.Logging;
using AutopilotMonitor.Agent.V2.Core.Security;
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using AutopilotMonitor.Shared.Models;
using Xunit;
namespace AutopilotMonitor.Agent.V2.Core.Tests.Security
@@ -234,5 +235,78 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Security
Assert.False(File.Exists(Path.Combine(tmp.Path, "session.created")));
Assert.False(File.Exists(Path.Combine(tmp.Path, "whiteglove.complete")));
}
// ============================================================ failed-registration record
private static RegistrationFailureSummary FailedRun(DateTime at, string outcome = "Failed", bool? linkUpAtEnd = false) =>
new RegistrationFailureSummary
{
FailedRuns = 1,
FirstFailedAtUtc = at,
LastFailedAtUtc = at,
Outcome = outcome,
LastError = "No such host is known.",
NetworkLinkUpAtStart = false,
NetworkLinkUpAtEnd = linkUpAtEnd,
AttemptWindowSeconds = 91.3,
ConfigFetchOutcome = "UsedDefaults",
};
[Fact]
public void RecordRegistrationFailure_counts_runs_keeps_the_first_time_and_describes_the_latest_run()
{
using var tmp = new TempDirectory();
var sut = new SessionIdPersistence(tmp.Path);
var first = new DateTime(2026, 8, 20, 9, 0, 0, DateTimeKind.Utc);
var second = new DateTime(2026, 9, 12, 7, 30, 0, DateTimeKind.Utc);
Assert.Null(sut.LoadRegistrationFailure());
sut.RecordRegistrationFailure(FailedRun(first));
sut.RecordRegistrationFailure(FailedRun(second, outcome: "AuthFailed", linkUpAtEnd: true));
// A fresh instance reads it back from disk, as the next boot's emergency break does.
var record = new SessionIdPersistence(tmp.Path).LoadRegistrationFailure();
Assert.NotNull(record);
Assert.Equal(2, record!.FailedRuns);
Assert.Equal(first, record.FirstFailedAtUtc);
Assert.Equal(second, record.LastFailedAtUtc);
Assert.Equal("AuthFailed", record.Outcome);
Assert.True(record.NetworkLinkUpAtEnd);
Assert.Equal(91.3, record.AttemptWindowSeconds);
Assert.Equal("UsedDefaults", record.ConfigFetchOutcome);
}
[Fact]
public void Registration_failure_record_is_cleared_by_success_delete_and_rotate()
{
using var tmp = new TempDirectory();
var sut = new SessionIdPersistence(tmp.Path);
sut.GetOrCreate();
var at = new DateTime(2026, 8, 20, 9, 0, 0, DateTimeKind.Utc);
sut.RecordRegistrationFailure(FailedRun(at));
sut.ClearRegistrationFailure();
Assert.Null(sut.LoadRegistrationFailure());
sut.RecordRegistrationFailure(FailedRun(at));
sut.Rotate();
Assert.Null(sut.LoadRegistrationFailure());
sut.RecordRegistrationFailure(FailedRun(at));
sut.Delete();
Assert.Null(sut.LoadRegistrationFailure());
Assert.False(File.Exists(Path.Combine(tmp.Path, "registration-failure.json")));
}
[Theory]
[InlineData("not json")]
[InlineData("{\"FailedRuns\":0}")]
public void LoadRegistrationFailure_reports_nothing_for_a_corrupt_or_empty_record(string content)
{
using var tmp = new TempDirectory();
File.WriteAllText(Path.Combine(tmp.Path, "registration-failure.json"), content);
Assert.Null(new SessionIdPersistence(tmp.Path).LoadRegistrationFailure());
}
}
}
@@ -137,6 +137,86 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Security
Assert.Equal(originalSessionId, result.RotatedFromSessionId);
}
private static BackendRefusalException TenantConflict()
=> new BackendRefusalException("Backend returned 409 Conflict with error code session_owner_mismatch.", 409,
AutopilotMonitor.Shared.Constants.AgentErrorCodes.SessionOwnerMismatch);
[Fact]
public async Task Tenant_conflict_409_rotates_once_like_an_owner_mismatch()
{
using var tmp = new TempDirectory();
var logger = NewLogger(tmp);
var config = NewConfig();
var originalSessionId = config.SessionId;
var rotatedTo = Guid.NewGuid().ToString();
var seenSessionIds = new System.Collections.Generic.List<string>();
var apiClient = new FakeApiClient(
attempt => attempt == 1
? throw TenantConflict()
: new RegisterSessionResponse { Success = true, SessionId = rotatedTo, ValidatedBy = ValidatorType.AutopilotV1 },
onRegister: r => seenSessionIds.Add(r.SessionId));
var tracker = new AuthFailureTracker(maxFailures: 5, timeoutMinutes: 0,
clock: SystemClock.Instance, logger: logger);
var result = await SessionRegistrationHelper.RegisterWithRetryAsync(
apiClient, config, agentVersion: "0.0.0", logger: logger,
authFailureTracker: tracker,
backoffDelay: _ => throw new InvalidOperationException("rotation must retry without backoff"),
networkLinkWait: _ => Task.CompletedTask,
rotateSession: () => { config.SessionId = rotatedTo; return rotatedTo; });
Assert.Equal(SessionRegistrationOutcome.Succeeded, result.Outcome);
Assert.Equal(new[] { originalSessionId, rotatedTo }, seenSessionIds);
Assert.Equal(originalSessionId, result.RotatedFromSessionId);
Assert.Equal(0, tracker.ConsecutiveFailures);
}
[Fact]
public async Task Coded_refusal_after_rotation_fails_without_retry_or_auth_failure()
{
using var tmp = new TempDirectory();
var logger = NewLogger(tmp);
var config = NewConfig();
var apiClient = new FakeApiClient(_ => throw TenantConflict());
var tracker = new AuthFailureTracker(maxFailures: 5, timeoutMinutes: 0,
clock: SystemClock.Instance, logger: logger);
var result = await SessionRegistrationHelper.RegisterWithRetryAsync(
apiClient, config, agentVersion: "0.0.0", logger: logger,
authFailureTracker: tracker,
backoffDelay: _ => throw new InvalidOperationException("a coded refusal must not be retried"),
networkLinkWait: _ => Task.CompletedTask,
rotateSession: () => { config.SessionId = Guid.NewGuid().ToString(); return config.SessionId; });
Assert.Equal(SessionRegistrationOutcome.Failed, result.Outcome);
Assert.Equal(2, apiClient.CallCount);
Assert.Equal(0, tracker.ConsecutiveFailures);
}
[Fact]
public async Task Rotation_hook_failure_on_a_tenant_conflict_fails_without_auth_failure()
{
using var tmp = new TempDirectory();
var logger = NewLogger(tmp);
var config = NewConfig();
var apiClient = new FakeApiClient(_ => throw TenantConflict());
var tracker = new AuthFailureTracker(maxFailures: 5, timeoutMinutes: 0,
clock: SystemClock.Instance, logger: logger);
var result = await SessionRegistrationHelper.RegisterWithRetryAsync(
apiClient, config, agentVersion: "0.0.0", logger: logger,
authFailureTracker: tracker, networkLinkWait: _ => Task.CompletedTask,
rotateSession: () => throw new IOException("disk full"));
Assert.Equal(SessionRegistrationOutcome.Failed, result.Outcome);
Assert.Equal(1, apiClient.CallCount);
Assert.Equal(0, tracker.ConsecutiveFailures);
}
[Fact]
public async Task Second_owner_mismatch_after_rotation_is_an_auth_failure()
{
@@ -99,6 +99,52 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
Assert.Equal(DecisionSignalKind.WhiteGloveShellCoreSuccess, posted.Kind);
}
[Theory]
[InlineData(true, "true")]
[InlineData(false, "false")]
public void WhiteGloveEvent_stamps_read_AccountSetup_progress_on_payload_and_evidence(bool progress, string expected)
{
using var f = new Fixture();
using var adapter = new EspAndHelloTrackerAdapter(
f.Coordinator, f.Ingress, f.Clock, accountSetupProgressProbe: () => progress);
adapter.TriggerWhiteGloveFromTest();
var posted = Assert.Single(f.Ingress.Posted);
Assert.Equal(expected, posted.Payload![SignalPayloadKeys.AccountSetupProgress]);
Assert.Equal(expected, posted.Evidence.DerivationInputs![SignalPayloadKeys.AccountSetupProgress]);
}
[Fact]
public void WhiteGloveEvent_with_unread_AccountSetup_registry_sends_no_progress_key()
{
// Unknown must keep the sealing classifier's AccountSetup excluder — the payload key
// is absent, the evidence records why.
using var f = new Fixture();
using var adapter = new EspAndHelloTrackerAdapter(
f.Coordinator, f.Ingress, f.Clock, accountSetupProgressProbe: () => null);
adapter.TriggerWhiteGloveFromTest();
var posted = Assert.Single(f.Ingress.Posted);
Assert.True(posted.Payload == null || !posted.Payload.ContainsKey(SignalPayloadKeys.AccountSetupProgress));
Assert.Equal("unread", posted.Evidence.DerivationInputs![SignalPayloadKeys.AccountSetupProgress]);
}
[Fact]
public void WhiteGloveEvent_default_probe_on_unstarted_coordinator_reports_unread()
{
// Production probe: the provisioning tracker does not exist before Start (and never on
// Device Preparation) — that is "unread", not "untouched".
using var f = new Fixture();
using var adapter = new EspAndHelloTrackerAdapter(f.Coordinator, f.Ingress, f.Clock);
adapter.TriggerWhiteGloveFromTest();
var posted = Assert.Single(f.Ingress.Posted);
Assert.True(posted.Payload == null || !posted.Payload.ContainsKey(SignalPayloadKeys.AccountSetupProgress));
}
[Fact]
public void EspFailureEvent_emits_EspTerminalFailure_with_merged_subSource_annotation()
{
@@ -0,0 +1,292 @@
using System;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
using AutopilotMonitor.Agent.V2.Core.SignalAdapters;
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using SharedEventTypes = AutopilotMonitor.Shared.Constants.EventTypes;
using Xunit;
namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
{
/// <summary>
/// A script run duration is the span between two CMTrace lines, each resolved on its own zone
/// belief. When the beliefs differ the span is a whole number of offset-grid steps plus the run
/// time, not the run time: session 4377911b read a 10 s script as 3610 s (start line-anchored
/// +120, result re-read after an overwrite rewind in the reader's zone +60 and rejected as
/// ahead of the clock), a fleet tenant read 2–9 s scripts as 17 h every day. The adapter judges
/// the pair from the provenance bound to each line and omits the span rather than lie.
/// </summary>
public sealed class ImeLogTrackerAdapterDurationProvenanceTests
{
private const string ServiceLog = "IntuneManagementExtension.log";
private const string ExecutorLog = "AgentExecutor.log";
private static CmTraceLineProvenance Line(
DateTime resolvedUtc, int offsetMinutes, CmTraceOffsetOrigin origin,
string file = ServiceLog, string? anchor = null, int? measured = null) =>
new CmTraceLineProvenance
{
// The writer's local time is the resolved value with the applied offset put back.
SourceLocalTs = DateTime.SpecifyKind(resolvedUtc.AddMinutes(offsetMinutes), DateTimeKind.Unspecified),
Origin = origin,
OffsetMinutes = offsetMinutes,
EraAnchorKind = anchor,
MeasuredWriterOffsetMinutes = measured,
SourceFileName = file,
};
private static ScriptExecutionState Platform(string policyId, DateTime startedAtUtc, CmTraceLineProvenance start,
DateTime? resultObservedAtUtc = null, CmTraceLineProvenance? result = null, string outcome = "Success", int exitCode = 0) =>
new ScriptExecutionState
{
PolicyId = policyId,
ScriptType = "platform",
ExitCode = exitCode,
Result = outcome,
ResultSource = "ime_policy_result",
StartedAtUtc = startedAtUtc,
StartedAtProvenance = start,
ResultObservedAtUtc = resultObservedAtUtc,
ResultProvenance = result,
};
[Fact]
public void Rejected_result_line_against_a_line_anchored_start_omits_the_span()
{
// Session 4377911b, script d94468af: start 15:19:57.005 local, self-anchored (+120);
// result 15:20:07.391 local, re-read after a rewind and resolved in the reader's
// zone (+60) → 14:20:07Z, one hour ahead of the clock. The raw pair reads 3610 s.
var clockNow = new DateTime(2026, 9, 17, 13, 20, 7, 437, DateTimeKind.Utc);
using var f = new ImeLogTrackerAdapterFixture(clockNow);
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
var startUtc = new DateTime(2026, 9, 17, 13, 19, 57, 5, DateTimeKind.Utc);
var resultRaw = new DateTime(2026, 9, 17, 14, 20, 7, 391, DateTimeKind.Utc);
adapter.TriggerScriptCompletedFromTest(Platform("d94468af",
startUtc, Line(startUtc, 120, CmTraceOffsetOrigin.LineAnchored, measured: 120),
resultRaw, Line(resultRaw, 60, CmTraceOffsetOrigin.None, measured: 120)));
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
Assert.Equal(clockNow, info.OccurredAtUtc); // stamp: clamped to the clock
Assert.Equal("true", info.Payload!["derivedTimestamp"]);
Assert.Equal(resultRaw.ToString("o"), info.Payload["rejectedSourceTimestamp"]);
Assert.False(info.Payload.ContainsKey("durationSeconds"));
Assert.False(info.Payload.ContainsKey("durationBasis"));
Assert.Equal("rejected-endpoint", info.Payload["durationSuppressedReason"]);
Assert.Equal("unverified", info.Payload["durationProvenance"]);
// The end line's own provenance and the start line's, side by side.
Assert.Equal("reader-zone-fallback", info.Payload["sourceOffsetOrigin"]);
Assert.Equal("60", info.Payload["sourceOffsetMinutes"]);
Assert.Equal("120", info.Payload["measuredWriterOffsetMinutes"]);
Assert.Equal("2026-09-17T15:20:07.3910000", info.Payload["sourceLocalTs"]);
Assert.Equal("line-anchored", info.Payload["startSourceOffsetOrigin"]);
Assert.Equal("120", info.Payload["startSourceOffsetMinutes"]);
}
[Fact]
public void Rejected_era_anchored_result_of_a_failed_script_omits_the_span_and_the_timeout_verdict()
{
// Fleet shape (script_failed, daily in one tenant): result era-anchored at −420 (the
// OOBE default zone's era) on a line written under +600 → 17 h ahead of the clock;
// the 61203 s "run" of a 3 s script fired script_timeout_suspected every day.
var clockNow = new DateTime(2026, 9, 21, 1, 30, 13, DateTimeKind.Utc);
using var f = new ImeLogTrackerAdapterFixture(clockNow);
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
var startUtc = clockNow.AddSeconds(-8);
var resultRaw = clockNow.AddSeconds(-5).AddHours(17);
adapter.TriggerScriptCompletedFromTest(Platform("88d406eb",
startUtc, Line(startUtc, 600, CmTraceOffsetOrigin.LineAnchored),
resultRaw, Line(resultRaw, -420, CmTraceOffsetOrigin.EraAnchored, anchor: "bootstrap-policy-result", measured: 600),
outcome: "Failed"));
var failed = f.InfoEvent(SharedEventTypes.ScriptFailed);
Assert.Equal("rejected-endpoint", failed.Payload!["durationSuppressedReason"]);
Assert.False(failed.Payload.ContainsKey("durationSeconds"));
Assert.Equal("era-anchored", failed.Payload["sourceOffsetOrigin"]);
Assert.Equal("bootstrap-policy-result", failed.Payload["sourceOffsetAnchor"]);
Assert.Empty(f.InfoEvents(SharedEventTypes.ScriptTimeoutSuspected));
}
[Fact]
public void Mixed_pair_on_the_offset_grid_omits_the_span_even_when_nothing_was_rejected()
{
// Session cbaed57b: start from AgentExecutor.log in the reader's zone (+120, two
// hours too early), result era-anchored at 0 in the service log → 7205 s.
var clockNow = new DateTime(2026, 9, 11, 8, 48, 25, DateTimeKind.Utc);
using var f = new ImeLogTrackerAdapterFixture(clockNow);
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
var resultUtc = clockNow.AddSeconds(-1);
var startUtc = resultUtc.AddSeconds(-7205);
adapter.TriggerScriptCompletedFromTest(Platform("846cea22",
startUtc, Line(startUtc, 120, CmTraceOffsetOrigin.None, file: ExecutorLog),
resultUtc, Line(resultUtc, 0, CmTraceOffsetOrigin.EraAnchored, anchor: "bootstrap-policy-result")));
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
Assert.False(info.Payload!.ContainsKey("derivedTimestamp"));
Assert.False(info.Payload.ContainsKey("durationSeconds"));
Assert.Equal("offset-grid", info.Payload["durationSuppressedReason"]);
Assert.Equal("unverified", info.Payload["durationProvenance"]);
}
[Fact]
public void Mixed_pair_off_the_grid_keeps_the_span_as_unverified()
{
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
using var f = new ImeLogTrackerAdapterFixture(clockNow);
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
var resultUtc = clockNow.AddSeconds(-1);
var startUtc = resultUtc.AddSeconds(-26);
adapter.TriggerScriptCompletedFromTest(Platform("f6f67f79",
startUtc, Line(startUtc, 120, CmTraceOffsetOrigin.LineAnchored),
resultUtc, Line(resultUtc, 120, CmTraceOffsetOrigin.None)));
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
Assert.Equal("26.00", info.Payload!["durationSeconds"]);
Assert.Equal("script_runtime", info.Payload["durationBasis"]);
Assert.Equal("unverified", info.Payload["durationProvenance"]);
Assert.False(info.Payload.ContainsKey("durationSuppressedReason"));
}
[Fact]
public void Two_line_anchored_ends_on_the_grid_are_a_verified_fifteen_minute_run()
{
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
using var f = new ImeLogTrackerAdapterFixture(clockNow);
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
var resultUtc = clockNow.AddSeconds(-1);
var startUtc = resultUtc.AddSeconds(-900);
adapter.TriggerScriptCompletedFromTest(Platform("11111111",
startUtc, Line(startUtc, 120, CmTraceOffsetOrigin.LineAnchored),
resultUtc, Line(resultUtc, 120, CmTraceOffsetOrigin.LineAnchored)));
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
Assert.Equal("900.00", info.Payload!["durationSeconds"]);
Assert.Equal("verified", info.Payload["durationProvenance"]);
}
[Fact]
public void Two_fallback_ends_from_the_same_file_share_their_error_and_stay_measurable()
{
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
using var f = new ImeLogTrackerAdapterFixture(clockNow);
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
var resultUtc = clockNow.AddSeconds(-1);
var startUtc = resultUtc.AddSeconds(-900);
adapter.TriggerScriptCompletedFromTest(Platform("22222222",
startUtc, Line(startUtc, 60, CmTraceOffsetOrigin.None),
resultUtc, Line(resultUtc, 60, CmTraceOffsetOrigin.None)));
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
Assert.Equal("900.00", info.Payload!["durationSeconds"]);
Assert.Equal("verified", info.Payload["durationProvenance"]);
}
[Fact]
public void Two_fallback_ends_from_different_files_are_different_writers()
{
// Same reader zone applied to both, but the executor child process and the service
// can hold different beliefs (cbaed57b) — a grid-sized span is not trusted.
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
using var f = new ImeLogTrackerAdapterFixture(clockNow);
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
var resultUtc = clockNow.AddSeconds(-1);
var startUtc = resultUtc.AddSeconds(-900);
adapter.TriggerScriptCompletedFromTest(Platform("33333333",
startUtc, Line(startUtc, 60, CmTraceOffsetOrigin.None, file: ExecutorLog),
resultUtc, Line(resultUtc, 60, CmTraceOffsetOrigin.None)));
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
Assert.False(info.Payload!.ContainsKey("durationSeconds"));
Assert.Equal("offset-grid", info.Payload["durationSuppressedReason"]);
}
[Fact]
public void Without_provenance_the_pair_is_taken_as_before()
{
// States from before the field (persisted by an older agent) and synthetic events:
// no snapshot on either end, the 30-minute Failed run still reads as a timeout.
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
using var f = new ImeLogTrackerAdapterFixture(clockNow);
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
f.Tracker.LastMatchedLogTimestamp = clockNow.AddSeconds(-1);
adapter.TriggerScriptCompletedFromTest(new ScriptExecutionState
{
PolicyId = "44444444",
ScriptType = "platform",
ExitCode = 0,
Result = "Failed",
StartedAtUtc = clockNow.AddSeconds(-1801),
});
var failed = f.InfoEvent(SharedEventTypes.ScriptFailed);
Assert.Equal("1800.00", failed.Payload!["durationSeconds"]);
Assert.False(failed.Payload.ContainsKey("durationProvenance"));
Assert.False(failed.Payload.ContainsKey("durationSuppressedReason"));
Assert.Single(f.InfoEvents(SharedEventTypes.ScriptTimeoutSuspected));
}
[Fact]
public void Negative_grid_sized_span_from_a_future_shifted_start_is_named_not_dropped_silently()
{
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
using var f = new ImeLogTrackerAdapterFixture(clockNow);
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
var resultUtc = clockNow.AddSeconds(-1);
var startUtc = resultUtc.AddSeconds(3595); // resolved one hour ahead of its real instant
adapter.TriggerScriptCompletedFromTest(Platform("55555555",
startUtc, Line(startUtc, 60, CmTraceOffsetOrigin.None),
resultUtc, Line(resultUtc, 120, CmTraceOffsetOrigin.LineAnchored)));
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
Assert.False(info.Payload!.ContainsKey("durationSeconds"));
Assert.Equal("offset-grid", info.Payload["durationSuppressedReason"]);
}
[Fact]
public void Health_script_cycle_is_judged_the_same_way()
{
// HS-SCRIPT-START self-anchored, HS-NEW-RESULT re-read in the reader's zone and
// rejected: the cycle duration is omitted, the compliance verdict stays.
var clockNow = ImeLogTrackerAdapterFixture.DefaultClockStart;
using var f = new ImeLogTrackerAdapterFixture(clockNow);
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
var startUtc = clockNow.AddSeconds(-40);
var resultRaw = clockNow.AddSeconds(-2).AddHours(1);
adapter.TriggerScriptCompletedFromTest(new ScriptExecutionState
{
PolicyId = "66666666",
ScriptType = "remediation",
ScriptPart = "detection",
ExitCode = 0,
ComplianceResult = "True",
StartedAtUtc = startUtc,
StartedAtProvenance = Line(startUtc, 120, CmTraceOffsetOrigin.LineAnchored),
ResultObservedAtUtc = resultRaw,
ResultProvenance = Line(resultRaw, 60, CmTraceOffsetOrigin.None),
DurationBasis = "cycle_including_reporting_latency",
});
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
Assert.Equal("True", info.Payload!["complianceResult"]);
Assert.False(info.Payload.ContainsKey("durationSeconds"));
Assert.Equal("rejected-endpoint", info.Payload["durationSuppressedReason"]);
}
}
}
@@ -1,4 +1,5 @@
using System;
using AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime;
using AutopilotMonitor.Agent.V2.Core.SignalAdapters;
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
using SharedEventTypes = AutopilotMonitor.Shared.Constants.EventTypes;
@@ -45,5 +46,46 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.SignalAdapters
Assert.Equal("ime_policy_result", info.Payload["resultSource"]);
Assert.Equal("92.00", info.Payload["durationSeconds"]);
}
[Fact]
public void Held_completion_carries_the_provenance_of_its_result_line()
{
using var f = new ImeLogTrackerAdapterFixture(ClockNow);
using var adapter = new ImeLogTrackerAdapter(f.Tracker, f.Ingress, f.Clock);
var startTs = ClockNow.AddSeconds(-95);
var resultTs = ClockNow.AddSeconds(-3);
// Start and result lines both self-anchored (+120).
f.Tracker.LastMatchedLogTimestamp = startTs;
f.Tracker.LastMatchedSourceLocalTimestamp = DateTime.SpecifyKind(startTs.AddMinutes(120), DateTimeKind.Unspecified);
f.Tracker.LastMatchedSourceOffsetOrigin = CmTraceOffsetOrigin.LineAnchored;
f.Tracker.LastMatchedSourceOffsetMinutes = 120;
f.Tracker.HandlePlatformScriptStarted("376ee51a");
f.Tracker.LastMatchedLogTimestamp = resultTs;
f.Tracker.LastMatchedSourceLocalTimestamp = DateTime.SpecifyKind(resultTs.AddMinutes(120), DateTimeKind.Unspecified);
f.Tracker.LastMatchedPatternId = "PS-SCRIPT-RESULT";
f.Tracker.CompletePlatformScriptFromImeResultForTesting("376ee51a", "Success", resultTs);
// By the time the held completion is emitted, the last matched line is an unrelated
// one resolved in the reader's zone.
f.Tracker.LastMatchedLogTimestamp = ClockNow.AddSeconds(-1);
f.Tracker.LastMatchedSourceLocalTimestamp = DateTime.SpecifyKind(ClockNow.AddSeconds(-1).AddMinutes(60), DateTimeKind.Unspecified);
f.Tracker.LastMatchedSourceOffsetOrigin = CmTraceOffsetOrigin.None;
f.Tracker.LastMatchedSourceOffsetMinutes = 60;
f.Tracker.LastMatchedPatternId = "IME-DOWNLOADING";
f.Tracker.RecordPlatformScriptExitCodeForTesting("376ee51a", 0, resultTs.AddMilliseconds(-8));
f.Tracker.FlushPendingPlatformScriptResults(f.Clock.UtcNow);
var info = f.InfoEvent(SharedEventTypes.ScriptCompleted);
Assert.Equal("line-anchored", info.Payload!["sourceOffsetOrigin"]);
Assert.Equal("120", info.Payload["sourceOffsetMinutes"]);
Assert.Equal(resultTs.AddMinutes(120).ToString("yyyy-MM-ddTHH:mm:ss.fffffff"), info.Payload["sourceLocalTs"]);
Assert.Equal("line-anchored", info.Payload["startSourceOffsetOrigin"]);
Assert.Equal("120", info.Payload["startSourceOffsetMinutes"]);
Assert.Equal("92.00", info.Payload["durationSeconds"]);
Assert.Equal("verified", info.Payload["durationProvenance"]);
}
}
}
@@ -564,6 +564,37 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Termination
Assert.False(File.Exists(Path.Combine(rig.StateDir, "enrollment-complete.marker")));
}
[Fact]
public void Handle_whiteglove_part1_writes_marker_before_the_later_exit_steps()
{
// The technician's reseal can kill the process anywhere after the seal. The marker
// is what lets the next boot skip the 48-hour break and resume Part 2, so it must
// exist before collectors stop, diagnostics upload, grace and drain run.
using var rig = new Rig();
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.WhiteGloveSealed }.Build();
bool? markerPresentAtCollectorStop = null;
rig.StopPeripheralCollectorsHook = () => markerPresentAtCollectorStop = rig.SessionPersistence.IsWhiteGloveResume();
rig.Build().Handle(sender: null!,
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Succeeded, SessionStage.WhiteGloveSealed));
Assert.True(markerPresentAtCollectorStop, "whiteglove.complete must be written before the peripheral collectors are stopped.");
var emitted = rig.EmittedEventTypes.ToList();
Assert.True(emitted.IndexOf("agent_shutting_down") >= 0, "agent_shutting_down must still be emitted.");
}
[Fact]
public void Handle_non_whiteglove_termination_never_writes_the_marker()
{
using var rig = new Rig();
rig.State = new DecisionStateBuilder(DecisionState.CreateInitial("S1", "T1")) { Stage = SessionStage.Completed }.Build();
rig.Build().Handle(sender: null!,
Args(EnrollmentTerminationReason.DecisionTerminalStage, EnrollmentTerminationOutcome.Succeeded, SessionStage.Completed));
Assert.False(rig.SessionPersistence.IsWhiteGloveResume());
}
[Fact]
public void Handle_whiteglove_part1_stops_collectors_before_emitting_part1_complete()
{
@@ -88,6 +88,35 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Transport
Assert.Null(ex.ErrorCode);
}
// ── coded 409: a refusal, never an auth failure ─────────────────────
[Fact]
public async Task Coded_409_is_a_refusal_not_an_auth_failure()
{
using var client = BuildClient(
HttpStatusCode.Conflict,
"{\"success\":false,\"message\":\"Session id is already registered to another tenant\",\"errorCode\":\"session_owner_mismatch\"}",
"application/json");
var ex = await Assert.ThrowsAsync<BackendRefusalException>(
() => client.RegisterSessionAsync(new AutopilotMonitor.Shared.Models.SessionRegistration()));
Assert.Equal(409, ex.StatusCode);
Assert.Equal("session_owner_mismatch", ex.ErrorCode);
}
[Fact]
public async Task Uncoded_409_stays_a_plain_http_error()
{
using var client = BuildClient(
HttpStatusCode.Conflict,
"{\"success\":false,\"message\":\"A diagnostics package with this name already exists\"}",
"application/json");
await Assert.ThrowsAsync<HttpRequestException>(
() => client.GetDiagnosticsUploadUrlAsync("tenant-1", "session-1", "package.zip"));
}
[Theory]
[InlineData(null, null)]
[InlineData("", null)]
@@ -0,0 +1,57 @@
using System;
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
{
/// <summary>
/// How ONE CMTrace line's UTC value was arrived at, captured at the line itself.
/// <para>
/// The tracker exposes the provenance of the line it matched last. A consumer that acts later —
/// a platform-script result held for its executor end block, a run duration spanning a start
/// line and a result line — must describe ITS line, not whichever line happened to be matched
/// last, so the snapshot travels on <see cref="ScriptExecutionState"/> (persisted as a plain
/// DTO; null on state files written before it existed).
/// </para>
/// </summary>
public sealed class CmTraceLineProvenance
{
/// <summary>
/// The line's local time exactly as the writer wrote it (Kind Unspecified, no zone). Null
/// when the value did not come from a CMTrace line at all (clock fallback).
/// </summary>
public DateTime? SourceLocalTs { get; set; }
/// <summary>How the offset applied to <see cref="SourceLocalTs"/> was obtained.</summary>
public CmTraceOffsetOrigin Origin { get; set; }
/// <summary>The offset that was applied, in minutes (local = UTC + offset).</summary>
public int? OffsetMinutes { get; set; }
/// <summary>For <see cref="CmTraceOffsetOrigin.EraAnchored"/>: which anchor established the era's offset.</summary>
public string EraAnchorKind { get; set; }
/// <summary>What the calibrator measured for the source file — observational, never applied.</summary>
public int? MeasuredWriterOffsetMinutes { get; set; }
/// <summary>Name of the log file the line was read from — the closest thing to a writer identity the tracker has.</summary>
public string SourceFileName { get; set; }
/// <summary>
/// True when the applied offset was ASSUMED for this line rather than declared by the
/// writer or measured against the agent clock: the reader's own zone (fallback), a writer
/// era's anchor, or the retired per-file calibration. A clock-derived value (no source
/// timestamp) sits on the true UTC axis and is not an assumption.
/// </summary>
public bool IsAssumed()
{
if (!SourceLocalTs.HasValue) return false;
switch (Origin)
{
case CmTraceOffsetOrigin.Bias:
case CmTraceOffsetOrigin.LineAnchored:
return false;
default:
return true;
}
}
}
}
@@ -159,6 +159,23 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
return true;
}
/// <summary>
/// Whether a span between two resolved lines is the signature of a wrong offset on one
/// of them rather than of elapsed time: a zone error is always a whole number of grid
/// steps, so a span within <see cref="MaxGridResidual"/> of k × <see cref="OffsetGrid"/>
/// (k ≥ 1) reads as an offset error plus a run time of seconds. Sign is ignored — a wrong
/// offset on the START end produces the same magnitude with the opposite sign.
/// </summary>
internal static bool IsOnOffsetGrid(TimeSpan span, out int gridSteps)
{
var magnitude = span.Duration();
gridSteps = (int)Math.Round(magnitude.TotalMinutes / OffsetGrid.TotalMinutes, MidpointRounding.AwayFromZero);
if (gridSteps < 1) return false;
var nearest = TimeSpan.FromMinutes(gridSteps * OffsetGrid.TotalMinutes);
return (magnitude - nearest).Duration() <= MaxGridResidual;
}
public bool TryCalibrate(string sourceKey, DateTime localTimestamp, DateTime agentUtcNow)
{
if (string.IsNullOrEmpty(sourceKey)) return false;
@@ -252,10 +252,22 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
// duration when the consolidated [HS] new result line arrives (the slot above is
// cleared by the early-signal HS-COMPLIANCE handler, so timing lives in its own
// map). Prefer the source CMTrace timestamp; latest start wins on a policy re-run.
_healthScriptStartTimes[id] = LastMatchedLogTimestamp ?? DateTime.UtcNow;
var startedAtUtc = LastMatchedLogTimestamp ?? UtcNowProvider();
_healthScriptStartTimes[id] = (startedAtUtc, CaptureLastMatchedProvenance());
_logger.Info($"ImeLogTracker: health script started: {id}");
try { OnScriptStarted?.Invoke(new ScriptStartedInfo { PolicyId = id, ScriptType = "remediation", PolicyType = policyType }); }
catch (Exception ex) { _logger.Warning($"ImeLogTracker: OnScriptStarted handler threw: {ex.Message}"); }
// A replayed line of a previous enrollment bypasses the recurrence gate: the
// adapter drops its event, and a dropped run must not count as the policy's
// first report.
if (!_currentLineIsHistoricReplay
&& !_recurringScripts.OnStart(id, startedAtUtc, policyType, LastMatchedPatternId))
{
_stateDirty = true;
_logger.Debug($"ImeLogTracker: health script {id} is a recurring policy — start held until its result is known");
return;
}
_stateDirty = true;
RaiseScriptStarted(new ScriptStartedInfo { PolicyId = id, ScriptType = "remediation", PolicyType = policyType });
}
else
{
@@ -269,6 +281,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
internal void HandlePlatformScriptStarted(string id, string source = null)
{
var currentStartTs = LastMatchedLogTimestamp ?? UtcNowProvider();
var currentStartProvenance = CaptureLastMatchedProvenance();
// A start line older than the result this policy already emitted is the late start
// line of THAT run: its AgentExecutor block surfaced after the IME result — the two
@@ -311,6 +324,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
// The slot was opened by its result while the start block was still hidden;
// the recovered start line dates the run.
pendingSlot.StartedAtUtc = currentStartTs;
pendingSlot.StartedAtProvenance = currentStartProvenance;
_stateDirty = true;
}
}
@@ -331,6 +345,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
// Set only at slot creation: the start line fires twice (agentexecutor + ime
// source) but the earliest wins.
StartedAtUtc = currentStartTs,
StartedAtProvenance = currentStartProvenance,
};
// Live "running" indicator — same signal health scripts emit. Gated on slot
// creation so the duplicate start line (agentexecutor + ime source) doesn't
@@ -421,7 +436,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
var script = GetCurrentScriptForLineUpdate(parameters, out var ownerPolicyId);
if (script != null)
ApplyExitCode(script, exitCode, LastMatchedLogTimestamp ?? UtcNowProvider());
ApplyExitCode(script, exitCode, LastMatchedLogTimestamp ?? UtcNowProvider(), CaptureLastMatchedProvenance());
else if (ownerPolicyId != null)
_logger.Debug($"ImeLogTracker: exit code {exitCode} belongs to platform script {ownerPolicyId}, whose completion was already emitted — dropped");
// An exit code means the executor just wrote its end block and IME is about to
@@ -430,15 +445,19 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
RequestOverwriteCheck();
}
private void ApplyExitCode(ScriptExecutionState script, int exitCode, DateTime observedAtUtc)
private void ApplyExitCode(ScriptExecutionState script, int exitCode, DateTime observedAtUtc, CmTraceLineProvenance exitProvenance)
{
script.ExitCode = exitCode;
// Stamp when we learned the script's exit code so the deadline-based fallback
// (FlushPendingPlatformScriptResults) can fire if IME never logs its authoritative
// PS-SCRIPT-RESULT line in time. Prefer the source CMTrace timestamp (already
// UTC-normalized by the parser) so replayed log content is dated correctly.
// UTC-normalized by the parser) so replayed log content is dated correctly. The
// line's provenance rides along: the fallback emit is bound to this line.
if (string.Equals(script.ScriptType, "platform", StringComparison.OrdinalIgnoreCase))
{
script.ExitObservedAtUtc = observedAtUtc;
script.ExitProvenance = exitProvenance;
}
_logger.Debug($"ImeLogTracker: script exit code {exitCode} for {script.PolicyId}");
}
@@ -488,7 +507,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
if (string.IsNullOrEmpty(id)) return;
CompletePlatformScriptFromImeResult(id, result, LastMatchedLogTimestamp, LastMatchedPatternId);
CompletePlatformScriptFromImeResult(id, result, LastMatchedLogTimestamp, LastMatchedPatternId, CaptureLastMatchedProvenance());
}
/// <summary>
@@ -502,7 +521,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
/// line reopened the slot, produced a fallback duplicate (session e7f3c910).
/// <see cref="FlushPendingPlatformScriptResults"/> emits the held completion.
/// </summary>
internal void CompletePlatformScriptFromImeResult(string policyId, string result, DateTime? resultLineTimestampUtc, string patternId)
internal void CompletePlatformScriptFromImeResult(string policyId, string result, DateTime? resultLineTimestampUtc, string patternId, CmTraceLineProvenance resultProvenance)
{
// Dedup: the deadline-based fallback (FlushPendingPlatformScriptResults) may already have
// emitted this script from its AgentExecutor exit code because IME's authoritative
@@ -547,6 +566,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
script.Result = result;
script.ResultSource = "ime_policy_result";
script.ResultObservedAtUtc = resultLineTimestampUtc ?? UtcNowProvider();
script.ResultProvenance = resultProvenance;
script.ResultPatternId = patternId;
_stateDirty = true;
@@ -572,7 +592,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
{
_logger.Info($"ImeLogTracker: platform script completed: {script.PolicyId}, result={script.Result}, exit={script.ExitCode}{(note != null ? $" ({note})" : string.Empty)}");
EmitScriptEvent(script);
_platformScriptResultEmitted[script.PolicyId] = script.ResultObservedAtUtc ?? script.ExitObservedAtUtc ?? UtcNowProvider();
// The run's source stamp, capped at the clock: a result line cannot be read before it
// was written, so a stamp ahead of the clock is a wrong zone assumption on that line
// (a rewound result resolved in the reader's zone, session 4377911b: +1 h). Left
// uncapped, the marker made the genuine NEXT run's start line read as a late line of
// this run and its result a duplicate.
var runStamp = script.ResultObservedAtUtc ?? script.ExitObservedAtUtc ?? UtcNowProvider();
var nowUtc = UtcNowProvider();
_platformScriptResultEmitted[script.PolicyId] = runStamp > nowUtc ? nowUtc : runStamp;
_pendingPlatformScripts.Remove(script.PolicyId);
_stateDirty = true;
}
@@ -669,7 +696,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
/// <summary>Test seam: inject a pending platform script as if AgentExecutor.log had reported
/// its start + exit code, without an IME PS-SCRIPT-RESULT line.</summary>
internal void SeedPendingPlatformScriptForTesting(string policyId, int? exitCode, DateTime? exitObservedAtUtc, string stdout = null, DateTime? startedAtUtc = null)
internal void SeedPendingPlatformScriptForTesting(string policyId, int? exitCode, DateTime? exitObservedAtUtc, string stdout = null, DateTime? startedAtUtc = null,
CmTraceLineProvenance startedAtProvenance = null, CmTraceLineProvenance exitProvenance = null)
{
// Mirrors a fresh execution start: a new run clears any prior emitted-marker (see
// HandleScriptStarted) so re-runs of the same policy within one lifetime emit again.
@@ -682,6 +710,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
ExitObservedAtUtc = exitObservedAtUtc,
Stdout = stdout,
StartedAtUtc = startedAtUtc,
StartedAtProvenance = startedAtProvenance,
ExitProvenance = exitProvenance,
};
NextTestEntry();
RecordInvocationMarker(policyId, isClose: false);
@@ -691,18 +721,18 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
/// (the production handler minus regex extraction). <paramref name="resultLineTimestampUtc"/>
/// stands in for the CMTrace timestamp of the PS-SCRIPT-RESULT line (production reads it
/// via <see cref="LastMatchedLogTimestamp"/>, the fallback here).</summary>
internal void CompletePlatformScriptFromImeResultForTesting(string policyId, string result, DateTime? resultLineTimestampUtc = null)
internal void CompletePlatformScriptFromImeResultForTesting(string policyId, string result, DateTime? resultLineTimestampUtc = null, CmTraceLineProvenance resultProvenance = null)
{
if (string.IsNullOrEmpty(policyId)) return;
CompletePlatformScriptFromImeResult(policyId, result, resultLineTimestampUtc ?? LastMatchedLogTimestamp, "PS-SCRIPT-RESULT");
CompletePlatformScriptFromImeResult(policyId, result, resultLineTimestampUtc ?? LastMatchedLogTimestamp, "PS-SCRIPT-RESULT", resultProvenance ?? CaptureLastMatchedProvenance());
}
/// <summary>Test seam: the AgentExecutor exit-code line of a pending platform script (the
/// production handler minus regex extraction and positional ownership).</summary>
internal void RecordPlatformScriptExitCodeForTesting(string policyId, int exitCode, DateTime observedAtUtc)
internal void RecordPlatformScriptExitCodeForTesting(string policyId, int exitCode, DateTime observedAtUtc, CmTraceLineProvenance exitProvenance = null)
{
if (_pendingPlatformScripts.TryGetValue(policyId, out var script))
ApplyExitCode(script, exitCode, observedAtUtc);
ApplyExitCode(script, exitCode, observedAtUtc, exitProvenance);
}
/// <summary>
@@ -778,8 +808,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
// HS-NEW-RESULT path whose end stamp includes IME's batched reporting latency.
// Peek only: HS-NEW-RESULT still consumes + removes the entry for cycle timing.
StartedAtUtc = _healthScriptStartTimes.TryGetValue(id, out var earlyStart)
? earlyStart
? earlyStart.Utc
: (DateTime?)null,
StartedAtProvenance = _healthScriptStartTimes.TryGetValue(id, out var earlyStartProvenance)
? earlyStartProvenance.Provenance
: null,
// The HS-COMPLIANCE line is the end of this phase; emitted synchronously, so the
// last matched line is it.
ResultProvenance = CaptureLastMatchedProvenance(),
DurationBasis = "script_runtime",
};
@@ -794,6 +830,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
_pendingHealthScript = null;
}
/// <summary>
/// Test seam: a health-script start line for <paramref name="id"/> stamped
/// <paramref name="startedAtUtc"/>, without driving the regex pipeline.
/// </summary>
internal void HandleHealthScriptStartForTest(string id, DateTime startedAtUtc)
{
LastMatchedLogTimestamp = startedAtUtc;
var match = System.Text.RegularExpressions.Regex.Match(id ?? string.Empty, @"(?<id>.+)");
HandleScriptStarted(match, new Dictionary<string, string> { ["scriptType"] = "remediation" });
}
/// <summary>
/// Test seam: simulates the full HS-SCRIPT-START → HS-RUN-CONTEXT / HS-EXITCODE /
/// HS-STDOUT / HS-STDERR → HS-COMPLIANCE sequence by directly populating the
@@ -837,10 +884,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
/// HS-SCRIPT-START line had been observed, so a subsequent
/// <see cref="HandleHealthScriptResultJson"/> surfaces a run duration without driving the
/// full regex pipeline.</summary>
internal void SeedHealthScriptStartForTesting(string policyId, DateTime startedAtUtc)
internal void SeedHealthScriptStartForTesting(string policyId, DateTime startedAtUtc, CmTraceLineProvenance provenance = null)
{
if (string.IsNullOrEmpty(policyId)) return;
_healthScriptStartTimes[policyId] = startedAtUtc;
_healthScriptStartTimes[policyId] = (startedAtUtc, provenance);
}
private void HandleHealthScriptResult(Match match, Dictionary<string, string> parameters)
@@ -897,10 +944,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
// emitted phase events — the remediation analog of platform-script timing. Consumed +
// removed so a later re-run of the same policy re-times from its own start. Null when
// the start line was never seen in the agent's window (e.g. a replayed result).
DateTime? cycleStartedAtUtc = _healthScriptStartTimes.TryGetValue(policyId, out var hsStart)
? hsStart
: (DateTime?)null;
var hasCycleStart = _healthScriptStartTimes.TryGetValue(policyId, out var hsStart);
DateTime? cycleStartedAtUtc = hasCycleStart ? hsStart.Utc : (DateTime?)null;
var cycleStartProvenance = hasCycleStart ? hsStart.Provenance : null;
_healthScriptStartTimes.Remove(policyId);
// Every phase ends on this HS-NEW-RESULT line.
var resultProvenance = CaptureLastMatchedProvenance();
// Common metadata — applied to every emitted phase event.
var remediationStatus = TryGetInt(root, "RemediationStatus");
@@ -940,7 +989,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
targetType: targetType,
errorCode: errorCode,
errorDetails: errorDetails,
startedAtUtc: cycleStartedAtUtc);
startedAtUtc: cycleStartedAtUtc,
startedAtProvenance: cycleStartProvenance,
resultProvenance: resultProvenance);
// complianceResult mirrors the legacy HS-COMPLIANCE event semantics: True when the
// pre-detection script reported compliant (exit 0), False otherwise.
detection.ComplianceResult = firstDetectExit == 0 ? "True" : (firstDetectExit.HasValue ? "False" : null);
@@ -964,7 +1015,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
targetType: targetType,
errorCode: errorCode,
errorDetails: errorDetails,
startedAtUtc: cycleStartedAtUtc);
startedAtUtc: cycleStartedAtUtc,
startedAtProvenance: cycleStartProvenance,
resultProvenance: resultProvenance);
// No complianceResult on the remediation phase — there is nothing to be compliant about.
EmitScriptEvent(remediation);
}
@@ -986,7 +1039,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
targetType: targetType,
errorCode: errorCode,
errorDetails: errorDetails,
startedAtUtc: cycleStartedAtUtc);
startedAtUtc: cycleStartedAtUtc,
startedAtProvenance: cycleStartProvenance,
resultProvenance: resultProvenance);
postDetection.ComplianceResult = lastDetectExit == 0 ? "True" : (lastDetectExit.HasValue ? "False" : null);
EmitScriptEvent(postDetection);
}
@@ -1009,7 +1064,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
int? targetType,
int? errorCode,
string errorDetails,
DateTime? startedAtUtc) =>
DateTime? startedAtUtc,
CmTraceLineProvenance startedAtProvenance,
CmTraceLineProvenance resultProvenance) =>
new ScriptExecutionState
{
PolicyId = policyId,
@@ -1026,6 +1083,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
// Cycle start (HS-SCRIPT-START). Every phase carries the same cycle start so the
// adapter computes the total run duration; the Web surfaces it once at card level.
StartedAtUtc = startedAtUtc,
StartedAtProvenance = startedAtProvenance,
ResultProvenance = resultProvenance,
// End stamp is the HS-NEW-RESULT line — written only after IME's batched report
// to the service, so this duration overstates the actual script execution time.
DurationBasis = "cycle_including_reporting_latency"
@@ -1052,9 +1111,58 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
private void EmitScriptEvent(ScriptExecutionState script)
{
if (script == null || string.IsNullOrEmpty(script.PolicyId)) return;
// Health scripts recur for as long as the device is up; platform scripts run once.
if (string.Equals(script.ScriptType, "remediation", StringComparison.OrdinalIgnoreCase)
&& !_currentLineIsHistoricReplay)
{
var emit = _recurringScripts.OnResult(script, LastMatchedLogTimestamp ?? UtcNowProvider(), out var releasedStart);
_stateDirty = true;
if (!emit)
{
_logger.Debug($"ImeLogTracker: health script {script.PolicyId} {script.ScriptPart} repeats its last reported result — counted, not emitted");
return;
}
if (releasedStart != null) RaiseScriptStarted(releasedStart);
}
OnScriptCompleted?.Invoke(script);
}
private void RaiseScriptStarted(ScriptStartedInfo info)
{
try { OnScriptStarted?.Invoke(info); }
catch (Exception ex) { _logger.Warning($"ImeLogTracker: OnScriptStarted handler threw: {ex.Message}"); }
}
/// <summary>
/// A held start whose run produced no result for <see cref="HeldScriptStartGrace"/> is
/// emitted after all: the script did not finish. On shutdown the shorter
/// <see cref="HeldScriptStartShutdownGrace"/> applies — a start read moments before the
/// stop stays held for the next run of this session instead of reading as unfinished.
/// </summary>
internal void FlushRecurringScripts(DateTime nowUtc, bool shuttingDown)
{
var released = _recurringScripts.ReleaseStartsWithoutResult(
nowUtc, shuttingDown ? HeldScriptStartShutdownGrace : HeldScriptStartGrace);
foreach (var start in released) RaiseScriptStarted(start);
if (shuttingDown)
{
foreach (var summary in _recurringScripts.TakeSummaries())
{
try { OnScriptRecurrenceSummary?.Invoke(summary); }
catch (Exception ex) { _logger.Warning($"ImeLogTracker: OnScriptRecurrenceSummary handler threw: {ex.Message}"); }
}
}
if (_recurringScripts.ConsumeDirty()) _stateDirty = true;
}
// IME aborts a health script after roughly 30 minutes.
internal static readonly TimeSpan HeldScriptStartGrace = TimeSpan.FromMinutes(30);
internal static readonly TimeSpan HeldScriptStartShutdownGrace = TimeSpan.FromMinutes(5);
private static string TruncateOutput(string output)
{
if (string.IsNullOrEmpty(output) || output.Length <= MaxScriptOutputLength)
@@ -505,6 +505,21 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
"imetokenfailure",
};
/// <summary>
/// Snapshot of the last matched line's provenance, for a consumer that acts later than
/// the match (a held platform-script result, a run duration across two lines) and must
/// describe THAT line rather than whichever line is matched by then.
/// </summary>
internal CmTraceLineProvenance CaptureLastMatchedProvenance() => new CmTraceLineProvenance
{
SourceLocalTs = LastMatchedSourceLocalTimestamp,
Origin = LastMatchedSourceOffsetOrigin,
OffsetMinutes = LastMatchedSourceOffsetMinutes,
EraAnchorKind = LastMatchedEraAnchorKind,
MeasuredWriterOffsetMinutes = LastMatchedMeasuredWriterOffsetMinutes,
SourceFileName = _currentSourceFileName,
};
private void HandlePatternMatch(CompiledPattern pattern, Match match, string message, CmTraceLogEntry entry)
{
LastMatchedPatternId = pattern.PatternId;
@@ -551,6 +566,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
// replays historic logs on purpose and bypasses the guard.
var isStaleReplayLine = !SimulationMode && entry != null
&& (UtcNowProvider() - NormalizeUtc(ResolveEntryUtc(entry))) > HistoricReplayThreshold;
_currentLineIsHistoricReplay = isStaleReplayLine;
if (isStaleReplayLine && AppMutatingActions.Contains(pattern.Action?.ToLower() ?? string.Empty))
{
_logger.Debug($"ImeLogTracker: skipped app action '{pattern.Action}' for historic line ({ResolveEntryUtc(entry):o})");
@@ -192,14 +192,23 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
// UI dedupe (dataCompleteness scoring).
private ScriptExecutionState _pendingHealthScript;
// Collapses recurring health-script runs; persisted with the file positions.
private readonly RecurringScriptGate _recurringScripts = new RecurringScriptGate();
// Set for the duration of one pattern dispatch: the matched line is older than
// HistoricReplayThreshold, so the adapter drops whatever it produces.
private bool _currentLineIsHistoricReplay;
// Cycle start timestamps for health (remediation) scripts, keyed by policyId. Captured
// from the HS-SCRIPT-START line ([HS] ProcessScript) so the consolidated HS-NEW-RESULT
// emit can surface the cycle's total run duration (start → result) on its phase events —
// the remediation-script analog of the platform-script StartedAtUtc timing. Kept in a
// dedicated map (not on _pendingHealthScript) because the early-signal HS-COMPLIANCE
// handler clears that slot before HS-NEW-RESULT arrives. Consumed + removed on result emit.
private readonly Dictionary<string, DateTime> _healthScriptStartTimes =
new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
// The start line's provenance rides along so the adapter can tell whether start and result
// were resolved on the same zone assumption before it subtracts them.
private readonly Dictionary<string, (DateTime Utc, CmTraceLineProvenance Provenance)> _healthScriptStartTimes =
new Dictionary<string, (DateTime Utc, CmTraceLineProvenance Provenance)>(StringComparer.OrdinalIgnoreCase);
// Restart-safe dedup for the adapter's one-shot script_timeout_suspected Warning.
// Owned by the tracker (not the adapter) solely so it rides the persisted state file —
@@ -498,6 +507,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
/// </summary>
public Action<ScriptStartedInfo> OnScriptStarted { get; set; }
/// <summary>
/// Fires when the tracker stops, once per health-script policy whose repeated runs were
/// counted instead of emitted since the last summary (see <see cref="RecurringScriptGate"/>).
/// </summary>
public Action<ScriptRecurrenceSummary> OnScriptRecurrenceSummary { get; set; }
/// <summary>
/// Fires on every pattern match with the matched <c>PatternId</c>. Plan §4.x M4.4.4.
/// Invoked by <c>HandlePatternMatch</c> after <see cref="LastMatchedPatternId"/> is
@@ -994,6 +1009,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
try { FlushPendingPlatformScriptResults(UtcNowProvider(), force: true); }
catch (Exception ex) { _logger.Warning($"ImeLogTracker: shutdown script flush failed: {ex.Message}"); }
try { FlushRecurringScripts(UtcNowProvider(), shuttingDown: true); }
catch (Exception ex) { _logger.Warning($"ImeLogTracker: shutdown recurring-script flush failed: {ex.Message}"); }
// Final state save on shutdown
if (_stateDirty)
{
@@ -1024,6 +1042,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
await CheckLogFilesAsync(token);
FlushPendingPlatformScriptResults(UtcNowProvider());
FlushRecurringScripts(UtcNowProvider(), shuttingDown: false);
CheckPendingTokenFailure(UtcNowProvider());
var endMs = MonotonicMillisProvider();
@@ -1163,6 +1182,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
_scriptTimeoutSuspectedPosted.Add(id);
}
_recurringScripts.Restore(state.RecurringScripts);
// Health counters + histogram: a restart (or WhiteGlove Part 2) must report the
// whole session, not only the lines seen since the last start. Null on state files
// written before these fields existed → counters start at zero.
@@ -1239,6 +1260,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
PlatformScriptResultEmittedAt = new Dictionary<string, DateTime>(_platformScriptResultEmitted, StringComparer.OrdinalIgnoreCase),
PendingPlatformScripts = _pendingPlatformScripts.Values.ToList(),
ScriptTimeoutSuspectedPosted = _scriptTimeoutSuspectedPosted.ToList(),
RecurringScripts = _recurringScripts.ToPersisted(),
};
lock (_healthLock)
@@ -153,6 +153,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
public List<ScriptExecutionState> PendingPlatformScripts { get; set; }
public List<string> ScriptTimeoutSuspectedPosted { get; set; }
// Recurring health-script runs collapsed per policy. Saved in the same write as
// FilePositions on purpose: after a hard kill both fall back together, so re-read lines
// are counted again instead of twice. Null on older state files → empty.
public Dictionary<string, RecurringScriptPolicyState> RecurringScripts { get; set; }
// Cumulative tracker health + per-pattern histogram (ime_pattern_hits / ime_tracker_degraded,
// 2026-08-30). Restart-safe on purpose: WhiteGlove Part 2 reports the whole session and the
// one-shot degraded event must not fire twice. Null on older state files → zero.
@@ -0,0 +1,257 @@
using System;
using System.Collections.Generic;
using System.Globalization;
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.Ime
{
/// <summary>
/// Collapses recurring health-script (proactive remediation) runs. IME re-runs every assigned
/// policy on its own schedule for as long as the device is up; an enrollment that waits for
/// its user for days would otherwise report every hourly run of every policy. A policy's
/// first run and every run whose result differs from the last reported one are emitted in
/// full; runs that repeat the last reported result are only counted and surface once per
/// policy as a recurrence summary.
/// <para>
/// The start signal of an already known policy is held until its result is known, because
/// the running indicators (web panel, session coverage) pair a start with a later result of
/// the same policy — a start whose result was collapsed would read as "still running".
/// </para>
/// <para>
/// The state is part of the tracker state file and is saved in the same write as the file
/// positions: after a hard kill both fall back together, the lines after the last save are
/// read again and counted again — nothing is lost and nothing counts twice.
/// </para>
/// Not thread-safe: called from the tracker's single poll thread only.
/// </summary>
public sealed class RecurringScriptGate
{
private readonly Dictionary<string, RecurringScriptPolicyState> _policies =
new Dictionary<string, RecurringScriptPolicyState>(StringComparer.OrdinalIgnoreCase);
/// <summary>True when any call changed persisted state since the last <see cref="ConsumeDirty"/>.</summary>
private bool _dirty;
public bool ConsumeDirty()
{
var wasDirty = _dirty;
_dirty = false;
return wasDirty;
}
/// <summary>
/// A start line was read. Returns <c>true</c> when the start signal is emitted right away
/// (first run of the policy); <c>false</c> when it is held until the run's result is known.
/// </summary>
public bool OnStart(string policyId, DateTime startedAtUtc, string policyType, string patternId)
{
if (string.IsNullOrEmpty(policyId)) return true;
var isKnown = _policies.TryGetValue(policyId, out var state);
if (!isKnown)
{
state = new RecurringScriptPolicyState();
_policies[policyId] = state;
}
CloseHeldRun(state);
state.RunsObserved++;
_dirty = true;
if (!isKnown) return true;
state.HeldStartAtUtc = startedAtUtc;
state.HeldStartPolicyType = policyType;
state.HeldStartPatternId = patternId;
state.HeldRunSawResult = false;
return false;
}
/// <summary>
/// A result (one phase event) is about to be emitted. Returns <c>true</c> to emit it; when
/// the run's start was held, <paramref name="releasedStart"/> carries the start signal to
/// emit first. Returns <c>false</c> when the result repeats the last reported one.
/// </summary>
public bool OnResult(ScriptExecutionState script, DateTime observedAtUtc, out ScriptStartedInfo releasedStart)
{
releasedStart = null;
if (script == null || string.IsNullOrEmpty(script.PolicyId)) return true;
if (!_policies.TryGetValue(script.PolicyId, out var state))
{
state = new RecurringScriptPolicyState();
_policies[script.PolicyId] = state;
}
var key = SignatureKey(script);
var signature = Signature(script);
_dirty = true;
if (state.Signatures.TryGetValue(key, out var last) && string.Equals(last, signature, StringComparison.Ordinal))
{
state.CollapsedResults++;
if (!state.FirstCollapsedAtUtc.HasValue) state.FirstCollapsedAtUtc = observedAtUtc;
state.LastCollapsedAtUtc = observedAtUtc;
if (state.HeldStartAtUtc.HasValue) state.HeldRunSawResult = true;
return false;
}
state.Signatures[key] = signature;
releasedStart = ReleaseHeldStart(script.PolicyId, state);
return true;
}
/// <summary>
/// Start signals that were held for at least <paramref name="minAge"/> without any result:
/// the script did not finish, which is exactly what the running indicators are for.
/// </summary>
public List<ScriptStartedInfo> ReleaseStartsWithoutResult(DateTime nowUtc, TimeSpan minAge)
{
var released = new List<ScriptStartedInfo>();
foreach (var kv in _policies)
{
var state = kv.Value;
if (!state.HeldStartAtUtc.HasValue || state.HeldRunSawResult) continue;
if (nowUtc - state.HeldStartAtUtc.Value < minAge) continue;
released.Add(ReleaseHeldStart(kv.Key, state));
_dirty = true;
}
return released;
}
/// <summary>
/// One summary per policy whose collapsed-run count grew since the last summary. Marks
/// the reported count, so a later stop of the same session only reports new growth.
/// </summary>
public List<ScriptRecurrenceSummary> TakeSummaries()
{
var summaries = new List<ScriptRecurrenceSummary>();
foreach (var kv in _policies)
{
var state = kv.Value;
var collapsedRuns = state.RunsCollapsed + (state.HeldStartAtUtc.HasValue && state.HeldRunSawResult ? 1 : 0);
if (collapsedRuns <= state.RunsCollapsedAtLastSummary) continue;
summaries.Add(new ScriptRecurrenceSummary
{
PolicyId = kv.Key,
RunsObserved = state.RunsObserved,
RunsCollapsed = collapsedRuns,
RunsWithoutResult = state.RunsWithoutResult,
CollapsedResults = state.CollapsedResults,
FirstCollapsedAtUtc = state.FirstCollapsedAtUtc,
LastCollapsedAtUtc = state.LastCollapsedAtUtc,
});
state.RunsCollapsedAtLastSummary = collapsedRuns;
_dirty = true;
}
return summaries;
}
public Dictionary<string, RecurringScriptPolicyState> ToPersisted() =>
new Dictionary<string, RecurringScriptPolicyState>(_policies, StringComparer.OrdinalIgnoreCase);
public void Restore(Dictionary<string, RecurringScriptPolicyState> persisted)
{
_policies.Clear();
if (persisted == null) return;
foreach (var kv in persisted)
{
if (string.IsNullOrEmpty(kv.Key) || kv.Value == null) continue;
if (kv.Value.Signatures == null)
kv.Value.Signatures = new Dictionary<string, string>(StringComparer.Ordinal);
_policies[kv.Key] = kv.Value;
}
}
// A held run ends when the next start of the policy arrives: all its results repeated the
// last report (collapsed), or it never produced one.
private static void CloseHeldRun(RecurringScriptPolicyState state)
{
if (!state.HeldStartAtUtc.HasValue) return;
if (state.HeldRunSawResult) state.RunsCollapsed++;
else state.RunsWithoutResult++;
ClearHeldStart(state);
}
private static ScriptStartedInfo ReleaseHeldStart(string policyId, RecurringScriptPolicyState state)
{
if (!state.HeldStartAtUtc.HasValue) return null;
var info = new ScriptStartedInfo
{
PolicyId = policyId,
ScriptType = "remediation",
PolicyType = state.HeldStartPolicyType,
SourceTimestampUtc = state.HeldStartAtUtc,
PatternId = state.HeldStartPatternId,
};
ClearHeldStart(state);
return info;
}
private static void ClearHeldStart(RecurringScriptPolicyState state)
{
state.HeldStartAtUtc = null;
state.HeldStartPolicyType = null;
state.HeldStartPatternId = null;
state.HeldRunSawResult = false;
}
// The early compliance signal and the consolidated result of one phase differ in
// completeness (only the latter knows RemediationStatus); keyed apart, or the two would
// overwrite each other's signature on every run and nothing would ever collapse.
private static string SignatureKey(ScriptExecutionState script) =>
(script.ScriptPart ?? string.Empty) + "|" + (script.DurationBasis ?? string.Empty);
private static string Signature(ScriptExecutionState script)
{
var culture = CultureInfo.InvariantCulture;
return string.Join("|",
script.ComplianceResult ?? string.Empty,
script.ExitCode.HasValue ? script.ExitCode.Value.ToString(culture) : string.Empty,
string.IsNullOrWhiteSpace(script.Stderr) ? "0" : "1",
script.RemediationStatus.HasValue ? script.RemediationStatus.Value.ToString(culture) : string.Empty,
script.ErrorCode.HasValue ? script.ErrorCode.Value.ToString(culture) : string.Empty);
}
}
/// <summary>Persisted per-policy state of <see cref="RecurringScriptGate"/>.</summary>
public class RecurringScriptPolicyState
{
/// <summary>Last reported result per phase and signal kind.</summary>
public Dictionary<string, string> Signatures { get; set; } = new Dictionary<string, string>(StringComparer.Ordinal);
/// <summary>Start lines read for the policy.</summary>
public int RunsObserved { get; set; }
/// <summary>Runs whose every result repeated the last reported one.</summary>
public int RunsCollapsed { get; set; }
/// <summary>Runs that were followed by the next start without any result in between.</summary>
public int RunsWithoutResult { get; set; }
/// <summary>Phase events that were not emitted.</summary>
public int CollapsedResults { get; set; }
public DateTime? FirstCollapsedAtUtc { get; set; }
public DateTime? LastCollapsedAtUtc { get; set; }
public DateTime? HeldStartAtUtc { get; set; }
public string HeldStartPolicyType { get; set; }
public string HeldStartPatternId { get; set; }
public bool HeldRunSawResult { get; set; }
public int RunsCollapsedAtLastSummary { get; set; }
}
/// <summary>What <see cref="RecurringScriptGate"/> collapsed for one policy.</summary>
public class ScriptRecurrenceSummary
{
public string PolicyId { get; set; }
public int RunsObserved { get; set; }
public int RunsCollapsed { get; set; }
public int RunsWithoutResult { get; set; }
public int CollapsedResults { get; set; }
public DateTime? FirstCollapsedAtUtc { get; set; }
public DateTime? LastCollapsedAtUtc { get; set; }
}
}
@@ -29,6 +29,15 @@ public class ScriptExecutionState
/// </summary>
public System.DateTime? StartedAtUtc { get; set; }
/// <summary>
/// Provenance of <see cref="StartedAtUtc"/>: how the start line's offset was obtained. Paired
/// with <see cref="ResultProvenance"/> / <see cref="ExitProvenance"/> by the adapter to decide
/// whether a run duration is measurable — two lines resolved on different zone assumptions
/// differ by whole offset-grid steps, not by run time (session 4377911b: a 10 s script read
/// as 3610 s). Null when the start was never observed or on state files from before the field.
/// </summary>
public CmTraceLineProvenance StartedAtProvenance { get; set; }
/// <summary>"detection", "remediation", or "post-detection" (remediation scripts only).</summary>
public string ScriptPart { get; set; }
@@ -66,6 +75,9 @@ public class ScriptExecutionState
/// </summary>
public System.DateTime? ExitObservedAtUtc { get; set; }
/// <summary>Provenance of the exit-code line behind <see cref="ExitObservedAtUtc"/> (the fallback emit's end).</summary>
public CmTraceLineProvenance ExitProvenance { get; set; }
/// <summary>
/// Source (CMTrace) timestamp of the IME <c>PS-SCRIPT-RESULT</c> line that delivered
/// <see cref="Result"/> (platform scripts, <c>ime_policy_result</c> only). The emitted event is
@@ -76,6 +88,14 @@ public class ScriptExecutionState
/// </summary>
public System.DateTime? ResultObservedAtUtc { get; set; }
/// <summary>
/// Provenance of the line that delivered <see cref="Result"/> — bound here for the same reason
/// as <see cref="ResultObservedAtUtc"/>: a held completion is emitted passes later, when the
/// tracker's "last matched" provenance describes an unrelated line. For health scripts the
/// result line of the phase (HS-COMPLIANCE early signal or HS-NEW-RESULT).
/// </summary>
public CmTraceLineProvenance ResultProvenance { get; set; }
/// <summary>Pattern id of the line that delivered <see cref="Result"/> (surfaced as <c>patternId</c> on the event).</summary>
public string ResultPatternId { get; set; }
@@ -142,4 +162,14 @@ public class ScriptStartedInfo
/// <summary>Numeric IME PolicyType from the start line (captured as string), e.g. "6" for health scripts.</summary>
public string PolicyType { get; set; }
/// <summary>
/// Source timestamp of the start line when the signal is emitted later than it was read
/// (a held start of a recurring health script, see <see cref="RecurringScriptGate"/>). Null
/// for a start emitted while its own line is the tracker's last matched one.
/// </summary>
public System.DateTime? SourceTimestampUtc { get; set; }
/// <summary>Pattern id of the start line; set together with <see cref="SourceTimestampUtc"/>.</summary>
public string PatternId { get; set; }
}
@@ -216,6 +216,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
/// </summary>
public bool HasAccountSetupProgress => _provisioningTracker?.HasAccountSetupProgress ?? false;
/// <summary>
/// <see cref="ProvisioningStatusTracker.AccountSetupProgressIfRead"/>; <c>null</c> also when
/// the provisioning tracker is not running (Device Preparation, before Start). Stamped on
/// the WhiteGloveShellCoreSuccess signal for the sealing classifier.
/// </summary>
public bool? AccountSetupProgressIfRead => _provisioningTracker?.AccountSetupProgressIfRead;
/// <summary>
/// True once WhiteGlove start has been detected (EventID 509 or persisted from prior run).
/// Forwarded from ModernDeploymentTracker.
@@ -24,10 +24,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
/// <item><c>EspTrackingWin32Apps\&lt;userGuid&gt;\&lt;appGuid&gt;_&lt;rev&gt;</c> — which apps IME
/// registered for ESP tracking and in which phase.</item>
/// <item><c>SideCarPolicies\StatusServiceReports\&lt;userGuid&gt;\&lt;appId&gt;</c> — the exact
/// AppInstallStatusReport the ESP page renders (Status 1000=Installed .. 3000=Failed).</item>
/// AppInstallStatusReport the ESP page renders (Status 1000=Installed, 1001=Installing,
/// 1003=InstallingPendingReboot, 2000=NotApplicable, 3000=Failed).</item>
/// <item><c>Win32Apps\OperationalState\&lt;userGuid&gt;\&lt;appGuid&gt;</c> (bare GUIDs) — IME's
/// per-app operational state: the install deadline a downloaded app is waiting for
/// (<c>ExecutionDeadlineTime</c>, IME 1.106+) and the app-in-use deferral counters
/// (<c>DeferralsUsed</c>, <c>DeferUntilTime</c>, ..., IME 1.105+).</item>
/// </list>
/// The observer is snapshot-and-diff driven (RegistryWatcher gives key-scope edges only,
/// coalesced — a per-write parse is impossible by design): every tick re-reads the three
/// coalesced — a per-write parse is impossible by design): every tick re-reads the four
/// surfaces and emits <c>registry_app_state</c> on real field changes. Pre-existing state at
/// agent start is the silent baseline — Win32Apps keys survive re-enrollments, so replaying
/// them as fresh events would be the registry twin of the historic-IME-replay bug.
@@ -162,6 +167,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
ReadWin32Apps(root, snapshot);
ReadEspTracking(root, snapshot);
ReadStatusServiceReports(root, snapshot);
ReadOperationalState(root, snapshot);
return snapshot;
}
@@ -250,6 +256,42 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
}
}
// Only the two wait states are read; the download/execution bookkeeping next to them
// (DownloadStatus, DownloadStartTime, ExecutionStatus, ...) duplicates the log narrative
// and would double the event volume without adding a state the timeline lacks.
private static void ReadOperationalState(RegistryKey root, ImeRegistrySnapshot snapshot)
{
using var operational = root.OpenSubKey(@"Win32Apps\OperationalState");
if (operational == null) return;
foreach (var userName in operational.GetSubKeyNames())
{
if (!LooksLikeGuid(userName)) continue;
using var userKey = operational.OpenSubKey(userName);
if (userKey == null) continue;
foreach (var appKeyName in userKey.GetSubKeyNames())
{
var appId = ExtractAppId(appKeyName);
if (appId == null) continue;
using var appKey = userKey.OpenSubKey(appKeyName);
if (appKey == null) continue;
var deadline = TryParseRegistryDateTime(appKey.GetValue("ExecutionDeadlineTime"));
var deferralsUsed = TryReadInt(appKey.GetValue("DeferralsUsed"));
if (deadline == null && deferralsUsed == null) continue; // no wait state — no entry of its own
var entry = snapshot.GetOrAdd(userName, appId);
entry.InstallDeadlineUtc = deadline;
entry.DeferralsUsed = deferralsUsed;
entry.DeferralMaxDeferrals = TryReadInt(appKey.GetValue("DeferralMaxDeferrals"));
entry.DeferUntilUtc = TryParseRegistryDateTime(appKey.GetValue("DeferUntilTime"));
entry.DeferralAutoDeferred = TryReadBool(appKey.GetValue("DeferralAutoDeferred"));
}
}
}
// ── pure helpers (unit-tested directly) ─────────────────────────────────
internal static bool LooksLikeGuid(string name) =>
@@ -301,6 +343,23 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
}
}
internal static bool? TryReadBool(object? value) =>
value is string s && bool.TryParse(s, out var parsed) ? parsed : (bool?)null;
/// <summary>
/// OperationalState timestamps are UTC but stored in two InvariantCulture shapes:
/// <c>ExecutionDeadlineTime</c> as <c>MM/dd/yyyy HH:mm:ss</c> without a kind marker,
/// <c>DeferUntilTime</c> round-trip ("o", trailing Z). Both come back as UTC here.
/// </summary>
internal static DateTime? TryParseRegistryDateTime(object? value)
{
if (!(value is string s) || string.IsNullOrWhiteSpace(s)) return null;
return DateTime.TryParse(s, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var parsed)
? parsed
: (DateTime?)null;
}
/// <summary>StateMessageEnforcementState bands (verified against decompiled IME 1.97/1.104).</summary>
internal static string ClassifyEnforcementState(int state)
{
@@ -312,15 +371,59 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
return "unknown";
}
/// <summary>AppInstallStatus (StatusService/ESP page): 1000er = installed, 3000 = failed.</summary>
/// <summary>
/// AppInstallStatus as IME writes it to StatusServiceReports (unchanged IME 1.50 .. 1.106):
/// 1000 Installed, 1001 Installing, 1002 InstalledButDependenciesNotPresent,
/// 1003 InstallingPendingReboot, 1004 InstalledPendingReboot, 2000 NotApplicable, 3000 Failed.
/// The 1000 band is NOT uniformly terminal — IME maps every InProgress enforcement state to
/// 1001 — so the mapping is explicit and an unknown value is not judged.
/// </summary>
internal static string? ClassifyStatusServiceStatus(int status)
{
if (status >= 1000 && status < 2000) return "installed";
if (status == 3000) return "failed";
switch (status)
{
case 1000:
case 1002:
case 1004:
return "installed";
case 1001:
case 1003:
return "installing";
case 3000:
return "failed";
}
if (status >= 2000 && status < 3000) return "notApplicable";
return null;
}
/// <summary>
/// Human-readable suffix for the two IME wait states (install deadline, app-in-use
/// deferral); empty when neither applies. Culture-invariant on purpose — the agent runs
/// under whatever culture the SYSTEM account carries.
/// </summary>
internal static string DescribeWaitState(AppRegistryEntry entry)
{
var parts = new List<string>(2);
if (entry.InstallDeadlineUtc is DateTime deadline)
parts.Add("downloaded, install deadline " + FormatUtcMinute(deadline));
if (entry.DeferralsUsed is int used && used > 0)
{
var kind = entry.DeferralAutoDeferred == true ? "auto-deferred" : "deferred by user";
var count = entry.DeferralMaxDeferrals is int max
? used.ToString(CultureInfo.InvariantCulture) + "/" + max.ToString(CultureInfo.InvariantCulture)
: used.ToString(CultureInfo.InvariantCulture);
parts.Add(entry.DeferUntilUtc is DateTime until
? kind + " " + count + " until " + FormatUtcMinute(until)
: kind + " " + count);
}
return parts.Count == 0 ? string.Empty : ", " + string.Join(", ", parts);
}
private static string FormatUtcMinute(DateTime utc) =>
utc.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC";
internal static List<AppRegistryChange> DiffSnapshots(ImeRegistrySnapshot previous, ImeRegistrySnapshot next)
{
var changes = new List<AppRegistryChange>();
@@ -343,6 +446,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
if (prev?.StatusServiceStatus != next.StatusServiceStatus) changed.Add("statusServiceStatus");
if ((prev?.EspTracked ?? false) != next.EspTracked) changed.Add("espTracked");
if (!string.Equals(prev?.EspPhase, next.EspPhase, StringComparison.OrdinalIgnoreCase)) changed.Add("espPhase");
// Wait states: the deadline and each recorded deferral are transitions worth an event;
// MaxDeferrals / AutoDeferred only travel along as data.
if (prev?.InstallDeadlineUtc != next.InstallDeadlineUtc) changed.Add("installDeadline");
if (prev?.DeferralsUsed != next.DeferralsUsed) changed.Add("deferralsUsed");
if (prev?.DeferUntilUtc != next.DeferUntilUtc) changed.Add("deferUntil");
return changed;
}
@@ -445,6 +553,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
}
if (e.EspTracked) data["espTracked"] = "true";
if (!string.IsNullOrEmpty(e.EspPhase)) data["espPhase"] = e.EspPhase!;
if (e.InstallDeadlineUtc is DateTime deadline) data["installDeadlineUtc"] = deadline.ToString("o", CultureInfo.InvariantCulture);
if (e.DeferralsUsed is int used) data["deferralsUsed"] = used.ToString(CultureInfo.InvariantCulture);
if (e.DeferralMaxDeferrals is int max) data["deferralMaxDeferrals"] = max.ToString(CultureInfo.InvariantCulture);
if (e.DeferUntilUtc is DateTime until) data["deferUntilUtc"] = until.ToString("o", CultureInfo.InvariantCulture);
if (e.DeferralAutoDeferred is bool auto) data["deferralAutoDeferred"] = auto ? "true" : "false";
var summary = data.TryGetValue("enforcementClass", out var encls) ? encls
: data.TryGetValue("statusServiceClass", out var sscls) ? sscls
@@ -453,7 +566,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
_post.Emit(
eventType: SharedEventTypes.RegistryAppState,
source: SourceLabel,
message: $"Registry app state: {e.AppId} ({(e.UserContext == ImeRegistrySnapshot.DeviceContext ? "device" : "user")}) -> {summary}",
message: $"Registry app state: {e.AppId} ({(e.UserContext == ImeRegistrySnapshot.DeviceContext ? "device" : "user")}) -> {summary}{DescribeWaitState(e)}",
severity: EventSeverity.Info,
data: data,
occurredAtUtc: nowUtc);
@@ -625,6 +738,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
public int? StatusServiceStatus { get; set; }
public bool EspTracked { get; set; }
public string? EspPhase { get; set; }
// Win32Apps\OperationalState — the two IME wait states (all UTC).
public DateTime? InstallDeadlineUtc { get; set; }
public int? DeferralsUsed { get; set; }
public int? DeferralMaxDeferrals { get; set; }
public DateTime? DeferUntilUtc { get; set; }
public bool? DeferralAutoDeferred { get; set; }
}
internal sealed class AppRegistryChange
@@ -254,16 +254,27 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
/// host to tell the real user-ESP page exit from the Device→Account handoff exit; not a
/// completion input.
/// </summary>
public bool HasAccountSetupProgress
public bool HasAccountSetupProgress => AccountSetupProgressIfRead == true;
/// <summary>
/// Tri-state form of <see cref="HasAccountSetupProgress"/>: <c>null</c> until the tracker
/// has actually read AccountSetup subcategories (not started yet, category not written,
/// empty), otherwise whether one has left <c>notStarted</c>. The WhiteGlove sealing
/// classifier treats only a read <c>false</c> as "user ESP untouched" — an unread
/// registry must never pass for an untouched one.
/// </summary>
public bool? AccountSetupProgressIfRead
{
get
{
lock (_stateLock)
{
if (_lastSubcategoryStates == null)
return false;
if (!_lastSubcategoryStates.TryGetValue("AccountSetupCategory.Status", out var subs) || subs == null)
return false;
return null;
if (!_lastSubcategoryStates.TryGetValue("AccountSetupCategory.Status", out var subs)
|| subs == null
|| subs.Count == 0)
return null;
foreach (var state in subs.Values)
{
if (!string.Equals(state, "notStarted", StringComparison.OrdinalIgnoreCase))
@@ -279,7 +290,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
/// with subcategoryState=succeeded. NOT a WhiteGlove indicator: on Win11 25H2 (build
/// 26200+) Windows writes this property as a trivially-succeeding step in EVERY
/// enrollment (validated 2026-08-18 — user-driven sessions f475e697/c601a24b/4219203f
/// all carry it). Kept for observability only (whiteglove_signal_* raw dumps); must not
/// all carry it). Kept for observability only (save_result_step_* raw dumps); must not
/// be used for classification. Reliable WhiteGlove anchors are ModernDeployment
/// EventID 509 and the Shell-Core WhiteGlove-success events.
/// </summary>
@@ -966,8 +977,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
_logger.Info($"ProvisioningStatusTracker: SaveWhiteGloveSuccessResult state " +
$"transition: {previousState} -> {state}");
// Neutral trigger name: the step exists in every 25H2 enrollment,
// and "whiteglove_*" was read as a pre-provisioning signal.
EmitRawRegistryDump(categoryLabel, jsonValue,
$"whiteglove_signal_{state}");
$"save_result_step_{state}");
if (string.Equals(state, "succeeded", StringComparison.OrdinalIgnoreCase))
{
@@ -237,6 +237,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
using (response)
{
await ThrowOnAuthFailureAsync(response).ConfigureAwait(false);
await ThrowOnCodedConflictAsync(response).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responseJson = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
@@ -338,6 +339,38 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
errorCode: errorCode);
}
/// <summary>
/// Throws <see cref="BackendRefusalException"/> for a 409 whose JSON body carries a
/// machine-readable <c>errorCode</c> — register-session answers
/// <c>session_owner_mismatch</c> when another tenant claimed the session id, which no retry
/// can clear but a session rotation can. A 409 without a code falls through to
/// <c>EnsureSuccessStatusCode</c> as before.
/// </summary>
private static async Task ThrowOnCodedConflictAsync(HttpResponseMessage response)
{
if (response.StatusCode != System.Net.HttpStatusCode.Conflict)
return;
string body = null;
try
{
body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch
{
// No body, no code — the generic 409 handling applies.
}
var errorCode = TryExtractErrorCode(body);
if (errorCode == null)
return;
throw new BackendRefusalException(
$"Backend returned 409 Conflict with error code {errorCode}.",
(int)response.StatusCode,
errorCode);
}
/// <summary>
/// Pulls <c>errorCode</c> out of a backend JSON error body. Tolerant: any parse failure
/// or a non-string value yields null, never an exception.
@@ -471,4 +504,24 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
ErrorCode = errorCode;
}
}
/// <summary>
/// Thrown when the backend refuses a request on a non-auth status (409) with a machine-readable
/// code from Shared <c>Constants.AgentErrorCodes</c>. Unlike <see cref="BackendAuthException"/>
/// it says nothing about the device's authorization and must never feed the auth-failure tracker.
/// </summary>
public class BackendRefusalException : Exception
{
/// <summary>HTTP status code returned by the backend (409).</summary>
public int StatusCode { get; }
/// <summary>Machine-readable code from the backend's JSON body (never null).</summary>
public string ErrorCode { get; }
public BackendRefusalException(string message, int statusCode, string errorCode) : base(message)
{
StatusCode = statusCode;
ErrorCode = errorCode;
}
}
}
@@ -79,6 +79,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
/// exist for callers whose process is about to exit and cannot come back later
/// (emergency break): retries stay INSIDE the one reservation, so they never
/// multiply against the per-session budget.
///
/// <paramref name="sessionAgeHours"/> is the emergency break's measured session age
/// (<see cref="AgentErrorReport.SessionAgeHours"/>) and <paramref name="priorRegistrationFailure"/>
/// its record of earlier starts that never registered
/// (<see cref="AgentErrorReport.PriorRegistrationFailure"/>); null for every other error type.
/// </summary>
public virtual async Task TrySendAsync(
AgentErrorType errorType,
@@ -87,7 +92,9 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
long? sequenceNumber = null,
int attempts = 1,
TimeSpan? perAttemptTimeout = null,
TimeSpan? retryDelay = null)
TimeSpan? retryDelay = null,
double? sessionAgeHours = null,
RegistrationFailureSummary priorRegistrationFailure = null)
{
// Deduplicate by error type + status code: same failure category sent only once per session.
// All anti-flood checks are protected by a lock to prevent race conditions when
@@ -135,6 +142,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
Message = message,
HttpStatusCode = httpStatusCode,
SequenceNumber = sequenceNumber,
SessionAgeHours = sessionAgeHours,
PriorRegistrationFailure = priorRegistrationFailure,
AgentVersion = _agentVersion,
Timestamp = DateTime.UtcNow
};
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
@@ -25,6 +26,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
/// </summary>
public string Ip { get; set; }
/// <summary>"City, Region, Country" without the parts a provider did not return.</summary>
public string Describe() =>
string.Join(", ", new[] { City, Region, Country }.Where(p => !string.IsNullOrEmpty(p)));
public Dictionary<string, object> ToDictionary()
{
return new Dictionary<string, object>
@@ -45,6 +50,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
public string PrimaryError { get; set; }
public string PrimaryRetryError { get; set; }
public string FallbackError { get; set; }
public string DoGeoError { get; set; }
}
public static class GeoLocationService
@@ -52,6 +58,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
private static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(5);
private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(2);
internal const string IpInfoUrl = "https://ipinfo.io/json";
internal const string IfConfigCoUrl = "https://ifconfig.co/json";
/// <summary>
/// Delivery Optimization's own geo endpoint. Country and egress IP only (no region, city,
/// coordinates or timezone), but it is part of the Windows Update / DO endpoint set that
/// Autopilot needs anyway, so it stays reachable in networks that block public geo services.
/// </summary>
internal const string DoGeoUrl = "https://geo.prod.do.dsp.mp.microsoft.com/geo";
// Static HttpClient to avoid socket exhaustion from repeated short-lived instances.
// HttpClient is designed to be reused across requests.
private static readonly HttpClient SharedHttpClient = CreateSharedHttpClient();
@@ -68,7 +84,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
var attempt = new GeoLocationAttemptResult();
// Try ipinfo.io first
var (result, error) = await TryIpInfo(logger);
var (result, error) = await TryProvider("ipinfo.io", IpInfoUrl, ParseIpInfo, logger);
if (result != null)
{
attempt.Location = result;
@@ -80,7 +96,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
logger?.Info($"GeoLocation: Retrying ipinfo.io after {RetryDelay.TotalSeconds}s...");
await Task.Delay(RetryDelay);
(result, error) = await TryIpInfo(logger);
(result, error) = await TryProvider("ipinfo.io", IpInfoUrl, ParseIpInfo, logger);
if (result != null)
{
attempt.Location = result;
@@ -89,7 +105,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
attempt.PrimaryRetryError = error;
// Fallback to ifconfig.co
(result, error) = await TryIfConfigCo(logger);
(result, error) = await TryProvider("ifconfig.co", IfConfigCoUrl, ParseIfConfigCo, logger);
if (result != null)
{
attempt.Location = result;
@@ -97,108 +113,111 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Transport
}
attempt.FallbackError = error;
// Last resort: Delivery Optimization geo — country only, but better than no location
(result, error) = await TryProvider("do-geo", DoGeoUrl, ParseDoGeo, logger);
if (result != null)
{
attempt.Location = result;
return attempt;
}
attempt.DoGeoError = error;
logger?.Warning("GeoLocation: All providers failed, skipping location event");
return attempt;
}
private static async Task<(GeoLocationResult result, string error)> TryIpInfo(AgentLogger logger)
private static async Task<(GeoLocationResult result, string error)> TryProvider(
string name, string url, Func<JObject, GeoLocationResult> parse, AgentLogger logger)
{
try
{
logger?.Info("GeoLocation: Querying ipinfo.io...");
logger?.Info($"GeoLocation: Querying {name}...");
using (var httpResponse = await SharedHttpClient.GetAsync("https://ipinfo.io/json"))
using (var httpResponse = await SharedHttpClient.GetAsync(url))
{
if (!httpResponse.IsSuccessStatusCode)
{
var error = $"HTTP {(int)httpResponse.StatusCode} ({httpResponse.ReasonPhrase})";
logger?.Warning($"GeoLocation: ipinfo.io failed: {error}");
logger?.Warning($"GeoLocation: {name} failed: {error}");
return (null, error);
}
var response = await httpResponse.Content.ReadAsStringAsync();
var json = JObject.Parse(response);
var result = new GeoLocationResult
var result = parse(JObject.Parse(response));
if (result == null)
{
Country = json.Value<string>("country"),
Region = json.Value<string>("region"),
City = json.Value<string>("city"),
Loc = json.Value<string>("loc"),
Timezone = json.Value<string>("timezone"),
Ip = json.Value<string>("ip"),
Source = "ipinfo"
};
var error = "No country in response";
logger?.Warning($"GeoLocation: {name} failed: {error}");
return (null, error);
}
logger?.Info($"GeoLocation: ipinfo.io returned {result.City}, {result.Region}, {result.Country}");
logger?.Info($"GeoLocation: {name} returned {result.Describe()}");
return (result, null);
}
}
catch (TaskCanceledException)
{
var error = "Timeout (5s)";
logger?.Warning($"GeoLocation: ipinfo.io failed: {error}");
var error = $"Timeout ({RequestTimeout.TotalSeconds}s)";
logger?.Warning($"GeoLocation: {name} failed: {error}");
return (null, error);
}
catch (Exception ex)
{
var error = ex.Message;
logger?.Warning($"GeoLocation: ipinfo.io failed: {error}");
logger?.Warning($"GeoLocation: {name} failed: {error}");
return (null, error);
}
}
private static async Task<(GeoLocationResult result, string error)> TryIfConfigCo(AgentLogger logger)
internal static GeoLocationResult ParseIpInfo(JObject json) =>
new GeoLocationResult
{
Country = json.Value<string>("country"),
Region = json.Value<string>("region"),
City = json.Value<string>("city"),
Loc = json.Value<string>("loc"),
Timezone = json.Value<string>("timezone"),
Ip = json.Value<string>("ip"),
Source = "ipinfo"
};
internal static GeoLocationResult ParseIfConfigCo(JObject json)
{
try
var latitude = json.Value<string>("latitude") ?? "";
var longitude = json.Value<string>("longitude") ?? "";
var loc = !string.IsNullOrEmpty(latitude) && !string.IsNullOrEmpty(longitude)
? $"{latitude},{longitude}"
: "";
return new GeoLocationResult
{
logger?.Info("GeoLocation: Falling back to ifconfig.co...");
Country = json.Value<string>("country_iso"),
Region = json.Value<string>("region_name"),
City = json.Value<string>("city"),
Loc = loc,
Timezone = json.Value<string>("time_zone"),
Ip = json.Value<string>("ip"),
Source = "ifconfig.co"
};
}
using (var httpResponse = await SharedHttpClient.GetAsync("https://ifconfig.co/json"))
{
if (!httpResponse.IsSuccessStatusCode)
{
var error = $"HTTP {(int)httpResponse.StatusCode} ({httpResponse.ReasonPhrase})";
logger?.Warning($"GeoLocation: ifconfig.co failed: {error}");
return (null, error);
}
/// <summary>
/// The DO geo response carries DO service configuration next to the geo fields; only
/// <c>CountryCode</c> and <c>ExternalIpAddress</c> are location data. Without a country
/// the response is worthless as a location, so it counts as a failure (null).
/// </summary>
internal static GeoLocationResult ParseDoGeo(JObject json)
{
var country = json.Value<string>("CountryCode");
if (string.IsNullOrEmpty(country))
return null;
var response = await httpResponse.Content.ReadAsStringAsync();
var json = JObject.Parse(response);
var latitude = json.Value<string>("latitude") ?? "";
var longitude = json.Value<string>("longitude") ?? "";
var loc = !string.IsNullOrEmpty(latitude) && !string.IsNullOrEmpty(longitude)
? $"{latitude},{longitude}"
: "";
var result = new GeoLocationResult
{
Country = json.Value<string>("country_iso"),
Region = json.Value<string>("region_name"),
City = json.Value<string>("city"),
Loc = loc,
Timezone = json.Value<string>("time_zone"),
Ip = json.Value<string>("ip"),
Source = "ifconfig.co"
};
logger?.Info($"GeoLocation: ifconfig.co returned {result.City}, {result.Region}, {result.Country}");
return (result, null);
}
}
catch (TaskCanceledException)
return new GeoLocationResult
{
var error = "Timeout (5s)";
logger?.Warning($"GeoLocation: ifconfig.co failed: {error}");
return (null, error);
}
catch (Exception ex)
{
var error = ex.Message;
logger?.Warning($"GeoLocation: ifconfig.co failed: {error}");
return (null, error);
}
Country = country,
Ip = json.Value<string>("ExternalIpAddress"),
Source = "do-geo"
};
}
}
}
@@ -420,7 +420,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
// Re-stamp AgentBootUtc so the current run's deadlines floor at "now" — the
// persisted boot anchor is from the prior run and using it would let replayed
// tail signals arm deadlines that are already past-due (premature fire).
seed = loadedState.ToBuilder().WithAgentBootUtc(agentBootUtc).Build();
// Re-stamp SessionId too: after a session rotation at registration
// (SESSION-OWNER-BINDING) the snapshot still names the refused session, and the
// timeline emitter takes each event's SessionId from this state.
var seedBuilder = loadedState.ToBuilder().WithAgentBootUtc(agentBootUtc);
seedBuilder.SessionId = sessionId;
seed = seedBuilder.Build();
signalsToReplay = CollectSignalLogTailAfter(signalLog, loadedState.LastAppliedSignalOrdinal);
branchTag = signalsToReplay.Count > 0 ? "b-tail-replay" : "b-snapshot-current";
}
@@ -61,6 +61,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
// detection — the exact scenario the power watcher exists to observe.
SharedConstants.EventTypes.PowerStateChange,
// Same for the network link: a dock or access point that flaps for hours (field:
// 288 lost/connected pairs in 11 h, each with its connectivity check) is not
// enrollment progress. Counted as activity it kept the periodic collectors running
// for the whole episode and hid the stall it was causing, because every flap reset
// the stall clock. Progress that follows a reconnect arrives as its own download,
// app or phase event.
SharedConstants.EventTypes.NetworkStateChange,
SharedConstants.EventTypes.NetworkConnectivityCheck,
// Same reasoning for the system timeline watcher: a clock step, a wake from standby,
// or a backfilled episode at agent start is environment observation and must not
// reset the idle/stall clocks.
@@ -81,6 +90,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
// says something about the agent, not about the device's enrollment progress.
SharedConstants.EventTypes.ImeTrackerDegraded,
SharedConstants.EventTypes.ImePatternHits,
// Bookkeeping of runs that were deliberately not reported as activity.
SharedConstants.EventTypes.ScriptRecurrenceSummary,
};
/// <summary>
@@ -18,7 +18,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Runtime
/// </para>
/// <list type="bullet">
/// <item><b>device_location</b> (or <c>agent_trace</c> on failure) — IP-based geo via
/// <see cref="GeoLocationService"/>. Skipped when <c>EnableGeoLocation=false</c>.</item>
/// <see cref="GeoLocationService"/>. Skipped when <c>EnableGeoLocation=false</c>. The
/// last-resort provider (DO geo) yields a country-only location without timezone.</item>
/// <item><b>timezone_auto_set</b> — only when <c>EnableTimezoneAutoSet=true</c> AND the
/// geo lookup returned an IANA timezone. Uses <see cref="TimezoneService"/> (tzutil).</item>
/// <item><b>ntp_time_check</b> — NTP offset from <c>NtpServer</c> (default time.windows.com).
@@ -225,7 +226,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Runtime
Source = "StartupEnvironmentProbes",
Phase = EnrollmentPhase.Unknown,
Timestamp = DateTime.UtcNow,
Message = $"Device location: {location.City}, {location.Region}, {location.Country} (via {location.Source})",
Message = $"Device location: {location.Describe()} (via {location.Source})",
Data = location.ToDictionary(),
ImmediateUpload = true,
};
@@ -266,8 +267,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Runtime
{ "primaryError", attempt?.PrimaryError ?? "unknown" },
{ "primaryRetryError", attempt?.PrimaryRetryError ?? "unknown" },
{ "fallbackError", attempt?.FallbackError ?? "unknown" },
{ "doGeoError", attempt?.DoGeoError ?? "unknown" },
{ "primaryProvider", "ipinfo.io" },
{ "fallbackProvider", "ifconfig.co" },
{ "lastResortProvider", "do-geo" },
},
};
@@ -1,6 +1,8 @@
using System;
using System.IO;
using AutopilotMonitor.Agent.V2.Core.Logging;
using AutopilotMonitor.Shared.Models;
using Newtonsoft.Json;
namespace AutopilotMonitor.Agent.V2.Core.Security
{
@@ -22,6 +24,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
private readonly string _sessionFilePath;
private readonly string _sessionCreatedFilePath;
private readonly string _whiteGloveMarkerPath;
private readonly string _registrationFailurePath;
private readonly object _lockObject = new object();
public SessionIdPersistence(string dataDirectory)
@@ -35,6 +38,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
_sessionFilePath = Path.Combine(dataDirectory, "session.id");
_sessionCreatedFilePath = Path.Combine(dataDirectory, "session.created");
_whiteGloveMarkerPath = Path.Combine(dataDirectory, "whiteglove.complete");
_registrationFailurePath = Path.Combine(dataDirectory, "registration-failure.json");
}
/// <summary>
@@ -164,6 +168,55 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
lock (_lockObject) TryDelete(_whiteGloveMarkerPath, logger);
}
/// <summary>
/// Folds one failed registration run into <c>registration-failure.json</c>: the run
/// counter grows, the first failure time is kept, everything else describes the latest
/// run. A run that never registers exits and leaves nothing else behind — the emergency
/// break reads this file so the backend learns why the session never appeared.
/// Best-effort; never throws.
/// </summary>
public void RecordRegistrationFailure(RegistrationFailureSummary latestRun, AgentLogger logger = null)
{
if (latestRun == null) return;
lock (_lockObject)
{
try
{
var previous = LoadRegistrationFailureInternal();
var merged = new RegistrationFailureSummary
{
FailedRuns = (previous?.FailedRuns ?? 0) + 1,
FirstFailedAtUtc = previous?.FirstFailedAtUtc ?? latestRun.LastFailedAtUtc,
LastFailedAtUtc = latestRun.LastFailedAtUtc,
Outcome = latestRun.Outcome,
LastError = latestRun.LastError,
NetworkLinkUpAtStart = latestRun.NetworkLinkUpAtStart,
NetworkLinkUpAtEnd = latestRun.NetworkLinkUpAtEnd,
AttemptWindowSeconds = latestRun.AttemptWindowSeconds,
ConfigFetchOutcome = latestRun.ConfigFetchOutcome,
};
File.WriteAllText(_registrationFailurePath, JsonConvert.SerializeObject(merged));
logger?.Info($"SessionIdPersistence: recorded failed registration run #{merged.FailedRuns}.");
}
catch (Exception ex)
{
logger?.Warning($"SessionIdPersistence: RecordRegistrationFailure failed: {ex.Message}");
}
}
}
/// <summary>The failed-registration record since the last success, or <c>null</c> (none, unreadable).</summary>
public RegistrationFailureSummary LoadRegistrationFailure()
{
lock (_lockObject) return LoadRegistrationFailureInternal();
}
/// <summary>Drops the failed-registration record — called once registration succeeds.</summary>
public void ClearRegistrationFailure(AgentLogger logger = null)
{
lock (_lockObject) TryDelete(_registrationFailurePath, logger);
}
/// <summary>Deletes the persisted SessionId. Next <see cref="GetOrCreate"/> starts a fresh session.</summary>
public void Delete(AgentLogger logger = null)
{
@@ -172,6 +225,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
TryDelete(_sessionFilePath, logger);
TryDelete(_sessionCreatedFilePath, logger);
TryDelete(_whiteGloveMarkerPath, logger);
TryDelete(_registrationFailurePath, logger);
}
}
@@ -191,11 +245,28 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
var fresh = Guid.NewGuid().ToString();
WriteAtomic(fresh, logger);
SaveSessionCreatedAtInternal(DateTime.UtcNow);
// Earlier failed runs belonged to the refused session id.
TryDelete(_registrationFailurePath, logger);
logger?.Info($"SessionIdPersistence: rotated SessionId to {fresh}.");
return fresh;
}
}
private RegistrationFailureSummary LoadRegistrationFailureInternal()
{
try
{
if (!File.Exists(_registrationFailurePath)) return null;
var record = JsonConvert.DeserializeObject<RegistrationFailureSummary>(File.ReadAllText(_registrationFailurePath));
return record != null && record.FailedRuns > 0 ? record : null;
}
catch
{
// Corrupt record: report nothing rather than a half-read account.
return null;
}
}
private static void TryDelete(string path, AgentLogger logger)
{
try { if (File.Exists(path)) File.Delete(path); }
@@ -34,13 +34,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
/// <see cref="AuthFailureTracker"/> (which fires the first-failure distress + may trip
/// the shutdown threshold) and return <see cref="SessionRegistrationOutcome.AuthFailed"/>
/// without retrying — the backend has definitively rejected the device cert.</item>
/// <item>Exception to the above — a 403 carrying error code
/// <item>Exception to the above — a 403 or 409 carrying error code
/// <c>session_owner_mismatch</c> (SESSION-OWNER-BINDING): the persisted SessionId names a
/// session bound to another device identity (typically an Intune re-enrollment without a
/// wipe, where <c>session.id</c> survived but the certificate identity changed). That is
/// not an auth failure: the session is rotated through <c>rotateSession</c> and
/// registration retried exactly once. The tracker is NOT fed — five of these would
/// otherwise soft-shutdown a perfectly authorized agent.</item>
/// session that is not this device's — bound to another device identity (403, typically an
/// Intune re-enrollment without a wipe, where <c>session.id</c> survived but the certificate
/// identity changed) or claimed by another tenant (409). That is not an auth failure: the
/// session is rotated through <c>rotateSession</c> and registration retried exactly once.
/// The tracker is NOT fed — five of these would otherwise soft-shutdown a perfectly
/// authorized agent.</item>
/// <item>Any other coded 409 (<see cref="BackendRefusalException"/>) → <see cref="SessionRegistrationOutcome.Failed"/>
/// without retrying — a refusal with a code does not clear by waiting.</item>
/// <item>Any other exception on the last attempt → <see cref="EmergencyReporter.TrySendAsync"/>
/// with <c>AgentErrorType.RegisterSessionFailed</c> so operators see the final cause.</item>
/// </list>
@@ -113,14 +116,14 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
lastError = response?.Message ?? "(null response)";
logger.Warning($"Session registration failed: {lastError}");
}
catch (BackendAuthException ex) when (
ex.ErrorCode == Constants.AgentErrorCodes.SessionOwnerMismatch
catch (Exception ex) when (
IsSessionOwnerMismatch(ex)
&& rotateSession != null
&& rotatedFromSessionId == null)
{
// SESSION-OWNER-BINDING: the id on disk belongs to a session this device
// identity does not own. Become a new session and register once more —
// immediately, no backoff, no auth-failure bookkeeping.
// SESSION-OWNER-BINDING: the id on disk names a session this device does not
// own. Become a new session and register once more — immediately, no backoff,
// no auth-failure bookkeeping.
rotatedFromSessionId = registration.SessionId;
string newSessionId;
try
@@ -130,15 +133,25 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
catch (Exception rotateEx)
{
logger.Error($"Session owner mismatch reported by backend but session rotation failed: {rotateEx.Message}", rotateEx);
authFailureTracker?.RecordFailure(ex.StatusCode, "agent/register-session", ex.EndpointUnavailable);
return SessionRegistrationResult.AuthFailed(ex.StatusCode, ex.Message);
if (ex is BackendAuthException authEx)
{
authFailureTracker?.RecordFailure(authEx.StatusCode, "agent/register-session", authEx.EndpointUnavailable);
return SessionRegistrationResult.AuthFailed(authEx.StatusCode, authEx.Message);
}
return SessionRegistrationResult.Failed(ex.Message);
}
logger.Warning(
$"Backend refused registration with {Constants.AgentErrorCodes.SessionOwnerMismatch}: session {rotatedFromSessionId} " +
$"is bound to another device identity (re-enrollment without wipe?). Rotated to {newSessionId}; re-registering.");
$"is not this device's (bound to another device identity after a re-enrollment without wipe, or claimed by another tenant). " +
$"Rotated to {newSessionId}; re-registering.");
registration = BuildRegistration(agentConfig, agentVersion, deviceHardware);
continue;
}
catch (BackendRefusalException ex)
{
logger.Error($"Session registration refused ({ex.StatusCode}, {ex.ErrorCode}): {ex.Message}");
return SessionRegistrationResult.Failed(ex.Message);
}
catch (BackendAuthException ex)
{
logger.Error($"Session registration authentication failed ({ex.StatusCode}): {ex.Message}");
@@ -195,6 +208,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Security
return SessionRegistrationResult.Failed(lastError ?? "max retries exceeded");
}
private static bool IsSessionOwnerMismatch(Exception ex)
{
var code = (ex as BackendAuthException)?.ErrorCode ?? (ex as BackendRefusalException)?.ErrorCode;
return code == Constants.AgentErrorCodes.SessionOwnerMismatch;
}
/// <summary>V1 parity exponential backoff: 2^attempt seconds.</summary>
private static Task DefaultBackoffDelay(int attempt)
=> Task.Delay(((int)Math.Pow(2, attempt)) * 1000);
@@ -24,7 +24,7 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
/// <list type="bullet">
/// <item><c>HelloCompleted</c> → <see cref="DecisionSignalKind.HelloResolved"/></item>
/// <item><c>FinalizingSetupPhaseTriggered</c> → <see cref="DecisionSignalKind.EspPhaseChanged"/> (phase=FinalizingSetup)</item>
/// <item><c>WhiteGloveCompleted</c> → <see cref="DecisionSignalKind.WhiteGloveShellCoreSuccess"/></item>
/// <item><c>WhiteGloveCompleted</c> → <see cref="DecisionSignalKind.WhiteGloveShellCoreSuccess"/> (payload: registry AccountSetup progress at that moment)</item>
/// <item><c>EspFailureDetected</c> → <see cref="DecisionSignalKind.EspTerminalFailure"/> (merged aus ShellCore + Provisioning)</item>
/// <item><c>DeviceSetupProvisioningComplete</c> → <see cref="DecisionSignalKind.DeviceSetupProvisioningComplete"/></item>
/// <item><c>AccountSetupProvisioningComplete</c> → <see cref="DecisionSignalKind.AccountSetupProvisioningComplete"/> (session 330f73f3 fix — strong AccountSetup-done gate)</item>
@@ -46,6 +46,7 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
private readonly EspAndHelloTracker _coordinator;
private readonly ISignalIngressSink _ingress;
private readonly IClock _clock;
private readonly Func<bool?> _accountSetupProgressProbe;
private bool _helloPosted;
private bool _helloWizardStartedPosted;
@@ -60,11 +61,14 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
public EspAndHelloTrackerAdapter(
EspAndHelloTracker coordinator,
ISignalIngressSink ingress,
IClock clock)
IClock clock,
Func<bool?>? accountSetupProgressProbe = null)
{
_coordinator = coordinator ?? throw new ArgumentNullException(nameof(coordinator));
_ingress = ingress ?? throw new ArgumentNullException(nameof(ingress));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
// Test seam; production reads the provisioning tracker's registry-derived flag.
_accountSetupProgressProbe = accountSetupProgressProbe ?? (() => _coordinator.AccountSetupProgressIfRead);
_coordinator.HelloCompleted += OnHelloCompleted;
_coordinator.FinalizingSetupPhaseTriggered += OnFinalizing;
@@ -216,13 +220,29 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
if (_whiteGloveSuccessPosted) return;
_whiteGloveSuccessPosted = true;
// Registry AccountSetup progress at the moment of the success page. The sealing
// classifier lifts its AccountSetup excluder only on an explicit "false" — IME logs
// AccountSetup from the device session once the device apps are done, which is no
// user activity. Sampled here so replay reads it from the SignalLog (L.2/L.5). An
// unread registry sends no key: unknown must keep the excluder, never lift it.
var progress = _accountSetupProgressProbe();
var progressText = progress.HasValue ? (progress.Value ? "true" : "false") : null;
var now = ResolveOccurredAt(out var derivedFromClock);
var derivationInputs = new Dictionary<string, string>(StringComparer.Ordinal)
{
["subSource"] = "ShellCoreTracker",
[SignalPayloadKeys.AccountSetupProgress] = progressText ?? "unread",
};
TagDerivedTimestamp(derivationInputs, derivedFromClock);
var payload = progressText == null
? null
: new Dictionary<string, string>(StringComparer.Ordinal)
{
[SignalPayloadKeys.AccountSetupProgress] = progressText,
};
_ingress.Post(
kind: DecisionSignalKind.WhiteGloveShellCoreSuccess,
occurredAtUtc: now,
@@ -231,7 +251,8 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
kind: EvidenceKind.Derived,
identifier: DetectorId,
summary: "WhiteGlove sealing success (coordinator-forwarded)",
derivationInputs: derivationInputs));
derivationInputs: derivationInputs),
payload: payload);
}
private void EmitEspFailure(EspFailureDetectedEventArgs args)
@@ -94,6 +94,8 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
private readonly Action<AppPackageState, DateTime?> _ourOnDoTelemetryReceived;
private readonly Action<ScriptExecutionState> _ourOnScriptCompleted;
private readonly Action<ScriptStartedInfo> _ourOnScriptStarted;
private readonly Action<ScriptRecurrenceSummary>? _prevOnScriptRecurrenceSummary;
private readonly Action<ScriptRecurrenceSummary> _ourOnScriptRecurrenceSummary;
private readonly Action<string, string> _ourOnImeTokenFailure;
// Dedup state for DecisionSignals.
@@ -195,6 +197,7 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
_prevOnDoTelemetryReceived = _tracker.OnDoTelemetryReceived;
_prevOnScriptCompleted = _tracker.OnScriptCompleted;
_prevOnScriptStarted = _tracker.OnScriptStarted;
_prevOnScriptRecurrenceSummary = _tracker.OnScriptRecurrenceSummary;
_prevOnImeTokenFailure = _tracker.OnImeTokenFailure;
_prevOnTrackerDegraded = _tracker.OnTrackerDegraded;
@@ -209,6 +212,7 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
_ourOnDoTelemetryReceived = OnDoTelemetryReceived;
_ourOnScriptCompleted = OnScriptCompleted;
_ourOnScriptStarted = OnScriptStarted;
_ourOnScriptRecurrenceSummary = OnScriptRecurrenceSummary;
_ourOnImeTokenFailure = OnImeTokenFailure;
_tracker.OnEspPhaseChanged = _ourOnEspPhaseChanged;
@@ -219,6 +223,7 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
_tracker.OnDoTelemetryReceived = _ourOnDoTelemetryReceived;
_tracker.OnScriptCompleted = _ourOnScriptCompleted;
_tracker.OnScriptStarted = _ourOnScriptStarted;
_tracker.OnScriptRecurrenceSummary = _ourOnScriptRecurrenceSummary;
_tracker.OnImeTokenFailure = _ourOnImeTokenFailure;
_tracker.OnTrackerDegraded = _ourOnTrackerDegraded;
}
@@ -245,6 +250,8 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
_tracker.OnScriptCompleted = _prevOnScriptCompleted;
if (ReferenceEquals(_tracker.OnScriptStarted, _ourOnScriptStarted))
_tracker.OnScriptStarted = _prevOnScriptStarted;
if (ReferenceEquals(_tracker.OnScriptRecurrenceSummary, _ourOnScriptRecurrenceSummary))
_tracker.OnScriptRecurrenceSummary = _prevOnScriptRecurrenceSummary;
if (ReferenceEquals(_tracker.OnImeTokenFailure, _ourOnImeTokenFailure))
_tracker.OnImeTokenFailure = _prevOnImeTokenFailure;
}
@@ -297,6 +304,12 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
EmitScriptStarted(info);
}
private void OnScriptRecurrenceSummary(ScriptRecurrenceSummary summary)
{
_prevOnScriptRecurrenceSummary?.Invoke(summary);
EmitScriptRecurrenceSummary(summary);
}
private void OnImeTokenFailure(string errorCode, string message)
{
_prevOnImeTokenFailure?.Invoke(errorCode, message);
@@ -448,31 +461,35 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
/// no second clock frame, so there is nothing to record.
/// </para>
/// </summary>
private void TagDerivedTimestamp(IDictionary<string, string> data, bool derivedFromClock, DateTime? rawSourceTs)
private void TagDerivedTimestamp(IDictionary<string, string> data, bool derivedFromClock, DateTime? rawSourceTs, CmTraceLineProvenance? lineProvenance = null)
{
var culture = System.Globalization.CultureInfo.InvariantCulture;
var sourceLocal = _tracker.LastMatchedSourceLocalTimestamp;
// The line the event is bound to. Callers that emit later than the match (a held
// platform-script result) pass the snapshot taken at their line; everyone else is
// emitting while its line is still the last matched one.
var line = lineProvenance ?? _tracker.CaptureLastMatchedProvenance();
var sourceLocal = line.SourceLocalTs;
if (sourceLocal.HasValue)
{
// No zone suffix: the value genuinely carries none, and formatting one in would
// re-introduce the very assumption this whole change removes.
data["sourceLocalTs"] = sourceLocal.Value.ToString("yyyy-MM-ddTHH:mm:ss.fffffff", culture);
data["sourceOffsetOrigin"] = OriginTag(_tracker.LastMatchedSourceOffsetOrigin);
data["sourceOffsetOrigin"] = OriginTag(line.Origin);
var offsetMinutes = _tracker.LastMatchedSourceOffsetMinutes;
var offsetMinutes = line.OffsetMinutes;
if (offsetMinutes.HasValue)
data["sourceOffsetMinutes"] = offsetMinutes.Value.ToString(culture);
// Which era anchor the offset came from — forensics for the era-anchored origin.
var anchorKind = _tracker.LastMatchedEraAnchorKind;
var anchorKind = line.EraAnchorKind;
if (!string.IsNullOrEmpty(anchorKind))
data["sourceOffsetAnchor"] = anchorKind;
// Observational only — what the calibrator measured, which since the 2026-08-20
// revert is deliberately NOT what was applied. Kept separate so the two can never
// be read as the same thing.
var measured = _tracker.LastMatchedMeasuredWriterOffsetMinutes;
var measured = line.MeasuredWriterOffsetMinutes;
if (measured.HasValue)
data["measuredWriterOffsetMinutes"] = measured.Value.ToString(culture);
}
@@ -1280,7 +1297,11 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
if (SuppressIfHistoricReplay(derivedFromClock, rawSourceTs, eventType, script.PolicyId))
return;
TagDerivedTimestamp(data, derivedFromClock, rawSourceTs);
// The line that delivered the result is bound on the state (D-247), so a completion
// emitted passes later still describes ITS line. Null (states from before the field,
// synthetic tests) falls back to the tracker's last matched line as before.
var endProvenance = isFallback ? script.ExitProvenance : script.ResultProvenance;
TagDerivedTimestamp(data, derivedFromClock, rawSourceTs, endProvenance);
// Per-script run duration (start line → this completion). Surfaced on every
// script completion so the UI can flag slow / inefficient scripts, not just timed-out
@@ -1288,11 +1309,13 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
// against clock skew between the (possibly clock-derived) completion stamp and start.
//
// When the completion timestamp was clock-derived because the source line's timestamp
// was rejected (future-skew CMTrace clock jump — the stale case never reaches here),
// `now` lives on the clock's timeline while StartedAtUtc was captured RAW from the
// source log. Mixing the two produced absurd durations (session eaf3d8c4: 170 h), so
// the duration uses the raw source pair — both ends on the same timeline, the
// difference is the true runtime. The event stamp stays `now` (timeline position).
// was rejected (future-skew — the stale case never reaches here), `now` lives on the
// clock's timeline while StartedAtUtc was captured RAW from the source log. Mixing the
// two produced absurd durations (session eaf3d8c4: 170 h), so the span is taken from
// the raw source pair. That pair is a run time only when both lines were resolved on
// the same zone belief — JudgeDurationPair decides, from the provenance bound to each
// line, whether the span is verified, unverified, or an offset error to omit (session
// 4377911b: a 10 s script read as 3610 s). The event stamp stays `now`.
//
// L19 (delta review 2026-07-02): the same field name carries two different semantics —
// start→own-end-signal (≈ script runtime) vs HS-SCRIPT-START→HS-NEW-RESULT (the whole
@@ -1304,15 +1327,26 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
var completionForDuration = derivedFromClock && rawSourceTs.HasValue
? NormalizeUtc(rawSourceTs.Value)
: now;
TimeSpan? measurableDuration = null;
if (script.StartedAtUtc.HasValue)
{
var durationSeconds = (completionForDuration - script.StartedAtUtc.Value).TotalSeconds;
var span = completionForDuration - script.StartedAtUtc.Value;
var verdict = JudgeDurationPair(script.StartedAtProvenance, endProvenance,
endStampRejected: derivedFromClock && rawSourceTs.HasValue, span, out var suppressedReason);
if (verdict != DurationPairVerdict.Unknown)
data["durationProvenance"] = verdict == DurationPairVerdict.Verified ? "verified" : "unverified";
if (verdict == DurationPairVerdict.Suppressed)
{
data["durationSuppressedReason"] = suppressedReason!;
}
// Plausibility backstop: IME's script execution timeout is ~30 min; anything above
// 24 h is a cross-run artifact (e.g. a stale pending start slot from a previous
// enrollment paired with a fresh completion) — omit rather than lie.
if (durationSeconds >= 0 && durationSeconds <= StaleSourceThreshold.TotalSeconds)
else if (span >= TimeSpan.Zero && span <= StaleSourceThreshold)
{
data["durationSeconds"] = durationSeconds.ToString("F2", culture);
measurableDuration = span;
data["durationSeconds"] = span.TotalSeconds.ToString("F2", culture);
data["durationBasis"] = script.DurationBasis
?? (IsRemediation(script.ScriptType)
? "cycle_including_reporting_latency"
@@ -1320,6 +1354,18 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
}
}
// The start line's provenance, next to the end line's (sourceOffset*), so the pair can
// be judged downstream as well.
var startProvenance = script.StartedAtProvenance;
if (startProvenance != null && startProvenance.SourceLocalTs.HasValue)
{
data["startSourceOffsetOrigin"] = OriginTag(startProvenance.Origin);
if (startProvenance.OffsetMinutes.HasValue)
data["startSourceOffsetMinutes"] = startProvenance.OffsetMinutes.Value.ToString(culture);
if (!string.IsNullOrEmpty(startProvenance.EraAnchorKind))
data["startSourceOffsetAnchor"] = startProvenance.EraAnchorKind;
}
var label = IsRemediation(script.ScriptType) ? "Remediation script" : "Platform script";
var shortId = script.PolicyId.Length >= 8 ? script.PolicyId.Substring(0, 8) : script.PolicyId;
string messageCore;
@@ -1362,7 +1408,51 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
$"ImeAdapter: script completed policyId={shortId} type={script.ScriptType ?? "?"} result={script.Result ?? "?"} exit={(script.ExitCode.HasValue ? script.ExitCode.Value.ToString() : "n/a")}");
MaybeEmitBootstrapDetected(script, now);
MaybeEmitScriptTimeoutSuspected(script, now, completionForDuration);
MaybeEmitScriptTimeoutSuspected(script, now, measurableDuration);
}
internal enum DurationPairVerdict { Unknown, Verified, Unverified, Suppressed }
/// <summary>
/// Whether the span between a start line and an end line measures elapsed time.
/// <para>
/// Each CMTrace line is resolved on its own zone belief: declared or measured (bias,
/// line-anchored, or the clock itself) — or ASSUMED (the reader's zone, a writer era's
/// anchor). Two measured ends sit on the true UTC axis; two assumed ends resolved with the
/// same offset from the same file share their error, which cancels (D-191). Any other pair
/// is unverified, and its span is omitted when the end stamp was rejected as ahead of the
/// clock — its assumption is proven wrong and the raw pair inherits the error (session
/// 4377911b: a 10 s script read as 3610 s) — or when the span sits on the 15-minute offset
/// grid, the signature of a wrong assumption on either end (session cbaed57b: 7200 s). A
/// missing snapshot (state files from before the field, synthetic tests) leaves the rule
/// off and the pair treated as before.
/// </para>
/// </summary>
internal static DurationPairVerdict JudgeDurationPair(
CmTraceLineProvenance? start, CmTraceLineProvenance? end, bool endStampRejected, TimeSpan span, out string? suppressedReason)
{
suppressedReason = null;
if (start == null || end == null) return DurationPairVerdict.Unknown;
var startAssumed = start.IsAssumed();
var endAssumed = end.IsAssumed();
var sameTimeline = (!startAssumed && !endAssumed)
|| (startAssumed && endAssumed
&& start.OffsetMinutes == end.OffsetMinutes
&& string.Equals(start.SourceFileName, end.SourceFileName, StringComparison.OrdinalIgnoreCase));
if (sameTimeline) return DurationPairVerdict.Verified;
if (endStampRejected)
{
suppressedReason = "rejected-endpoint";
return DurationPairVerdict.Suppressed;
}
if (CmTraceOffsetCalibrator.IsOnOffsetGrid(span, out _))
{
suppressedReason = "offset-grid";
return DurationPairVerdict.Suppressed;
}
return DurationPairVerdict.Unverified;
}
/// <summary>
@@ -1374,19 +1464,19 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
/// late start / pre-failed ESP. Advisory only: no state mutation, the underlying
/// <c>script_failed</c> is still emitted separately. Health (remediation) scripts are
/// excluded — they re-run on their own cadence and have a different timeout regime.
/// <paramref name="durationEndUtc"/> is the timeline-consistent completion for duration
/// math (raw source ts on rejected-timestamp emissions); <paramref name="occurredAtUtc"/>
/// stamps the emitted event.
/// <paramref name="measurableDuration"/> is the run duration the completion event carries —
/// null when it was omitted (no start line, implausible span, or a start/end pair resolved
/// on different zone assumptions: the fleet's daily 17 h "timeouts" of 2–9 s scripts were
/// offset errors); <paramref name="occurredAtUtc"/> stamps the emitted event.
/// </summary>
private void MaybeEmitScriptTimeoutSuspected(ScriptExecutionState script, DateTime occurredAtUtc, DateTime durationEndUtc)
private void MaybeEmitScriptTimeoutSuspected(ScriptExecutionState script, DateTime occurredAtUtc, TimeSpan? measurableDuration)
{
if (IsRemediation(script.ScriptType)) return; // platform scripts only
if (!script.StartedAtUtc.HasValue) return; // no start ⇒ no duration
if (!measurableDuration.HasValue) return; // no measurable duration ⇒ no verdict
if (!string.Equals(script.Result, "Failed", StringComparison.OrdinalIgnoreCase)) return;
var duration = durationEndUtc - script.StartedAtUtc.Value;
var duration = measurableDuration.Value;
if (duration < ScriptTimeoutSuspectedThreshold) return;
if (duration > StaleSourceThreshold) return; // implausible — cross-run artifact, not a hung script
if (!_tracker.TryClaimScriptTimeoutSuspected(script.PolicyId)) return; // restart-safe dedup per policyId (persisted tracker state)
@@ -1464,10 +1554,13 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
};
if (!string.IsNullOrEmpty(info.ScriptType)) data["scriptType"] = info.ScriptType!;
if (!string.IsNullOrEmpty(info.PolicyType)) data["policyType"] = info.PolicyType!;
var patternId = _tracker.LastMatchedPatternId;
// A held start of a recurring health script arrives with its own line's stamp and
// pattern — by now the tracker's "last matched" line is the result line.
var wasHeld = info.SourceTimestampUtc.HasValue;
var patternId = wasHeld ? info.PatternId : _tracker.LastMatchedPatternId;
if (!string.IsNullOrEmpty(patternId)) data["patternId"] = patternId!;
var now = ResolveOccurredAt(out var derivedFromClock, out var rawSourceTs);
var now = ResolveOccurredAt(info.SourceTimestampUtc, out var derivedFromClock, out var rawSourceTs);
// Historic replay — suppressing here also kills the immediateUpload flood the
// replayed batch caused (session eaf3d8c4: 3× ingress_backpressure).
@@ -1485,13 +1578,42 @@ namespace AutopilotMonitor.Agent.V2.Core.SignalAdapters
message: $"{label} {shortId}: started",
// Live UI indicator — flush immediately so the running card appears within seconds,
// not at the next batch boundary (which would defeat the purpose of a live signal).
immediateUpload: true,
// A held start is no longer live and rides the normal batch.
immediateUpload: !wasHeld,
data: data,
occurredAtUtc: now);
_logger?.Debug($"ImeAdapter: script started policyId={shortId} type={info.ScriptType ?? "?"} policyType={info.PolicyType ?? "?"}");
}
private void EmitScriptRecurrenceSummary(ScriptRecurrenceSummary summary)
{
if (summary == null || string.IsNullOrEmpty(summary.PolicyId)) return;
var culture = System.Globalization.CultureInfo.InvariantCulture;
var data = new Dictionary<string, string>(StringComparer.Ordinal)
{
["policyId"] = summary.PolicyId,
["scriptType"] = "remediation",
["runsObserved"] = summary.RunsObserved.ToString(culture),
["runsCollapsed"] = summary.RunsCollapsed.ToString(culture),
["runsWithoutResult"] = summary.RunsWithoutResult.ToString(culture),
["collapsedResults"] = summary.CollapsedResults.ToString(culture),
};
if (summary.FirstCollapsedAtUtc.HasValue)
data["firstCollapsedAt"] = NormalizeUtc(summary.FirstCollapsedAtUtc.Value).ToString("o", culture);
if (summary.LastCollapsedAtUtc.HasValue)
data["lastCollapsedAt"] = NormalizeUtc(summary.LastCollapsedAtUtc.Value).ToString("o", culture);
var shortId = summary.PolicyId.Length >= 8 ? summary.PolicyId.Substring(0, 8) : summary.PolicyId;
_post.Emit(
eventType: SharedEventTypes.ScriptRecurrenceSummary,
source: SourceLabel,
message: $"Health script {shortId}: {summary.RunsCollapsed} further run(s) repeated the last reported result",
severity: EventSeverity.Info,
data: data);
}
private static bool IsRemediation(string? scriptType) =>
string.Equals(scriptType, "remediation", StringComparison.OrdinalIgnoreCase);
@@ -169,6 +169,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
_logger.Info(
$"EnrollmentTerminationHandler: handling Terminated (reason={args.Reason}, outcome={args.Outcome}, stage={args.StageName}).");
// The seal is already persisted in the decision snapshot. The marker goes down
// before anything else: the technician's reseal can kill this process at any
// later step, and a missing marker makes the next boot run the 48-hour break
// against the Part-1 session age instead of resuming Part 2.
if (isWhiteGlovePart1)
{
TrySaveWhiteGloveComplete();
}
var state = TryGetCurrentState();
// M4.6.δ — shutdown analyzers run BEFORE the dialog / diagnostics upload so
@@ -254,7 +263,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
// WhiteGlove Part-1 exit: keep the session alive, but announce the handoff so
// the timeline clearly marks the transition. The `whiteglove.complete` marker
// lets the next agent boot classify itself as a Part-2 resume.
// (written at the top of this handler) lets the next agent boot classify itself
// as a Part-2 resume.
if (isWhiteGlovePart1)
{
// Stop peripheral collectors BEFORE the Part-1-complete marker so their
@@ -298,7 +308,6 @@ namespace AutopilotMonitor.Agent.V2.Core.Termination
DelayLateEventGrace();
DrainSpool();
TrySaveWhiteGloveComplete();
// Option 2 (WG Part 1 graceful-exit hardening, 2026-04-30): write the
// clean-exit marker BEFORE _signalShutdown returns control to the main
// thread. The AppDomain.ProcessExit handler still writes it as a second
@@ -308,7 +308,7 @@ namespace AutopilotMonitor.Agent.V2
Func<CleanupService> cleanupServiceFactory,
AgentLogger logger,
bool consoleMode,
Action onBreakFired = null)
Action<double> onBreakFired = null)
{
try
{
@@ -347,7 +347,7 @@ namespace AutopilotMonitor.Agent.V2
// (tasks/enrollment-status-reclassification.md). Fired BEFORE cleanup, while the
// session state and network are still intact. Never throws — a send failure (e.g. no
// network) must not block the cleanup/exit that is the whole point of this guard.
try { onBreakFired?.Invoke(); }
try { onBreakFired?.Invoke(sessionAgeHours); }
catch (Exception cbEx) { logger.Debug($"Emergency-break notify callback failed: {cbEx.Message}"); }
// Write enrollment-complete.marker so the next start exits cleanly even if
@@ -273,7 +273,9 @@ namespace AutopilotMonitor.Agent.V2
var registration = Runtime.BackendSessionRegistration.Register(
bootstrap.AgentConfig, auth, telemetry.MtlsHttpClient, GetAgentVersion(), consoleMode, logger,
rotateSession: () => Runtime.BackendSessionRegistration.RotateSession(
bootstrap.AgentConfig, bootstrap.SessionPersistence, auth, transportDir, logger));
bootstrap.AgentConfig, bootstrap.SessionPersistence, auth, transportDir, logger),
sessionPersistence: bootstrap.SessionPersistence,
configFetchOutcome: runtimeConfig.RemoteConfigService.LastFetchOutcome.ToString());
if (registration.ShouldExit)
{
return registration.ExitCode;
@@ -87,7 +87,11 @@ namespace AutopilotMonitor.Agent.V2.Runtime
cleanupServiceFactory, logger, consoleMode,
// Best-effort: surface the otherwise-silent 48h break to the backend before cleanup
// (tasks/enrollment-status-reclassification.md). Never blocks the exit.
onBreakFired: () => EmergencyBreakReporter.TrySend(agentConfig, Program.GetAgentVersion(), logger)))
// The failed-registration record is read here, before the break deletes the
// session files.
onBreakFired: sessionAgeHours => EmergencyBreakReporter.TrySend(
agentConfig, Program.GetAgentVersion(), sessionAgeHours,
sessionPersistence.LoadRegistrationFailure(), logger)))
{
logger.Info("Emergency break fired — agent exiting.");
return BootstrapResult.Exit(0);
@@ -1,6 +1,7 @@
using System;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using AutopilotMonitor.Agent.V2.Core.Configuration;
using AutopilotMonitor.Agent.V2.Core.Logging;
@@ -17,7 +18,8 @@ namespace AutopilotMonitor.Agent.V2.Runtime
/// <c>IncrementSessionEventCountAsync</c> / <c>UpdateSessionStatusAsync</c> silently
/// no-op and session status / phase / admin-overrides / validator reconcile all break.
/// On registration failure we follow V1's rule: collectors MUST NOT start and the
/// agent exits cleanly so the next Scheduled-Task tick can retry.
/// agent exits cleanly; the Scheduled Task has only a boot trigger, so the next attempt is
/// the next boot. The failed run is recorded for the emergency break report.
/// </summary>
internal static class BackendSessionRegistration
{
@@ -28,12 +30,19 @@ namespace AutopilotMonitor.Agent.V2.Runtime
string agentVersion,
bool consoleMode,
AgentLogger logger,
Func<string> rotateSession = null)
Func<string> rotateSession = null,
SessionIdPersistence sessionPersistence = null,
string configFetchOutcome = null)
{
if (agentConfig == null) throw new ArgumentNullException(nameof(agentConfig));
if (auth == null) throw new ArgumentNullException(nameof(auth));
if (logger == null) throw new ArgumentNullException(nameof(logger));
// Wall clock on purpose: a window far above the retry schedule is the evidence that
// the device slept or was suspended while this run tried to register.
var startedUtc = DateTime.UtcNow;
var linkUpAtStart = TryIsNetworkLinkUp();
var registrationResult = SessionRegistrationHelper.RegisterWithRetryAsync(
apiClient: auth.BackendApiClient,
agentConfig: agentConfig,
@@ -48,6 +57,10 @@ namespace AutopilotMonitor.Agent.V2.Runtime
rotateSession: rotateSession)
.GetAwaiter().GetResult();
RecordRegistrationRun(
sessionPersistence, registrationResult, startedUtc, DateTime.UtcNow,
linkUpAtStart, TryIsNetworkLinkUp(), configFetchOutcome, logger);
if (registrationResult.Outcome != SessionRegistrationOutcome.Succeeded)
{
logger.Error(
@@ -65,13 +78,71 @@ namespace AutopilotMonitor.Agent.V2.Runtime
return SessionRegistrationOutcomeResult.Continue(registrationResult);
}
/// <summary>Longest <see cref="RegistrationFailureSummary.LastError"/> kept on disk and on the wire.</summary>
internal const int MaxRecordedErrorLength = 256;
/// <summary>
/// Keeps <c>registration-failure.json</c> in step with this run: a failed run is folded
/// into the record (the emergency break later reports it — for a session that never
/// registered, the only account of why), a successful one clears it. Never throws.
/// </summary>
internal static void RecordRegistrationRun(
SessionIdPersistence sessionPersistence,
SessionRegistrationResult registrationResult,
DateTime startedUtc,
DateTime endedUtc,
bool? linkUpAtStart,
bool? linkUpAtEnd,
string configFetchOutcome,
AgentLogger logger)
{
if (sessionPersistence == null || registrationResult == null) return;
try
{
if (registrationResult.Outcome == SessionRegistrationOutcome.Succeeded)
{
sessionPersistence.ClearRegistrationFailure(logger);
return;
}
var error = registrationResult.ErrorMessage;
if (error != null && error.Length > MaxRecordedErrorLength)
error = error.Substring(0, MaxRecordedErrorLength);
sessionPersistence.RecordRegistrationFailure(new RegistrationFailureSummary
{
FailedRuns = 1,
FirstFailedAtUtc = endedUtc,
LastFailedAtUtc = endedUtc,
Outcome = registrationResult.Outcome.ToString(),
LastError = error,
NetworkLinkUpAtStart = linkUpAtStart,
NetworkLinkUpAtEnd = linkUpAtEnd,
AttemptWindowSeconds = Math.Round(Math.Max(0, (endedUtc - startedUtc).TotalSeconds), 1),
ConfigFetchOutcome = configFetchOutcome,
}, logger);
}
catch (Exception ex)
{
logger?.Warning($"Registration run record failed (best-effort): {ex.Message}");
}
}
private static bool? TryIsNetworkLinkUp()
{
try { return NetworkInterface.GetIsNetworkAvailable(); }
catch { return null; }
}
/// <summary>
/// SESSION-OWNER-BINDING: the one place that turns "backend says this session id is not
/// ours" into a new session. Rotates the persisted id, points the runtime config at it,
/// drops the transport spool (its lines carry the refused session's partition key and
/// would otherwise be uploaded against it after the rotation) and re-targets the
/// emergency reporter, which snapshotted the id before registration. Everything else
/// reads <c>agentConfig.SessionId</c> live after Phase 6.
/// emergency reporter, which snapshotted the id before registration. Everything else that
/// holds a session id (orchestrator, emitters, spool) is built in Phase 7 from the rotated
/// <c>agentConfig.SessionId</c> — keep it that way: a component built before Phase 6 needs
/// its own re-target here.
/// </summary>
internal static string RotateSession(
AgentConfiguration agentConfig,
@@ -36,15 +36,20 @@ namespace AutopilotMonitor.Agent.V2.Runtime
// Upper bound for the blocking wait: NIC wait + 3×15s attempts + 2×5s delays + slack.
private static readonly TimeSpan OverallBudget = TimeSpan.FromSeconds(75);
public static void TrySend(AgentConfiguration agentConfig, string agentVersion, AgentLogger logger)
public static void TrySend(
AgentConfiguration agentConfig,
string agentVersion,
double sessionAgeHours,
RegistrationFailureSummary priorRegistrationFailure,
AgentLogger logger)
{
try
{
WaitForNetwork(logger);
var auth = BackendClientFactory.BuildAuthClients(agentConfig, agentVersion, logger);
var message =
$"Agent absolute session-age emergency break fired (cap {agentConfig.AbsoluteMaxSessionHours}h) — cleaning up and exiting.";
var roundedAgeHours = Math.Round(sessionAgeHours, 1);
var message = BuildMessage(roundedAgeHours, agentConfig.AbsoluteMaxSessionHours, priorRegistrationFailure);
// The process is about to exit, so block on the otherwise fire-and-forget send
// rather than let it be abandoned mid-flight. TrySendAsync swallows its own HTTP
@@ -56,7 +61,9 @@ namespace AutopilotMonitor.Agent.V2.Runtime
message,
attempts: SendAttempts,
perAttemptTimeout: PerAttemptTimeout,
retryDelay: RetryDelay)
retryDelay: RetryDelay,
sessionAgeHours: roundedAgeHours,
priorRegistrationFailure: priorRegistrationFailure)
.Wait(OverallBudget);
}
catch (Exception ex)
@@ -65,6 +72,25 @@ namespace AutopilotMonitor.Agent.V2.Runtime
}
}
/// <summary>
/// Invariant culture: the text lands in the backend's ops feed and timeline, and a device
/// locale would otherwise print "478,2h". The registration clause names what the ops feed
/// cannot otherwise show for a session that never registered.
/// </summary>
internal static string BuildMessage(double roundedAgeHours, int capHours, RegistrationFailureSummary priorRegistrationFailure)
{
var message = FormattableString.Invariant(
$"Agent absolute session-age emergency break fired at session age {roundedAgeHours:F1}h (cap {capHours}h) — cleaning up and exiting.");
if (priorRegistrationFailure != null && priorRegistrationFailure.FailedRuns > 0)
{
message += FormattableString.Invariant(
$" {priorRegistrationFailure.FailedRuns} earlier start(s) failed to register (last: {priorRegistrationFailure.Outcome}, network link at end: {FormatLink(priorRegistrationFailure.NetworkLinkUpAtEnd)}).");
}
return message;
}
private static string FormatLink(bool? up) => up == null ? "unknown" : (up.Value ? "up" : "down");
/// <summary>
/// Boot-time NIC grace: the break fires during bootstrap, often seconds after boot while
/// Wi-Fi is still associating. Polls the cheap link-level signal — it cannot prove backend
@@ -522,7 +522,8 @@ namespace AutopilotMonitor.DecisionCore.Tests
.WithSkipUserEsp(value: true, sourceSignalOrdinal: 4)
.WithEspSyncFailureTimeoutMinutes(value: 90, sourceSignalOrdinal: 5)
.WithRegistrySelfDeployingProfile(value: false, sourceSignalOrdinal: 6)
.WithCloudPc(value: true, sourceSignalOrdinal: 7))
.WithCloudPc(value: true, sourceSignalOrdinal: 7)
.WithAccountSetupProgressAtWhiteGloveSuccess(value: false, sourceSignalOrdinal: 8))
.Build();
var json = StateSerializer.Serialize(state);
@@ -538,6 +539,8 @@ namespace AutopilotMonitor.DecisionCore.Tests
Assert.Equal(6, o.RegistrySelfDeployingProfile!.SourceSignalOrdinal);
Assert.True(o.CloudPc!.Value);
Assert.Equal(7, o.CloudPc!.SourceSignalOrdinal);
Assert.False(o.AccountSetupProgressAtWhiteGloveSuccess!.Value);
Assert.Equal(8, o.AccountSetupProgressAtWhiteGloveSuccess!.SourceSignalOrdinal);
// Never-observed facts must rehydrate as null (null ≠ veto — session 62e603c9).
Assert.Null(o.WhiteGloveSealingPatternSeen);
@@ -31,7 +31,6 @@ namespace AutopilotMonitor.DecisionCore.Tests
DecisionSignalKind.HelloResolved,
DecisionSignalKind.ImeUserSessionCompleted,
DecisionSignalKind.DeviceSetupProvisioningComplete,
DecisionSignalKind.WhiteGloveShellCoreSuccess,
DecisionSignalKind.WhiteGloveSealingPatternDetected,
DecisionSignalKind.AadUserJoinedLate,
DecisionSignalKind.DeviceInfoCollected,
@@ -0,0 +1,155 @@
using System;
using System.Collections.Generic;
using AutopilotMonitor.DecisionCore.Classifiers;
using AutopilotMonitor.DecisionCore.Engine;
using AutopilotMonitor.DecisionCore.Serialization;
using AutopilotMonitor.DecisionCore.Signals;
using AutopilotMonitor.DecisionCore.State;
using Xunit;
namespace AutopilotMonitor.DecisionCore.Tests
{
/// <summary>
/// The sealing classifier's AccountSetup excluder (-40) applies only when the IME reported
/// the AccountSetup phase AND the WhiteGlove_Success signal did not report an untouched
/// AccountSetup registry. IME logs "EspPhase: AccountSetup" from the device session once
/// the device apps are done — on pre-provisioning with the user ESP enabled that line
/// routinely precedes the technician's success page and used to leave Part 1 unsealed.
/// The gate may only ever lift the excluder, never add one.
/// </summary>
public sealed class WhiteGloveAccountSetupProgressGateTests
{
private static readonly DateTime T0 = new DateTime(2026, 9, 29, 7, 25, 9, DateTimeKind.Utc);
[Fact]
public void Ime_account_setup_with_untouched_registry_seals_on_the_fast_path()
{
var step = new DecisionEngine().Reduce(
StateWithImeAccountSetup(), MakeShellCoreSignal(ordinal: 3, accountSetupProgress: "false"));
Assert.Equal(SessionStage.WhiteGloveSealed, step.NewState.Stage);
Assert.Equal(SessionOutcome.WhiteGlovePart1Sealed, step.NewState.Outcome);
Assert.Equal(HypothesisLevel.Confirmed, step.NewState.ClassifierOutcomes.WhiteGloveSealing.Level);
Assert.Equal(WhiteGloveSealingClassifier.WeightShellCoreWhiteGloveSuccess,
step.NewState.ClassifierOutcomes.WhiteGloveSealing.Score);
var fact = step.NewState.ScenarioObservations.AccountSetupProgressAtWhiteGloveSuccess;
Assert.NotNull(fact);
Assert.False(fact!.Value);
Assert.Equal(3, fact.SourceSignalOrdinal);
}
[Fact]
public void Ime_account_setup_with_registry_progress_keeps_the_excluder()
{
var step = new DecisionEngine().Reduce(
StateWithImeAccountSetup(), MakeShellCoreSignal(ordinal: 3, accountSetupProgress: "true"));
Assert.Equal(SessionStage.EspAccountSetup, step.NewState.Stage);
Assert.Contains(step.Effects, e => e.Kind == DecisionEffectKind.RunClassifier);
Assert.True(DecisionEngine.BuildWhiteGloveSealingSnapshot(step.NewState).HasAccountSetupActivity);
}
[Fact]
public void Missing_progress_payload_keeps_the_excluder_for_older_agents()
{
var step = new DecisionEngine().Reduce(
StateWithImeAccountSetup(), MakeShellCoreSignal(ordinal: 3, accountSetupProgress: null));
Assert.Equal(SessionStage.EspAccountSetup, step.NewState.Stage);
Assert.Null(step.NewState.ScenarioObservations.AccountSetupProgressAtWhiteGloveSuccess);
Assert.True(DecisionEngine.BuildWhiteGloveSealingSnapshot(step.NewState).HasAccountSetupActivity);
}
[Theory]
[InlineData("")]
[InlineData("yes")]
public void Unparseable_progress_payload_is_treated_as_missing(string raw)
{
var step = new DecisionEngine().Reduce(
StateWithImeAccountSetup(), MakeShellCoreSignal(ordinal: 3, accountSetupProgress: raw));
Assert.Null(step.NewState.ScenarioObservations.AccountSetupProgressAtWhiteGloveSuccess);
Assert.NotEqual(SessionStage.WhiteGloveSealed, step.NewState.Stage);
}
[Fact]
public void Registry_progress_without_ime_account_setup_adds_no_excluder()
{
var state = DecisionState.CreateInitial("s-gate", "t-gate").ToBuilder()
.WithStage(SessionStage.EspDeviceSetup)
.WithStepIndex(1)
.WithLastAppliedSignalOrdinal(0)
.Build();
var step = new DecisionEngine().Reduce(state, MakeShellCoreSignal(ordinal: 1, accountSetupProgress: "true"));
Assert.Equal(SessionStage.WhiteGloveSealed, step.NewState.Stage);
}
[Fact]
public void Untouched_registry_does_not_lift_a_hard_excluder()
{
var builder = DecisionState.CreateInitial("s-gate", "t-gate").ToBuilder()
.WithStage(SessionStage.EspAccountSetup)
.WithStepIndex(3)
.WithLastAppliedSignalOrdinal(2);
builder.AccountSetupEnteredUtc = new SignalFact<DateTime>(T0.AddMinutes(-3), 1);
builder.DesktopArrivedUtc = new SignalFact<DateTime>(T0.AddMinutes(-1), 2);
var step = new DecisionEngine().Reduce(builder.Build(), MakeShellCoreSignal(ordinal: 3, accountSetupProgress: "false"));
Assert.NotEqual(SessionStage.WhiteGloveSealed, step.NewState.Stage);
var snapshot = DecisionEngine.BuildWhiteGloveSealingSnapshot(step.NewState);
Assert.False(snapshot.HasAccountSetupActivity);
Assert.True(snapshot.DesktopArrived);
}
[Fact]
public void Progress_fact_survives_the_state_serializer()
{
var step = new DecisionEngine().Reduce(
StateWithImeAccountSetup(), MakeShellCoreSignal(ordinal: 3, accountSetupProgress: "false"));
var roundTripped = StateSerializer.Deserialize(StateSerializer.Serialize(step.NewState));
var fact = roundTripped.ScenarioObservations.AccountSetupProgressAtWhiteGloveSuccess;
Assert.NotNull(fact);
Assert.False(fact!.Value);
Assert.Equal(3, fact.SourceSignalOrdinal);
}
private static DecisionState StateWithImeAccountSetup()
{
// The IME device-session line: AccountSetup entered before the success page.
var builder = DecisionState.CreateInitial("s-gate", "t-gate").ToBuilder()
.WithStage(SessionStage.EspAccountSetup)
.WithStepIndex(3)
.WithLastAppliedSignalOrdinal(2);
builder.AccountSetupEnteredUtc = new SignalFact<DateTime>(T0.AddMinutes(-3), 2);
return builder.Build();
}
private static DecisionSignal MakeShellCoreSignal(long ordinal, string? accountSetupProgress)
{
var payload = new Dictionary<string, string>(StringComparer.Ordinal);
if (accountSetupProgress != null)
{
payload[SignalPayloadKeys.AccountSetupProgress] = accountSetupProgress;
}
return new DecisionSignal(
sessionSignalOrdinal: ordinal,
sessionTraceOrdinal: ordinal,
kind: DecisionSignalKind.WhiteGloveShellCoreSuccess,
kindSchemaVersion: 1,
occurredAtUtc: T0,
sourceOrigin: "EspAndHelloTracker",
evidence: new Evidence(
kind: EvidenceKind.Raw,
identifier: "ShellCore-62407",
summary: "WhiteGlove_Success"),
payload: payload);
}
}
}
@@ -0,0 +1,276 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutopilotMonitor.Functions.DataAccess.TableStorage;
using AutopilotMonitor.Functions.Functions.Config;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared;
using AutopilotMonitor.Shared.DataAccess;
using AutopilotMonitor.Shared.Models;
using Azure;
using Azure.Data.Tables;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Newtonsoft.Json.Linq;
using Xunit;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// D-285: the admin configuration row is changed only through the changed-columns write — fresh
/// read, mutation on a copy, only the columns whose value changed are laid onto the freshly read
/// row, conditional on its ETag. Pins the 2026-09-25 incident: a Global Settings page loaded before
/// an agent release saved one toggle and reverted the release's hashes with the full-model PUT.
/// </summary>
public class AdminConfigurationChangedFieldsTests
{
private const string ReleaseVersion = "2.0.1465";
private const string ReleaseZipSha = "9f0b5403da7e49202274fdf8f38675bc5cfea85f7d881e85d5fe4bd71308250e";
private const string ReleaseExeSha = "503dd02b3c3690acfe20c44dfce82c367ca1e56dcedaba3ecc91ff6ce893d726";
/// <summary>
/// A one-row table that behaves like storage: reads hand out copies with the current ETag,
/// a replace with a stale ETag fails 412, a create on an existing row fails 409.
/// </summary>
private sealed class FakeAdminTable
{
private int _version = 1;
public TableEntity? Current;
public int Writes;
public TableUpdateMode? LastMode;
/// <summary>Runs once, right before the first replace is checked — a concurrent writer.</summary>
public Action<FakeAdminTable>? BeforeFirstReplace;
public TableConfigRepository Sut { get; }
public FakeAdminTable(TableEntity? current)
{
Current = current;
var table = new Mock<TableClient>();
table.Setup(c => c.GetEntityAsync<TableEntity>(
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), It.IsAny<CancellationToken>()))
.Returns(() => Current == null
? throw new RequestFailedException(404, "Not Found", "ResourceNotFound", null)
: Task.FromResult(Response.FromValue(Copy(Current, _version), Mock.Of<Response>())));
table.Setup(c => c.UpdateEntityAsync(
It.IsAny<TableEntity>(), It.IsAny<ETag>(), It.IsAny<TableUpdateMode>(), It.IsAny<CancellationToken>()))
.Returns<TableEntity, ETag, TableUpdateMode, CancellationToken>((e, ifMatch, mode, _) =>
{
if (BeforeFirstReplace != null)
{
var concurrent = BeforeFirstReplace;
BeforeFirstReplace = null;
concurrent(this);
}
if (ifMatch != Etag(_version))
throw new RequestFailedException(412, "Precondition Failed", "UpdateConditionNotSatisfied", null);
Current = Copy(e, _version);
_version++;
Writes++;
LastMode = mode;
return Task.FromResult(Mock.Of<Response>());
});
table.Setup(c => c.AddEntityAsync(It.IsAny<TableEntity>(), It.IsAny<CancellationToken>()))
.Returns<TableEntity, CancellationToken>((e, _) =>
{
if (Current != null)
throw new RequestFailedException(409, "Conflict", "EntityAlreadyExists", null);
Current = Copy(e, _version);
Writes++;
return Task.FromResult(Mock.Of<Response>());
});
var serviceClient = new Mock<TableServiceClient>();
serviceClient.Setup(c => c.GetTableClient(It.IsAny<string>())).Returns(table.Object);
Sut = new TableConfigRepository(
new TableStorageService(serviceClient.Object, NullLogger<TableStorageService>.Instance),
new Mock<IConfigBackupRepository>().Object,
NullLogger<TableConfigRepository>.Instance);
}
/// <summary>A write by someone else (the release pipeline's Merge), bumping the ETag.</summary>
public void ExternalMerge(string column, object value)
{
Current![column] = value;
_version++;
}
private static ETag Etag(int version) => new($"W/\"v{version}\"");
private static TableEntity Copy(TableEntity source, int version)
=> new(source.Where(kv => kv.Key != "odata.etag").ToDictionary(kv => kv.Key, kv => kv.Value)) { ETag = Etag(version) };
}
/// <summary>The stored row right after the agent release: the pipeline's hashes plus a column this build does not know.</summary>
private static TableEntity ReleasedRow()
{
var row = TableConfigRepository.ConvertToAdminTableEntity(new AdminConfiguration
{
UpdatedBy = "ga@operator.example",
GlobalRateLimitRequestsPerMinute = 100,
NvdApiKey = "stored-key",
LatestAgentV2Version = ReleaseVersion,
LatestAgentV2Sha256 = ReleaseZipSha,
LatestAgentV2ExeSha256 = ReleaseExeSha,
});
row["ColumnOfANewerBuild"] = "keep-me";
return row;
}
[Fact]
public async Task Stale_page_toggle_writes_only_that_field_and_keeps_the_release_hashes()
{
var table = new FakeAdminTable(ReleasedRow());
// The page was loaded before the release; it sends only what the operator changed.
var fields = JObject.Parse("{ \"enforceClientAppBinding\": true }");
Assert.Null(PatchAdminConfigurationFunction.CheckFields(fields));
var result = await table.Sut.UpdateAdminConfigurationAsync(
draft => PatchAdminConfigurationFunction.ApplyFields(draft, fields), "ga@operator.example");
Assert.Null(result.Error);
Assert.Equal(new[] { "EnforceClientAppBinding" }, result.ChangedColumns);
var row = table.Current!;
Assert.True(row.GetBoolean("EnforceClientAppBinding"));
Assert.Equal(ReleaseVersion, row.GetString("LatestAgentV2Version"));
Assert.Equal(ReleaseZipSha, row.GetString("LatestAgentV2Sha256"));
Assert.Equal(ReleaseExeSha, row.GetString("LatestAgentV2ExeSha256"));
Assert.Equal("keep-me", row.GetString("ColumnOfANewerBuild"));
Assert.Equal("stored-key", row.GetString("NvdApiKey"));
Assert.Equal(TableUpdateMode.Replace, table.LastMode);
Assert.Equal(1, table.Writes);
}
[Fact]
public async Task A_concurrent_pipeline_write_is_reread_and_kept()
{
var table = new FakeAdminTable(ReleasedRow())
{
// The release pipeline lands between the backend's read and its write.
BeforeFirstReplace = t => t.ExternalMerge("LatestAgentV2Version", "2.0.1466"),
};
var result = await table.Sut.UpdateAdminConfigurationAsync(
c => { c.GlobalRateLimitRequestsPerMinute = 250; return null; }, "System (test)");
Assert.Null(result.Error);
Assert.Equal("2.0.1466", table.Current!.GetString("LatestAgentV2Version"));
Assert.Equal(250, table.Current.GetInt32("GlobalRateLimitRequestsPerMinute"));
Assert.Equal(1, table.Writes);
}
[Fact]
public async Task A_mutation_that_changes_nothing_writes_nothing()
{
var table = new FakeAdminTable(ReleasedRow());
var result = await table.Sut.UpdateAdminConfigurationAsync(
c => { c.GlobalRateLimitRequestsPerMinute = 100; return null; }, "ga@operator.example");
Assert.Null(result.Error);
Assert.Empty(result.ChangedColumns);
Assert.Equal(0, table.Writes);
}
[Fact]
public async Task A_rejected_mutation_writes_nothing()
{
var table = new FakeAdminTable(ReleasedRow());
var result = await table.Sut.UpdateAdminConfigurationAsync(
c => { c.GlobalRateLimitRequestsPerMinute = 999; return "nope"; }, "ga@operator.example");
Assert.Equal("nope", result.Error);
Assert.Equal(0, table.Writes);
Assert.Equal(100, table.Current!.GetInt32("GlobalRateLimitRequestsPerMinute"));
}
[Fact]
public async Task A_null_value_drops_its_column()
{
var table = new FakeAdminTable(ReleasedRow());
var result = await table.Sut.UpdateAdminConfigurationAsync(
c => { c.NvdApiKey = null!; return null; }, "ga@operator.example"); // what a JSON null in a patch does
Assert.Equal(new[] { "NvdApiKey" }, result.ChangedColumns);
Assert.False(table.Current!.ContainsKey("NvdApiKey"));
Assert.Equal(ReleaseExeSha, table.Current.GetString("LatestAgentV2ExeSha256"));
}
[Fact]
public async Task Without_a_row_the_first_change_creates_it()
{
var table = new FakeAdminTable(current: null);
var result = await table.Sut.UpdateAdminConfigurationAsync(
c => { c.EnforceClientAppBinding = true; return null; }, "ga@operator.example");
Assert.Null(result.Error);
Assert.True(table.Current!.GetBoolean("EnforceClientAppBinding"));
Assert.Equal(1, table.Writes);
}
[Fact]
public async Task Default_creation_never_replaces_an_existing_row()
{
var table = new FakeAdminTable(ReleasedRow());
var created = await table.Sut.CreateAdminConfigurationIfMissingAsync(AdminConfiguration.CreateDefault());
Assert.False(created);
Assert.Equal(ReleaseVersion, table.Current!.GetString("LatestAgentV2Version"));
}
[Theory]
[InlineData("latestAgentV2Version")]
[InlineData("LatestAgentV2Sha256")]
[InlineData("latestAgentV2ExeSha256")]
[InlineData("latestBootstrapV2ScriptVersion")]
[InlineData("updatedBy")]
[InlineData("lastUpdated")]
[InlineData("planTierDefinitionsJson")]
[InlineData("msrcLastSyncUtc")]
public void The_gate_rejects_pipeline_stamp_and_flow_owned_fields(string field)
{
var error = PatchAdminConfigurationFunction.CheckFields(new JObject { [field] = "x" });
Assert.NotNull(error);
Assert.Contains("not writable", error);
}
[Fact]
public void The_gate_rejects_unknown_fields_and_redacted_placeholders()
{
Assert.Contains("Unknown field", PatchAdminConfigurationFunction.CheckFields(new JObject { ["noSuchField"] = 1 }));
Assert.Contains("placeholder", PatchAdminConfigurationFunction.CheckFields(
new JObject { ["nvdApiKey"] = Constants.RedactedSecretPlaceholder }));
}
[Fact]
public void Patchable_fields_are_the_persisted_settings()
{
var patchable = PatchAdminConfigurationFunction.PatchableFields;
Assert.Contains("EnforceClientAppBinding", patchable);
Assert.Contains("McpClientRegistrationEnabled", patchable);
Assert.Contains("McpAccessPolicy", patchable);
Assert.Contains("NvdApiKey", patchable);
Assert.Contains("OpsNotificationChannelsJson", patchable);
Assert.DoesNotContain("LatestAgentV2ExeSha256", patchable);
Assert.DoesNotContain("PartitionKey", patchable);
Assert.DoesNotContain("UpdatedBy", patchable);
}
[Fact]
public void Applying_validates_the_result_without_echoing_values()
{
var draft = AdminConfiguration.CreateDefault();
Assert.Contains("at least 1", PatchAdminConfigurationFunction.ApplyFields(
draft, JObject.Parse("{ \"globalRateLimitRequestsPerMinute\": 0 }")));
var typeError = PatchAdminConfigurationFunction.ApplyFields(
AdminConfiguration.CreateDefault(), JObject.Parse("{ \"collectorIdleTimeoutMinutes\": \"https://secret.example/sas?sig=abc\" }"));
Assert.NotNull(typeError);
Assert.DoesNotContain("secret.example", typeError);
}
}
@@ -14,7 +14,7 @@ namespace AutopilotMonitor.Functions.Tests;
/// for the device path and UserRateLimitMiddleware for the user path). These tests pin the
/// removal of the former background sync job:
/// <list type="bullet">
/// <item>Saving the admin config must NOT enumerate or write ANY tenant configuration.</item>
/// <item>Changing the admin config must NOT enumerate or write ANY tenant configuration.</item>
/// </list>
/// <para>
/// Historical context: the sync used to copy <c>GlobalRateLimitRequestsPerMinute</c> into every
@@ -28,30 +28,35 @@ namespace AutopilotMonitor.Functions.Tests;
public class AdminConfigurationRateLimitSyncTests
{
[Fact]
public async Task SaveConfigurationAsync_DoesNotEnumerateOrWriteTenantConfigs()
public async Task UpdateAsync_DoesNotEnumerateOrWriteTenantConfigs()
{
var repo = new Mock<IConfigRepository>(MockBehavior.Strict);
repo.Setup(r => r.SaveAdminConfigurationAsync(It.IsAny<AdminConfiguration>()))
.ReturnsAsync(true);
repo.Setup(r => r.UpdateAdminConfigurationAsync(
It.IsAny<Func<AdminConfiguration, string?>>(), It.IsAny<string>(), It.IsAny<string?>()))
.ReturnsAsync(new AdminConfigurationUpdateResult
{
Before = new AdminConfiguration(),
After = new AdminConfiguration(),
ChangedColumns = new[] { "GlobalRateLimitRequestsPerMinute", "UserRateLimitRequestsPerMinute" },
});
var sut = new AdminConfigurationService(
repo.Object,
NullLogger<AdminConfigurationService>.Instance,
new MemoryCache(new MemoryCacheOptions()));
await sut.SaveConfigurationAsync(new AdminConfiguration
await sut.UpdateAsync(c =>
{
UpdatedBy = "global-admin@contoso.com",
GlobalRateLimitRequestsPerMinute = 200,
UserRateLimitRequestsPerMinute = 240,
});
c.GlobalRateLimitRequestsPerMinute = 200;
c.UserRateLimitRequestsPerMinute = 240;
return null;
}, "global-admin@contoso.com");
// The admin config row is written...
repo.Verify(r => r.SaveAdminConfigurationAsync(It.IsAny<AdminConfiguration>()), Times.Once);
repo.Verify(r => r.UpdateAdminConfigurationAsync(
It.IsAny<Func<AdminConfiguration, string?>>(), "global-admin@contoso.com", It.IsAny<string?>()), Times.Once);
// ...but NO tenant configuration is enumerated or mutated (sync removed).
repo.Verify(r => r.GetAllTenantConfigurationsAsync(), Times.Never);
repo.Verify(r => r.SaveTenantConfigurationAsync(It.IsAny<TenantConfiguration>()), Times.Never);
repo.Verify(r => r.SaveTenantConfigurationAsync(
It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
repo.VerifyNoTenantConfigWrite();
}
}
@@ -1,4 +1,5 @@
using AutopilotMonitor.Functions.Security;
using AutopilotMonitor.Functions.Functions.Admin;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Functions.Services.GraphResolution;
using AutopilotMonitor.Functions.Services.Notifications;
@@ -32,6 +33,7 @@ public class AppHomingServiceTests
private readonly Mock<AdminConfigurationService> _adminConfigMock;
private readonly Mock<TenantConfigurationService> _tenantConfigMock;
private readonly StoredTenantConfig _store;
private readonly Mock<GraphTokenService> _graphTokenMock;
private readonly Mock<IGraphFeatureDetector> _detectorMock;
private readonly Mock<IMaintenanceRepository> _maintenanceMock;
@@ -99,13 +101,10 @@ public class AppHomingServiceTests
new TelemetryClient(new TelemetryConfiguration { DisableTelemetry = true }));
// Defaults: flag on, legacy-homed config exists, both apps mint a role-less token (the
// superset rule passes trivially). FlipAsync reads via the cache-bypassing
// GetConfigurationFreshAsync (read-modify-write on the whole entity).
// superset rule passes trivially). FlipAsync writes through UpdateAsync (conditional
// write on the fresh row), stubbed over one stored row.
_adminConfigMock.Setup(x => x.IsSelfServiceAppHomingEnabledAsync()).ReturnsAsync(true);
var config = LegacyHomedConfig();
_tenantConfigMock.Setup(x => x.GetConfigurationFreshAsync(TenantId)).ReturnsAsync(config);
_tenantConfigMock.Setup(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()))
.Returns(Task.CompletedTask);
_store = _tenantConfigMock.StubWrites(TenantId, LegacyHomedConfig());
SetupProbe(GraphTokenResult.Success(Jwt()));
SetupLegacyToken(GraphTokenResult.Success(Jwt()));
}
@@ -143,8 +142,7 @@ public class AppHomingServiceTests
It.IsAny<CancellationToken>()))
.ReturnsAsync(result);
private void VerifyNeverSaved() =>
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
private void VerifyNeverSaved() => Assert.Empty(_store.Writes);
// ── IsFunnelEligibleAsync ───────────────────────────────────────────────
@@ -340,9 +338,10 @@ public class AppHomingServiceTests
var outcome = await _sut.TryAutoFlipToPrimaryAsync(LegacyHomedConfig(), Actor);
Assert.Equal(AppHomingAutoFlipOutcome.Flipped, outcome.Outcome);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.Is<TenantConfiguration>(c =>
string.Equals(c.HomedAppClientId, PrimaryId, StringComparison.OrdinalIgnoreCase)
&& c.UpdatedBy == Actor), It.IsAny<string?>(), It.IsAny<string?>()), Times.Once);
var (written, source, _) = Assert.Single(_store.Writes);
Assert.Equal(PrimaryId, written.HomedAppClientId, ignoreCase: true);
Assert.Equal(Actor, written.UpdatedBy);
Assert.Equal("app-homing", source);
_detectorMock.Verify(x => x.InvalidateTenant(TenantId), Times.Once);
_maintenanceMock.Verify(m => m.LogAuditEntryAsync(TenantId, "UPDATE", "TenantConfiguration",
TenantId, Actor, It.Is<Dictionary<string, string>?>(d =>
@@ -359,7 +358,7 @@ public class AppHomingServiceTests
var outcome = await _sut.TryAutoFlipToPrimaryAsync(LegacyHomedConfig(), Actor);
Assert.Equal(AppHomingAutoFlipOutcome.ProbeFailed, outcome.Outcome);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
VerifyNeverSaved();
}
[Fact]
@@ -370,7 +369,7 @@ public class AppHomingServiceTests
var outcome = await _sut.TryAutoFlipToPrimaryAsync(LegacyHomedConfig(), Actor);
Assert.Equal(AppHomingAutoFlipOutcome.ProbeTransient, outcome.Outcome);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
VerifyNeverSaved();
}
[Fact]
@@ -394,7 +393,7 @@ public class AppHomingServiceTests
var outcome = await _sut.TryAutoFlipToPrimaryAsync(LegacyHomedConfig(), Actor);
Assert.Equal(AppHomingAutoFlipOutcome.NotEligible, outcome.Outcome);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
VerifyNeverSaved();
}
// ── FlipAsync ───────────────────────────────────────────────────────────
@@ -404,7 +403,7 @@ public class AppHomingServiceTests
{
var config = LegacyHomedConfig();
config.EntraAppRolesEnabled = true;
_tenantConfigMock.Setup(x => x.GetConfigurationFreshAsync(TenantId)).ReturnsAsync(config);
_store.Row = config;
await _sut.FlipAsync(TenantId, PrimaryId, Actor, "manual-ga");
@@ -417,11 +416,11 @@ public class AppHomingServiceTests
{
var config = LegacyHomedConfig();
config.HomedAppClientId = PrimaryId;
_tenantConfigMock.Setup(x => x.GetConfigurationFreshAsync(TenantId)).ReturnsAsync(config);
_store.Row = config;
await _sut.FlipAsync(TenantId, PrimaryId, Actor, "manual-ga");
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
VerifyNeverSaved();
_detectorMock.Verify(x => x.InvalidateTenant(It.IsAny<string>()), Times.Never);
Assert.Empty(_savedOpsEvents);
}
@@ -430,30 +429,68 @@ public class AppHomingServiceTests
public async Task Flip_throws_when_config_row_missing_and_saves_nothing()
{
// A flip must never materialize a default row (e.g. resurrect an offboarded tenant);
// the fresh read returning null is a hard stop.
_tenantConfigMock.Setup(x => x.GetConfigurationFreshAsync(TenantId))
.ReturnsAsync((TenantConfiguration?)null);
// a missing row is a hard stop.
_store.Row = null;
await Assert.ThrowsAsync<InvalidOperationException>(
() => _sut.FlipAsync(TenantId, PrimaryId, Actor, "manual-ga"));
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
VerifyNeverSaved();
_detectorMock.Verify(x => x.InvalidateTenant(It.IsAny<string>()), Times.Never);
Assert.Empty(_savedOpsEvents);
}
[Fact]
public async Task Flip_decides_on_the_stored_row_not_the_callers_view()
{
// The caller's (cached) view is legacy-homed; the stored row was flipped meanwhile.
var stored = LegacyHomedConfig();
stored.HomedAppClientId = PrimaryId;
_store.Row = stored;
await _sut.FlipAsync(TenantId, PrimaryId, Actor, "consent-auto-flip");
VerifyNeverSaved();
Assert.Empty(_savedOpsEvents);
}
[Fact]
public async Task Flip_skips_a_tenant_being_offboarded()
{
var tombstone = LegacyHomedConfig();
tombstone.Disabled = true;
tombstone.DisabledReason = TenantOffboardFunction.OffboardingDisabledReason;
_store.Row = tombstone;
await _sut.FlipAsync(TenantId, PrimaryId, Actor, "manual-ga");
VerifyNeverSaved();
_detectorMock.Verify(x => x.InvalidateTenant(It.IsAny<string>()), Times.Never);
Assert.Empty(_savedOpsEvents);
}
[Fact]
public async Task Flip_throws_when_every_conditional_write_lost()
{
_store.Force = TenantConfigUpdateStatus.Conflict;
await Assert.ThrowsAsync<InvalidOperationException>(
() => _sut.FlipAsync(TenantId, PrimaryId, Actor, "manual-ga"));
Assert.Empty(_savedOpsEvents);
}
[Fact]
public async Task Flip_back_to_legacy_persists_null_homing()
{
var config = LegacyHomedConfig();
config.HomedAppClientId = PrimaryId;
_tenantConfigMock.Setup(x => x.GetConfigurationFreshAsync(TenantId)).ReturnsAsync(config);
_store.Row = config;
await _sut.FlipAsync(TenantId, null, Actor, "manual-ga");
// The null-homing invariant: legacy is represented as null, never as the legacy GUID.
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.Is<TenantConfiguration>(c =>
c.HomedAppClientId == null), It.IsAny<string?>(), It.IsAny<string?>()), Times.Once);
Assert.Null(Assert.Single(_store.Writes).Row.HomedAppClientId);
_detectorMock.Verify(x => x.InvalidateTenant(TenantId), Times.Once);
}
}
@@ -306,7 +306,7 @@ public class AppInstallIdentityAndEspBlockingTests
};
var root = TestWire.SerializeToElement(await AppsAnalyticsHelper.BuildAnalyticsResponseAsync(
summaries, repo.Object, "Company Portal", days: 30));
summaries, repo.Object, "Company Portal", AppInstallSources.Ime, days: 30));
Assert.Equal(1, root.GetProperty("collisionExcluded").GetInt32());
var stats = root.GetProperty("summary");
@@ -325,7 +325,7 @@ public class AppInstallIdentityAndEspBlockingTests
var summaries = new List<AppInstallSummary> { Summary("Company Portal", collision: true) };
var root = TestWire.SerializeToElement(await AppsAnalyticsHelper.BuildAnalyticsResponseAsync(
summaries, repo.Object, "Company Portal", days: 30));
summaries, repo.Object, "Company Portal", AppInstallSources.Ime, days: 30));
Assert.Equal(1, root.GetProperty("collisionExcluded").GetInt32());
Assert.Equal(0, root.GetProperty("summary").GetProperty("totalInstalls").GetInt32());
@@ -195,6 +195,37 @@ public class AppVersionRegressionRadarTests
Assert.Empty(AppVersionRegressionRadar.Evaluate(rows2));
}
[Fact]
public void Evaluate_SameNameInTwoChannels_IsTwoApps()
{
// The RealmJoin package regressed; the Intune app of the same name did not. A shared
// group would dilute the RealmJoin medians with the Intune rows and hide the regression.
var rows = new List<AppInstallSummary>();
rows.AddRange(Batch("1.0", 10, 300, Now.AddDays(-20)).Select(s => { s.Source = AppInstallSources.RealmJoin; return s; }));
rows.AddRange(Batch("2.0", 10, 900, Now.AddDays(-5)).Select(s => { s.Source = AppInstallSources.RealmJoin; return s; }));
rows.AddRange(Batch("1.0", 30, 300, Now.AddDays(-20)));
rows.AddRange(Batch("2.0", 30, 300, Now.AddDays(-5)));
var finding = Assert.Single(AppVersionRegressionRadar.Evaluate(rows));
Assert.Equal(AppInstallSources.RealmJoin, finding.Source);
Assert.Equal(App, finding.AppName);
Assert.Equal(900, finding.CurrentMedianSeconds);
}
[Fact]
public void ShouldReArm_ReadsTheAlertsOwnChannel()
{
// The IME app still regresses; the RealmJoin episode's version has no measured installs.
var rows = new List<AppInstallSummary>();
rows.AddRange(Batch("1.0", 10, 300, Now.AddDays(-20)));
rows.AddRange(Batch("2.0", 10, 900, Now.AddDays(-5)));
var rjAlert = Alert();
rjAlert.Source = AppInstallSources.RealmJoin;
Assert.True(AppVersionRegressionRadar.ShouldReArm(rows, rjAlert));
Assert.False(AppVersionRegressionRadar.ShouldReArm(rows, Alert()));
}
[Fact]
public void Evaluate_DeterministicOrdering_LiftDesc_ThenAppNameOrdinal()
{
@@ -279,13 +310,25 @@ public class AppVersionRegressionRadarTests
{
Assert.Equal("appversionregression|contoso app_2|1.0_beta_",
TableHardwareRejectionNotificationTracker.BuildAppVersionRegressionRowKey(
" Contoso App/2 ", " 1.0#Beta? "));
AppInstallSources.Ime, " Contoso App/2 ", " 1.0#Beta? "));
}
[Fact]
public void AppVersionRegressionRowKey_ImeKeepsPreChannelShape_OtherChannelsPrefixTheApp()
{
// Episodes written before channels existed must keep resolving (re-arm deletes them by key).
Assert.Equal("appversionregression|contoso vpn|2.0",
TableHardwareRejectionNotificationTracker.BuildAppVersionRegressionRowKey(null, App, "2.0"));
Assert.Equal("appversionregression|contoso vpn|2.0",
TableHardwareRejectionNotificationTracker.BuildAppVersionRegressionRowKey(string.Empty, App, "2.0"));
Assert.Equal("appversionregression|realmjoin:contoso vpn|2.0",
TableHardwareRejectionNotificationTracker.BuildAppVersionRegressionRowKey(AppInstallSources.RealmJoin, App, "2.0"));
}
[Fact]
public void AppVersionRegressionRowKey_NoPrefixCollisionWithOtherKeyspaces()
{
var key = TableHardwareRejectionNotificationTracker.BuildAppVersionRegressionRowKey(App, "1.0");
var key = TableHardwareRejectionNotificationTracker.BuildAppVersionRegressionRowKey(AppInstallSources.RealmJoin, App, "1.0");
Assert.StartsWith("appversionregression|", key, StringComparison.Ordinal);
// The prefix range [prefix, "appversionregression}") must not swallow the sibling
// keyspaces ("ruleregression|", "tpmpss|", "{mfr}|{model}").
@@ -293,6 +336,39 @@ public class AppVersionRegressionRadarTests
Assert.True(string.CompareOrdinal("tpmpss|", "appversionregression}") > 0);
}
[Fact]
public void AppVersionRegressionEntity_RealmJoinChannel_RoundTripsWithPrefixedKey()
{
var alert = new AppVersionRegressionAlert
{
TenantId = TenantA,
AppName = App,
Source = AppInstallSources.RealmJoin,
CurrentVersion = "2.4.0",
PreviousVersion = "2.3.9",
FirstNotifiedAt = Now,
LastEvaluatedAt = Now,
};
var entity = TableHardwareRejectionNotificationTracker.BuildAppVersionRegressionEntity(TenantA, alert);
Assert.Equal("appversionregression|realmjoin:contoso vpn|2.4.0", entity.RowKey);
Assert.Equal(AppInstallSources.RealmJoin,
TableHardwareRejectionNotificationTracker.MapToAppVersionRegressionAlert(entity).Source);
}
[Fact]
public void AppVersionRegressionEntity_RowWithoutSourceColumn_MapsToIme()
{
var entity = new Azure.Data.Tables.TableEntity(TenantA.ToLowerInvariant(), "appversionregression|contoso vpn|2.4.0")
{
["TenantId"] = TenantA,
["AppName"] = App,
["CurrentVersion"] = "2.4.0",
};
Assert.Equal(AppInstallSources.Ime,
TableHardwareRejectionNotificationTracker.MapToAppVersionRegressionAlert(entity).Source);
}
[Fact]
public void AppVersionRegressionEntity_RoundTripsAllFields()
{
@@ -318,6 +394,7 @@ public class AppVersionRegressionRadarTests
var mapped = TableHardwareRejectionNotificationTracker.MapToAppVersionRegressionAlert(entity);
Assert.Equal(TenantA, mapped.TenantId);
Assert.Equal(App, mapped.AppName);
Assert.Equal(AppInstallSources.Ime, mapped.Source);
Assert.Equal("2.4.0", mapped.CurrentVersion);
Assert.Equal("2.3.9", mapped.PreviousVersion);
Assert.Equal(1740, mapped.CurrentMedianSeconds);
@@ -371,7 +448,7 @@ public class AppVersionRegressionRadarTests
};
var root = TestWire.SerializeToElement(await AppsAnalyticsHelper.BuildAnalyticsResponseAsync(
rows, sessionRepo.Object, App, days: 30));
rows, sessionRepo.Object, App, AppInstallSources.Ime, days: 30));
var version = root.GetProperty("versionBreakdown")[0];
Assert.Equal("1.0", version.GetProperty("appVersion").GetString());
@@ -395,12 +472,12 @@ public class AppVersionRegressionRadarTests
// Empty-data early return still surfaces the block (episodes can outlive window data).
var emptyRoot = TestWire.SerializeToElement(await AppsAnalyticsHelper.BuildAnalyticsResponseAsync(
new List<AppInstallSummary>(), sessionRepo.Object, App, days: 30,
new List<AppInstallSummary>(), sessionRepo.Object, App, AppInstallSources.Ime, days: 30,
new List<AppVersionRegressionAlert> { alert }));
Assert.Equal(1, emptyRoot.GetProperty("versionRegressions").GetArrayLength());
var root = TestWire.SerializeToElement(await AppsAnalyticsHelper.BuildAnalyticsResponseAsync(
new List<AppInstallSummary> { Install("1.0", 100, Recent) }, sessionRepo.Object, App, days: 30,
new List<AppInstallSummary> { Install("1.0", 100, Recent) }, sessionRepo.Object, App, AppInstallSources.Ime, days: 30,
new List<AppVersionRegressionAlert> { alert }));
var regression = root.GetProperty("versionRegressions")[0];
@@ -131,7 +131,7 @@ public class AppsAnalyticsFailureRateTests
sessionRepo = mock.Object;
}
var result = await AppsAnalyticsHelper.BuildAnalyticsResponseAsync(
summaries, sessionRepo, "Contoso App", days: 30);
summaries, sessionRepo, "Contoso App", AppInstallSources.Ime, days: 30);
return TestWire.SerializeToElement(result);
}
@@ -31,9 +31,9 @@ public class AuditLogDeletionExclusionTests
public void Global_fanout_filter_includes_deletion_exclusion_only_when_requested()
{
var without = TableStorageService.BuildAuditLogFilterWithRowKeyBound(
Tenant.ToString(), null, null, lastRowKey: null, excludeDeletions: false);
Tenant.ToString(), null, null, rowKeyBound: null, excludeDeletions: false);
var with = TableStorageService.BuildAuditLogFilterWithRowKeyBound(
Tenant.ToString(), null, null, lastRowKey: null, excludeDeletions: true);
Tenant.ToString(), null, null, rowKeyBound: null, excludeDeletions: true);
Assert.DoesNotContain("deletion_started", without);
Assert.Contains("Action ne 'deletion_started'", with);
@@ -47,7 +47,7 @@ public class AuditLogDeletionExclusionTests
// noise leak back into one of the two views.
var tenant = TableStorageService.BuildAuditLogFilter(Tenant.ToString(), null, null, excludeDeletions: true);
var global = TableStorageService.BuildAuditLogFilterWithRowKeyBound(
Tenant.ToString(), null, null, lastRowKey: null, excludeDeletions: true);
Tenant.ToString(), null, null, rowKeyBound: null, excludeDeletions: true);
var clause = TableStorageService.DeletionExclusionClause();
Assert.Contains(clause, tenant);
@@ -51,7 +51,7 @@ public class AuditLogFieldFilterTests
var filters = new AuditLogQueryFilters { Action = "device_blocked", EntityType = "Device" };
var f = TableStorageService.BuildAuditLogFilterWithRowKeyBound(
Tenant, null, null, lastRowKey: null, excludeDeletions: false, filters);
Tenant, null, null, rowKeyBound: null, excludeDeletions: false, filters);
Assert.Contains("Action eq 'device_blocked'", f);
Assert.Contains("EntityType eq 'Device'", f);
@@ -1,5 +1,9 @@
using AutopilotMonitor.Functions.Functions.Config;
using AutopilotMonitor.Functions.Functions.Infrastructure;
using AutopilotMonitor.Functions.Security;
using AutopilotMonitor.Functions.Tests.Offboarding;
using AutopilotMonitor.Shared;
using AutopilotMonitor.Shared.Models.Offboarding;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.DataAccess;
using AutopilotMonitor.Shared.Models;
@@ -32,6 +36,8 @@ public class AuthFunctionSideEffectTests
private readonly Mock<IMetricsRepository> _metricsRepoMock;
private readonly Mock<AutopilotMonitor.Functions.Services.Activation.ITenantAutoApproveEnqueuer> _autoApproveEnqueuerMock;
private readonly FakeSignalRNotificationService _signalR;
private readonly FakeOffboardingAuditRepository _offboardingRepo = new();
private readonly StoredTenantConfig _store;
private readonly AuthFunction _sut;
public AuthFunctionSideEffectTests()
@@ -107,12 +113,13 @@ public class AuthFunctionSideEffectTests
Mock.Of<ILogger<AutopilotMonitor.Functions.Security.EntraAppRegistry>>()),
new Mock<AdminIdentityResolver>(
_metricsRepoMock.Object, _tenantConfigMock.Object, Mock.Of<ILogger<AdminIdentityResolver>>()) { CallBase = false }.Object,
_signalR);
_signalR,
adminConfigService.Object,
_offboardingRepo);
// Default: all fire-and-forget calls succeed
_tenantConfigMock
.Setup(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()))
.Returns(Task.CompletedTask);
// Writes go through UpdateAsync / CreateOrUpdateAsync over one stored row (none by default:
// a brand-new tenant). Default: all fire-and-forget calls succeed.
_store = _tenantConfigMock.StubWrites(TenantId, row: null);
_telegramMock
.Setup(x => x.SendNewTenantSignupAsync(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
@@ -201,7 +208,7 @@ public class AuthFunctionSideEffectTests
Assert.True(string.IsNullOrEmpty(config.DomainName));
Assert.Null(config.OnboardedBy);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
Assert.Empty(_store.Writes);
_telegramMock.Verify(x => x.SendNewTenantSignupAsync(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
@@ -221,7 +228,11 @@ public class AuthFunctionSideEffectTests
Assert.Equal(Upn, config.OnboardedBy);
// The DPA version rides along in the same onboarding write (D-252).
Assert.Equal(CurrentDpa, config.DpaVersion);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(config, It.IsAny<string?>(), It.IsAny<string?>()), Times.Once);
var (written, source, _) = Assert.Single(_store.Writes);
Assert.Equal("contoso.com", written.DomainName);
Assert.Equal(Upn, written.OnboardedBy);
Assert.Equal(CurrentDpa, written.DpaVersion);
Assert.Equal("auth", source);
_telegramMock.Verify(x => x.SendNewTenantSignupAsync(TenantId, Upn), Times.Once);
_globalNotificationMock.Verify(x => x.CreateNotificationAsync(
"preview_signup", "New Tenant Signup",
@@ -236,6 +247,122 @@ public class AuthFunctionSideEffectTests
It.IsAny<CancellationToken>()), Times.Once);
}
// -------------------------------------------------------------------------
// Returning tenant (D-288): the offboarding deleted the configuration, the pointer
// carries the consumed self-service trial into the first-login write.
// -------------------------------------------------------------------------
private void SeedOffboardingPointer(bool trialConsumed) =>
_offboardingRepo.Pointers[TenantId] = (new OffboardingByTenantPointer
{
PartitionKey = Constants.OffboardingPartitionKeys.ByTenant,
RowKey = TenantId,
TenantId = TenantId,
LatestStatus = "Completed",
OffboardCount = 1,
TrialConsumed = trialConsumed,
}, "\"etag\"");
private static TenantConfiguration ReturningTenantDefault()
{
// What auth/me hands over once the offboarding deleted the row: an unpersisted default.
var config = TenantConfiguration.CreateDefault(TenantId);
Assert.False(config.TrialConsumed);
return config;
}
[Fact]
public async Task HandleNewTenantDomain_ReturningTenantThatUsedTheTrial_CarriesItIntoTheOnboardingWrite()
{
SeedOffboardingPointer(trialConsumed: true);
var config = ReturningTenantDefault();
await _sut.HandleNewTenantDomainAsync(config, TenantId, Upn);
Assert.True(config.TrialConsumed);
Assert.Equal(Upn, config.OnboardedBy);
var written = Assert.Single(_store.Writes).Row;
Assert.True(written.TrialConsumed);
Assert.Equal(Upn, written.OnboardedBy);
// Re-onboarding itself stays unrestricted: same signup path, auto-approve included.
_autoApproveEnqueuerMock.Verify(x => x.EnqueueAsync(
It.IsAny<AutopilotMonitor.Functions.Services.Activation.TenantAutoApproveEnvelope>(),
It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>()), Times.Once);
// The verify criterion of the finding: the trial gate refuses the returning tenant.
var deny = PlanManagementFunction.EvaluateTrialStart(config, DateTime.UtcNow);
Assert.Equal(Constants.ApiErrorCodes.TrialAlreadyConsumed, deny?.Code);
}
[Theory]
[InlineData(false)] // offboarded without ever using the trial
[InlineData(null)] // never offboarded
public async Task HandleNewTenantDomain_NoConsumedTrialOnRecord_LeavesTheTrialAvailable(bool? pointerTrialConsumed)
{
if (pointerTrialConsumed is { } consumed)
SeedOffboardingPointer(consumed);
var config = ReturningTenantDefault();
await _sut.HandleNewTenantDomainAsync(config, TenantId, Upn);
Assert.False(config.TrialConsumed);
Assert.Equal("contoso.com", config.DomainName);
Assert.False(Assert.Single(_store.Writes).Row.TrialConsumed);
}
[Fact]
public async Task HandleNewTenantDomain_OffboardingLookupFails_WritesNothingAndRetriesOnTheNextLogin()
{
// An onboarded row without the carry-over would hand the trial back; no write at all instead.
_offboardingRepo.ThrowOnPointerRead = new Azure.RequestFailedException(503, "Server busy");
var config = ReturningTenantDefault();
await _sut.HandleNewTenantDomainAsync(config, TenantId, Upn);
Assert.True(string.IsNullOrEmpty(config.DomainName));
Assert.Null(config.OnboardedBy);
Assert.Empty(_store.Writes);
_telegramMock.Verify(x => x.SendNewTenantSignupAsync(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
_autoApproveEnqueuerMock.Verify(x => x.EnqueueAsync(
It.IsAny<AutopilotMonitor.Functions.Services.Activation.TenantAutoApproveEnvelope>(),
It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>()), Times.Never);
}
[Fact]
public async Task HandleNewTenantDomain_ConcurrentFirstLogin_NeverOverwritesOnboardedBy()
{
// This login's view still has no domain, but another login seeded the stored row meanwhile:
// OnboardedBy is write-once (D-061), and the signup side effects belong to the winner.
var stored = DefaultConfig();
stored.DomainName = "contoso.com";
stored.OnboardedBy = "first@contoso.com";
_store.Row = stored;
var view = DefaultConfig();
await _sut.HandleNewTenantDomainAsync(view, TenantId, "second@contoso.com");
Assert.Empty(_store.Writes);
Assert.Equal("first@contoso.com", _store.Row!.OnboardedBy);
_telegramMock.Verify(x => x.SendNewTenantSignupAsync(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
_autoApproveEnqueuerMock.Verify(x => x.EnqueueAsync(
It.IsAny<AutopilotMonitor.Functions.Services.Activation.TenantAutoApproveEnvelope>(),
It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>()), Times.Never);
}
[Fact]
public async Task HandleNewTenantDomain_OffboardingTombstone_IsNeverSeeded()
{
// The offboard click writes a Disabled tombstone even onto a row without a domain.
var tombstone = DefaultConfig();
tombstone.Disabled = true;
tombstone.DisabledReason = AutopilotMonitor.Functions.Functions.Admin.TenantOffboardFunction.OffboardingDisabledReason;
_store.Row = tombstone;
await _sut.HandleNewTenantDomainAsync(DefaultConfig(), TenantId, Upn);
Assert.Empty(_store.Writes);
_telegramMock.Verify(x => x.SendNewTenantSignupAsync(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
// -------------------------------------------------------------------------
// HandleAuthClientIdTrackingAsync — the write must mutate a cache-BYPASSING
// read, never the (possibly stale) cached view. Regression for the prod
@@ -260,16 +387,16 @@ public class AuthFunctionSideEffectTests
fresh.LastAuthClientId = LegacyAppId;
fresh.HomedAppClientId = PrimaryAppId; // the concurrent flip that must survive
_tenantConfigMock.Setup(x => x.GetConfigurationFreshAsync(TenantId)).ReturnsAsync(fresh);
_store.Row = fresh;
await _sut.HandleAuthClientIdTrackingAsync(cached, TenantId, $"api://{PrimaryAppId}");
// The FRESH entity was mutated and saved — the flip survives, the stale view is discarded.
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(fresh, It.IsAny<string?>(), It.IsAny<string?>()), Times.Once);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(cached, It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
Assert.Equal(PrimaryAppId, fresh.HomedAppClientId);
Assert.Equal(PrimaryAppId, fresh.LastAuthClientId);
Assert.NotNull(fresh.LastAuthClientIdSince);
// The FRESH row was mutated and written — the flip survives, the stale view is discarded.
var written = Assert.Single(_store.Writes).Row;
Assert.Equal(PrimaryAppId, written.HomedAppClientId);
Assert.Equal(PrimaryAppId, written.LastAuthClientId);
Assert.NotNull(written.LastAuthClientIdSince);
Assert.Null(cached.HomedAppClientId);
}
[Fact]
@@ -285,11 +412,11 @@ public class AuthFunctionSideEffectTests
fresh.DomainName = "contoso.com";
fresh.LastAuthClientId = PrimaryAppId;
_tenantConfigMock.Setup(x => x.GetConfigurationFreshAsync(TenantId)).ReturnsAsync(fresh);
_store.Row = fresh;
await _sut.HandleAuthClientIdTrackingAsync(cached, TenantId, PrimaryAppId);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
Assert.Empty(_store.Writes);
}
[Fact]
@@ -302,8 +429,9 @@ public class AuthFunctionSideEffectTests
await _sut.HandleAuthClientIdTrackingAsync(cached, TenantId, $"api://{PrimaryAppId}");
_tenantConfigMock.Verify(x => x.GetConfigurationFreshAsync(It.IsAny<string>()), Times.Never);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
_tenantConfigMock.Verify(x => x.UpdateAsync(It.IsAny<string>(), It.IsAny<Func<TenantConfiguration, bool>>(),
It.IsAny<string>(), It.IsAny<string>()), Times.Never);
Assert.Empty(_store.Writes);
}
private const string CurrentDpa = AutopilotMonitor.Shared.Constants.CurrentDpaVersion;
@@ -320,7 +448,7 @@ public class AuthFunctionSideEffectTests
await _sut.HandleNewTenantDomainAsync(config, TenantId, Upn);
Assert.Null(config.DpaVersion);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
Assert.Empty(_store.Writes);
}
[Fact]
@@ -331,10 +459,12 @@ public class AuthFunctionSideEffectTests
var config = DefaultConfig();
config.DomainName = null!;
config.OnboardedBy = "original.requester@contoso.com";
_store.Row = ConfigRepoMockExtensions.Clone(config);
await _sut.HandleNewTenantDomainAsync(config, TenantId, Upn);
Assert.Equal("original.requester@contoso.com", config.OnboardedBy);
Assert.Equal("original.requester@contoso.com", Assert.Single(_store.Writes).Row.OnboardedBy);
}
[Fact]
@@ -345,7 +475,7 @@ public class AuthFunctionSideEffectTests
await _sut.HandleNewTenantDomainAsync(config, TenantId, Upn);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
Assert.Empty(_store.Writes);
_telegramMock.Verify(x => x.SendNewTenantSignupAsync(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
}
@@ -357,7 +487,7 @@ public class AuthFunctionSideEffectTests
await _sut.HandleNewTenantDomainAsync(config, TenantId, "");
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
Assert.Empty(_store.Writes);
}
[Fact]
@@ -368,7 +498,7 @@ public class AuthFunctionSideEffectTests
await _sut.HandleNewTenantDomainAsync(config, TenantId, "nodomain");
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
Assert.Empty(_store.Writes);
}
[Fact]
@@ -384,8 +514,8 @@ public class AuthFunctionSideEffectTests
// Should not throw — Telegram is fire-and-forget
await _sut.HandleNewTenantDomainAsync(config, TenantId, Upn);
// SaveConfig should still have been called before the fire-and-forget
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(config, It.IsAny<string?>(), It.IsAny<string?>()), Times.Once);
// The write still landed before the fire-and-forget
Assert.Single(_store.Writes);
}
// -------------------------------------------------------------------------
@@ -399,14 +529,68 @@ public class AuthFunctionSideEffectTests
config.Disabled = true;
config.DisabledReason = "Maintenance";
config.DisabledUntil = DateTime.UtcNow.AddHours(-1); // expired
_store.Row = ConfigRepoMockExtensions.Clone(config);
await _sut.HandleAutoReEnableAsync(config, TenantId);
Assert.False(config.Disabled);
Assert.Null(config.DisabledReason);
Assert.Null(config.DisabledUntil);
Assert.Equal("System (auto-re-enable)", config.UpdatedBy);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(config, It.IsAny<string?>(), It.IsAny<string?>()), Times.Once);
var written = Assert.Single(_store.Writes).Row;
Assert.False(written.Disabled);
Assert.Null(written.DisabledUntil);
Assert.Equal("System (auto-re-enable)", written.UpdatedBy);
}
[Fact]
public async Task HandleAutoReEnable_SuspensionRenewedMeanwhile_StaysSuspended()
{
// This instance cached the expired suspension; a Global Admin renewed it since.
var view = DefaultConfig();
view.Disabled = true;
view.DisabledReason = "Maintenance";
view.DisabledUntil = DateTime.UtcNow.AddHours(-1);
var stored = ConfigRepoMockExtensions.Clone(view);
stored.DisabledReason = "Abuse review";
stored.DisabledUntil = DateTime.UtcNow.AddDays(2);
_store.Row = stored;
await _sut.HandleAutoReEnableAsync(view, TenantId);
Assert.Empty(_store.Writes);
Assert.True(view.IsCurrentlyDisabled());
Assert.Equal("Abuse review", view.DisabledReason);
}
[Fact]
public async Task HandleAutoReEnable_RowIsTheOffboardingTombstone_StaysSuspended()
{
var view = DefaultConfig();
view.Disabled = true;
view.DisabledUntil = DateTime.UtcNow.AddHours(-1);
var tombstone = ConfigRepoMockExtensions.Clone(view);
tombstone.DisabledReason = AutopilotMonitor.Functions.Functions.Admin.TenantOffboardFunction.OffboardingDisabledReason;
tombstone.DisabledUntil = null;
_store.Row = tombstone;
await _sut.HandleAutoReEnableAsync(view, TenantId);
Assert.Empty(_store.Writes);
Assert.True(view.IsCurrentlyDisabled());
}
[Fact]
public async Task HandleAutoReEnable_StorageFails_ThisLoginStillPasses()
{
var view = DefaultConfig();
view.Disabled = true;
view.DisabledUntil = DateTime.UtcNow.AddHours(-1);
_store.ThrowOnRead = new Azure.RequestFailedException(503, "Server busy");
await _sut.HandleAutoReEnableAsync(view, TenantId);
Assert.False(view.Disabled);
Assert.Empty(_store.Writes);
}
[Fact]
@@ -419,7 +603,7 @@ public class AuthFunctionSideEffectTests
await _sut.HandleAutoReEnableAsync(config, TenantId);
Assert.True(config.Disabled);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
Assert.Empty(_store.Writes);
}
[Fact]
@@ -430,7 +614,7 @@ public class AuthFunctionSideEffectTests
await _sut.HandleAutoReEnableAsync(config, TenantId);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
Assert.Empty(_store.Writes);
}
[Fact]
@@ -443,7 +627,7 @@ public class AuthFunctionSideEffectTests
await _sut.HandleAutoReEnableAsync(config, TenantId);
Assert.True(config.Disabled);
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
Assert.Empty(_store.Writes);
}
// -------------------------------------------------------------------------
@@ -63,7 +63,7 @@ public class AuthenticationMiddlewareTests
[InlineData("GET", "/api/progress/sessions/lookup")] // AuthenticatedUserWithRole
[InlineData("GET", "/api/sessions")] // MemberRead
[InlineData("GET", "/api/audit/logs")] // MemberRead
[InlineData("PUT", "/api/config/11111111-1111-1111-1111-111111111111")] // TenantAdminOrGA
[InlineData("PATCH", "/api/config/11111111-1111-1111-1111-111111111111/fields")] // TenantAdminOrGA
[InlineData("GET", "/api/global/sessions")] // GlobalReadOrDelegatedSubset
[InlineData("POST", "/api/global/raw/logs")] // GlobalAdminOnly (KQL proxy)
[InlineData("GET", "/api/health/detailed")] // AuthenticatedUser (sub-route is NOT blanket-exempt)
@@ -0,0 +1,156 @@
using System.Text.Json;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Shared.Models;
using AutopilotMonitor.Shared.Models.Backup;
using Xunit;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// Wire-identity proof for moving the backup job, row-restore and queued-run bodies off their
/// private <c>WriteJsonAsync(req, status, object)</c> wrappers onto <c>ResponseHelper</c>.
/// Two things changed at once and both are pinned here: the anonymous 202 bodies became DTOs,
/// and the typed bodies left <see cref="BackupManifestJson.SerializerOptions"/> for the worker
/// pipeline (<see cref="ApiJsonOptions"/>). The two option sets differ only in how they READ
/// enums (<c>allowIntegerValues</c>); the facts below keep the WRITE side honest if either set
/// ever gains a naming policy, a key policy or a converter.
/// </summary>
public class BackupWireParityTests
{
private static readonly JsonSerializerOptions WireOptions = ApiJsonOptions.Create();
private static JsonElement Json(string raw)
{
using var doc = JsonDocument.Parse(raw);
return doc.RootElement.Clone();
}
private static void AssertSameUnderBothOptionSets(object body)
{
var backupSurface = JsonSerializer.Serialize(body, body.GetType(), BackupManifestJson.SerializerOptions);
var pipeline = JsonSerializer.Serialize(body, body.GetType(), WireOptions);
Assert.Equal(backupSurface, pipeline);
}
[Fact]
public void BackupJobStatus_serializes_identically_under_both_option_sets()
{
var t = new DateTime(2026, 9, 21, 4, 0, 0, DateTimeKind.Utc);
AssertSameUnderBothOptionSets(new BackupJobStatus
{
JobId = "0f8fad5bd9cb469fa16570867728950e",
Kind = BackupJobKind.RestoreTable,
State = BackupJobState.BlockedTerminal,
RequestedBy = "admin@contoso.example",
QueuedAtUtc = t,
StartedAtUtc = t.AddSeconds(3),
CompletedAtUtc = t.AddMinutes(2),
LastHeartbeatUtc = t.AddMinutes(2),
BackupId = "20260921T040000Z_a1b2c3d4",
SourceBackupId = "20260920T040000Z_e5f6a7b8",
TableName = "TenantConfiguration",
Strategy = "upsert-only",
Progress = "{\"phase\":\"copy\",\"rows\":12}",
Error = "IntegrityCheckFailed",
BackupOutcome = BackupOutcome.Partial,
});
// Freshly queued: every nullable slot absent on both sides.
AssertSameUnderBothOptionSets(new BackupJobStatus
{
JobId = "0f8fad5bd9cb469fa16570867728950e",
Kind = BackupJobKind.Backup,
State = BackupJobState.Queued,
RequestedBy = "admin@contoso.example",
QueuedAtUtc = t,
LastHeartbeatUtc = t,
});
}
[Fact]
public void RestoreRowPreviewResponse_serializes_identically_under_both_option_sets()
{
var text = new RestoreRowPropertySnapshot { EdmType = "Edm.String", Value = Json("\"Pro\"") };
var flag = new RestoreRowPropertySnapshot { EdmType = "Edm.Boolean", Value = Json("true") };
var number = new RestoreRowPropertySnapshot { EdmType = "Edm.Int64", Value = Json("\"9007199254740993\"") };
AssertSameUnderBothOptionSets(new RestoreRowPreviewResponse
{
BackupId = "20260921T040000Z_a1b2c3d4",
TableName = "TenantConfiguration",
PartitionKey = "tenant/with+odd%chars",
RowKey = "config",
// Case-faithful column names: a key policy on either side would rewrite them.
BackupProperties = { ["PlanTier"] = text, ["IsEnabled"] = flag, ["lowerCaseColumn"] = number },
CurrentProperties = new Dictionary<string, RestoreRowPropertySnapshot> { ["PlanTier"] = text },
Diff =
{
new RestoreRowPropertyDiff { Name = "IsEnabled", Kind = RestoreRowDiffKind.Added, Backup = flag },
new RestoreRowPropertyDiff { Name = "PlanTier", Kind = RestoreRowDiffKind.Unchanged, Backup = text, Current = text },
},
RowSha256 = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
CurrentETag = "W/\"datetime'2026-09-21T04%3A00%3A00Z'\"",
IsAuthTable = true,
});
// Live row absent: currentProperties and currentETag vanish on both sides.
AssertSameUnderBothOptionSets(new RestoreRowPreviewResponse
{
BackupId = "20260921T040000Z_a1b2c3d4",
TableName = "TenantConfiguration",
PartitionKey = "pk",
RowKey = "rk",
BackupProperties = { ["PlanTier"] = text },
Diff = { new RestoreRowPropertyDiff { Name = "PlanTier", Kind = RestoreRowDiffKind.Added, Backup = text } },
RowSha256 = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
});
}
[Fact]
public void RestoreRowCommitResponse_serializes_identically_under_both_option_sets()
{
AssertSameUnderBothOptionSets(new RestoreRowCommitResponse
{
BackupId = "20260921T040000Z_a1b2c3d4",
TableName = "TenantConfiguration",
PartitionKey = "pk",
RowKey = "rk",
Outcome = RestoreRowCommitOutcome.Replaced,
});
}
[Fact]
public void BackupTriggerResponse_matches_the_anonymous_202_body()
{
const string jobId = "0f8fad5bd9cb469fa16570867728950e";
var old = new { jobId, statusUrl = $"/api/global/backups/jobs/{jobId}" };
Assert.Equal(
JsonSerializer.Serialize(old, old.GetType(), BackupManifestJson.SerializerOptions),
JsonSerializer.Serialize(
new BackupTriggerResponse { JobId = jobId, StatusUrl = $"/api/global/backups/jobs/{jobId}" },
WireOptions));
}
[Fact]
public void SessionDeletionMaintenanceTriggerResponse_matches_the_anonymous_202_body()
{
var old = new { message = "Maintenance run queued.", triggeredBy = "admin@contoso.example" };
// The old wrapper serialized with DEFAULT options; its keys were camelCase by hand.
Assert.Equal(
JsonSerializer.Serialize(old, old.GetType()),
JsonSerializer.Serialize(
new SessionDeletionMaintenanceTriggerResponse { Message = "Maintenance run queued.", TriggeredBy = "admin@contoso.example" },
WireOptions));
}
[Fact]
public void Delegation_acknowledgements_match_the_anonymous_message_body()
{
ApiResponseWireParityTests.AssertWireIdentical(
new { message = "Delegation ended" },
new MessageResponse { Message = "Delegation ended" });
}
}
@@ -156,6 +156,8 @@ public sealed class BootstrapRouteFailClosedTests
reqMock.SetupGet(r => r.Headers).Returns(headers);
reqMock.SetupGet(r => r.Url).Returns(new Uri(url));
// Query is virtual: without CallBase a loose mock answers null instead of parsing Url.
reqMock.SetupGet(r => r.Query).CallBase();
return reqMock.Object;
}
}
@@ -152,7 +152,7 @@ public class BusinessTimestampFilterClauseTests
var plain = TableStorageService.BuildAuditLogFilter(Tenant, from, to);
var fanOut = TableStorageService.BuildAuditLogFilterWithRowKeyBound(
Tenant, from, to, lastRowKey: "!0123_x", excludeDeletions: false);
Tenant, from, to, rowKeyBound: new PerPartitionFanOutMerge.RowKeyBound("!0123_x", Inclusive: false), excludeDeletions: false);
foreach (var f in new[] { plain!, fanOut })
{
@@ -1,3 +1,5 @@
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using AutopilotMonitor.Functions.Security;
@@ -13,6 +15,7 @@ namespace AutopilotMonitor.Functions.Tests;
/// must validate successfully. This guards against rollouts where the embedded root/intermediate
/// bundle drifts from the chain Microsoft is actually issuing.
/// - Negative path: self-signed leaf certs (with or without Intune-shaped DNs) must NOT validate.
/// - No network I/O: a leaf from an unknown CA must be rejected without fetching its AIA URL.
/// </summary>
public class CertificateValidatorTests
{
@@ -131,6 +134,31 @@ public class CertificateValidatorTests
Assert.Contains("expired", result.ErrorMessage, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void ValidateCertificate_WithUnknownIssuerAndAiaUrl_NeverFetchesTheIssuer()
{
// The caller mints the leaf, so the AIA caIssuers URL points wherever they like. A
// self-signed leaf never reaches the issuer-download path; it takes a leaf signed by a
// CA that is neither embedded nor sent.
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
try
{
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
var b64 = CreateLeafFromUnknownCaBase64($"http://127.0.0.1:{port}/{Guid.NewGuid():N}.cer");
var result = CertificateValidator.ValidateCertificate(b64);
Assert.False(result.IsValid);
Assert.Contains("chain validation failed", result.ErrorMessage, StringComparison.OrdinalIgnoreCase);
Assert.False(listener.Pending(), "Chain building connected to the certificate's AIA URL");
}
finally
{
listener.Stop();
}
}
private static string ResolveSamplePath()
{
var assemblyDir = Path.GetDirectoryName(typeof(CertificateValidatorTests).Assembly.Location)!;
@@ -165,4 +193,24 @@ public class CertificateValidatorTests
return Convert.ToBase64String(cert.Export(X509ContentType.Cert));
}
private static string CreateLeafFromUnknownCaBase64(string aiaCaIssuersUrl)
{
using var caKey = RSA.Create(2048);
var caReq = new CertificateRequest("CN=Unknown Test CA", caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
caReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
using var ca = caReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1));
using var leafKey = RSA.Create(2048);
var leafReq = new CertificateRequest("CN=test-device.contoso.example", leafKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
leafReq.CertificateExtensions.Add(
new X509EnhancedKeyUsageExtension(
new OidCollection { new Oid("1.3.6.1.5.5.7.3.2") },
critical: false));
leafReq.CertificateExtensions.Add(
new X509AuthorityInformationAccessExtension(ocspUris: null, caIssuersUris: new[] { aiaCaIssuersUrl }));
using var leaf = leafReq.Create(ca, DateTimeOffset.UtcNow.AddHours(-1), DateTimeOffset.UtcNow.AddDays(30), RandomNumberGenerator.GetBytes(16));
return Convert.ToBase64String(leaf.Export(X509ContentType.Cert));
}
}
@@ -0,0 +1,498 @@
using System.Security.Claims;
using System.Text;
using AutopilotMonitor.Functions.Extensions;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Middleware;
using AutopilotMonitor.Functions.Security;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared;
using AutopilotMonitor.Shared.DataAccess;
using AutopilotMonitor.Shared.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// Client-app binding of delegated tokens: a user token obtained by an application outside the platform's
/// own registrations is measured always and, while <c>EnforceClientAppBinding</c> is on, admitted only when
/// that application is an enabled member of the caller's tenant — the person then acts under the same caps
/// as an application principal (Viewer, no platform role, DelegatedReader). The switch off must leave every
/// request exactly as it was: only the request-row items appear.
/// </summary>
public class ClientAppBindingTests
{
private const string TenantA = "11111111-1111-1111-1111-111111111111";
private const string TenantB = "22222222-2222-2222-2222-222222222222";
private const string OwnClientId = "aaaaaaaa-0000-0000-0000-00000000000a";
private const string LegacyClientId = "bbbbbbbb-0000-0000-0000-00000000000b";
private const string ForeignClientId = "cccccccc-0000-0000-0000-00000000000c";
private const string UserUpn = "alice@contoso.example";
private const string UserOid = "dddddddd-0000-0000-0000-00000000000d";
private static readonly string ForeignAppKey = Constants.PrincipalKeys.ForApplication(ForeignClientId);
private static readonly string[] Trusted = { OwnClientId, LegacyClientId };
private static ClaimsPrincipal UserToken(string? clientId = ForeignClientId, string clientClaim = "azp",
string upn = UserUpn, string tenantId = TenantA)
{
var claims = new List<Claim>
{
new("tid", tenantId), new("upn", upn), new("oid", UserOid), new("scp", "access_as_user"),
};
if (clientId != null) claims.Add(new Claim(clientClaim, clientId));
return new ClaimsPrincipal(new ClaimsIdentity(claims, "AuthenticationTypes.Federation"));
}
private static ClaimsPrincipal AppToken(string clientId = ForeignClientId)
=> new(new ClaimsIdentity(new[]
{
new Claim("tid", TenantA), new Claim("idtyp", "app"), new Claim("appid", clientId),
new Claim("oid", "eeeeeeee-0000-0000-0000-00000000000e"),
new Claim("roles", Constants.ApplicationPermissions.AccessAsApplication),
}, "AuthenticationTypes.Federation"));
// ── Classification ──────────────────────────────────────────────────────────
[Theory]
[InlineData(OwnClientId, "azp")]
[InlineData(LegacyClientId, "azp")]
[InlineData(OwnClientId, "appid")]
[InlineData("AAAAAAAA-0000-0000-0000-00000000000A", "azp")]
public void OwnRegistrations_AreNotForeign(string clientId, string claim)
=> Assert.False(ClientAppBinding.IsForeignDelegatedToken(UserToken(clientId, claim), Trusted, out _));
[Theory]
[InlineData("azp")]
[InlineData("appid")]
public void AnotherClient_IsForeign_AndNamed(string claim)
{
Assert.True(ClientAppBinding.IsForeignDelegatedToken(UserToken(ForeignClientId, claim), Trusted, out var id));
Assert.Equal(ForeignClientId, id);
}
[Fact]
public void ATokenNamingNoClient_IsForeign_Unidentified()
{
Assert.True(ClientAppBinding.IsForeignDelegatedToken(UserToken(clientId: null), Trusted, out var id));
Assert.Null(id);
}
[Fact]
public void AppOnlyTokens_AreNeverForeign_TheyHaveTheirOwnGate()
=> Assert.False(ClientAppBinding.IsForeignDelegatedToken(AppToken(), Trusted, out _));
[Fact]
public void TheTrustedSet_IsTheAudienceTrustSet_PrimaryLegacyAndAdditional()
{
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["EntraId:ClientId"] = OwnClientId,
["EntraId:LegacyClientId"] = LegacyClientId,
["EntraId:AdditionalClientIds"] = ForeignClientId.ToUpperInvariant() + ", not-a-guid",
}).Build();
var ids = AuthenticationMiddleware.ResolveTrustedClientIds(config, out _, out var rejected);
Assert.Equal(new[] { OwnClientId, LegacyClientId, ForeignClientId }, ids);
Assert.Equal(new[] { "not-a-guid" }, rejected);
}
[Fact]
public void ClientOnlyTrust_WidensTheClientSet_ButNotTheAudiences()
{
const string DevClientId = "ffffffff-0000-0000-0000-00000000000f";
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["EntraId:ClientId"] = OwnClientId,
["EntraId:TrustedClientAppIds"] = DevClientId,
}).Build();
var clients = ClientAppBindingMiddleware.ResolveTrustedClientApps(config);
var audiences = AuthenticationMiddleware.ResolveTrustedClientIds(config, out _, out _);
Assert.Contains(DevClientId, clients);
Assert.Contains(OwnClientId, clients);
Assert.DoesNotContain(DevClientId, audiences);
Assert.False(ClientAppBinding.IsForeignDelegatedToken(UserToken(DevClientId), clients, out _));
}
// ── The cap marker ──────────────────────────────────────────────────────────
[Fact]
public void AMarkedPrincipal_KeepsItsIdentity_ButIsCapped()
{
var principal = UserToken();
ClientAppBinding.MarkCapped(principal, ForeignClientId);
var identity = AdminIdentity.FromPrincipal(principal)!;
Assert.True(principal.IsClientCapped());
Assert.True(principal.IsCappedPrincipal());
Assert.Equal(UserUpn, principal.GetUserPrincipalName());
Assert.Equal(UserUpn, identity.Upn);
Assert.False(identity.IsApplication);
Assert.True(identity.IsCapped);
}
[Fact]
public void ATokenCarryingTheMarkerClaim_IsNotCapped()
{
// The marker is an identity with the middleware's own authentication type — a token-derived identity
// can carry the same claim name but never that authentication type.
var principal = UserToken();
((ClaimsIdentity)principal.Identity!).AddClaim(new Claim(ClientAppBinding.ClientAppClaimType, ForeignClientId));
Assert.False(principal.IsClientCapped());
Assert.False(AdminIdentity.FromPrincipal(principal)!.IsCapped);
}
// ── Middleware: measure always, enforce behind the switch ─────────────────────
private sealed class Run
{
public required bool NextCalled { get; init; }
public required IDictionary<object, object> Items { get; init; }
public required HttpContext Http { get; init; }
public required ClaimsPrincipal? Principal { get; init; }
public string Body()
{
Http.Response.Body.Position = 0;
return new StreamReader(Http.Response.Body, Encoding.UTF8).ReadToEnd();
}
}
private static async Task<Run> InvokeAsync(ClaimsPrincipal? principal, bool enforced, TenantMember? appRow = null)
{
var repo = new Mock<IAdminRepository>();
repo.Setup(r => r.GetTenantMemberAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync((TenantMember?)null);
if (appRow != null)
repo.Setup(r => r.GetTenantMemberAsync(TenantA, ForeignAppKey)).ReturnsAsync(appRow);
var cache = new MemoryCache(new MemoryCacheOptions());
var adminConfig = new Mock<AdminConfigurationService>(Mock.Of<IConfigRepository>(), NullLogger<AdminConfigurationService>.Instance, cache) { CallBase = false };
adminConfig.Setup(x => x.GetConfigurationAsync()).ReturnsAsync(new AdminConfiguration { EnforceClientAppBinding = enforced });
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["EntraId:ClientId"] = OwnClientId,
["EntraId:LegacyClientId"] = LegacyClientId,
}).Build();
var sut = new ClientAppBindingMiddleware(
NullLogger<ClientAppBindingMiddleware>.Instance, config,
new TenantAdminsService(repo.Object, cache, NullLogger<TenantAdminsService>.Instance), adminConfig.Object);
var http = new DefaultHttpContext();
http.Response.Body = new MemoryStream();
var items = new Dictionary<object, object> { ["HttpRequestContext"] = http, ["CorrelationId"] = "cid-1" };
if (principal != null) items["ClaimsPrincipal"] = principal;
var context = new Mock<FunctionContext>();
context.SetupGet(c => c.Items).Returns(items);
var nextCalled = false;
await sut.Invoke(context.Object, _ => { nextCalled = true; return Task.CompletedTask; });
return new Run { NextCalled = nextCalled, Items = items, Http = http, Principal = principal };
}
private static TenantMember AppRow(bool enabled = true)
=> new() { TenantId = TenantA, Upn = ForeignAppKey, Role = Constants.TenantRoles.Viewer, IsEnabled = enabled };
[Fact]
public async Task NoValidatedPrincipal_PassesThrough_Unmeasured()
{
var run = await InvokeAsync(principal: null, enforced: true);
Assert.True(run.NextCalled);
Assert.False(run.Items.ContainsKey(ClientAppBinding.OutcomeItemKey));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task OwnClientTokens_PassUntouched_InBothModes(bool enforced)
{
var run = await InvokeAsync(UserToken(OwnClientId), enforced);
Assert.True(run.NextCalled);
Assert.False(run.Items.ContainsKey(ClientAppBinding.OutcomeItemKey));
Assert.False(run.Principal!.IsClientCapped());
}
[Fact]
public async Task SwitchOff_MeasuresAnUnregisteredClient_AndLetsItThrough()
{
var run = await InvokeAsync(UserToken(), enforced: false);
Assert.True(run.NextCalled);
Assert.Equal(ClientAppBinding.Outcomes.Unregistered, run.Items[ClientAppBinding.OutcomeItemKey]);
Assert.Equal(ForeignClientId, run.Items[ClientAppBinding.ClientAppIdItemKey]);
Assert.False(run.Principal!.IsClientCapped());
}
[Fact]
public async Task SwitchOff_MeasuresARegisteredClient_WithoutCapping()
{
var run = await InvokeAsync(UserToken(), enforced: false, appRow: AppRow());
Assert.True(run.NextCalled);
Assert.Equal(ClientAppBinding.Outcomes.Registered, run.Items[ClientAppBinding.OutcomeItemKey]);
Assert.False(run.Principal!.IsClientCapped());
}
[Fact]
public async Task SwitchOn_RefusesAnUnregisteredClient_With403NamingTheApp()
{
var run = await InvokeAsync(UserToken(), enforced: true);
Assert.False(run.NextCalled);
Assert.Equal(403, run.Http.Response.StatusCode);
var body = run.Body();
Assert.Contains(Constants.ApiErrorCodes.ClientAppNotRegistered, body);
Assert.Contains(ForeignClientId, body);
Assert.Equal(ClientAppBinding.Outcomes.Unregistered, run.Items[ClientAppBinding.OutcomeItemKey]);
}
[Fact]
public async Task SwitchOn_RefusesADisabledAppRow()
{
var run = await InvokeAsync(UserToken(), enforced: true, appRow: AppRow(enabled: false));
Assert.False(run.NextCalled);
Assert.Equal(403, run.Http.Response.StatusCode);
}
[Fact]
public async Task SwitchOn_RefusesATokenNamingNoClient()
{
var run = await InvokeAsync(UserToken(clientId: null), enforced: true);
Assert.False(run.NextCalled);
Assert.Equal(403, run.Http.Response.StatusCode);
Assert.Equal(ClientAppBinding.Outcomes.Unidentified, run.Items[ClientAppBinding.OutcomeItemKey]);
}
[Fact]
public async Task SwitchOn_AdmitsARegisteredClient_AndCapsThePerson()
{
var run = await InvokeAsync(UserToken(), enforced: true, appRow: AppRow());
Assert.True(run.NextCalled);
Assert.True(run.Principal!.IsClientCapped());
Assert.Equal(UserUpn, run.Principal!.GetUserPrincipalName());
}
[Fact]
public async Task TheAppRowIsLookedUp_InTheCallersOwnTenant()
{
// A registration in another tenant admits nothing: the row must live in the token's tid.
var run = await InvokeAsync(UserToken(tenantId: TenantB), enforced: true, appRow: AppRow());
Assert.False(run.NextCalled);
Assert.Equal(403, run.Http.Response.StatusCode);
}
// ── Caps through the real policy middleware ─────────────────────────────────
private sealed class Harness
{
public required PolicyEnforcementMiddleware Middleware { get; init; }
public required Mock<IAdminRepository> Repo { get; init; }
public void UserRow(string role) =>
Repo.Setup(r => r.GetTenantMemberAsync(TenantA, UserUpn))
.ReturnsAsync(new TenantMember { TenantId = TenantA, Upn = UserUpn, Role = role, IsEnabled = true, CanManageBootstrapTokens = true });
}
private static Harness BuildHarness()
{
var repo = new Mock<IAdminRepository>();
repo.Setup(r => r.GetGlobalRoleAsync(It.IsAny<string>())).ReturnsAsync((string?)null);
repo.Setup(r => r.GetTenantMemberAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync((TenantMember?)null);
repo.Setup(r => r.GetDelegatedTenantsAsync(It.IsAny<string>())).ReturnsAsync(new List<DelegatedAdminEntry>());
repo.Setup(r => r.GetGroupAssignmentsForUpnAsync(It.IsAny<string>())).ReturnsAsync(new List<TenantGroupAssignment>());
repo.Setup(r => r.GetIdentityBindingAsync(It.IsAny<string>()))
.ReturnsAsync(new AdminIdentityBinding { TenantId = TenantA, ObjectId = UserOid });
var configRepo = new Mock<IConfigRepository>();
configRepo.Setup(r => r.GetTenantConfigurationAsync(It.IsAny<string>())).ReturnsAsync((TenantConfiguration?)null);
var cache = new MemoryCache(new MemoryCacheOptions());
var bindings = new AdminIdentityBindingService(repo.Object, cache, NullLogger<AdminIdentityBindingService>.Instance);
var globalAdmin = new GlobalAdminService(repo.Object, bindings, cache, NullLogger<GlobalAdminService>.Instance);
var delegatedAdmin = new DelegatedAdminService(
repo.Object, bindings, new StubTenantEntitlementService(TenantEdition.Pro), cache, NullLogger<DelegatedAdminService>.Instance);
var tenantAdmins = new TenantAdminsService(repo.Object, cache, NullLogger<TenantAdminsService>.Instance);
var tenantConfig = new TenantConfigurationService(configRepo.Object, NullLogger<TenantConfigurationService>.Instance, cache);
var mw = new PolicyEnforcementMiddleware(
NullLogger<PolicyEnforcementMiddleware>.Instance, globalAdmin, delegatedAdmin,
new TenantMemberRoleResolver(tenantAdmins, tenantConfig), tenantConfig, new RecordingDenialReporter());
return new Harness { Middleware = mw, Repo = repo };
}
private static ClaimsPrincipal CappedUser()
{
var principal = UserToken();
ClientAppBinding.MarkCapped(principal, ForeignClientId);
return principal;
}
[Fact]
public async Task Control_TheSamePersonUncapped_KeepsTheirAdminRole()
{
var h = BuildHarness();
h.UserRow(Constants.TenantRoles.Admin);
var r = await h.Middleware.DecideAsync("GET", "/api/sessions", null, UserToken(OwnClientId));
Assert.True(r.Allowed);
Assert.Equal(Constants.TenantRoles.Admin, r.Context!.UserRole);
Assert.False(r.Context.ClientCapped);
}
[Fact]
public async Task ACappedAdmin_ReadsAsViewer()
{
var h = BuildHarness();
h.UserRow(Constants.TenantRoles.Admin);
var r = await h.Middleware.DecideAsync("GET", "/api/sessions", null, CappedUser());
Assert.True(r.Allowed);
Assert.Equal(Constants.TenantRoles.Viewer, r.Context!.UserRole);
Assert.False(r.Context.IsTenantAdmin);
Assert.True(r.Context.ClientCapped);
Assert.True(AdminIdentity.FromRequestContext(r.Context)!.IsCapped);
}
[Theory]
[InlineData("POST", "/api/sessions/abc/actions")]
[InlineData("PUT", "/api/sessions/abc/annotations/operator")]
[InlineData("POST", "/api/config/11111111-1111-1111-1111-111111111111")]
public async Task ACappedAdmin_CannotWrite(string method, string path)
{
var h = BuildHarness();
h.UserRow(Constants.TenantRoles.Admin);
var r = await h.Middleware.DecideAsync(method, path, null, CappedUser());
Assert.False(r.Allowed);
Assert.Equal(403, r.StatusCode);
}
[Fact]
public async Task RolelessTiers_AreClosed_ButTheMcpFrontDoorIsOpen()
{
var h = BuildHarness();
h.UserRow(Constants.TenantRoles.Viewer);
var me = await h.Middleware.DecideAsync("GET", "/api/auth/me", null, CappedUser());
var mcp = await h.Middleware.DecideAsync("GET", "/api/auth/mcp", null, CappedUser());
Assert.False(me.Allowed);
Assert.Equal("ApplicationPrincipalNotAllowed", me.LogReason);
Assert.True(mcp.Allowed);
Assert.Equal(UserUpn, mcp.Context!.UserPrincipalName);
}
[Fact]
public async Task APlatformRole_IsInert_WhileCapped()
{
var h = BuildHarness();
h.Repo.Setup(r => r.GetGlobalRoleAsync(UserUpn)).ReturnsAsync(Constants.GlobalRoles.GlobalAdmin);
var uncapped = await h.Middleware.DecideAsync("GET", "/api/global/raw/access-probe", null, UserToken(OwnClientId));
var capped = await h.Middleware.DecideAsync("GET", "/api/global/raw/access-probe", null, CappedUser());
Assert.True(uncapped.Allowed);
Assert.False(capped.Allowed);
Assert.Equal(403, capped.StatusCode);
}
[Fact]
public async Task ADelegatedAdminGrant_IsReaderOnly_WhileCapped()
{
var h = BuildHarness();
h.Repo.Setup(r => r.GetDelegatedTenantsAsync(UserUpn)).ReturnsAsync(new List<DelegatedAdminEntry>
{
new()
{
TenantId = TenantB, Role = Constants.DelegatedRoles.DelegatedAdmin, IsEnabled = true,
Status = Constants.DelegatedStatus.Active, Source = Constants.DelegatedSource.OperatorGranted,
},
});
var r = await h.Middleware.DecideAsync("GET", $"/api/config/{TenantB}", null, CappedUser());
Assert.True(r.Allowed);
Assert.True(r.Context!.IsDelegatedReader);
Assert.False(r.Context.IsDelegatedAdmin);
}
// ── Resolver overload and the MCP front door ────────────────────────────────
[Theory]
[InlineData(false, Constants.TenantRoles.Admin, true)]
[InlineData(true, Constants.TenantRoles.Viewer, false)]
public async Task Resolver_CapsOnlyWhenAsked(bool capped, string expectedRole, bool expectedBootstrap)
{
var repo = new Mock<IAdminRepository>();
repo.Setup(r => r.GetTenantMemberAsync(TenantA, UserUpn))
.ReturnsAsync(new TenantMember { TenantId = TenantA, Upn = UserUpn, Role = Constants.TenantRoles.Admin, IsEnabled = true, CanManageBootstrapTokens = true });
var cache = new MemoryCache(new MemoryCacheOptions());
var sut = new TenantMemberRoleResolver(
new TenantAdminsService(repo.Object, cache, NullLogger<TenantAdminsService>.Instance),
new TenantConfigurationService(Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache));
var role = await sut.ResolveAsync(TenantA, UserUpn, null, capped);
Assert.Equal(expectedRole, role?.Role);
Assert.Equal(expectedBootstrap, role!.CanManageBootstrapTokens);
}
[Fact]
public async Task Resolver_NeverTurnsANonMemberIntoAViewer()
{
var repo = new Mock<IAdminRepository>();
repo.Setup(r => r.GetTenantMemberAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync((TenantMember?)null);
var cache = new MemoryCache(new MemoryCacheOptions());
var sut = new TenantMemberRoleResolver(
new TenantAdminsService(repo.Object, cache, NullLogger<TenantAdminsService>.Instance),
new TenantConfigurationService(Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache));
Assert.Null(await sut.ResolveAsync(TenantA, UserUpn, null, clientCapped: true));
}
[Fact]
public async Task McpAccessCheck_ResolvesTheCappedIdentity()
{
var adminRepo = new Mock<IAdminRepository>();
adminRepo.Setup(x => x.GetMcpUserAsync(It.IsAny<string>())).ReturnsAsync((McpUserEntry?)null);
var cache = new MemoryCache(new MemoryCacheOptions());
var bindings = new StubAdminIdentityBindingService(bound: true);
var seen = new List<AdminIdentity?>();
var globalAdmin = new Mock<GlobalAdminService>(adminRepo.Object, bindings, cache, NullLogger<GlobalAdminService>.Instance) { CallBase = false };
globalAdmin.Setup(x => x.GetGlobalRoleAsync(It.IsAny<AdminIdentity?>()))
.Callback<AdminIdentity?>(seen.Add).ReturnsAsync((string?)null);
var delegatedAdmin = new Mock<DelegatedAdminService>(
adminRepo.Object, bindings, new StubTenantEntitlementService(TenantEdition.Pro), cache, NullLogger<DelegatedAdminService>.Instance) { CallBase = false };
delegatedAdmin.Setup(x => x.GetScopeAsync(It.IsAny<AdminIdentity?>()))
.Callback<AdminIdentity?>(seen.Add).ReturnsAsync(DelegatedScope.Empty);
var adminConfig = new Mock<AdminConfigurationService>(Mock.Of<IConfigRepository>(), NullLogger<AdminConfigurationService>.Instance, cache) { CallBase = false };
adminConfig.Setup(x => x.GetConfigurationAsync())
.ReturnsAsync(new AdminConfiguration { McpAccessPolicy = McpAccessPolicy.AllMembers.ToString() });
var members = StubTenantMemberRoleResolver.Everyone();
var sut = new McpUserService(
adminRepo.Object, bindings, cache, NullLogger<McpUserService>.Instance,
globalAdmin.Object, delegatedAdmin.Object, adminConfig.Object, members,
new TenantConfigurationService(Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache));
var result = await sut.IsAllowedAsync(UserUpn, TenantA, UserOid, null, clientCapped: true);
Assert.True(result.IsAllowed);
Assert.Equal("AllMembers", result.AccessGrant);
Assert.NotEmpty(seen);
Assert.All(seen, identity => Assert.True(identity!.IsCapped));
}
}
@@ -40,14 +40,23 @@ public class CollectLogsQuickConfigOpsEventTests
new TenantConfiguration { TenantId = "t1", DiagnosticsUploadMode = "OnFailure", DiagnosticsUploadDestination = "Hosted" })!;
[Theory]
[InlineData("collect-logs", UpdateTenantConfigurationFunction.CollectLogsSource)]
[InlineData("COLLECT-LOGS", UpdateTenantConfigurationFunction.CollectLogsSource)]
[InlineData(null, "portal-put")]
[InlineData("", "portal-put")]
[InlineData("something-else", "portal-put")]
public void ResolveWriteSource_only_honours_the_allow_listed_intent(string? intent, string expected)
[InlineData("?intent=collect-logs", "patch", PatchTenantConfigurationFieldsFunction.CollectLogsSource)]
[InlineData("?intent=COLLECT-LOGS", "patch", PatchTenantConfigurationFieldsFunction.CollectLogsSource)]
[InlineData("", "patch", "api-patch")]
[InlineData("?intent=", "patch", "api-patch")]
[InlineData("?intent=something-else", "patch", "api-patch")]
[InlineData("?intent=collect-logs", "revert", "api-revert")] // a revert is never the quick-config dialog
public void ResolveSource_only_honours_the_allow_listed_intent(string query, string operation, string expected)
{
Assert.Equal(expected, UpdateTenantConfigurationFunction.ResolveWriteSource(intent));
var (req, _) = EndpointHarness.Request("t1", queryString: query);
Assert.Equal(expected, PatchTenantConfigurationFieldsFunction.ResolveSource(req, operation));
}
[Fact]
public void ResolveSource_mcp_header_without_intent_is_mcp()
{
var (req, _) = EndpointHarness.Request("t1", headers: new Dictionary<string, string> { ["X-Client-Source"] = "mcp" });
Assert.Equal("mcp-patch", PatchTenantConfigurationFieldsFunction.ResolveSource(req, "patch"));
}
[Fact]
@@ -56,7 +65,7 @@ public class CollectLogsQuickConfigOpsEventTests
var (service, saved) = Rig();
await service.RecordDiagnosticsUploadConfigChangedAsync(
"t1", "contoso.com", EnableFlip(), "admin@contoso.com", UpdateTenantConfigurationFunction.CollectLogsSource);
"t1", "contoso.com", EnableFlip(), "admin@contoso.com", PatchTenantConfigurationFieldsFunction.CollectLogsSource);
var evt = Assert.Single(saved);
Assert.Equal("CollectLogsQuickConfigEnabled", evt.EventType);
@@ -85,7 +94,7 @@ public class CollectLogsQuickConfigOpsEventTests
new TenantConfiguration { TenantId = "t1", DiagnosticsUploadMode = "Always", DiagnosticsUploadDestination = "Hosted" },
new TenantConfiguration { TenantId = "t1", DiagnosticsUploadMode = "Off", DiagnosticsUploadDestination = "Hosted" })!;
await service.RecordDiagnosticsUploadConfigChangedAsync("t1", null, disable, "ga@x", UpdateTenantConfigurationFunction.CollectLogsSource);
await service.RecordDiagnosticsUploadConfigChangedAsync("t1", null, disable, "ga@x", PatchTenantConfigurationFieldsFunction.CollectLogsSource);
Assert.Equal("DiagnosticsUploadDisabled", Assert.Single(saved).EventType);
}
@@ -56,6 +56,19 @@ public class ConfigBackupHookTests
Upserts.Add(e);
return Task.FromResult(Mock.Of<Response>());
});
Table.Setup(c => c.AddEntityAsync(It.IsAny<TableEntity>(), It.IsAny<CancellationToken>()))
.Returns<TableEntity, CancellationToken>((e, _) =>
{
Upserts.Add(e);
return Task.FromResult(Mock.Of<Response>());
});
Table.Setup(c => c.UpdateEntityAsync(
It.IsAny<TableEntity>(), It.IsAny<ETag>(), It.IsAny<TableUpdateMode>(), It.IsAny<CancellationToken>()))
.Returns<TableEntity, ETag, TableUpdateMode, CancellationToken>((e, _, _, _) =>
{
Upserts.Add(e);
return Task.FromResult(Mock.Of<Response>());
});
var serviceClient = new Mock<TableServiceClient>();
serviceClient.Setup(c => c.GetTableClient(It.IsAny<string>())).Returns(Table.Object);
@@ -102,13 +115,13 @@ public class ConfigBackupHookTests
.Callback<ConfigBackupEntry, CancellationToken>((e, _) => snapshot = e)
.Returns(Task.CompletedTask);
var saved = await harness.Sut.SaveTenantConfigurationAsync(incoming, "portal-put", "test change");
var saved = await harness.Sut.TryReplaceTenantConfigurationAsync(incoming, "\"etag\"", "api-patch", "test change");
Assert.True(saved);
Assert.Single(harness.Upserts); // the config row itself
Assert.NotNull(snapshot);
Assert.Equal(TenantId, snapshot!.PartitionKey);
Assert.Equal("portal-put", snapshot.Source);
Assert.Equal("api-patch", snapshot.Source);
Assert.Equal("test change", snapshot.Reason);
Assert.Equal("ga@operator.example", snapshot.ChangedBy); // identity about to write
// The snapshot holds the STORED row (retention 30), not the incoming one.
@@ -123,11 +136,11 @@ public class ConfigBackupHookTests
}
[Fact]
public async Task RowCreation_NoExistingRow_NoSnapshot()
public async Task RowCreation_ConditionalInsert_NoSnapshot()
{
var harness = new Harness(stored: null);
var saved = await harness.Sut.SaveTenantConfigurationAsync(StoredConfig(), "portal-put", null);
var saved = await harness.Sut.TryCreateTenantConfigurationAsync(StoredConfig());
Assert.True(saved);
Assert.Single(harness.Upserts);
@@ -137,6 +150,16 @@ public class ConfigBackupHookTests
b => b.PruneAsync(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<CancellationToken>()), Times.Never);
}
[Fact]
public async Task RowCreation_RowAlreadyExists_ReturnsFalse()
{
var harness = new Harness(stored: null);
harness.Table.Setup(c => c.AddEntityAsync(It.IsAny<TableEntity>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new RequestFailedException(409, "Conflict", "EntityAlreadyExists", null));
Assert.False(await harness.Sut.TryCreateTenantConfigurationAsync(StoredConfig()));
}
[Fact]
public async Task NoiseOnlyChange_AuthClientIdFlip_NoSnapshot()
{
@@ -150,7 +173,7 @@ public class ConfigBackupHookTests
incoming.LastUpdated = DateTime.UtcNow;
incoming.UpdatedBy = "System (auth)";
var saved = await harness.Sut.SaveTenantConfigurationAsync(incoming, "auth", null);
var saved = await harness.Sut.TryReplaceTenantConfigurationAsync(incoming, "\"etag\"", "auth", null);
Assert.True(saved); // the save itself still goes through
Assert.Single(harness.Upserts);
@@ -164,7 +187,7 @@ public class ConfigBackupHookTests
var stored = StoredConfig();
var harness = new Harness(TableConfigRepository.ConvertToTenantTableEntity(stored));
var saved = await harness.Sut.SaveTenantConfigurationAsync(RoundtripClone(stored), "portal-put", null);
var saved = await harness.Sut.TryReplaceTenantConfigurationAsync(RoundtripClone(stored), "\"etag\"", "api-patch", null);
Assert.True(saved);
harness.Backup.Verify(
@@ -183,14 +206,14 @@ public class ConfigBackupHookTests
var incoming = RoundtripClone(stored);
incoming.DataRetentionDays = 90;
var saved = await harness.Sut.SaveTenantConfigurationAsync(incoming, "portal-put", null);
var saved = await harness.Sut.TryReplaceTenantConfigurationAsync(incoming, "\"etag\"", "api-patch", null);
Assert.True(saved);
Assert.Single(harness.Upserts); // the config write went through regardless
}
[Fact]
public async Task LegacyOneArgOverload_StillSnapshots_WithUnknownSource()
public async Task NoSource_StillSnapshots_WithUnknownSource()
{
var stored = StoredConfig();
var harness = new Harness(TableConfigRepository.ConvertToTenantTableEntity(stored));
@@ -203,7 +226,7 @@ public class ConfigBackupHookTests
var incoming = RoundtripClone(stored);
incoming.DataRetentionDays = 90;
await harness.Sut.SaveTenantConfigurationAsync(incoming);
await harness.Sut.TryReplaceTenantConfigurationAsync(incoming, "\"etag\"", null, null);
Assert.NotNull(snapshot);
Assert.Equal("unknown", snapshot!.Source);
@@ -225,15 +248,11 @@ public class ConfigBackupHookTests
.Callback<ConfigBackupEntry, CancellationToken>((e, _) => snapshot = e)
.Returns(Task.CompletedTask);
var incoming = new AdminConfiguration
{
UpdatedBy = "ga@operator.example",
GlobalRateLimitRequestsPerMinute = 200,
};
var result = await harness.Sut.UpdateAdminConfigurationAsync(
c => { c.GlobalRateLimitRequestsPerMinute = 200; return null; }, "ga@operator.example");
var saved = await harness.Sut.SaveAdminConfigurationAsync(incoming);
Assert.True(saved);
Assert.Null(result.Error);
Assert.Equal(new[] { "GlobalRateLimitRequestsPerMinute" }, result.ChangedColumns);
Assert.NotNull(snapshot);
Assert.Equal("GlobalConfig", snapshot!.PartitionKey);
Assert.Equal("admin-config", snapshot.Source);
@@ -0,0 +1,132 @@
using AutopilotMonitor.Functions.DataAccess.TableStorage;
using AutopilotMonitor.Functions.Functions.Admin;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.DataAccess;
using AutopilotMonitor.Shared.Models;
using Moq;
namespace AutopilotMonitor.Functions.Tests;
internal static class ConfigRepoMockExtensions
{
/// <summary>
/// Asserts that no tenant configuration row was created or replaced — the only two ways the
/// repository can write one (D-290).
/// </summary>
public static void VerifyNoTenantConfigWrite(this Mock<IConfigRepository> repo)
{
repo.Verify(r => r.TryCreateTenantConfigurationAsync(It.IsAny<TenantConfiguration>()), Times.Never);
repo.Verify(r => r.TryReplaceTenantConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string>()), Times.Never);
repo.Verify(r => r.TryReplaceTenantConfigurationAsync(
It.IsAny<TenantConfiguration>(), It.IsAny<string>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
}
/// <summary>
/// Backs <see cref="TenantConfigurationService.UpdateAsync"/> and
/// <see cref="TenantConfigurationService.CreateOrUpdateAsync"/> of a service mock with one stored row
/// and the real contract: the mutation sees a fresh copy (never the caller's object), the offboarding
/// tombstone is refused, a declined mutation writes nothing, and every write is recorded.
/// </summary>
public static StoredTenantConfig StubWrites(this Mock<TenantConfigurationService> service, string tenantId, TenantConfiguration? row)
{
var store = new StoredTenantConfig { Row = row };
Task<TenantConfigUpdate> Run(Func<TenantConfiguration, bool> mutate, string source, string reason, bool createIfMissing)
{
if (store.Force is { } forced)
return Task.FromResult(new TenantConfigUpdate(forced, null));
if (store.ThrowOnRead is { } ex)
throw ex;
TenantConfiguration fresh;
if (store.Row == null)
{
if (!createIfMissing)
return Task.FromResult(new TenantConfigUpdate(TenantConfigUpdateStatus.NotFound, null));
fresh = TenantConfiguration.CreateDefault(tenantId);
}
else
{
fresh = Clone(store.Row);
if (TenantOffboardFunction.IsOffboardingTombstone(fresh))
return Task.FromResult(new TenantConfigUpdate(TenantConfigUpdateStatus.OffboardingInProgress, fresh));
}
if (!mutate(fresh))
return Task.FromResult(new TenantConfigUpdate(TenantConfigUpdateStatus.Declined, fresh));
fresh.LastUpdated = DateTime.UtcNow;
store.Row = fresh;
store.Writes.Add((fresh, source, reason));
return Task.FromResult(new TenantConfigUpdate(TenantConfigUpdateStatus.Updated, fresh));
}
service.Setup(x => x.UpdateAsync(tenantId, It.IsAny<Func<TenantConfiguration, bool>>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns((string _, Func<TenantConfiguration, bool> mutate, string source, string reason) => Run(mutate, source, reason, false));
service.Setup(x => x.CreateOrUpdateAsync(tenantId, It.IsAny<Func<TenantConfiguration, bool>>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns((string _, Func<TenantConfiguration, bool> mutate, string source, string reason) => Run(mutate, source, reason, true));
return store;
}
/// <summary>
/// Backs the tenant-configuration reads and writes of a repository mock with one stored row and
/// the storage contract: every read hands back a fresh copy, the replace succeeds only with the
/// current ETag, the insert only while no row exists, and every write is recorded.
/// </summary>
public static StoredTenantConfig BackWithRow(this Mock<IConfigRepository> repo, TenantConfiguration? row)
{
var store = new StoredTenantConfig { Row = row };
var version = 0;
string ETag() => $"etag-{version}";
TenantConfiguration? Read()
{
if (store.ThrowOnRead is { } ex) throw ex;
return store.Row == null ? null : Clone(store.Row);
}
bool Write(TenantConfiguration config, string source, string reason)
{
if (store.ThrowOnWrite is { } ex) throw ex;
if (store.RejectWrites) return false;
store.Row = Clone(config);
version++;
store.Writes.Add((store.Row, source, reason));
return true;
}
repo.Setup(r => r.GetTenantConfigurationAsync(It.IsAny<string>())).ReturnsAsync(() => Read());
repo.Setup(r => r.GetTenantConfigurationWithEtagAsync(It.IsAny<string>()))
.ReturnsAsync(() => Read() is { } fresh ? (fresh, ETag()) : null);
repo.Setup(r => r.TryReplaceTenantConfigurationAsync(
It.IsAny<TenantConfiguration>(), It.IsAny<string>(), It.IsAny<string?>(), It.IsAny<string?>()))
.ReturnsAsync((TenantConfiguration c, string etag, string? source, string? reason) =>
store.Row != null && etag == ETag() && Write(c, source ?? "", reason ?? ""));
repo.Setup(r => r.TryCreateTenantConfigurationAsync(It.IsAny<TenantConfiguration>()))
.ReturnsAsync((TenantConfiguration c) => store.Row == null && Write(c, "(create)", ""));
return store;
}
/// <summary>A storage round trip: what a fresh read of the stored row hands back.</summary>
public static TenantConfiguration Clone(TenantConfiguration config)
=> TableConfigRepository.ConvertFromTenantTableEntity(TableConfigRepository.ConvertToTenantTableEntity(config));
}
/// <summary>The stored row behind <see cref="ConfigRepoMockExtensions.StubWrites"/> and what was written to it.</summary>
internal sealed class StoredTenantConfig
{
public TenantConfiguration? Row { get; set; }
public List<(TenantConfiguration Row, string Source, string Reason)> Writes { get; } = new();
/// <summary>When set, every write returns this status without touching the row (e.g. Conflict).</summary>
public TenantConfigUpdateStatus? Force { get; set; }
/// <summary>When set, every read (and, for the service stub, every write) throws it — a storage outage.</summary>
public Exception? ThrowOnRead { get; set; }
/// <summary>Repository double only: when set, every write throws it.</summary>
public Exception? ThrowOnWrite { get; set; }
/// <summary>Repository double only: every conditional write loses (as if a concurrent writer always won).</summary>
public bool RejectWrites { get; set; }
}
@@ -713,31 +713,6 @@ public class ConfigWireParityTests
// ---- UpdateTenantConfiguration -------------------------------------------------------
[Fact]
public void UpdateTenantConfigurationResponse_matches_the_ack_plus_config_shape()
{
var config = new TenantConfiguration
{
TenantId = "6a6a35a2-30b2-4f2f-9a1b-6d9f1a2b3c4d",
DomainName = "contoso.com",
UpdatedBy = "admin@contoso.com",
};
AssertParity(
new
{
success = true,
message = "Configuration updated successfully",
config = config
},
new UpdateTenantConfigurationResponse
{
Success = true,
Message = "Configuration updated successfully",
Config = config
});
}
private static void AssertParity(object anonymousLiteral, IApiResponse typed)
=> ApiResponseWireParityTests.AssertWireIdentical(anonymousLiteral, typed);
}
@@ -74,8 +74,7 @@ public class CrossTenantAccessTests
[Theory]
[InlineData("GET", "/api/config/{0}")]
[InlineData("PUT", "/api/config/{0}")]
[InlineData("POST", "/api/config/{0}")]
[InlineData("PATCH", "/api/config/{0}/fields")]
[InlineData("GET", "/api/config/{0}/feature-flags")]
[InlineData("GET", "/api/tenants/{0}/admins")]
[InlineData("POST", "/api/tenants/{0}/admins")]
@@ -96,8 +95,7 @@ public class CrossTenantAccessTests
[Theory]
[InlineData("GET", "/api/config/{0}")]
[InlineData("PUT", "/api/config/{0}")]
[InlineData("POST", "/api/config/{0}")]
[InlineData("PATCH", "/api/config/{0}/fields")]
[InlineData("GET", "/api/config/{0}/feature-flags")]
[InlineData("GET", "/api/tenants/{0}/admins")]
[InlineData("POST", "/api/tenants/{0}/admins")]
@@ -118,7 +116,7 @@ public class CrossTenantAccessTests
[Theory]
[InlineData("GET", "/api/config/{0}")]
[InlineData("PUT", "/api/config/{0}")]
[InlineData("PATCH", "/api/config/{0}/fields")]
[InlineData("GET", "/api/tenants/{0}/admins")]
[InlineData("DELETE", "/api/tenants/{0}/offboard")]
public void CrossTenant_GlobalAdmin_IsAllowed(string httpMethod, string pathTemplate)
@@ -526,7 +526,41 @@ public class DelegationSelfServiceTests
Assert.Equal(Now.AddDays(-3), owned.SinceUtc);
var direct = managers.Single(m => m.GroupId == null);
Assert.Equal(DelegationSelfService.SourceOperator, direct.Source);
Assert.Equal(DelegationSelfService.OperatorLabel, direct.Name);
Assert.False(direct.Revocable);
Assert.Single(direct.Assignees); // the revoked row confers nothing
}
[Fact]
public async Task ListManagers_OperatorGroup_ShowsNeutralLabelNotItsName_ButItsAssignees()
{
const string operatorGroupId = "0f1e2d3c4b5a69788796a5b4c3d2e1f0";
var h = Build();
h.Repo.Setup(x => x.GetGroupIdsContainingTenantAsync(Customer)).ReturnsAsync(new List<string> { operatorGroupId });
h.Repo.Setup(x => x.GetTenantGroupAsync(operatorGroupId)).ReturnsAsync(new TenantGroup
{
GroupId = operatorGroupId,
Name = "Internal MSP customers north",
OwnerTenantId = null,
TenantIds = new List<string> { Customer, Other },
Assignees = new List<TenantGroupAssignment>
{
new() { Upn = "ops@vendor.example", GroupId = operatorGroupId, Role = Constants.DelegatedRoles.DelegatedReader, IsEnabled = true },
new() { Upn = "ops2@vendor.example", GroupId = operatorGroupId, Role = Constants.DelegatedRoles.DelegatedReader, IsEnabled = true },
},
});
var managers = await h.Svc.ListManagersAsync(Customer);
var group = Assert.Single(managers);
Assert.Equal(operatorGroupId, group.GroupId);
Assert.Equal(DelegationSelfService.OperatorLabel, group.Name);
Assert.DoesNotContain("north", group.Name, StringComparison.OrdinalIgnoreCase);
Assert.Null(group.OwnerTenantId);
Assert.Null(group.OwnerDomain);
Assert.Null(group.SinceUtc);
Assert.Equal(DelegationSelfService.SourceOperator, group.Source);
Assert.False(group.Revocable);
Assert.Equal(2, group.Assignees.Count);
}
}
@@ -194,7 +194,7 @@ public class DelegationWireParityTests
managers = new object[]
{
new { groupId = (string?)("msp-" + Home), ownerTenantId = (string?)Home, ownerDomain = (string?)"partner.example", name = "Customers of partner.example", source = "self-service", assignees, sinceUtc = (DateTime?)since, revocable = true },
new { groupId = nullGroup, ownerTenantId = nullOwner, ownerDomain = nullDomain, name = "Platform operators", source = "operator", assignees, sinceUtc = (DateTime?)null, revocable = false },
new { groupId = nullGroup, ownerTenantId = nullOwner, ownerDomain = nullDomain, name = "Platform support", source = "operator", assignees, sinceUtc = (DateTime?)null, revocable = false },
},
},
new TenantManagerListResponse
@@ -204,7 +204,7 @@ public class DelegationWireParityTests
{
new() { GroupId = "msp-" + Home, OwnerTenantId = Home, OwnerDomain = "partner.example", Name = "Customers of partner.example", Source = "self-service",
Assignees = new List<TenantManagerAssignee> { new() { Upn = "analyst@partner.example", Role = "DelegatedReader", IsEnabled = true } }, SinceUtc = since, Revocable = true },
new() { Name = "Platform operators", Source = "operator",
new() { Name = "Platform support", Source = "operator",
Assignees = new List<TenantManagerAssignee> { new() { Upn = "analyst@partner.example", Role = "DelegatedReader", IsEnabled = true } }, Revocable = false },
},
});
@@ -32,24 +32,28 @@ public sealed class EmailServiceTests
// ----- configuration gates -----
[Fact]
public async Task SendAsync_EmptyApiKey_NoOps_AndLogsMissingKeyDebugLine()
public async Task SendAsync_EmptyApiKey_NoOps_ReturnsFalse_AndLogsMissingKeyWarning()
{
var (sut, handler, logger) = Build(apiKey: "");
await sut.SendAsync("ops@contoso.invalid", "contoso.invalid", TenantId, CancellationToken.None);
var sent = await sut.SendAsync("ops@contoso.invalid", "contoso.invalid", TenantId, CancellationToken.None);
Assert.False(sent);
Assert.Equal(0, handler.CallCount);
// Warning, not Debug: same reasoning as the welcome mail — worker logs below Warning never
// reach Application Insights, and the handler records FarewellEmailFailed on the false.
Assert.Contains(logger.Entries,
e => e.Level == LogLevel.Debug && e.Message.Contains("Email:ApiKey not configured"));
e => e.Level == LogLevel.Warning && e.Message.Contains("Email:ApiKey not configured"));
}
[Fact]
public async Task SendAsync_EmptyRecipient_NoOps_AndLogsMissingEmailDebugLine()
public async Task SendAsync_EmptyRecipient_NoOps_ReturnsFalse_AndLogsMissingEmailDebugLine()
{
var (sut, handler, logger) = Build(apiKey: "any-non-empty-key");
await sut.SendAsync("", "contoso.invalid", TenantId);
var sent = await sut.SendAsync("", "contoso.invalid", TenantId);
Assert.False(sent);
Assert.Equal(0, handler.CallCount);
Assert.Contains(logger.Entries,
e => e.Level == LogLevel.Debug && e.Message.Contains("No notification email captured"));
@@ -65,7 +69,7 @@ public sealed class EmailServiceTests
await sut.SendAsync("", "contoso.invalid", TenantId);
Assert.Contains(logger.Entries,
e => e.Level == LogLevel.Debug && e.Message.Contains("Email:ApiKey not configured"));
e => e.Level == LogLevel.Warning && e.Message.Contains("Email:ApiKey not configured"));
Assert.DoesNotContain(logger.Entries,
e => e.Message.Contains("No notification email captured"));
}
@@ -123,8 +127,9 @@ public sealed class EmailServiceTests
{
var (sut, handler, logger) = Build(apiKey: "md-test-key");
await sut.SendAsync("ops@contoso.invalid", "contoso.invalid", TenantId);
var sent = await sut.SendAsync("ops@contoso.invalid", "contoso.invalid", TenantId);
Assert.True(sent);
using var doc = JsonDocument.Parse(handler.LastBody!);
var message = doc.RootElement.GetProperty("message");
Assert.Equal(EmailTemplates.OffboardingFarewellSubject, message.GetProperty("subject").GetString());
@@ -161,8 +166,9 @@ public sealed class EmailServiceTests
responder: _ => Json(HttpStatusCode.InternalServerError,
"{\"status\":\"error\",\"code\":-1,\"name\":\"Invalid_Key\",\"message\":\"Invalid API key\"}"));
await sut.SendAsync("ops@contoso.invalid", "contoso.invalid", TenantId);
var sent = await sut.SendAsync("ops@contoso.invalid", "contoso.invalid", TenantId);
Assert.False(sent);
Assert.Contains(logger.Entries,
e => e.Level == LogLevel.Warning && e.Message.Contains("500") && e.Message.Contains("Invalid_Key"));
Assert.DoesNotContain(logger.Entries, e => e.Level == LogLevel.Information);
@@ -175,8 +181,9 @@ public sealed class EmailServiceTests
responder: _ => Json(HttpStatusCode.OK,
"[{\"email\":\"ops@contoso.invalid\",\"status\":\"rejected\",\"reject_reason\":\"hard-bounce\",\"_id\":\"abc\"}]"));
await sut.SendAsync("ops@contoso.invalid", "contoso.invalid", TenantId);
var sent = await sut.SendAsync("ops@contoso.invalid", "contoso.invalid", TenantId);
Assert.False(sent);
Assert.Contains(logger.Entries,
e => e.Level == LogLevel.Warning && e.Message.Contains("rejected") && e.Message.Contains("hard-bounce"));
Assert.DoesNotContain(logger.Entries, e => e.Level == LogLevel.Information);
@@ -192,8 +199,9 @@ public sealed class EmailServiceTests
responder: _ => Json(HttpStatusCode.OK,
$"[{{\"email\":\"ops@contoso.invalid\",\"status\":\"{status}\",\"_id\":\"abc\"}}]"));
await sut.SendAsync("ops@contoso.invalid", "contoso.invalid", TenantId);
var sent = await sut.SendAsync("ops@contoso.invalid", "contoso.invalid", TenantId);
Assert.True(sent);
Assert.Contains(logger.Entries, e => e.Level == LogLevel.Information);
Assert.DoesNotContain(logger.Entries, e => e.Level == LogLevel.Warning);
}
@@ -204,8 +212,9 @@ public sealed class EmailServiceTests
var (sut, _, logger) = Build(apiKey: "md-test-key",
responder: _ => Json(HttpStatusCode.OK, "not json"));
await sut.SendAsync("ops@contoso.invalid", "contoso.invalid", TenantId);
var sent = await sut.SendAsync("ops@contoso.invalid", "contoso.invalid", TenantId);
Assert.False(sent);
Assert.Contains(logger.Entries, e => e.Level == LogLevel.Warning);
Assert.DoesNotContain(logger.Entries, e => e.Level == LogLevel.Information);
}
@@ -0,0 +1,74 @@
using System.Net;
using System.Text;
using System.Text.Json;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Shared;
using Azure.Core.Serialization;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.DependencyInjection;
using Moq;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// Minimal HTTP endpoint harness: a mocked <see cref="HttpRequestData"/> whose FunctionContext carries the
/// <see cref="RequestContext"/> the policy middleware would have resolved, serialized with the production
/// wire settings.
/// </summary>
internal static class EndpointHarness
{
public static (HttpRequestData Req, FunctionContext Context) Request(
string tenantId, string upn = "admin@contoso.com", string? jsonBody = null, string queryString = "",
IDictionary<string, string>? headers = null)
{
var services = new ServiceCollection();
services.AddOptions();
services.Configure<WorkerOptions>(o => o.Serializer = new JsonObjectSerializer(ApiJsonOptions.Create()));
var provider = services.BuildServiceProvider();
var items = new Dictionary<object, object>
{
["RequestContext"] = new RequestContext
{
TenantId = tenantId,
TargetTenantId = tenantId,
UserPrincipalName = upn,
IsTenantAdmin = true,
UserRole = Constants.TenantRoles.Admin,
},
};
var context = new Mock<FunctionContext>();
context.SetupGet(c => c.Items).Returns(items);
context.SetupGet(c => c.InstanceServices).Returns(provider);
var req = new Mock<HttpRequestData>(context.Object);
var headerCollection = new HttpHeadersCollection();
foreach (var (name, value) in headers ?? new Dictionary<string, string>())
headerCollection.Add(name, value);
req.SetupGet(r => r.Headers).Returns(headerCollection);
// Query parses the Url in the base class (a bare mock would hand back null).
req.SetupGet(r => r.Url).Returns(new Uri("https://localhost/api/test" + queryString));
req.SetupGet(r => r.Query).CallBase();
req.SetupGet(r => r.Body).Returns(new MemoryStream(Encoding.UTF8.GetBytes(jsonBody ?? "")));
req.Setup(r => r.CreateResponse()).Returns(() => new FakeResponse(context.Object));
return (req.Object, context.Object);
}
/// <summary>The <c>code</c> of an error envelope; null when the body carries none.</summary>
public static string? ErrorCode(HttpResponseData response)
{
response.Body.Position = 0;
using var doc = JsonDocument.Parse(response.Body);
return doc.RootElement.TryGetProperty("code", out var code) ? code.GetString() : null;
}
private sealed class FakeResponse : HttpResponseData
{
public FakeResponse(FunctionContext context) : base(context) { }
public override HttpStatusCode StatusCode { get; set; } = HttpStatusCode.OK;
public override HttpHeadersCollection Headers { get; set; } = new();
public override Stream Body { get; set; } = new MemoryStream();
public override HttpCookies Cookies { get; } = new Mock<HttpCookies>().Object;
}
}
@@ -156,14 +156,17 @@ public class EndpointPolicyCatalogCompletenessTests
public void SameRoute_DifferentMethods_ResolveToDifferentPolicies()
{
var getConfig = EndpointAccessPolicyCatalog.FindPolicy("GET", "/api/config/tenant-1");
var putConfig = EndpointAccessPolicyCatalog.FindPolicy("PUT", "/api/config/tenant-1");
var patchConfig = EndpointAccessPolicyCatalog.FindPolicy("PATCH", "/api/config/tenant-1/fields");
Assert.NotNull(getConfig);
Assert.NotNull(putConfig);
Assert.NotNull(patchConfig);
// GET config read is member-tier (Operators/Viewers get the redacted read-only Settings
// view; the handler redacts for every non-admin caller); PUT config write stays Admin/GA only.
// view; the handler redacts for every non-admin caller); the field PATCH stays Admin/GA only.
Assert.Equal(EndpointPolicy.MemberRead, getConfig.Policy);
Assert.Equal(EndpointPolicy.TenantAdminOrGA, putConfig.Policy);
Assert.Equal(EndpointPolicy.TenantAdminOrGA, patchConfig.Policy);
// There is no full-model write of the tenant configuration (D-290).
Assert.Null(EndpointAccessPolicyCatalog.FindPolicy("PUT", "/api/config/tenant-1"));
Assert.Null(EndpointAccessPolicyCatalog.FindPolicy("POST", "/api/config/tenant-1"));
var getRules = EndpointAccessPolicyCatalog.FindPolicy("GET", "/api/rules/gather");
var postRules = EndpointAccessPolicyCatalog.FindPolicy("POST", "/api/rules/gather");
@@ -237,6 +240,22 @@ public class EndpointPolicyCatalogCompletenessTests
string.Join("\n", missing.Select(m => $" - {m}")));
}
/// <summary>
/// AllowedDuringOffboarding punches a hole in the tenant suspension gate (offboarding tombstone only).
/// It exists for exactly one route — the farewell feedback a departing admin submits after the offboard
/// endpoint has already tombstoned their tenant. Any second route here needs the same justification.
/// </summary>
[Fact]
public void AllowedDuringOffboarding_IsOnlyTheFarewellFeedbackRoute()
{
var routes = EndpointAccessPolicyCatalog.Entries
.Where(e => e.AllowedDuringOffboarding)
.Select(e => $"{e.HttpMethod} {e.RouteTemplate}")
.ToList();
Assert.Equal(new[] { "POST tenants/{tenantId}/offboard/feedback" }, routes);
}
/// <summary>
/// Every entry with TenantScoping.RouteParam must have {tenantId} in its route template.
/// Prevents misattributed scoping declarations.

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