mirror of
https://github.com/okieselbach/AutopilotMonitor.git
synced 2026-10-25 13:10:13 +00:00
Compare commits
113 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5a182f3f16 | |||
| 889b843d6d | |||
| 9b91119239 | |||
| 1e74d67da9 | |||
| ed013bbdda | |||
| 4b40619d1d | |||
| 3ce1f2b036 | |||
| 673f045212 | |||
| df640e3684 | |||
| 59bea9d888 | |||
| e2c91afda2 | |||
| eb47c4d69a | |||
| 91d56f2bbb | |||
| 12b847360c | |||
| 2e736f40ad | |||
| 9c3e5ecb30 | |||
| 27ce316206 | |||
| 7280b61d28 | |||
| 79f1ecd378 | |||
| b6791d37e0 | |||
| 4f1b4f8c03 | |||
| 869580c9df | |||
| 1a96cd20da | |||
| 8e637cf86a | |||
| 93c6e1facb | |||
| 4a4bbc056a | |||
| c59b366560 | |||
| d0aded5401 | |||
| 8f9c683b7c | |||
| e82878af57 | |||
| d60e858e95 | |||
| f6ce9ae0a0 | |||
| b4f26401f5 | |||
| 2b5004fb33 | |||
| 00f4cb1f26 | |||
| e091e50862 | |||
| 27ce07b111 | |||
| f06fe5afc0 | |||
| 37e920237c | |||
| 7279650772 | |||
| d8ab70b166 | |||
| fb8703a4c6 | |||
| ac3fa8b2b6 | |||
| efcb4f9ca1 | |||
| 7a7a31e8e3 | |||
| 3fdcbabd48 | |||
| b2e8c7627f | |||
| bd08d13011 | |||
| 10c69f592e | |||
| fe0b2dc7fe | |||
| a0f007fd43 | |||
| 1b27babd17 | |||
| 100d2242fa | |||
| 089b1b38fd | |||
| ac465839a5 | |||
| ef280b7bb5 | |||
| 233737f333 | |||
| 909904e928 | |||
| 59ab47de8c | |||
| f252a0709f | |||
| d6d9638981 | |||
| 020248fbda | |||
| a06a0dbfff | |||
| 96c24e0688 | |||
| c156350183 | |||
| 15b25ff509 | |||
| 5163d7d6a0 | |||
| 9fd343d328 | |||
| aef88f3337 | |||
| 12af1d6c76 | |||
| 5433bff3db | |||
| 355509aa7c | |||
| 7fb78a7e29 | |||
| bfd8d58142 | |||
| 8ad472d1bc | |||
| fc5e2cd751 | |||
| 9540791441 | |||
| 058da1627f | |||
| cb9b3fe404 | |||
| 12315b2f2d | |||
| 0a4a051866 | |||
| f47d961947 | |||
| c701d0d694 | |||
| d4a3edf849 | |||
| e164eac1eb | |||
| c81591b498 | |||
| d8c03d9d95 | |||
| ffb133f0b9 | |||
| b3fe321f0d | |||
| 69d210c51d | |||
| 06a88e9897 | |||
| aee30f68e8 | |||
| 3db9a884de | |||
| 0037b8cb12 | |||
| 205b13dbb9 | |||
| b938a03367 | |||
| d474c2be9f | |||
| 96390beeb9 | |||
| fe63a0a352 | |||
| 2e36e9c234 | |||
| b83aa6d97d | |||
| f42fcbcb3c | |||
| f70ba354f8 | |||
| fc17047290 | |||
| 7bbc2cbddf | |||
| 9a78daa880 | |||
| 5d532d3dbc | |||
| a22c26eb9d | |||
| b84c467255 | |||
| 53124e94a6 | |||
| 838068fd31 | |||
| 71282f3556 | |||
| 7080dcc45a |
@@ -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
|
||||
|
||||
+1
-1
Submodule .claude/commands updated: 01a067ad9b...a3bfa8983a
@@ -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
|
||||
|
||||
@@ -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: ['*']
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 }}
|
||||
|
||||
@@ -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 }}
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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 }}
|
||||
|
||||
@@ -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: |
|
||||
|
||||
@@ -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 }}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,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
|
||||
|
||||
@@ -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 }}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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: 742249e7e3...be0165a223
+1
-1
Submodule internal updated: a5d4e0da0f...22e709ef72
@@ -300,6 +300,7 @@
|
||||
"script_completed",
|
||||
"script_failed",
|
||||
"script_timeout_suspected",
|
||||
"script_recurrence_summary",
|
||||
"esp_phase_changed",
|
||||
"ime_agent_version",
|
||||
"ime_token_failure",
|
||||
|
||||
@@ -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
|
||||
Generated
+315
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
using System;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Gather
|
||||
{
|
||||
/// <summary>
|
||||
/// A configured diagnostics entry is resolved to the folder and pattern that get
|
||||
/// enumerated, and the guard judges exactly that folder. The cases below pin the
|
||||
/// property that matters: no spelling of an allowed entry ever selects its parent.
|
||||
/// </summary>
|
||||
public sealed class DiagnosticsPathGuardsTests
|
||||
{
|
||||
private const string TestProfile = @"C:\Users\TestUser";
|
||||
|
||||
private static readonly Func<string, bool> IsDirectory = _ => true;
|
||||
private static readonly Func<string, bool> IsNotDirectory = _ => false;
|
||||
|
||||
private static DiagnosticsPathGuards.CollectionTarget Resolve(
|
||||
string path,
|
||||
bool includeSubfolders = false,
|
||||
bool unrestrictedMode = false,
|
||||
string? userProfilePath = null,
|
||||
Func<string, bool>? directoryExists = null)
|
||||
{
|
||||
Assert.True(DiagnosticsPathGuards.TryResolveCollectionTarget(
|
||||
path, includeSubfolders, unrestrictedMode, userProfilePath!, directoryExists ?? IsDirectory, out var target));
|
||||
return target;
|
||||
}
|
||||
|
||||
private static void AssertRefused(
|
||||
string path,
|
||||
bool unrestrictedMode = false,
|
||||
string? userProfilePath = null,
|
||||
Func<string, bool>? directoryExists = null)
|
||||
{
|
||||
Assert.False(DiagnosticsPathGuards.TryResolveCollectionTarget(
|
||||
path, true, unrestrictedMode, userProfilePath!, directoryExists ?? IsDirectory, out var target));
|
||||
Assert.Null(target);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ folder entries
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"C:\Windows\Logs")]
|
||||
[InlineData(@"C:\Windows\Logs\")]
|
||||
[InlineData(@"C:\Windows\SetupDiag")]
|
||||
[InlineData(@"C:\ProgramData\AutopilotMonitor")]
|
||||
[InlineData(@"C:\ProgramData\Microsoft\DiagnosticLogCSP")]
|
||||
public void Folder_entry_collects_from_itself_never_from_its_parent(string configured)
|
||||
{
|
||||
var target = Resolve(configured, includeSubfolders: true);
|
||||
|
||||
Assert.Equal(configured.TrimEnd('\\'), target.Folder, ignoreCase: true);
|
||||
Assert.Equal("*", target.Pattern);
|
||||
Assert.True(target.Recurse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Trailing_separator_means_folder_even_when_the_folder_does_not_exist_yet()
|
||||
{
|
||||
var target = Resolve(@"C:\Windows\Logs\NotThereYet\", directoryExists: IsNotDirectory);
|
||||
|
||||
Assert.Equal(@"C:\Windows\Logs\NotThereYet", target.Folder, ignoreCase: true);
|
||||
Assert.Equal("*", target.Pattern);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Folder_name_with_a_dot_is_still_a_folder()
|
||||
{
|
||||
var target = Resolve(@"C:\Windows\Logs\vendor.v2");
|
||||
|
||||
Assert.Equal(@"C:\Windows\Logs\vendor.v2", target.Folder, ignoreCase: true);
|
||||
Assert.Equal("*", target.Pattern);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ wildcard entries
|
||||
|
||||
[Fact]
|
||||
public void Wildcard_entry_collects_the_pattern_from_its_validated_parent()
|
||||
{
|
||||
var target = Resolve(@"C:\Windows\Panther\*.log", includeSubfolders: true);
|
||||
|
||||
Assert.Equal(@"C:\Windows\Panther", target.Folder, ignoreCase: true);
|
||||
Assert.Equal("*.log", target.Pattern);
|
||||
Assert.True(target.Recurse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wildcard_beside_an_allowlisted_file_is_refused()
|
||||
{
|
||||
// Only ReportingEvents.log is on the allowlist, not the folder it lives in.
|
||||
AssertRefused(@"C:\Windows\SoftwareDistribution\*.log");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ file entries
|
||||
|
||||
[Fact]
|
||||
public void File_entry_never_recurses_because_its_folder_was_not_validated()
|
||||
{
|
||||
var target = Resolve(
|
||||
@"C:\Windows\SoftwareDistribution\ReportingEvents.log",
|
||||
includeSubfolders: true,
|
||||
directoryExists: IsNotDirectory);
|
||||
|
||||
Assert.Equal(@"C:\Windows\SoftwareDistribution", target.Folder, ignoreCase: true);
|
||||
Assert.Equal("ReportingEvents.log", target.Pattern);
|
||||
Assert.False(target.Recurse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Missing_path_without_a_dot_is_one_file_name_not_a_wildcard_on_the_parent()
|
||||
{
|
||||
var target = Resolve(@"C:\Windows\Logs\nodot", includeSubfolders: true, directoryExists: IsNotDirectory);
|
||||
|
||||
Assert.Equal(@"C:\Windows\Logs", target.Folder, ignoreCase: true);
|
||||
Assert.Equal("nodot", target.Pattern);
|
||||
Assert.False(target.Recurse);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ refusals
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"C:\Windows")]
|
||||
[InlineData(@"C:\ProgramData")]
|
||||
[InlineData(@"C:\ProgramData\Microsoft")]
|
||||
[InlineData(@"C:\Windows\Logs\..\System32")]
|
||||
[InlineData(@"C:\Windows\LogsEvil")]
|
||||
[InlineData("")]
|
||||
public void Paths_outside_the_allowlist_are_refused(string configured)
|
||||
{
|
||||
AssertRefused(configured);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"C:\Users")]
|
||||
[InlineData(@"C:\Users\TestUser\Documents")]
|
||||
[InlineData(@"C:\Windows\System32\config")]
|
||||
[InlineData(@"C:\Windows\System32\config\*")]
|
||||
public void Hard_blocks_hold_in_unrestricted_mode(string configured)
|
||||
{
|
||||
AssertRefused(configured, unrestrictedMode: true);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ user-profile token
|
||||
|
||||
[Fact]
|
||||
public void Expanded_token_path_outside_AppData_is_refused_even_in_unrestricted_mode()
|
||||
{
|
||||
// The service expands %LOGGED_ON_USER_PROFILE% before the guard sees the path; an
|
||||
// unexpanded token is not under C:\Users lexically and used to slip past the block.
|
||||
AssertRefused(TestProfile + @"\Documents", unrestrictedMode: true, userProfilePath: TestProfile);
|
||||
AssertRefused(TestProfile + @"\Documents\*.txt", unrestrictedMode: true, userProfilePath: TestProfile);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Expanded_token_path_on_the_profile_allowlist_is_admitted_in_restricted_mode()
|
||||
{
|
||||
var target = Resolve(
|
||||
TestProfile + @"\AppData\Local\RealmJoin\Logs\*.log",
|
||||
userProfilePath: TestProfile);
|
||||
|
||||
Assert.Equal(TestProfile + @"\AppData\Local\RealmJoin\Logs", target.Folder, ignoreCase: true);
|
||||
Assert.Equal("*.log", target.Pattern);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Profile_path_without_the_token_stays_blocked()
|
||||
{
|
||||
AssertRefused(TestProfile + @"\AppData\Local\RealmJoin\Logs\*.log", userProfilePath: null);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ recursion guard
|
||||
|
||||
[Theory]
|
||||
[InlineData(@"C:\Users")]
|
||||
[InlineData(@"C:\Users\TestUser")]
|
||||
[InlineData(@"C:\Windows\System32\config")]
|
||||
[InlineData(@"C:\Windows\System32\config\RegBack")]
|
||||
public void Recursion_never_enters_a_hard_blocked_subtree_in_unrestricted_mode(string directory)
|
||||
{
|
||||
Assert.False(DiagnosticsPathGuards.IsDirectoryEnterable(directory, unrestrictedMode: true, userProfilePath: null));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Recursion_enters_ordinary_subfolders()
|
||||
{
|
||||
Assert.True(DiagnosticsPathGuards.IsDirectoryEnterable(@"C:\Windows\System32\drivers", unrestrictedMode: true, userProfilePath: null));
|
||||
Assert.True(DiagnosticsPathGuards.IsDirectoryEnterable(@"C:\Windows\Logs\CBS", unrestrictedMode: false, userProfilePath: null));
|
||||
Assert.False(DiagnosticsPathGuards.IsDirectoryEnterable(@"C:\Windows\System32\drivers", unrestrictedMode: false, userProfilePath: null));
|
||||
}
|
||||
}
|
||||
}
|
||||
+15
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+24
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+40
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+267
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
#nullable enable
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using AutopilotMonitor.Agent.V2.Core.Configuration;
|
||||
using AutopilotMonitor.Agent.V2.Core.Logging;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather;
|
||||
using AutopilotMonitor.Agent.V2.Core.Monitoring.Transport;
|
||||
using AutopilotMonitor.Agent.V2.Core.Tests.Harness;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Runtime
|
||||
{
|
||||
/// <summary>
|
||||
/// The hard-blocked event-log channels (Security, PowerShell, Sysmon) are unreadable through
|
||||
/// the diagnostics package as well — by path, by wildcard, by resolved channel, and in
|
||||
/// unrestricted mode. Before this the block held only in the event-log collector.
|
||||
/// </summary>
|
||||
public sealed class DiagnosticsEventLogBlockTests
|
||||
{
|
||||
private const string WinevtLogs = @"C:\Windows\System32\winevt\Logs";
|
||||
|
||||
// A channel no machine has: the export fails and the packager falls back to the raw copy.
|
||||
private const string HarmlessChannel = "AutopilotMonitor-Tests-NoSuchChannel/Operational";
|
||||
|
||||
[Theory]
|
||||
[InlineData("Security.evtx")]
|
||||
[InlineData("security.EVTX")]
|
||||
[InlineData("Microsoft-Windows-PowerShell%4Operational.evtx")]
|
||||
[InlineData("Microsoft-Windows-PowerShell%4Admin.evtx")]
|
||||
[InlineData("Windows PowerShell.evtx")]
|
||||
[InlineData("Microsoft-Windows-Sysmon%4Operational.evtx")]
|
||||
[InlineData("Archive-Security-2026-09-21-10-15-30-123.evtx")]
|
||||
[InlineData("Archive-Microsoft-Windows-PowerShell%4Operational-2026-09-21-10-15-30-123.evtx")]
|
||||
public void Hard_blocked_channel_files_are_recognised_by_name(string fileName)
|
||||
{
|
||||
Assert.True(DiagnosticsPathGuards.IsHardBlockedEventLogFile(Path.Combine(WinevtLogs, fileName)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("System.evtx")]
|
||||
[InlineData("Application.evtx")]
|
||||
[InlineData("SecurityAudit.evtx")]
|
||||
[InlineData("Security.log")]
|
||||
[InlineData("Microsoft-Windows-Security-Mitigations%4KernelMode.evtx")]
|
||||
// Same boundary as the collector: only '/' continues a blocked channel name.
|
||||
[InlineData("Microsoft-Windows-PowerShell-DesiredStateConfiguration-FileDownloadManager%4Operational.evtx")]
|
||||
[InlineData("Archive-System-2026-09-21-10-15-30-123.evtx")]
|
||||
public void Other_files_are_not_mistaken_for_a_blocked_channel(string fileName)
|
||||
{
|
||||
Assert.False(DiagnosticsPathGuards.IsHardBlockedEventLogFile(Path.Combine(WinevtLogs, fileName)));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void Path_guard_refuses_a_blocked_channel_file_in_every_mode(bool unrestrictedMode)
|
||||
{
|
||||
Assert.False(DiagnosticsPathGuards.IsDiagnosticsPathAllowed(
|
||||
WinevtLogs + @"\Security.evtx", unrestrictedMode));
|
||||
Assert.False(DiagnosticsPathGuards.IsDiagnosticsPathAllowed(
|
||||
WinevtLogs + @"\Microsoft-Windows-PowerShell%4Operational.evtx", unrestrictedMode));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Path_guard_still_admits_other_channels_and_wildcards()
|
||||
{
|
||||
Assert.True(DiagnosticsPathGuards.IsDiagnosticsPathAllowed(WinevtLogs + @"\System.evtx"));
|
||||
// Undecidable on the string — the packager filters per file (tests below).
|
||||
Assert.True(DiagnosticsPathGuards.IsDiagnosticsPathAllowed(WinevtLogs + @"\*.evtx"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Security", true)]
|
||||
[InlineData("Microsoft-Windows-PowerShell/Operational", true)]
|
||||
[InlineData(" Windows PowerShell ", true)]
|
||||
[InlineData("Microsoft-Windows-Sysmon/Operational", true)]
|
||||
[InlineData("System", false)]
|
||||
[InlineData("", false)]
|
||||
[InlineData(null, false)]
|
||||
public void Channel_block_is_one_matcher_for_collector_and_package(string? channel, bool blocked)
|
||||
{
|
||||
Assert.Equal(blocked, GatherRuleGuards.IsHardBlockedEventLogChannel(channel!));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ packager ----
|
||||
|
||||
// %TEMP% lives under C:\Users, which the path guard blocks in every mode, so the
|
||||
// configured folder sits beside the test assembly and the run is unrestricted — which
|
||||
// is also the strongest form of the claim: not even unrestricted mode collects these.
|
||||
private sealed class EvtxFolder : System.IDisposable
|
||||
{
|
||||
public string Path { get; } = System.IO.Path.Combine(
|
||||
System.AppContext.BaseDirectory, "diag-evtx-" + System.Guid.NewGuid().ToString("N"));
|
||||
|
||||
public EvtxFolder(params string[] fileNames)
|
||||
{
|
||||
Directory.CreateDirectory(Path);
|
||||
foreach (var name in fileNames)
|
||||
File.WriteAllBytes(System.IO.Path.Combine(Path, name), new byte[] { 1, 2, 3 });
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Directory.Delete(Path, recursive: true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private static DiagnosticsPackageService BuildService(
|
||||
TempDirectory scratch, string configuredPath, System.Func<string, string> channelResolver)
|
||||
{
|
||||
var logger = new AgentLogger(Directory.CreateDirectory(Path.Combine(scratch.Path, "logs")).FullName);
|
||||
var apiClient = new BackendApiClient(
|
||||
httpClient: new System.Net.Http.HttpClient(),
|
||||
baseUrl: "http://localhost",
|
||||
manufacturer: string.Empty,
|
||||
model: string.Empty,
|
||||
serialNumber: string.Empty,
|
||||
useBootstrapTokenAuth: false,
|
||||
bootstrapToken: null,
|
||||
agentVersion: "0.0.0",
|
||||
logger: logger);
|
||||
|
||||
var cfg = new AgentConfiguration
|
||||
{
|
||||
SessionId = "S1",
|
||||
TenantId = "T1",
|
||||
ApiBaseUrl = "http://localhost",
|
||||
UnrestrictedMode = true,
|
||||
};
|
||||
cfg.DiagnosticsLogPaths.Add(new DiagnosticsLogPath { Path = configuredPath });
|
||||
|
||||
string Sub(string name) => Directory.CreateDirectory(Path.Combine(scratch.Path, name)).FullName;
|
||||
return new DiagnosticsPackageService(
|
||||
cfg,
|
||||
logger,
|
||||
apiClient,
|
||||
agentLogFolderOverride: Sub("agentlogs"),
|
||||
imeLogFolderOverride: Sub("ime"),
|
||||
agentStateFolderOverride: Sub("state"),
|
||||
agentSpoolFolderOverride: Sub("spool"),
|
||||
agentDataFolderOverride: Sub("data"),
|
||||
sectionFolderOverrides: null,
|
||||
devicePreparationProbe: () => false)
|
||||
{
|
||||
EventLogChannelResolver = channelResolver,
|
||||
};
|
||||
}
|
||||
|
||||
private static List<string> ZipEntryNames(byte[] bytes)
|
||||
{
|
||||
using var ms = new MemoryStream(bytes);
|
||||
using var archive = new ZipArchive(ms, ZipArchiveMode.Read);
|
||||
return archive.Entries.Select(e => e.FullName).ToList();
|
||||
}
|
||||
|
||||
private static string ReadManifest(byte[] bytes)
|
||||
{
|
||||
using var ms = new MemoryStream(bytes);
|
||||
using var archive = new ZipArchive(ms, ZipArchiveMode.Read);
|
||||
using var reader = new StreamReader(archive.GetEntry("package-manifest.txt")!.Open());
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Wildcard_entry_skips_blocked_channel_files_and_keeps_the_rest()
|
||||
{
|
||||
using var scratch = new TempDirectory();
|
||||
using var folder = new EvtxFolder(
|
||||
"Security.evtx", "Microsoft-Windows-PowerShell%4Operational.evtx", "Setup.evtx");
|
||||
|
||||
var service = BuildService(scratch, Path.Combine(folder.Path, "*.evtx"), _ => HarmlessChannel);
|
||||
var bytes = service.BuildArchiveBytes(enrollmentSucceeded: false);
|
||||
|
||||
var entries = ZipEntryNames(bytes);
|
||||
Assert.Contains(entries, e => e.EndsWith("/Setup.evtx"));
|
||||
Assert.DoesNotContain(entries, e => e.EndsWith("Security.evtx"));
|
||||
Assert.DoesNotContain(entries, e => e.Contains("PowerShell"));
|
||||
|
||||
var manifest = ReadManifest(bytes);
|
||||
Assert.Contains("BLOCKED (event-log channel guard", manifest);
|
||||
Assert.Contains("Security.evtx", manifest);
|
||||
Assert.Equal(2, service.LastPackaging!.ProblemsByKind["path-guard"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void File_with_a_harmless_name_is_blocked_when_it_resolves_to_a_blocked_channel()
|
||||
{
|
||||
// A channel is free to write to any file name; and the resolver's naming fallback
|
||||
// maps a stray file onto a live channel. The export must never read that channel.
|
||||
using var scratch = new TempDirectory();
|
||||
using var folder = new EvtxFolder("Harmless.evtx");
|
||||
|
||||
var service = BuildService(scratch, Path.Combine(folder.Path, "Harmless.evtx"), _ => "Security");
|
||||
var bytes = service.BuildArchiveBytes(enrollmentSucceeded: false);
|
||||
|
||||
Assert.DoesNotContain(ZipEntryNames(bytes), e => e.EndsWith("Harmless.evtx"));
|
||||
Assert.Contains("BLOCKED (event-log channel guard, channel 'Security')", ReadManifest(bytes));
|
||||
}
|
||||
}
|
||||
}
|
||||
+85
@@ -206,6 +206,91 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Monitoring.Runtime
|
||||
Assert.Contains($"BLOCKED (path guard): {configuredPath}", manifest);
|
||||
}
|
||||
|
||||
// %TEMP% lives under C:\Users, which the guard blocks in every mode — the positive
|
||||
// configured-path cases run beside the test assembly, in unrestricted mode.
|
||||
private sealed class ConfiguredPathTree : System.IDisposable
|
||||
{
|
||||
public string Root { get; } = Path.Combine(
|
||||
System.AppContext.BaseDirectory, "diag-paths-" + System.Guid.NewGuid().ToString("N"));
|
||||
public string Logs => Path.Combine(Root, "Logs");
|
||||
|
||||
public ConfiguredPathTree()
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(Logs, "sub"));
|
||||
File.WriteAllText(Path.Combine(Root, "parent-only.txt"), "not configured");
|
||||
File.WriteAllText(Path.Combine(Logs, "app.log"), "configured");
|
||||
File.WriteAllText(Path.Combine(Logs, "sub", "app.log"), "below");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Directory.Delete(Root, recursive: true); } catch { /* best effort */ }
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("\\")]
|
||||
public void BuildArchiveBytes_folder_entry_collects_the_folder_not_its_parent(string trailing)
|
||||
{
|
||||
using var rig = new Rig();
|
||||
using var tree = new ConfiguredPathTree();
|
||||
|
||||
var bytes = rig.Build(cfg =>
|
||||
{
|
||||
cfg.UnrestrictedMode = true;
|
||||
cfg.DiagnosticsLogPaths.Add(new AutopilotMonitor.Shared.Models.DiagnosticsLogPath
|
||||
{
|
||||
Path = tree.Logs + trailing,
|
||||
IncludeSubfolders = true,
|
||||
});
|
||||
})
|
||||
.BuildArchiveBytes(enrollmentSucceeded: true);
|
||||
|
||||
var entries = ZipEntryNames(bytes);
|
||||
Assert.Contains("AdditionalLogs/Logs/app.log", entries);
|
||||
Assert.Contains("AdditionalLogs/Logs/sub/app.log", entries);
|
||||
Assert.DoesNotContain(entries, e => e.EndsWith("parent-only.txt"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildArchiveBytes_file_entry_ignores_include_subfolders()
|
||||
{
|
||||
using var rig = new Rig();
|
||||
using var tree = new ConfiguredPathTree();
|
||||
|
||||
var bytes = rig.Build(cfg =>
|
||||
{
|
||||
cfg.UnrestrictedMode = true;
|
||||
cfg.DiagnosticsLogPaths.Add(new AutopilotMonitor.Shared.Models.DiagnosticsLogPath
|
||||
{
|
||||
Path = Path.Combine(tree.Logs, "app.log"),
|
||||
IncludeSubfolders = true,
|
||||
});
|
||||
})
|
||||
.BuildArchiveBytes(enrollmentSucceeded: true);
|
||||
|
||||
var entries = ZipEntryNames(bytes);
|
||||
Assert.Contains("AdditionalLogs/Logs/app.log", entries);
|
||||
Assert.DoesNotContain("AdditionalLogs/Logs/sub/app.log", entries);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnumerateFilesNoReparseDirs_asks_the_guard_before_entering_a_subfolder()
|
||||
{
|
||||
using var tree = new ConfiguredPathTree();
|
||||
var refused = new List<string>();
|
||||
|
||||
var files = DiagnosticsPackageService.EnumerateFilesNoReparseDirs(
|
||||
tree.Root, "*", recurse: true,
|
||||
mayEnterDirectory: dir => !dir.EndsWith("sub"),
|
||||
refusedDirectories: refused);
|
||||
|
||||
Assert.Contains(Path.Combine(tree.Logs, "app.log"), files);
|
||||
Assert.DoesNotContain(Path.Combine(tree.Logs, "sub", "app.log"), files);
|
||||
Assert.Equal(new[] { Path.Combine(tree.Logs, "sub") }, refused);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildArchiveBytes_excludes_top_level_session_id_and_bootstrap_config()
|
||||
{
|
||||
|
||||
+137
-2
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+88
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -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.
|
||||
|
||||
@@ -302,6 +302,114 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Program
|
||||
Assert.False(File.Exists(path));
|
||||
}
|
||||
|
||||
// ================================================================= Multi-instance guard
|
||||
|
||||
private static AutopilotMonitor.Agent.V2.Program.AgentProcessFact Proc(int pid, int sessionId)
|
||||
=> new AutopilotMonitor.Agent.V2.Program.AgentProcessFact(pid, sessionId);
|
||||
|
||||
[Fact]
|
||||
public void FindSiblingAgentPid_ignores_a_same_named_process_in_a_user_session()
|
||||
{
|
||||
// The agent (pid 100, session 0) starts while a standard user keeps a process with
|
||||
// the agent's image name resident in their own session. It must not block the start.
|
||||
var matches = new[] { Proc(100, 0), Proc(200, 1) };
|
||||
|
||||
Assert.Equal(0, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(matches, ownPid: 100));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1)]
|
||||
[InlineData(2)]
|
||||
[InlineData(7)]
|
||||
[InlineData(-1)]
|
||||
public void FindSiblingAgentPid_ignores_every_session_but_zero(int sessionId)
|
||||
{
|
||||
var matches = new[] { Proc(100, 0), Proc(200, sessionId) };
|
||||
|
||||
Assert.Equal(0, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(matches, ownPid: 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindSiblingAgentPid_reports_a_second_runtime_in_session_zero()
|
||||
{
|
||||
// Self-update restart while the old runtime is still alive — the single-agent
|
||||
// invariant the guard exists for.
|
||||
var matches = new[] { Proc(100, 0), Proc(300, 0) };
|
||||
|
||||
Assert.Equal(300, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(matches, ownPid: 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindSiblingAgentPid_never_reports_the_caller_itself()
|
||||
{
|
||||
var matches = new[] { Proc(100, 0) };
|
||||
|
||||
Assert.Equal(0, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(matches, ownPid: 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindSiblingAgentPid_skips_user_session_processes_listed_before_the_runtime()
|
||||
{
|
||||
// Install-mode launch verification: a user-session process enumerated first must not
|
||||
// be reported as the launched runtime.
|
||||
var matches = new[] { Proc(200, 1), Proc(201, 2), Proc(100, 0), Proc(300, 0) };
|
||||
|
||||
Assert.Equal(300, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(matches, ownPid: 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindSiblingAgentPid_blocks_an_interactive_start_next_to_the_session_zero_runtime()
|
||||
{
|
||||
// --console run from an admin prompt (session 1) while the Scheduled Task runtime is up.
|
||||
var matches = new[] { Proc(100, 1), Proc(300, 0) };
|
||||
|
||||
Assert.Equal(300, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(matches, ownPid: 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindSiblingAgentPid_returns_zero_for_no_matches()
|
||||
{
|
||||
Assert.Equal(0, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(
|
||||
new AutopilotMonitor.Agent.V2.Program.AgentProcessFact[0], ownPid: 100));
|
||||
Assert.Equal(0, AutopilotMonitor.Agent.V2.Program.FindSiblingAgentPid(null, ownPid: 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SnapshotProcessesByName_reads_pid_and_session_of_the_running_test_host()
|
||||
{
|
||||
using var self = System.Diagnostics.Process.GetCurrentProcess();
|
||||
|
||||
var facts = AutopilotMonitor.Agent.V2.Program.SnapshotProcessesByName(self.ProcessName);
|
||||
|
||||
var own = Assert.Single(facts, f => f.Pid == self.Id);
|
||||
Assert.Equal(self.SessionId, own.SessionId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SnapshotProcessesByName_reads_the_session_of_system_owned_processes_without_access_rights()
|
||||
{
|
||||
// Positive control for the fail-open direction: the session id comes from the process
|
||||
// snapshot, not from an opened handle, so even an unprivileged caller reads it for
|
||||
// SYSTEM-owned service hosts. A skipped process would let a real sibling go unseen.
|
||||
var expected = System.Diagnostics.Process.GetProcessesByName("svchost");
|
||||
foreach (var p in expected) p.Dispose();
|
||||
|
||||
var facts = AutopilotMonitor.Agent.V2.Program.SnapshotProcessesByName("svchost");
|
||||
|
||||
Assert.NotEmpty(facts);
|
||||
Assert.All(facts, f => Assert.True(f.Pid > 0));
|
||||
Assert.Contains(facts, f => f.SessionId == 0);
|
||||
// Service hosts come and go; a wholesale access failure would drop (nearly) all of them.
|
||||
Assert.True(facts.Count >= expected.Length / 2,
|
||||
$"Snapshot returned {facts.Count} of ~{expected.Length} svchost processes.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SnapshotProcessesByName_returns_empty_for_an_unknown_name()
|
||||
{
|
||||
Assert.Empty(AutopilotMonitor.Agent.V2.Program.SnapshotProcessesByName("no-such-process-" + Guid.NewGuid().ToString("N")));
|
||||
}
|
||||
|
||||
// ================================================================= Crash log writer
|
||||
|
||||
[Fact]
|
||||
|
||||
+16
@@ -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
|
||||
|
||||
+292
@@ -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"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -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"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+57
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
@@ -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;
|
||||
|
||||
+132
-24
@@ -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)
|
||||
|
||||
+16
@@ -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})");
|
||||
|
||||
+24
-2
@@ -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)
|
||||
|
||||
+5
@@ -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.
|
||||
|
||||
+257
@@ -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; }
|
||||
}
|
||||
}
|
||||
+30
@@ -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; }
|
||||
}
|
||||
|
||||
+126
-6
@@ -24,10 +24,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Enrollment.SystemSignals
|
||||
/// <item><c>EspTrackingWin32Apps\<userGuid>\<appGuid>_<rev></c> — which apps IME
|
||||
/// registered for ESP tracking and in which phase.</item>
|
||||
/// <item><c>SideCarPolicies\StatusServiceReports\<userGuid>\<appId></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\<userGuid>\<appGuid></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
|
||||
|
||||
+70
-28
@@ -99,7 +99,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
|
||||
/// <summary>
|
||||
/// Packaging problems that are not cap skips, per kind: <c>path-guard</c> (configured path
|
||||
/// refused), <c>no-user-session</c> (user-profile token without a signed-in user),
|
||||
/// or hard-blocked event log refused),<c>no-user-session</c> (user-profile token without a signed-in user),
|
||||
/// <c>folder-rejected</c>, <c>enumerate</c>, <c>open</c>, <c>copy</c>.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, int> ProblemsByKind { get; set; } = Empty;
|
||||
@@ -145,6 +145,10 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
// exact point production is exposed. Null in production.
|
||||
internal Action<string> BeforeSourceFileOpen { get; set; }
|
||||
|
||||
// Test seam: which channel writes to an .evtx file. Production asks the registered
|
||||
// channels; a test cannot register one.
|
||||
internal Func<string, string> EventLogChannelResolver { get; set; } = ResolveChannelForEvtxFile;
|
||||
|
||||
// Tracks per-build inclusion totals + skip reasons. Threaded through every
|
||||
// AddLogFiles call so caps are global across all sections, not per section.
|
||||
private sealed class BudgetTracker
|
||||
@@ -462,17 +466,12 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
// 3. Configured additional log paths (global + tenant, validated by guards)
|
||||
foreach (var entry in _configuration.DiagnosticsLogPaths ?? new System.Collections.Generic.List<Shared.Models.DiagnosticsLogPath>())
|
||||
{
|
||||
// Resolve %LOGGED_ON_USER_PROFILE% token and get profile path for guard exception
|
||||
// The profile path only lifts the C:\Users block for entries that use the token.
|
||||
var userProfilePath = UserProfileResolver.ContainsUserProfileToken(entry.Path)
|
||||
? UserProfileResolver.GetLoggedOnUserProfilePath() : null;
|
||||
|
||||
if (!DiagnosticsPathGuards.IsDiagnosticsPathAllowed(entry.Path, _configuration.UnrestrictedMode, userProfilePath))
|
||||
{
|
||||
_logger.Warning($"Diagnostics path blocked by guard: {entry.Path}");
|
||||
ManifestLine($"BLOCKED (path guard): {entry.Path}");
|
||||
tracker.RecordProblem("path-guard");
|
||||
continue;
|
||||
}
|
||||
// Expand BEFORE the guard: the guard must judge the path that is read,
|
||||
// and an unresolved token is not a path it can judge.
|
||||
var expandedPath = UserProfileResolver.ExpandCustomTokens(entry.Path);
|
||||
if (expandedPath == null)
|
||||
{
|
||||
@@ -481,13 +480,23 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
tracker.RecordProblem("no-user-session");
|
||||
continue;
|
||||
}
|
||||
var folder = Path.GetDirectoryName(expandedPath);
|
||||
var pattern = Path.GetFileName(expandedPath);
|
||||
if (string.IsNullOrEmpty(folder)) continue;
|
||||
if (string.IsNullOrEmpty(pattern) || !pattern.Contains(".")) pattern = "*";
|
||||
var zipFolder = $"AdditionalLogs/{Path.GetFileName(folder)}";
|
||||
ManifestLine($"CONFIGURED PATH: '{entry.Path}' -> folder='{folder}' pattern='{pattern}'");
|
||||
AddLogFiles(archive, folder, zipFolder, pattern, tracker, entry.IncludeSubfolders);
|
||||
|
||||
// The guard validates the folder that gets enumerated — never a path
|
||||
// derived from the validated one afterwards.
|
||||
if (!DiagnosticsPathGuards.TryResolveCollectionTarget(
|
||||
expandedPath, entry.IncludeSubfolders, _configuration.UnrestrictedMode, userProfilePath, out var target))
|
||||
{
|
||||
_logger.Warning($"Diagnostics path blocked by guard: {entry.Path}");
|
||||
ManifestLine($"BLOCKED (path guard): {entry.Path}");
|
||||
tracker.RecordProblem("path-guard");
|
||||
continue;
|
||||
}
|
||||
|
||||
var unrestrictedMode = _configuration.UnrestrictedMode;
|
||||
var zipFolder = $"AdditionalLogs/{Path.GetFileName(target.Folder)}";
|
||||
ManifestLine($"CONFIGURED PATH: '{entry.Path}' -> folder='{target.Folder}' pattern='{target.Pattern}' recursive={target.Recurse}");
|
||||
AddLogFiles(archive, target.Folder, zipFolder, target.Pattern, tracker, target.Recurse,
|
||||
dir => DiagnosticsPathGuards.IsDirectoryEnterable(dir, unrestrictedMode, userProfilePath));
|
||||
}
|
||||
|
||||
// Packaging manifest — always written, even when empty of problems, so its
|
||||
@@ -617,14 +626,18 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
// Recursive enumeration that skips reparse-point directories. Materializes the
|
||||
// result into a list so the caller can iterate without holding a directory handle.
|
||||
// Errors during enumeration are swallowed (logged via _logger by the caller).
|
||||
private static List<string> EnumerateFilesNoReparseDirs(string folder, string pattern, bool recurse)
|
||||
// mayEnterDirectory (configured paths only) is asked for every subdirectory before the
|
||||
// walk descends: a hard-blocked subtree can sit below a folder that passed the guard.
|
||||
internal static List<string> EnumerateFilesNoReparseDirs(string folder, string pattern, bool recurse,
|
||||
Func<string, bool> mayEnterDirectory, List<string> refusedDirectories)
|
||||
{
|
||||
var result = new List<string>();
|
||||
CollectFilesNoReparseDirs(folder, pattern, recurse, result);
|
||||
CollectFilesNoReparseDirs(folder, pattern, recurse, mayEnterDirectory, refusedDirectories, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void CollectFilesNoReparseDirs(string folder, string pattern, bool recurse, List<string> result)
|
||||
private static void CollectFilesNoReparseDirs(string folder, string pattern, bool recurse,
|
||||
Func<string, bool> mayEnterDirectory, List<string> refusedDirectories, List<string> result)
|
||||
{
|
||||
string[] files;
|
||||
try { files = Directory.GetFiles(folder, pattern, SearchOption.TopDirectoryOnly); }
|
||||
@@ -643,12 +656,17 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
try { attrs = File.GetAttributes(sub); }
|
||||
catch { continue; }
|
||||
if (IsReparsePoint(attrs)) continue;
|
||||
CollectFilesNoReparseDirs(sub, pattern, recurse: true, result);
|
||||
if (mayEnterDirectory != null && !mayEnterDirectory(sub))
|
||||
{
|
||||
refusedDirectories.Add(sub);
|
||||
continue;
|
||||
}
|
||||
CollectFilesNoReparseDirs(sub, pattern, recurse: true, mayEnterDirectory, refusedDirectories, result);
|
||||
}
|
||||
}
|
||||
|
||||
private void AddLogFiles(ZipArchive archive, string sourceFolder, string zipFolder, string searchPattern,
|
||||
BudgetTracker tracker, bool includeSubfolders = false)
|
||||
BudgetTracker tracker, bool includeSubfolders = false, Func<string, bool> mayEnterDirectory = null)
|
||||
{
|
||||
// The folder stays pinned (open handle) for this whole section. The path guards and
|
||||
// the enumeration below only ever judge path strings; every byte that reaches the
|
||||
@@ -673,9 +691,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
}
|
||||
|
||||
List<string> files;
|
||||
var refusedDirectories = new List<string>();
|
||||
try
|
||||
{
|
||||
files = EnumerateFilesNoReparseDirs(pinned.LexicalPath, searchPattern, includeSubfolders);
|
||||
files = EnumerateFilesNoReparseDirs(pinned.LexicalPath, searchPattern, includeSubfolders,
|
||||
mayEnterDirectory, refusedDirectories);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -685,6 +705,13 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
return;
|
||||
}
|
||||
|
||||
// Expected outcome, not a packaging problem: the subtree is off limits by design.
|
||||
foreach (var refused in refusedDirectories)
|
||||
{
|
||||
_logger.Info($"Diagnostics subfolder skipped by guard: {refused}");
|
||||
ManifestLine($"SKIPPED DIR (path guard): {refused}");
|
||||
}
|
||||
|
||||
if (files.Count == 0)
|
||||
ManifestLine($"NO MATCH: {sourceFolder} pattern '{searchPattern}'");
|
||||
|
||||
@@ -704,7 +731,22 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
// the tenant-configured BootstrapperAgent channel never made it into the ZIP.
|
||||
if (file.EndsWith(".evtx", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
tempExport = TryExportEventLogChannel(file);
|
||||
// Hard-blocked channels are refused for every source and in every mode,
|
||||
// by file name AND by the channel the export would read: the path guard
|
||||
// cannot judge what a wildcard or folder entry resolves to, and the %4
|
||||
// fallback of the resolver turns a "Security.evtx" in any allowed folder
|
||||
// into the live Security channel.
|
||||
var channel = EventLogChannelResolver(file);
|
||||
if (DiagnosticsPathGuards.IsHardBlockedEventLogFile(file) ||
|
||||
GatherRuleGuards.IsHardBlockedEventLogChannel(channel))
|
||||
{
|
||||
_logger.Warning($"Event log blocked by channel guard (channel '{channel}'): {file}");
|
||||
ManifestLine($"BLOCKED (event-log channel guard, channel '{channel}'): {file}");
|
||||
tracker.RecordProblem("path-guard");
|
||||
return;
|
||||
}
|
||||
|
||||
tempExport = TryExportEventLogChannel(file, channel);
|
||||
if (tempExport == null)
|
||||
{
|
||||
// Export failed (channel not resolvable / wevtutil error) — fall through
|
||||
@@ -850,16 +892,16 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Runtime
|
||||
/// <summary>
|
||||
/// Exports the event-log channel behind a winevt .evtx file to a temp copy via
|
||||
/// <c>wevtutil epl</c> (active channels hold their file exclusively locked, so a raw
|
||||
/// copy fails). Channel resolution happens against the registered channels — see
|
||||
/// <see cref="ResolveChannelForEvtxFile"/>. Returns the temp file path (caller deletes)
|
||||
/// or null when the export failed.
|
||||
/// copy fails). The caller resolved <paramref name="channel"/> against the registered
|
||||
/// channels — see <see cref="ResolveChannelForEvtxFile"/> — and checked it against the
|
||||
/// hard-blocked channels. Returns the temp file path (caller deletes) or null when the
|
||||
/// export failed.
|
||||
/// </summary>
|
||||
private string TryExportEventLogChannel(string evtxPath)
|
||||
private string TryExportEventLogChannel(string evtxPath, string channel)
|
||||
{
|
||||
string tempPath = null;
|
||||
try
|
||||
{
|
||||
var channel = ResolveChannelForEvtxFile(evtxPath);
|
||||
tempPath = Path.Combine(Path.GetTempPath(), $"am-evtx-{Guid.NewGuid():N}.evtx");
|
||||
var psi = new System.Diagnostics.ProcessStartInfo
|
||||
{
|
||||
|
||||
+209
-45
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
{
|
||||
@@ -124,51 +125,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
if (IsSymlinkOrReparsePoint(normalizedDir))
|
||||
return false;
|
||||
|
||||
// C:\Users block always applies (even in unrestricted mode)
|
||||
// Exception: paths under <userProfilePath>\AppData\Local or AppData\Roaming
|
||||
// are allowed when the %LOGGED_ON_USER_PROFILE% token was used.
|
||||
if (normalizedDir.StartsWith(BlockedUsersPrefix, StringComparison.OrdinalIgnoreCase) &&
|
||||
(normalizedDir.Length == BlockedUsersPrefix.Length ||
|
||||
normalizedDir[BlockedUsersPrefix.Length] == Path.DirectorySeparatorChar))
|
||||
{
|
||||
if (!GatherRuleGuards.IsUserProfileSubpathAllowed(normalizedDir, userProfilePath))
|
||||
return false;
|
||||
}
|
||||
|
||||
// Additional hard-blocked paths (even in unrestricted mode)
|
||||
foreach (var blocked in AdditionalHardBlockedPrefixes)
|
||||
{
|
||||
var normalizedBlocked = Path.GetFullPath(blocked);
|
||||
if (normalizedDir.StartsWith(normalizedBlocked, StringComparison.OrdinalIgnoreCase) &&
|
||||
(normalizedDir.Length == normalizedBlocked.Length ||
|
||||
normalizedDir[normalizedBlocked.Length] == Path.DirectorySeparatorChar))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// In unrestricted mode, everything except hard-blocked paths is allowed
|
||||
if (unrestrictedMode)
|
||||
return true;
|
||||
|
||||
foreach (var prefix in AllowedDiagnosticsPathPrefixes)
|
||||
{
|
||||
var normalizedPrefix = Path.GetFullPath(prefix);
|
||||
if (normalizedDir.StartsWith(normalizedPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// Segment-bounded: next char must be '\' or end-of-string
|
||||
if (normalizedDir.Length == normalizedPrefix.Length ||
|
||||
normalizedDir[normalizedPrefix.Length] == Path.DirectorySeparatorChar)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Vendor folders under the signed-in user's profile — same allowlist the file
|
||||
// collectors use, since it answers the same question: which folders below a
|
||||
// profile carry enrollment-relevant logs rather than the user's own data.
|
||||
return GatherRuleGuards.IsUserProfilePathOnAllowlist(normalizedDir, userProfilePath);
|
||||
return IsNormalizedPathAllowed(normalizedDir, unrestrictedMode, userProfilePath);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -177,6 +134,213 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the package actually reads for one configured entry: every file matching
|
||||
/// <see cref="Pattern"/> in <see cref="Folder"/>, optionally below it.
|
||||
/// </summary>
|
||||
public sealed class CollectionTarget
|
||||
{
|
||||
public CollectionTarget(string folder, string pattern, bool recurse)
|
||||
{
|
||||
Folder = folder;
|
||||
Pattern = pattern;
|
||||
Recurse = recurse;
|
||||
}
|
||||
|
||||
/// <summary>Full path without a trailing separator (drive roots keep theirs).</summary>
|
||||
public string Folder { get; }
|
||||
public string Pattern { get; }
|
||||
public bool Recurse { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves a configured entry to the folder and pattern that get enumerated, and
|
||||
/// validates exactly that. Returns false when the guard refuses the entry.
|
||||
///
|
||||
/// <paramref name="expandedPath"/> must already have the %LOGGED_ON_USER_PROFILE% token
|
||||
/// resolved: validating the raw token would judge a different path than the one read.
|
||||
///
|
||||
/// A wildcard in the last segment selects files in its parent folder. A trailing
|
||||
/// separator or an existing directory selects every file in that folder. Anything else
|
||||
/// names one file — validated as that file and never recursed, because its parent
|
||||
/// folder has not passed the guard. The filesystem decides folder-vs-file, never the
|
||||
/// spelling of the last segment.
|
||||
/// </summary>
|
||||
public static bool TryResolveCollectionTarget(
|
||||
string expandedPath,
|
||||
bool includeSubfolders,
|
||||
bool unrestrictedMode,
|
||||
string userProfilePath,
|
||||
out CollectionTarget target)
|
||||
=> TryResolveCollectionTarget(
|
||||
expandedPath, includeSubfolders, unrestrictedMode, userProfilePath, Directory.Exists, out target);
|
||||
|
||||
internal static bool TryResolveCollectionTarget(
|
||||
string expandedPath,
|
||||
bool includeSubfolders,
|
||||
bool unrestrictedMode,
|
||||
string userProfilePath,
|
||||
Func<string, bool> directoryExists,
|
||||
out CollectionTarget target)
|
||||
{
|
||||
target = null;
|
||||
if (string.IsNullOrWhiteSpace(expandedPath))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
var expanded = Environment.ExpandEnvironmentVariables(expandedPath.Trim());
|
||||
var lastSegment = Path.GetFileName(expanded);
|
||||
|
||||
if (lastSegment.Contains('*') || lastSegment.Contains('?'))
|
||||
{
|
||||
var parent = Path.GetDirectoryName(expanded);
|
||||
if (string.IsNullOrEmpty(parent))
|
||||
return false;
|
||||
var folder = TrimTrailingSeparators(Path.GetFullPath(parent));
|
||||
if (!IsDiagnosticsPathAllowed(folder, unrestrictedMode, userProfilePath))
|
||||
return false;
|
||||
target = new CollectionTarget(folder, lastSegment, includeSubfolders);
|
||||
return true;
|
||||
}
|
||||
|
||||
var full = TrimTrailingSeparators(Path.GetFullPath(expanded));
|
||||
if (!IsDiagnosticsPathAllowed(full, unrestrictedMode, userProfilePath))
|
||||
return false;
|
||||
|
||||
if (lastSegment.Length == 0 || directoryExists(full))
|
||||
{
|
||||
target = new CollectionTarget(full, "*", includeSubfolders);
|
||||
return true;
|
||||
}
|
||||
|
||||
var fileFolder = Path.GetDirectoryName(full);
|
||||
if (string.IsNullOrEmpty(fileFolder))
|
||||
return false;
|
||||
target = new CollectionTarget(fileFolder, Path.GetFileName(full), recurse: false);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
target = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Guard for every subdirectory a recursive collection is about to enter. The start
|
||||
/// folder passed <see cref="IsDiagnosticsPathAllowed(string, bool, string)"/>, but a
|
||||
/// hard-blocked subtree can sit below an allowed folder (unrestricted mode, drive
|
||||
/// root). Lexical only: reparse points are skipped by the enumeration and refused
|
||||
/// again on the handle that is read.
|
||||
/// </summary>
|
||||
public static bool IsDirectoryEnterable(string directory, bool unrestrictedMode, string userProfilePath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(directory))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
return IsNormalizedPathAllowed(Path.GetFullPath(directory), unrestrictedMode, userProfilePath);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string TrimTrailingSeparators(string fullPath)
|
||||
{
|
||||
var root = Path.GetPathRoot(fullPath);
|
||||
var trimmed = fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
return root != null && trimmed.Length < root.Length ? root : trimmed;
|
||||
}
|
||||
|
||||
// Hard blocks, then (restricted mode) the allowlists — on an already normalized path.
|
||||
private static bool IsNormalizedPathAllowed(string normalizedDir, bool unrestrictedMode, string userProfilePath)
|
||||
{
|
||||
// C:\Users block always applies (even in unrestricted mode)
|
||||
// Exception: paths under <userProfilePath>\AppData\Local or AppData\Roaming
|
||||
// are allowed when the %LOGGED_ON_USER_PROFILE% token was used.
|
||||
if (normalizedDir.StartsWith(BlockedUsersPrefix, StringComparison.OrdinalIgnoreCase) &&
|
||||
(normalizedDir.Length == BlockedUsersPrefix.Length ||
|
||||
normalizedDir[BlockedUsersPrefix.Length] == Path.DirectorySeparatorChar))
|
||||
{
|
||||
if (!GatherRuleGuards.IsUserProfileSubpathAllowed(normalizedDir, userProfilePath))
|
||||
return false;
|
||||
}
|
||||
|
||||
// Additional hard-blocked paths (even in unrestricted mode)
|
||||
foreach (var blocked in AdditionalHardBlockedPrefixes)
|
||||
{
|
||||
var normalizedBlocked = Path.GetFullPath(blocked);
|
||||
if (normalizedDir.StartsWith(normalizedBlocked, StringComparison.OrdinalIgnoreCase) &&
|
||||
(normalizedDir.Length == normalizedBlocked.Length ||
|
||||
normalizedDir[normalizedBlocked.Length] == Path.DirectorySeparatorChar))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Hard-blocked event logs (even in unrestricted mode). Only a path that names the
|
||||
// file is caught here; a wildcard or folder entry is judged per file by
|
||||
// DiagnosticsPackageService, which is the enforcement point.
|
||||
if (IsHardBlockedEventLogFile(normalizedDir))
|
||||
return false;
|
||||
|
||||
// In unrestricted mode, everything except hard-blocked paths is allowed
|
||||
if (unrestrictedMode)
|
||||
return true;
|
||||
|
||||
foreach (var prefix in AllowedDiagnosticsPathPrefixes)
|
||||
{
|
||||
var normalizedPrefix = Path.GetFullPath(prefix);
|
||||
if (normalizedDir.StartsWith(normalizedPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// Segment-bounded: next char must be '\' or end-of-string
|
||||
if (normalizedDir.Length == normalizedPrefix.Length ||
|
||||
normalizedDir[normalizedPrefix.Length] == Path.DirectorySeparatorChar)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Vendor folders under the signed-in user's profile — same allowlist the file
|
||||
// collectors use, since it answers the same question: which folders below a
|
||||
// profile carry enrollment-relevant logs rather than the user's own data.
|
||||
return GatherRuleGuards.IsUserProfilePathOnAllowlist(normalizedDir, userProfilePath);
|
||||
}
|
||||
|
||||
// Windows archives a full channel as "Archive-<file name>-yyyy-MM-dd-HH-mm-ss-fff.evtx".
|
||||
private static readonly Regex ArchivedEventLogRegex = new Regex(
|
||||
@"^Archive-(.+)-\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}-\d{3}$",
|
||||
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// True when the .evtx file name belongs to one of
|
||||
/// <see cref="GatherRuleGuards.HardBlockedEventLogChannels"/> — live file
|
||||
/// ("Microsoft-Windows-PowerShell%4Operational.evtx", where %4 encodes '/') or
|
||||
/// archived copy. Judges the NAME only; a channel may write to a file that does not
|
||||
/// follow the convention, so the packager also checks the channel it resolved.
|
||||
/// </summary>
|
||||
internal static bool IsHardBlockedEventLogFile(string path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path))
|
||||
return false;
|
||||
|
||||
var name = Path.GetFileName(path);
|
||||
if (!name.EndsWith(".evtx", StringComparison.OrdinalIgnoreCase))
|
||||
return false;
|
||||
|
||||
var stem = name.Substring(0, name.Length - ".evtx".Length);
|
||||
var archived = ArchivedEventLogRegex.Match(stem);
|
||||
if (archived.Success)
|
||||
stem = archived.Groups[1].Value;
|
||||
|
||||
return GatherRuleGuards.IsHardBlockedEventLogChannel(stem.Replace("%4", "/"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether any component of the path (directories or file) is a symlink,
|
||||
/// junction, or other reparse point. Returns true if a reparse point is detected.
|
||||
|
||||
+16
-5
@@ -451,11 +451,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
var trimmed = channel.Trim();
|
||||
|
||||
// Hard blocks apply even in unrestricted mode
|
||||
foreach (var blocked in HardBlockedEventLogChannels)
|
||||
{
|
||||
if (MatchesChannel(trimmed, blocked))
|
||||
return false;
|
||||
}
|
||||
if (IsHardBlockedEventLogChannel(trimmed))
|
||||
return false;
|
||||
|
||||
if (unrestrictedMode)
|
||||
return true;
|
||||
@@ -463,6 +460,20 @@ namespace AutopilotMonitor.Agent.V2.Core.Monitoring.Telemetry.Gather
|
||||
return AllowedEventLogChannels.Any(allowed => MatchesChannel(trimmed, allowed));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when the channel is one of <see cref="HardBlockedEventLogChannels"/>. Every
|
||||
/// path that can read an event log asks here — the event-log collector and the
|
||||
/// diagnostics package alike — so the block cannot hold in one and leak through another.
|
||||
/// </summary>
|
||||
internal static bool IsHardBlockedEventLogChannel(string channel)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(channel))
|
||||
return false;
|
||||
|
||||
var trimmed = channel.Trim();
|
||||
return HardBlockedEventLogChannels.Any(blocked => MatchesChannel(trimmed, blocked));
|
||||
}
|
||||
|
||||
private static bool MatchesChannel(string channel, string prefix)
|
||||
=> channel.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) &&
|
||||
(channel.Length == prefix.Length || channel[prefix.Length] == '/');
|
||||
|
||||
+87
-68
@@ -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"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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" },
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.Eventing.Reader;
|
||||
using System.IO;
|
||||
@@ -41,17 +42,31 @@ namespace AutopilotMonitor.Agent.V2
|
||||
|
||||
// ----------------------------------------------------------------- Multi-instance guard
|
||||
|
||||
/// <summary>Pid and terminal-services session of one name-matched process.</summary>
|
||||
internal readonly struct AgentProcessFact
|
||||
{
|
||||
public AgentProcessFact(int pid, int sessionId)
|
||||
{
|
||||
Pid = pid;
|
||||
SessionId = sessionId;
|
||||
}
|
||||
|
||||
public int Pid { get; }
|
||||
public int SessionId { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>true</c> when another process with the same filename (module name) is alive.
|
||||
/// Race-safe by design: we count processes sharing our name; if 1, only we exist.
|
||||
/// <c>true</c> when another agent runtime is alive. A process name is not a protected
|
||||
/// namespace — any user session can run a binary named like the agent — so a name match
|
||||
/// only counts in session 0. Every runtime start (Scheduled Task, WMI launch, self-update
|
||||
/// restart) lands there, and a standard user cannot start a process in it.
|
||||
/// </summary>
|
||||
internal static bool IsAnotherAgentInstanceRunning()
|
||||
{
|
||||
try
|
||||
{
|
||||
var self = Process.GetCurrentProcess();
|
||||
var siblings = Process.GetProcessesByName(self.ProcessName);
|
||||
return siblings.Length > 1;
|
||||
using (var self = Process.GetCurrentProcess())
|
||||
return FindSiblingAgentPid(SnapshotProcessesByName(self.ProcessName), self.Id) != 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -61,6 +76,40 @@ namespace AutopilotMonitor.Agent.V2
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pid of the first name-matched process that is a real agent runtime — session 0 and not
|
||||
/// the caller itself — or <c>0</c> when there is none. Shared by the multi-instance guard
|
||||
/// and install mode's launch verification so both trust the same identity.
|
||||
/// </summary>
|
||||
internal static int FindSiblingAgentPid(IEnumerable<AgentProcessFact> nameMatches, int ownPid)
|
||||
{
|
||||
if (nameMatches == null) return 0;
|
||||
foreach (var candidate in nameMatches)
|
||||
{
|
||||
if (candidate.Pid == ownPid) continue;
|
||||
if (candidate.SessionId != 0) continue;
|
||||
return candidate.Pid;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads pid and session of every process with the given name. A process that vanished
|
||||
/// between enumeration and read is skipped: it is not a live sibling, and failing open
|
||||
/// means the worst case is two agents, never none.
|
||||
/// </summary>
|
||||
internal static List<AgentProcessFact> SnapshotProcessesByName(string processName)
|
||||
{
|
||||
var facts = new List<AgentProcessFact>();
|
||||
foreach (var process in Process.GetProcessesByName(processName))
|
||||
{
|
||||
try { facts.Add(new AgentProcessFact(process.Id, process.SessionId)); }
|
||||
catch { /* exited mid-read */ }
|
||||
finally { process.Dispose(); }
|
||||
}
|
||||
return facts;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- clean-exit marker
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -731,7 +731,8 @@ namespace AutopilotMonitor.Agent.V2
|
||||
/// 10s / 500ms contract as the bootstrap script's Get-Process probe. The install-mode
|
||||
/// process shares the runtime's exe name, so the own pid is excluded; a pre-existing
|
||||
/// foreign runtime cannot be running here because install mode bails earlier on the
|
||||
/// Deployed marker.
|
||||
/// Deployed marker. Same identity rule as the multi-instance guard: a same-named process
|
||||
/// in a user session is not the runtime and must not satisfy the verification.
|
||||
/// </summary>
|
||||
private static int WaitForDetachedRuntimePid(string exePath, AgentLogger logger)
|
||||
{
|
||||
@@ -742,16 +743,8 @@ namespace AutopilotMonitor.Agent.V2
|
||||
{
|
||||
try
|
||||
{
|
||||
var candidates = Process.GetProcessesByName(processName);
|
||||
try
|
||||
{
|
||||
var runtime = candidates.FirstOrDefault(p => p.Id != ownPid);
|
||||
if (runtime != null) return runtime.Id;
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var p in candidates) p.Dispose();
|
||||
}
|
||||
var runtimePid = FindSiblingAgentPid(SnapshotProcessesByName(processName), ownPid);
|
||||
if (runtimePid != 0) return runtimePid;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+17
-10
@@ -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,26 +28,33 @@ 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);
|
||||
|
||||
@@ -447,41 +447,27 @@ public class AdminWireParityTests
|
||||
// ---- TriggerMaintenance --------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void TriggerMaintenanceResponse_matches_the_manual_trigger_shape()
|
||||
public void TriggerMaintenanceResponse_matches_the_queued_trigger_shape()
|
||||
{
|
||||
var result = new MaintenanceResult
|
||||
{
|
||||
Success = true,
|
||||
TriggeredBy = "admin@contoso.com",
|
||||
TriggeredAt = new DateTime(2026, 8, 30, 13, 10, 0, DateTimeKind.Utc),
|
||||
DurationMs = 1234,
|
||||
StalledSessionsChecked = true,
|
||||
MetricsAggregated = true,
|
||||
AggregatedDate = "2026-08-29",
|
||||
DataCleanupExecuted = false,
|
||||
PlatformStatsRecomputed = true,
|
||||
DevicesBlockedForExcessiveData = 0,
|
||||
ContactEmailsBackfilled = 2,
|
||||
};
|
||||
var userEmail = "admin@contoso.com";
|
||||
var triggeredAt = new DateTime(2026, 8, 30, 13, 10, 5, DateTimeKind.Utc);
|
||||
|
||||
AssertParity(
|
||||
new
|
||||
{
|
||||
success = true,
|
||||
message = "Maintenance tasks completed",
|
||||
result = result,
|
||||
message = "Maintenance run queued",
|
||||
triggeredBy = userEmail,
|
||||
triggeredAt
|
||||
triggeredAt,
|
||||
targetDate = "2026-08-29",
|
||||
aggregateOnly = true
|
||||
},
|
||||
new TriggerMaintenanceResponse
|
||||
{
|
||||
Success = true,
|
||||
Message = "Maintenance tasks completed",
|
||||
Result = result,
|
||||
Message = "Maintenance run queued",
|
||||
TriggeredBy = userEmail,
|
||||
TriggeredAt = triggeredAt
|
||||
TriggeredAt = triggeredAt,
|
||||
TargetDate = "2026-08-29",
|
||||
AggregateOnly = true
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,13 @@ public class AppVersionRegressionRadarTests
|
||||
private const string App = "Contoso VPN";
|
||||
private static readonly DateTime Now = new(2026, 8, 13, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
/// <summary>
|
||||
/// For the analytics tests only: AppsAnalyticsHelper windows off the REAL clock (DateTime.UtcNow − days),
|
||||
/// so their rows must be dated relative to it — a row dated off the fixed <see cref="Now"/> falls out of
|
||||
/// the 30-day window once the calendar moves on (it did on 2026-09-11).
|
||||
/// </summary>
|
||||
private static readonly DateTime Recent = DateTime.UtcNow.AddDays(-1);
|
||||
|
||||
private static int _sessionCounter;
|
||||
|
||||
private static AppInstallSummary Install(
|
||||
@@ -357,10 +364,10 @@ public class AppVersionRegressionRadarTests
|
||||
|
||||
var rows = new List<AppInstallSummary>
|
||||
{
|
||||
Install("1.0", 100), Install("1.0", 200), Install("1.0", 300), Install("1.0", 400),
|
||||
Install("1.0", 0), // unmeasured — excluded from stats
|
||||
Install("1.0", 50, terminalState: "Skipped"), // skip — excluded
|
||||
Install("1.0", 50, status: "Failed"), // failed — excluded from durations
|
||||
Install("1.0", 100, Recent), Install("1.0", 200, Recent), Install("1.0", 300, Recent), Install("1.0", 400, Recent),
|
||||
Install("1.0", 0, Recent), // unmeasured — excluded from stats
|
||||
Install("1.0", 50, Recent, terminalState: "Skipped"), // skip — excluded
|
||||
Install("1.0", 50, Recent, status: "Failed"), // failed — excluded from durations
|
||||
};
|
||||
|
||||
var root = TestWire.SerializeToElement(await AppsAnalyticsHelper.BuildAnalyticsResponseAsync(
|
||||
@@ -393,7 +400,7 @@ public class AppVersionRegressionRadarTests
|
||||
Assert.Equal(1, emptyRoot.GetProperty("versionRegressions").GetArrayLength());
|
||||
|
||||
var root = TestWire.SerializeToElement(await AppsAnalyticsHelper.BuildAnalyticsResponseAsync(
|
||||
new List<AppInstallSummary> { Install("1.0", 100) }, sessionRepo.Object, App, days: 30,
|
||||
new List<AppInstallSummary> { Install("1.0", 100, Recent) }, sessionRepo.Object, App, days: 30,
|
||||
new List<AppVersionRegressionAlert> { alert }));
|
||||
|
||||
var regression = root.GetProperty("versionRegressions")[0];
|
||||
|
||||
@@ -107,7 +107,8 @@ 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);
|
||||
|
||||
// Default: all fire-and-forget calls succeed
|
||||
_tenantConfigMock
|
||||
@@ -219,6 +220,8 @@ public class AuthFunctionSideEffectTests
|
||||
// OnboardedBy is the immutable copy of the first-login UPN that auto-promote on
|
||||
// preview approval reads — UpdatedBy may later be clobbered by background syncs.
|
||||
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);
|
||||
_telegramMock.Verify(x => x.SendNewTenantSignupAsync(TenantId, Upn), Times.Once);
|
||||
_globalNotificationMock.Verify(x => x.CreateNotificationAsync(
|
||||
@@ -304,6 +307,23 @@ public class AuthFunctionSideEffectTests
|
||||
_tenantConfigMock.Verify(x => x.SaveConfigurationAsync(It.IsAny<TenantConfiguration>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
|
||||
}
|
||||
|
||||
private const string CurrentDpa = AutopilotMonitor.Shared.Constants.CurrentDpaVersion;
|
||||
|
||||
[Fact]
|
||||
public async Task HandleNewTenantDomain_WhenDomainAlreadySet_NeverStampsDpaVersion()
|
||||
{
|
||||
// The DPA version is written once, with the onboarding (D-252): an existing tenant's
|
||||
// login writes nothing — no stamp, no save.
|
||||
var config = DefaultConfig();
|
||||
config.DomainName = "contoso.com";
|
||||
config.DpaVersion = null;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleNewTenantDomain_PreservesExistingOnboardedBy()
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,13 @@ public class ConfigBackupHookTests
|
||||
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);
|
||||
@@ -225,15 +232,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);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using AutopilotMonitor.Functions.Functions.Config;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Models.Config;
|
||||
@@ -619,12 +620,26 @@ public class ConfigWireParityTests
|
||||
// keys omitted on the wire).
|
||||
TenantDailyRequestLimit = 3000,
|
||||
TenantMonthlyRequestLimit = 60000,
|
||||
// Per purchased delegation slot (the community tier leaves these unset too).
|
||||
SlotDailyRequestLimit = 300,
|
||||
SlotMonthlyRequestLimit = 6000,
|
||||
SlotTenantDailyRequestLimit = 900,
|
||||
SlotTenantMonthlyRequestLimit = 18000,
|
||||
},
|
||||
};
|
||||
|
||||
AssertParity(
|
||||
new { tiers },
|
||||
new PlanTierDefinitionsResponse { Tiers = tiers });
|
||||
new
|
||||
{
|
||||
tiers,
|
||||
// The built-in fallbacks per edition — what a blank definition field means.
|
||||
catalog = new[]
|
||||
{
|
||||
new { edition = "community", dailyRequestLimit = 100, monthlyRequestLimit = 3000, tenantDailyRequestLimit = 300, tenantMonthlyRequestLimit = 9000, includedDelegatedSlots = 0, slotDailyRequestLimit = 0, slotMonthlyRequestLimit = 0, slotTenantDailyRequestLimit = 0, slotTenantMonthlyRequestLimit = 0 },
|
||||
new { edition = "pro", dailyRequestLimit = 1000, monthlyRequestLimit = 20000, tenantDailyRequestLimit = 3000, tenantMonthlyRequestLimit = 60000, includedDelegatedSlots = 2, slotDailyRequestLimit = 300, slotMonthlyRequestLimit = 6000, slotTenantDailyRequestLimit = 900, slotTenantMonthlyRequestLimit = 18000 },
|
||||
},
|
||||
},
|
||||
new PlanTierDefinitionsResponse { Tiers = tiers, Catalog = PlanManagementFunction.BuildUsagePlanCatalog() });
|
||||
}
|
||||
|
||||
// ---- TestWebhookNotification (dual-purpose: success carries the delivery verdict) ----
|
||||
|
||||
@@ -66,16 +66,12 @@ public class DelegatedAdminServiceTests
|
||||
private static void ReturnsGroups(Mock<IAdminRepository> repo, params TenantGroupAssignment[] assignments) =>
|
||||
repo.Setup(r => r.GetGroupAssignmentsForUpnAsync(It.IsAny<string>())).ReturnsAsync(assignments.ToList());
|
||||
|
||||
/// <summary>Stubs the hot-path membership read (tenants from one partition read).</summary>
|
||||
private static void GroupTenants(Mock<IAdminRepository> repo, string groupId, params string[] tenantIds) =>
|
||||
GroupMembership(repo, groupId, chargeHomeTenantQuota: false, tenantIds);
|
||||
|
||||
/// <summary>Stubs the hot-path membership read (tenants + meta flags from one partition read).</summary>
|
||||
private static void GroupMembership(Mock<IAdminRepository> repo, string groupId, bool chargeHomeTenantQuota, params string[] tenantIds) =>
|
||||
repo.Setup(r => r.GetGroupMembershipAsync(groupId)).ReturnsAsync(new TenantGroupMembership
|
||||
{
|
||||
GroupId = groupId,
|
||||
TenantIds = tenantIds.ToList(),
|
||||
ChargeHomeTenantQuota = chargeHomeTenantQuota,
|
||||
});
|
||||
|
||||
private static DelegatedAdminEntry Row(
|
||||
@@ -390,96 +386,6 @@ public class DelegatedAdminServiceTests
|
||||
repo.Verify(r => r.GetGroupMembershipAsync(GroupId1), Times.Once);
|
||||
}
|
||||
|
||||
// --- ChargeHomeTenantQuota: MCP billing attribution rides in the scope (never authorization) ---
|
||||
|
||||
[Fact]
|
||||
public async Task GetScope_FlaggedGroup_MarksItsTenantsHomeCharged()
|
||||
{
|
||||
var (svc, repo) = Build();
|
||||
ReturnsGroups(repo, Assignment(GroupId1));
|
||||
GroupMembership(repo, GroupId1, chargeHomeTenantQuota: true, TenantA, TenantB);
|
||||
|
||||
var scope = await svc.GetScopeAsync(Id(Upn));
|
||||
|
||||
Assert.True(scope.Covers(TenantA));
|
||||
Assert.True(scope.ChargesHome(TenantA));
|
||||
Assert.True(scope.ChargesHome(TenantB));
|
||||
Assert.Equal(2, scope.HomeChargedTenantIds.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetScope_UnflaggedGroup_NothingIsHomeCharged()
|
||||
{
|
||||
var (svc, repo) = Build();
|
||||
ReturnsGroups(repo, Assignment(GroupId1));
|
||||
GroupTenants(repo, GroupId1, TenantA);
|
||||
|
||||
var scope = await svc.GetScopeAsync(Id(Upn));
|
||||
|
||||
Assert.True(scope.Covers(TenantA));
|
||||
Assert.False(scope.ChargesHome(TenantA));
|
||||
Assert.Empty(scope.HomeChargedTenantIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetScope_DirectGrantAndFlaggedGroup_TheFlagWins()
|
||||
{
|
||||
// The operator's explicit group flag is the more privileged choice — a parallel direct grant on the
|
||||
// same tenant does not re-attribute the reads to the managed tenant.
|
||||
var (svc, repo) = Build();
|
||||
Returns(repo, Row(TenantA, Constants.DelegatedRoles.DelegatedAdmin));
|
||||
ReturnsGroups(repo, Assignment(GroupId1));
|
||||
GroupMembership(repo, GroupId1, chargeHomeTenantQuota: true, TenantA);
|
||||
|
||||
var scope = await svc.GetScopeAsync(Id(Upn));
|
||||
|
||||
Assert.Equal(Constants.DelegatedRoles.DelegatedAdmin, scope.RoleFor(TenantA)); // stronger role kept
|
||||
Assert.True(scope.ChargesHome(TenantA));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetScope_DisabledAssignmentToFlaggedGroup_ConfersNothing()
|
||||
{
|
||||
var (svc, repo) = Build();
|
||||
ReturnsGroups(repo, Assignment(GroupId1, enabled: false));
|
||||
GroupMembership(repo, GroupId1, chargeHomeTenantQuota: true, TenantA);
|
||||
|
||||
var scope = await svc.GetScopeAsync(Id(Upn));
|
||||
|
||||
Assert.False(scope.Covers(TenantA));
|
||||
Assert.False(scope.ChargesHome(TenantA));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetChargeHomeTenantQuota_InvalidatesEveryAssignee()
|
||||
{
|
||||
var (svc, repo) = Build();
|
||||
ReturnsGroups(repo, Assignment(GroupId1));
|
||||
GroupMembership(repo, GroupId1, chargeHomeTenantQuota: false, TenantA);
|
||||
repo.Setup(r => r.SetTenantGroupChargeHomeTenantQuotaAsync(GroupId1, true)).ReturnsAsync(true);
|
||||
repo.Setup(r => r.GetGroupAssigneesAsync(GroupId1)).ReturnsAsync(new List<TenantGroupAssignment> { Assignment(GroupId1) });
|
||||
|
||||
await svc.GetScopeAsync(Id(Upn));
|
||||
var ok = await svc.SetChargeHomeTenantQuotaAsync(GroupId1, true);
|
||||
await svc.GetScopeAsync(Id(Upn));
|
||||
|
||||
Assert.True(ok);
|
||||
// The flag rides in the cached scope, so the flip forces a re-resolution for the assignee.
|
||||
repo.Verify(r => r.GetGroupMembershipAsync(GroupId1), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetChargeHomeTenantQuota_UnknownGroup_IsFalse_AndInvalidatesNobody()
|
||||
{
|
||||
var (svc, repo) = Build();
|
||||
repo.Setup(r => r.SetTenantGroupChargeHomeTenantQuotaAsync(It.IsAny<string>(), It.IsAny<bool>())).ReturnsAsync(false);
|
||||
|
||||
var ok = await svc.SetChargeHomeTenantQuotaAsync("no-such-group", true);
|
||||
|
||||
Assert.False(ok);
|
||||
repo.Verify(r => r.GetGroupAssigneesAsync(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
// --- Group mutations go through the service and invalidate cached scope (no stale auth) ---
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -45,7 +45,10 @@ public class DelegationSelfServiceTests
|
||||
public required Mock<ProConferralService> ProConferral { get; init; }
|
||||
}
|
||||
|
||||
private static Harness Build(TenantEdition homeEdition = TenantEdition.Pro, int? slotOverride = null)
|
||||
/// <summary>Pro by conferral only (managed by a Pro MSP): the shape that must never delegate onward.</summary>
|
||||
private static readonly EditionResolution ConferredPro = new(TenantEdition.Pro, EditionSource.Msp, OwnPro: false);
|
||||
|
||||
private static Harness Build(TenantEdition homeEdition = TenantEdition.Pro, int? slotOverride = null, EditionResolution? homeResolution = null)
|
||||
{
|
||||
var rows = new List<DelegationInvitation>();
|
||||
var groupTenants = new List<string>();
|
||||
@@ -104,7 +107,9 @@ public class DelegationSelfServiceTests
|
||||
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
var time = new TestTimeProvider(Now);
|
||||
var entitlements = new StubTenantEntitlementService(t => t == Home ? homeEdition : TenantEdition.Community);
|
||||
var entitlements = homeResolution is EditionResolution resolution
|
||||
? new StubTenantEntitlementService(t => t == Home ? resolution : new EditionResolution(TenantEdition.Community, EditionSource.Community, OwnPro: false), null)
|
||||
: new StubTenantEntitlementService(t => t == Home ? homeEdition : TenantEdition.Community);
|
||||
var delegatedAdmins = new DelegatedAdminService(repo.Object, new StubAdminIdentityBindingService(bound: true), entitlements, cache, NullLogger<DelegatedAdminService>.Instance);
|
||||
var slots = new DelegatedSlotService(repo.Object, configRepo.Object, invitations.Object, cache, NullLogger<DelegatedSlotService>.Instance, time);
|
||||
var audit = new Mock<IMaintenanceRepository>();
|
||||
@@ -199,6 +204,18 @@ public class DelegationSelfServiceTests
|
||||
Assert.Empty(h.Rows);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateInvitation_ConferredProHome_403_NoTransitiveDelegation()
|
||||
{
|
||||
// The would-be manager is Pro only because a Pro MSP manages IT — conferred Pro carries no delegation right.
|
||||
var h = Build(homeResolution: ConferredPro);
|
||||
var r = await h.Svc.CreateInvitationAsync(Home, MspAdmin);
|
||||
Assert.False(r.Ok);
|
||||
Assert.Equal(403, r.Failure!.Status);
|
||||
Assert.Equal(Constants.DelegationCodes.DelegatedAdminNotAllowed, r.Failure.Code);
|
||||
Assert.Empty(h.Rows);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateInvitation_NoFreeSlot_409_WithViolation()
|
||||
{
|
||||
@@ -322,6 +339,17 @@ public class DelegationSelfServiceTests
|
||||
Assert.Equal(Constants.DelegationCodes.ManagerNotEntitled, r.Failure!.Code);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Accept_ManagerConferredProOnly_409()
|
||||
{
|
||||
// The inviting tenant lost its own Pro and is now Pro by conferral: its pending link is not redeemable.
|
||||
var h = Build(homeResolution: ConferredPro);
|
||||
h.Rows.Add(Pending());
|
||||
var r = await h.Svc.AcceptAsync(Token(), Customer, CustomerAdmin);
|
||||
Assert.Equal(Constants.DelegationCodes.ManagerNotEntitled, r.Failure!.Code);
|
||||
Assert.Equal(Constants.DelegationInvitationStatus.Pending, h.Rows[0].Status); // untouched
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Accept_LimitLoweredSinceInvitation_409_SlotViolation()
|
||||
{
|
||||
@@ -453,6 +481,16 @@ public class DelegationSelfServiceTests
|
||||
h.Repo.Verify(x => x.EnsureOwnedTenantGroupAsync(GroupId, It.IsAny<string>(), Home), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Assign_ConferredProHome_403()
|
||||
{
|
||||
var h = Build(homeResolution: ConferredPro);
|
||||
var r = await h.Svc.AssignAsync(Home, "Analyst@Partner.Example", MspAdmin);
|
||||
Assert.Equal(403, r.Failure!.Status);
|
||||
Assert.Equal(Constants.DelegationCodes.DelegatedAdminNotAllowed, r.Failure.Code);
|
||||
h.Repo.Verify(x => x.AssignGroupAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unassign_NotAssigned_404()
|
||||
{
|
||||
@@ -488,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,12 +106,11 @@ public class DelegationWireParityTests
|
||||
// ---- Self-service delegation ------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void ManagedTenantListResponse_matches_the_managed_shape_and_omits_null_usage()
|
||||
public void ManagedTenantListResponse_matches_the_managed_shape_and_omits_null_domain_and_since()
|
||||
{
|
||||
var since = new DateTime(2026, 9, 1, 8, 0, 0, DateTimeKind.Utc);
|
||||
var slots = new DelegatedSlotUsageResponse { HomeTenantId = Home, Limit = 2, CatalogLimit = 2, Used = 1, ManagedTenantIds = new[] { TenantA }, PendingInvitations = 0, Holds = Array.Empty<DelegatedSlotHold>() };
|
||||
string? domainB = null;
|
||||
ManagedTenantQuotaUsage? usageB = null;
|
||||
DateTime? sinceB = null;
|
||||
|
||||
AssertParity(
|
||||
@@ -121,9 +120,8 @@ public class DelegationWireParityTests
|
||||
slots,
|
||||
tenants = new[]
|
||||
{
|
||||
new { tenantId = TenantA, domain = (string?)"customer.example", source = "self-service", sinceUtc = (DateTime?)since, removable = true,
|
||||
usage = (ManagedTenantQuotaUsage?)new ManagedTenantQuotaUsage { TenantPlan = "community", TenantDailyLimit = 300, TenantMonthlyLimit = 9000, TenantDailyUsed = 12, TenantMonthlyUsed = 340 } },
|
||||
new { tenantId = TenantB, domain = domainB, source = "operator", sinceUtc = sinceB, removable = false, usage = usageB },
|
||||
new { tenantId = TenantA, domain = (string?)"customer.example", source = "self-service", sinceUtc = (DateTime?)since, removable = true },
|
||||
new { tenantId = TenantB, domain = domainB, source = "operator", sinceUtc = sinceB, removable = false },
|
||||
},
|
||||
},
|
||||
new ManagedTenantListResponse
|
||||
@@ -132,8 +130,7 @@ public class DelegationWireParityTests
|
||||
Slots = slots,
|
||||
Tenants = new List<ManagedTenantItem>
|
||||
{
|
||||
new() { TenantId = TenantA, Domain = "customer.example", Source = "self-service", SinceUtc = since, Removable = true,
|
||||
Usage = new ManagedTenantQuotaUsage { TenantPlan = "community", TenantDailyLimit = 300, TenantMonthlyLimit = 9000, TenantDailyUsed = 12, TenantMonthlyUsed = 340 } },
|
||||
new() { TenantId = TenantA, Domain = "customer.example", Source = "self-service", SinceUtc = since, Removable = true },
|
||||
new() { TenantId = TenantB, Source = "operator", Removable = false },
|
||||
},
|
||||
});
|
||||
@@ -197,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
|
||||
@@ -207,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);
|
||||
}
|
||||
|
||||
+16
@@ -237,6 +237,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.
|
||||
|
||||
@@ -158,6 +158,11 @@ public class FeatureEntitlementCatalogTests
|
||||
Assert.Equal(pro.McpMonthlyRequestLimit, conferred.McpMonthlyRequestLimit);
|
||||
Assert.Equal(pro.McpTenantDailyRequestLimit, conferred.McpTenantDailyRequestLimit);
|
||||
Assert.Equal(pro.McpTenantMonthlyRequestLimit, conferred.McpTenantMonthlyRequestLimit);
|
||||
// …except the slot growth, which follows the delegation right.
|
||||
Assert.Equal(0, conferred.McpSlotDailyRequestLimit);
|
||||
Assert.Equal(0, conferred.McpSlotMonthlyRequestLimit);
|
||||
Assert.Equal(0, conferred.McpSlotTenantDailyRequestLimit);
|
||||
Assert.Equal(0, conferred.McpSlotTenantMonthlyRequestLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -207,6 +212,10 @@ public class FeatureEntitlementCatalogTests
|
||||
Assert.Equal(3000, e.McpMonthlyRequestLimit);
|
||||
Assert.Equal(300, e.McpTenantDailyRequestLimit);
|
||||
Assert.Equal(9000, e.McpTenantMonthlyRequestLimit);
|
||||
Assert.Equal(0, e.McpSlotDailyRequestLimit);
|
||||
Assert.Equal(0, e.McpSlotMonthlyRequestLimit);
|
||||
Assert.Equal(0, e.McpSlotTenantDailyRequestLimit);
|
||||
Assert.Equal(0, e.McpSlotTenantMonthlyRequestLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -224,6 +233,11 @@ public class FeatureEntitlementCatalogTests
|
||||
Assert.Equal(20000, e.McpMonthlyRequestLimit);
|
||||
Assert.Equal(3000, e.McpTenantDailyRequestLimit);
|
||||
Assert.Equal(60000, e.McpTenantMonthlyRequestLimit);
|
||||
// Per purchased delegation slot: 30 % of the Pro windows (an additional slot costs 30 % of Pro).
|
||||
Assert.Equal(300, e.McpSlotDailyRequestLimit);
|
||||
Assert.Equal(6000, e.McpSlotMonthlyRequestLimit);
|
||||
Assert.Equal(900, e.McpSlotTenantDailyRequestLimit);
|
||||
Assert.Equal(18000, e.McpSlotTenantMonthlyRequestLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -115,4 +115,21 @@ public class GeographicDrilldownFilterTests
|
||||
Assert.Equal("Saxony", fal.Region);
|
||||
Assert.Equal("Falkenstein", fal.City);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("city")]
|
||||
[InlineData("region")]
|
||||
[InlineData("country")]
|
||||
public void CountryOnlySession_KeyIsTheCountryAndDrillsDownToItself(string groupBy)
|
||||
{
|
||||
// The agent's last-resort geo provider returns the country only.
|
||||
var countryOnly = Geo("de-only", "DE", "", "");
|
||||
var sessions = new List<SessionSummary> { countryOnly, Geo("de-bav", "DE", "Bavaria", "Munich") };
|
||||
|
||||
var key = GetGeographicMetricsFunction.GetLocationKey(countryOnly, groupBy);
|
||||
var drilled = GetGeographicLocationSessionsFunction.FilterSessionsByLocation(sessions, key, groupBy);
|
||||
|
||||
Assert.Equal("DE", key); // never ", DE" or ", , DE"
|
||||
Assert.Contains(drilled, s => s.SessionId == "de-only");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +44,9 @@ public class GetTenantFeatureFlagsPayloadTests
|
||||
// Non-sensitive by review: bool only ("is a contact address set"), never the
|
||||
// address itself (admin-gated full config only).
|
||||
"contactEmailSet",
|
||||
// Non-sensitive by review: bool only ("is any device validation method enabled"),
|
||||
// never which one or any Graph detail.
|
||||
"deviceValidationEnabled",
|
||||
"diagnosticsUploadConfigured",
|
||||
"edition",
|
||||
// Non-sensitive by review: one of "community" | "plan" | "trial" | "msp" — says WHY the
|
||||
@@ -59,7 +62,6 @@ public class GetTenantFeatureFlagsPayloadTests
|
||||
// wire options omit null keys (WhenWritingNull) — exactly what production always
|
||||
// served. Payload_ActiveTrial_IsTrialWithExpiry pins the key on an active trial.
|
||||
"unrestrictedMode",
|
||||
"validateAutopilotDevice",
|
||||
}, fieldNames);
|
||||
}
|
||||
|
||||
@@ -81,13 +83,30 @@ public class GetTenantFeatureFlagsPayloadTests
|
||||
var element = Serialize(config);
|
||||
|
||||
Assert.True(element.GetProperty("bootstrapTokenEnabled").GetBoolean());
|
||||
Assert.True(element.GetProperty("validateAutopilotDevice").GetBoolean());
|
||||
Assert.True(element.GetProperty("deviceValidationEnabled").GetBoolean());
|
||||
Assert.False(element.GetProperty("showScriptOutput").GetBoolean());
|
||||
Assert.True(element.GetProperty("enableSoftwareInventoryAnalyzer").GetBoolean());
|
||||
Assert.False(element.GetProperty("enableIntegrityBypassAnalyzer").GetBoolean());
|
||||
Assert.True(element.GetProperty("unrestrictedMode").GetBoolean());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false, false, false)]
|
||||
[InlineData(true, false, true)]
|
||||
[InlineData(false, true, true)]
|
||||
public void Payload_DeviceValidationEnabled_IsAnyMethod_NotJustAutopilot(bool autopilot, bool intuneEnrollment, bool expected)
|
||||
{
|
||||
// A device-preparation tenant that validates only via Intune enrollment (or device
|
||||
// association) must not see the "agent ingestion is blocked" banner.
|
||||
var element = Serialize(new TenantConfiguration
|
||||
{
|
||||
ValidateAutopilotDevice = autopilot,
|
||||
ValidateIntuneDeviceBinding = intuneEnrollment,
|
||||
});
|
||||
|
||||
Assert.Equal(expected, element.GetProperty("deviceValidationEnabled").GetBoolean());
|
||||
}
|
||||
|
||||
// ── Effective feature gates (plan-derived) ──────────────────────────────
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The IME pattern self-seed behind the newest-source-wins gate (<see cref="RuleCatalogSeedGate"/>):
|
||||
/// a GitHub reseed newer than the build owns the table (nothing written, nothing deleted), an
|
||||
/// older one hands it back to the binary (missing ids written, retired ids sunset), an empty
|
||||
/// table is always seeded, and the code reseed stamps <c>embedded</c>. The retired id stands in
|
||||
/// for PS-SCRIPT-EXITCODE, which the deployed binary re-inserted on 2026-09-11 after the reseed
|
||||
/// had deleted it.
|
||||
/// </summary>
|
||||
public class ImeLogPatternServiceSeedTests
|
||||
{
|
||||
private const string RetiredId = "IME-RETIRED-TEST";
|
||||
private static readonly DateTime Build = new(2026, 9, 10, 19, 19, 57, DateTimeKind.Utc);
|
||||
private static readonly BackendBuildInfo BuildInfo = new("1.5.1205", "e3b2113", Build);
|
||||
|
||||
private static RuleCatalogStamp GitHubStamp(DateTime at) => new()
|
||||
{
|
||||
Kind = RuleCatalogStamp.KindIme, Source = RuleCatalogStamp.SourceGitHub, StampedAt = at, Count = 82,
|
||||
};
|
||||
|
||||
/// <summary>Global partition = the embedded catalog minus its first id plus one retired built-in row.</summary>
|
||||
private static (List<ImeLogPattern> table, string missingId) DriftedTable()
|
||||
{
|
||||
var embedded = BuiltInImeLogPatterns.GetAll();
|
||||
var missing = embedded[0].PatternId;
|
||||
var table = embedded.Skip(1).Select(p => p.Clone()).ToList();
|
||||
table.Add(new ImeLogPattern
|
||||
{
|
||||
PatternId = RetiredId, Category = "always", Pattern = "^retired", Action = "scriptExitCode",
|
||||
Parameters = new Dictionary<string, string>(), Enabled = true, Description = "retired", IsBuiltIn = true,
|
||||
});
|
||||
return (table, missing);
|
||||
}
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public readonly Mock<IRuleRepository> Repo = new();
|
||||
public readonly List<string> Stored = new();
|
||||
public readonly List<string> Deleted = new();
|
||||
|
||||
public Rig(List<ImeLogPattern> global, RuleCatalogStamp? stamp)
|
||||
{
|
||||
Repo.Setup(r => r.GetImeLogPatternsAsync("global")).ReturnsAsync(() => global.Select(p => p.Clone()).ToList());
|
||||
Repo.Setup(r => r.GetImeLogPatternsAsync(It.Is<string>(k => k != "global"))).ReturnsAsync(new List<ImeLogPattern>());
|
||||
Repo.Setup(r => r.GetRuleCatalogStampAsync(RuleCatalogStamp.KindIme)).ReturnsAsync(stamp);
|
||||
Repo.Setup(r => r.StoreImeLogPatternAsync(It.IsAny<ImeLogPattern>(), "global"))
|
||||
.Callback<ImeLogPattern, string>((p, _) => Stored.Add(p.PatternId)).ReturnsAsync(true);
|
||||
Repo.Setup(r => r.DeleteImeLogPatternAsync("global", It.IsAny<string>()))
|
||||
.Callback<string, string>((_, id) => Deleted.Add(id)).ReturnsAsync(true);
|
||||
Repo.Setup(r => r.SetRuleCatalogStampAsync(It.IsAny<RuleCatalogStamp>())).ReturnsAsync(true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GitHub_reseed_newer_than_the_build_owns_the_table()
|
||||
{
|
||||
var (table, missing) = DriftedTable();
|
||||
var rig = new Rig(table, GitHubStamp(Build.AddHours(6)));
|
||||
var service = new ImeLogPatternService(rig.Repo.Object, NullLogger<ImeLogPatternService>.Instance, BuildInfo);
|
||||
|
||||
var catalog = await service.GetGlobalCatalogAsync();
|
||||
|
||||
Assert.Empty(rig.Stored);
|
||||
Assert.Empty(rig.Deleted);
|
||||
Assert.Contains(catalog, p => p.PatternId == RetiredId); // the reseed's table, untouched
|
||||
Assert.DoesNotContain(catalog, p => p.PatternId == missing);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GitHub_reseed_older_than_the_build_hands_the_table_to_the_binary()
|
||||
{
|
||||
var (table, missing) = DriftedTable();
|
||||
var rig = new Rig(table, GitHubStamp(Build.AddHours(-1)));
|
||||
var service = new ImeLogPatternService(rig.Repo.Object, NullLogger<ImeLogPatternService>.Instance, BuildInfo);
|
||||
|
||||
await service.GetGlobalCatalogAsync();
|
||||
|
||||
Assert.Contains(missing, rig.Stored); // added from the embedded catalog
|
||||
Assert.Equal(new[] { RetiredId }, rig.Deleted); // sunset: no longer shipped
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Without_build_info_the_gate_is_open_and_the_stamp_is_never_read()
|
||||
{
|
||||
var (table, missing) = DriftedTable();
|
||||
var rig = new Rig(table, GitHubStamp(Build.AddHours(6)));
|
||||
var service = new ImeLogPatternService(rig.Repo.Object, NullLogger<ImeLogPatternService>.Instance);
|
||||
|
||||
await service.GetGlobalCatalogAsync();
|
||||
|
||||
Assert.Contains(missing, rig.Stored);
|
||||
rig.Repo.Verify(r => r.GetRuleCatalogStampAsync(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Empty_table_is_seeded_even_behind_a_newer_reseed()
|
||||
{
|
||||
var rig = new Rig(new List<ImeLogPattern>(), GitHubStamp(Build.AddHours(6)));
|
||||
var service = new ImeLogPatternService(rig.Repo.Object, NullLogger<ImeLogPatternService>.Instance, BuildInfo);
|
||||
|
||||
await service.GetGlobalCatalogAsync();
|
||||
|
||||
Assert.Equal(BuiltInImeLogPatterns.GetAll().Count, rig.Stored.Count);
|
||||
Assert.Empty(rig.Deleted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Seed_runs_once_per_instance_also_when_the_gate_is_closed()
|
||||
{
|
||||
var (table, _) = DriftedTable();
|
||||
var rig = new Rig(table, GitHubStamp(Build.AddHours(6)));
|
||||
var service = new ImeLogPatternService(rig.Repo.Object, NullLogger<ImeLogPatternService>.Instance, BuildInfo);
|
||||
|
||||
await service.GetGlobalCatalogAsync();
|
||||
await service.GetGlobalCatalogAsync();
|
||||
|
||||
rig.Repo.Verify(r => r.GetRuleCatalogStampAsync(RuleCatalogStamp.KindIme), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Code_reseed_stamps_the_embedded_source()
|
||||
{
|
||||
var (table, _) = DriftedTable();
|
||||
var rig = new Rig(table, GitHubStamp(Build.AddHours(6)));
|
||||
var service = new ImeLogPatternService(rig.Repo.Object, NullLogger<ImeLogPatternService>.Instance, BuildInfo);
|
||||
|
||||
var (deleted, written) = await service.ReseedBuiltInPatternsAsync();
|
||||
|
||||
Assert.Equal(table.Count, deleted);
|
||||
Assert.Equal(BuiltInImeLogPatterns.GetAll().Count, written);
|
||||
rig.Repo.Verify(r => r.SetRuleCatalogStampAsync(It.Is<RuleCatalogStamp>(s =>
|
||||
s.Kind == RuleCatalogStamp.KindIme && s.Source == RuleCatalogStamp.SourceEmbedded && s.Count == written)), Times.Once);
|
||||
}
|
||||
}
|
||||
@@ -441,6 +441,96 @@ public class ImeMsiArchiverTests
|
||||
Assert.Equal(0, archiver.ProvenanceCalls);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Archive already holds the version before the walk (operator backfill of a
|
||||
// build no host serves any more). The 409 path can never be reached for it —
|
||||
// without the pre-walk check the row stays Failed:VersionMismatch forever.
|
||||
// =========================================================================
|
||||
|
||||
[Fact]
|
||||
public async Task ArchiveAsync_VersionAlreadyInArchive_NoHostServesIt_ArchivedWithoutDownload()
|
||||
{
|
||||
var archivedPayload = new byte[1024];
|
||||
new Random(11).NextBytes(archivedPayload);
|
||||
var expectedSha = Convert.ToHexString(SHA256.HashData(archivedPayload)).ToLowerInvariant();
|
||||
var archiver = new RecordingArchiver
|
||||
{
|
||||
ArchivedMsiExists = true,
|
||||
ArchivedPayload = archivedPayload,
|
||||
DefaultProductVersion = "9.9.9.0", // every host has moved on
|
||||
};
|
||||
archiver.ProductVersionByUrl[RecordingArchiver.ArchivedOrigin] = Version;
|
||||
|
||||
var result = await archiver.ArchiveAsync(Envelope());
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.Equal(ImeMsiArchiver.Statuses.Archived, result.Status);
|
||||
Assert.False(result.Retryable);
|
||||
Assert.Equal($"{Version}/IntuneWindowsAgent.msi", result.BlobPath);
|
||||
// The row must describe the archived bytes; the source URL of a backfill is unknown.
|
||||
Assert.Equal(expectedSha, result.Sha256);
|
||||
Assert.Equal(archivedPayload.Length, result.SizeBytes);
|
||||
Assert.Null(result.SourceUrl);
|
||||
Assert.Equal(0, archiver.DownloadCalls);
|
||||
Assert.Equal(0, archiver.UploadCalls);
|
||||
Assert.Equal(0, archiver.ProvenanceCalls); // sidecar came with the backfill
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ArchiveAsync_VersionAlreadyInArchive_MissingSidecar_IsWrittenWithoutSourceUrl()
|
||||
{
|
||||
var archiver = new RecordingArchiver { ArchivedMsiExists = true, ProvenanceExists = false };
|
||||
|
||||
var result = await archiver.ArchiveAsync(Envelope());
|
||||
|
||||
Assert.True(result.Success);
|
||||
Assert.Equal(0, archiver.DownloadCalls);
|
||||
Assert.Equal(1, archiver.ProvenanceCalls);
|
||||
Assert.Equal($"{Version}/provenance.json", archiver.ProvenanceLastPath);
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(archiver.ProvenanceLastJson);
|
||||
Assert.Equal(System.Text.Json.JsonValueKind.Null, doc.RootElement.GetProperty("url").ValueKind);
|
||||
// A null source must not compare equal to a null event URL.
|
||||
Assert.False(doc.RootElement.GetProperty("urlFromEvent").GetBoolean());
|
||||
Assert.Equal(0, doc.RootElement.GetProperty("candidates").GetArrayLength());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("1.103.101.0")] // another ring's build filed under this version
|
||||
[InlineData(null)] // not a readable package
|
||||
public async Task ArchiveAsync_ArchiveEntryIsNotTheObservedVersion_NotAccepted_WalkRuns(string? archivedProductVersion)
|
||||
{
|
||||
var archiver = new RecordingArchiver
|
||||
{
|
||||
ArchivedMsiExists = true,
|
||||
DefaultProductVersion = "9.9.9.0",
|
||||
};
|
||||
archiver.ProductVersionByUrl[RecordingArchiver.ArchivedOrigin] = archivedProductVersion;
|
||||
|
||||
var result = await archiver.ArchiveAsync(Envelope());
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal(ImeMsiArchiver.Statuses.FailedVersionMismatch, result.Status);
|
||||
Assert.Equal(ImeMsiArchiver.BuildCandidateUrls(EventUrl).Count, archiver.DownloadCalls);
|
||||
Assert.Equal(0, archiver.ProvenanceCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ArchiveAsync_ArchiveCheckFails_RetryableError_NoDownload()
|
||||
{
|
||||
var archiver = new RecordingArchiver
|
||||
{
|
||||
ArchivedMsiExists = true,
|
||||
ArchivedOpenException = new RequestFailedException(500, "read failed"),
|
||||
};
|
||||
|
||||
var result = await archiver.ArchiveAsync(Envelope());
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal(ImeMsiArchiver.Statuses.FailedError, result.Status);
|
||||
Assert.True(result.Retryable);
|
||||
Assert.Equal(0, archiver.DownloadCalls);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Provenance-write gap (daily review 2026-08-18): MSI upload is write-once,
|
||||
// so a first attempt that dies between the MSI and the provenance upload
|
||||
@@ -660,6 +750,10 @@ public class ImeMsiArchiverTests
|
||||
public Exception? UploadException { get; set; }
|
||||
public Exception? ProvenanceException { get; set; }
|
||||
public bool ProvenanceExists { get; set; } = true;
|
||||
/// <summary>Whether the archive already holds an installer for the version BEFORE the walk (operator backfill).</summary>
|
||||
public bool ArchivedMsiExists { get; set; }
|
||||
/// <summary>Key into <see cref="ProductVersionByUrl"/> for the archived bytes — they have no URL of their own.</summary>
|
||||
public const string ArchivedOrigin = "archive://existing";
|
||||
public byte[]? ArchivedPayload { get; set; }
|
||||
public Exception? ArchivedOpenException { get; set; }
|
||||
|
||||
@@ -722,12 +816,15 @@ public class ImeMsiArchiverTests
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
protected override Task<bool> ProvenanceExistsAsync(string blobPath, CancellationToken cancellationToken)
|
||||
=> Task.FromResult(ProvenanceExists);
|
||||
protected override Task<bool> ArchiveBlobExistsAsync(string blobPath, CancellationToken cancellationToken)
|
||||
=> Task.FromResult(blobPath.EndsWith("provenance.json", StringComparison.Ordinal)
|
||||
? ProvenanceExists
|
||||
: ArchivedMsiExists);
|
||||
|
||||
protected override Task<Stream> OpenArchivedMsiAsync(string blobPath, CancellationToken cancellationToken)
|
||||
{
|
||||
if (ArchivedOpenException is not null) throw ArchivedOpenException;
|
||||
_currentUrl = ArchivedOrigin;
|
||||
return Task.FromResult<Stream>(new MemoryStream(ArchivedPayload ?? Payload));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,8 +93,9 @@ public class ImePatternHealthTests
|
||||
["PS-AGENT-OUTPUT"] = "not-a-number",
|
||||
};
|
||||
var data = new Dictionary<string, object> { ["hits"] = hits, ["imeVersion"] = "1.105.103.0" };
|
||||
var shipped = new HashSet<string>(new[] { "IME-ESP-PHASE", "IME-STARTED", "IME-DO-TEL", "PS-AGENT-OUTPUT" }, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
var result = ImePatternHealthService.ExtractBuiltInHits(data);
|
||||
var result = ImePatternHealthService.ExtractBuiltInHits(data, shipped);
|
||||
|
||||
Assert.Equal(12, result["IME-ESP-PHASE"]);
|
||||
Assert.Equal(1, result["IME-STARTED"]);
|
||||
@@ -106,8 +107,9 @@ public class ImePatternHealthTests
|
||||
[Fact]
|
||||
public void ExtractBuiltInHits_without_a_histogram_is_empty()
|
||||
{
|
||||
Assert.Empty(ImePatternHealthService.ExtractBuiltInHits(null));
|
||||
Assert.Empty(ImePatternHealthService.ExtractBuiltInHits(new Dictionary<string, object> { ["linesRead"] = 5 }));
|
||||
var shipped = new HashSet<string>(new[] { "IME-ESP-PHASE" }, StringComparer.OrdinalIgnoreCase);
|
||||
Assert.Empty(ImePatternHealthService.ExtractBuiltInHits(null, shipped));
|
||||
Assert.Empty(ImePatternHealthService.ExtractBuiltInHits(new Dictionary<string, object> { ["linesRead"] = 5 }, shipped));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -128,9 +130,13 @@ public class ImePatternHealthTests
|
||||
new() { PatternId = "IME-NEW-THING", Category = "currentPhase", Enabled = true }, // no data yet
|
||||
};
|
||||
|
||||
var r = ImePatternHealthService.BuildResponse(stats, history, catalog, flaggedAt);
|
||||
var stamp = new RuleCatalogStamp { Kind = RuleCatalogStamp.KindIme, Source = RuleCatalogStamp.SourceGitHub, StampedAt = flaggedAt.AddDays(-1), Count = 3 };
|
||||
var r = ImePatternHealthService.BuildResponse(stats, history, catalog, stamp, flaggedAt);
|
||||
|
||||
Assert.Equal("1.104.102.0", r.BaselineVersion);
|
||||
Assert.Equal("github", r.Catalog.Source);
|
||||
Assert.Equal(flaggedAt.AddDays(-1), r.Catalog.StampedAt);
|
||||
Assert.Equal(3, r.Catalog.PatternCount);
|
||||
Assert.Equal("1.105.103.0", r.Versions[0].Version); // newest first
|
||||
Assert.Equal(30, r.Versions[0].Sessions);
|
||||
Assert.Equal(31, r.Versions[0].FleetSessions);
|
||||
@@ -150,11 +156,13 @@ public class ImePatternHealthTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuiltInPatternIds_matches_the_embedded_catalog()
|
||||
public void BuildResponse_without_a_stamp_reports_the_embedded_source()
|
||||
{
|
||||
var ids = BuiltInImeLogPatterns.BuiltInPatternIds.Value;
|
||||
Assert.Contains("IME-ESP-PHASE", ids);
|
||||
Assert.Contains("PS-SCRIPT-RESULT", ids);
|
||||
Assert.Equal(BuiltInImeLogPatterns.GetAll().Count, ids.Count);
|
||||
var r = ImePatternHealthService.BuildResponse(new List<ImePatternStatsEntry>(), new List<ImeVersionHistoryEntry>(),
|
||||
new List<ImeLogPattern> { new() { PatternId = "IME-ESP-PHASE", Category = "always", Enabled = true } }, null, DateTime.UtcNow);
|
||||
|
||||
Assert.Equal("embedded", r.Catalog.Source);
|
||||
Assert.Null(r.Catalog.StampedAt);
|
||||
Assert.Equal(1, r.Catalog.PatternCount);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ public class InfrastructureWireParityTests
|
||||
homedApp = "primary",
|
||||
bootstrapTokenEnabled = true,
|
||||
unrestrictedModeEnabled = false,
|
||||
mcpClientRegistrationEnabled = true,
|
||||
whatsNewSeenPlatformUtc = platformSeen,
|
||||
whatsNewSeenAgentUtc = agentSeen
|
||||
},
|
||||
@@ -69,6 +70,7 @@ public class InfrastructureWireParityTests
|
||||
HomedApp = "primary",
|
||||
BootstrapTokenEnabled = true,
|
||||
UnrestrictedModeEnabled = false,
|
||||
McpClientRegistrationEnabled = true,
|
||||
WhatsNewSeenPlatformUtc = platformSeen,
|
||||
WhatsNewSeenAgentUtc = agentSeen
|
||||
});
|
||||
@@ -105,6 +107,7 @@ public class InfrastructureWireParityTests
|
||||
homedApp = "legacy",
|
||||
bootstrapTokenEnabled = false,
|
||||
unrestrictedModeEnabled = false,
|
||||
mcpClientRegistrationEnabled = false,
|
||||
whatsNewSeenPlatformUtc,
|
||||
whatsNewSeenAgentUtc
|
||||
},
|
||||
@@ -125,6 +128,7 @@ public class InfrastructureWireParityTests
|
||||
HomedApp = "legacy",
|
||||
BootstrapTokenEnabled = false,
|
||||
UnrestrictedModeEnabled = false,
|
||||
McpClientRegistrationEnabled = false,
|
||||
WhatsNewSeenPlatformUtc = null,
|
||||
WhatsNewSeenAgentUtc = null
|
||||
});
|
||||
@@ -656,7 +660,8 @@ public class InfrastructureWireParityTests
|
||||
// DELIBERATE wire change (error-envelope pass): the body now leads with the envelope prefix
|
||||
// error/code/correlationId (error carries the former `message`); quotaExceeded stays as the
|
||||
// MCP's discriminator. These literals pin the NEW shape (correlationId is stamped by the writer,
|
||||
// so the builder leaves it empty).
|
||||
// so the builder leaves it empty). Both windows belong to the caller's own tenant since 2026-09-11
|
||||
// (the budget follows the delegating tenant) — there is no managed-tenant shape any more.
|
||||
|
||||
[Fact]
|
||||
public void McpQuotaExceededResponse_matches_the_daily_blocked_shape()
|
||||
@@ -745,62 +750,6 @@ public class InfrastructureWireParityTests
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void McpQuotaExceededResponse_matches_the_managed_tenant_blocked_shape()
|
||||
{
|
||||
// A delegated (MSP) read charged to a MANAGED Community tenant whose organization window is spent:
|
||||
// level=tenant, the managed tenant is named (label + targetTenantId) and the upgrade path is spelled out.
|
||||
var decision = McpQuotaService.BuildDecision(
|
||||
new McpPlanLimits("pro", 1000, 20000, "community", 300, 9000),
|
||||
dailyUsed: 12, monthlyUsed: 340, tenantDailyUsed: 300, tenantMonthlyUsed: 2100,
|
||||
new DateTime(2026, 8, 30, 15, 0, 0, DateTimeKind.Utc),
|
||||
targetTenantId: "7aa20c11-0002-4b7c-a1d2-52f3aaaa0002");
|
||||
|
||||
AssertParity(
|
||||
new
|
||||
{
|
||||
error = "MCP daily request quota of the managed tenant 'customer.example' exceeded (tenant plan 'community', shared by all its members and delegated admins). That tenant is on the Community plan, which is sized for occasional use; its own plan governs this window, not yours. Upgrading that tenant to Pro lifts its organization windows. Resets at 2026-08-31T00:00:00Z.",
|
||||
code = "QuotaExceeded",
|
||||
correlationId = "",
|
||||
quotaExceeded = true,
|
||||
plan = "pro",
|
||||
scope = "daily",
|
||||
level = "tenant",
|
||||
limit = 300,
|
||||
used = 300L,
|
||||
resetUtc = "2026-08-31T00:00:00Z",
|
||||
targetTenantId = "7aa20c11-0002-4b7c-a1d2-52f3aaaa0002"
|
||||
},
|
||||
McpQuotaEnforcementMiddleware.BuildExceededResponse(decision, "customer.example"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void McpQuotaExceededResponse_matches_the_all_managed_tenants_exhausted_shape()
|
||||
{
|
||||
// The fleet aggregate where EVERY managed tenant is spent: no single target, the count is named.
|
||||
var decision = McpQuotaService.BuildDecision(
|
||||
new McpPlanLimits("pro", 1000, 20000, "community", 300, 9000),
|
||||
dailyUsed: 12, monthlyUsed: 340, tenantDailyUsed: 300, tenantMonthlyUsed: 2100,
|
||||
new DateTime(2026, 8, 30, 15, 0, 0, DateTimeKind.Utc),
|
||||
targetTenantId: "7aa20c11-0002-4b7c-a1d2-52f3aaaa0002");
|
||||
|
||||
AssertParity(
|
||||
new
|
||||
{
|
||||
error = "MCP request quota exceeded for all 2 managed tenants in scope (each managed tenant's own plan governs its organization windows; upgrading a managed tenant to Pro lifts them). Earliest reset at 2026-08-31T00:00:00Z.",
|
||||
code = "QuotaExceeded",
|
||||
correlationId = "",
|
||||
quotaExceeded = true,
|
||||
plan = "pro",
|
||||
scope = "daily",
|
||||
level = "tenant",
|
||||
limit = 300,
|
||||
used = 300L,
|
||||
resetUtc = "2026-08-31T00:00:00Z"
|
||||
},
|
||||
McpQuotaEnforcementMiddleware.BuildExceededResponse(decision, exhaustedTenantCount: 2));
|
||||
}
|
||||
|
||||
private static void AssertParity(object anonymousLiteral, IApiResponse typed)
|
||||
=> ApiResponseWireParityTests.AssertWireIdentical(anonymousLiteral, typed);
|
||||
}
|
||||
|
||||
@@ -162,6 +162,7 @@ public class IntuneDeviceBindingValidatorTests
|
||||
[InlineData(IntuneDeviceBindingOutcome.NotFound)]
|
||||
[InlineData(IntuneDeviceBindingOutcome.NoDeviceIdInCert)]
|
||||
[InlineData(IntuneDeviceBindingOutcome.PermissionMissing)]
|
||||
[InlineData(IntuneDeviceBindingOutcome.NotManaged)]
|
||||
public void DefinitiveNegatives_AreNotTransient(IntuneDeviceBindingOutcome outcome)
|
||||
{
|
||||
// Only Transient may be retried / left uncached. A missing grant or a foreign device is a
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using AutopilotMonitor.Functions.Helpers;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Functions.Services.GraphResolution;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using AutopilotMonitor.Shared.Models.Graph;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Intune Enrollment Validation: the certificate's Intune device id admits a device without any
|
||||
/// pre-registration (<see cref="IntuneDeviceBindingValidator.ValidateAsync"/>), and observes
|
||||
/// devices another validator admitted (<see cref="IntuneDeviceBindingValidator.ObserveInBackground"/>)
|
||||
/// — the latter only when the tenant granted the Graph permission, so a tenant without the add-on
|
||||
/// costs no Graph call at all.
|
||||
/// </summary>
|
||||
public class IntuneEnrollmentValidationTests
|
||||
{
|
||||
private const string TenantId = "11111111-1111-1111-1111-111111111111";
|
||||
private const string DeviceId = "07bc0167-9061-43b7-b243-0bb6aeda736e";
|
||||
|
||||
private static readonly DateTimeOffset OldCert = DateTimeOffset.UtcNow.AddDays(-30);
|
||||
private static readonly DateTimeOffset RecentCert = DateTimeOffset.UtcNow.AddMinutes(-5);
|
||||
|
||||
private const string MatchBody =
|
||||
"{\"id\":\"07bc0167-9061-43b7-b243-0bb6aeda736e\",\"deviceName\":\"TEST-DEVICE-01\",\"managementState\":\"managed\","
|
||||
+ "\"serialNumber\":\"TESTSERIAL01\",\"managedDeviceOwnerType\":\"company\",\"deviceEnrollmentType\":\"windowsAzureADJoin\"}";
|
||||
|
||||
// ------------------------------------------------------------------ harness
|
||||
|
||||
private sealed class ScriptedHandler : HttpMessageHandler
|
||||
{
|
||||
private readonly Queue<Func<HttpResponseMessage>> _responses;
|
||||
public List<HttpRequestMessage> Requests { get; } = new();
|
||||
|
||||
public ScriptedHandler(params Func<HttpResponseMessage>[] responses) => _responses = new(responses);
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||
{
|
||||
lock (Requests) Requests.Add(request);
|
||||
var next = _responses.Count > 1 ? _responses.Dequeue() : _responses.Peek();
|
||||
return Task.FromResult(next());
|
||||
}
|
||||
}
|
||||
|
||||
private static Func<HttpResponseMessage> Respond(HttpStatusCode status, string body = "{}")
|
||||
=> () => new HttpResponseMessage(status) { Content = new StringContent(body) };
|
||||
|
||||
private sealed record Sut(
|
||||
IntuneDeviceBindingValidator Validator,
|
||||
ScriptedHandler Handler,
|
||||
MemoryCache Cache,
|
||||
Mock<GraphTokenService> Tokens,
|
||||
Mock<IGraphFeatureDetector> Detector);
|
||||
|
||||
private static Sut Build(bool permissionGranted, params Func<HttpResponseMessage>[] responses)
|
||||
{
|
||||
var handler = new ScriptedHandler(responses.Length == 0 ? new[] { Respond(HttpStatusCode.OK, MatchBody) } : responses);
|
||||
var factory = new Mock<IHttpClientFactory>();
|
||||
factory.Setup(f => f.CreateClient(It.IsAny<string>())).Returns(() => new HttpClient(handler, disposeHandler: false));
|
||||
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["EntraId:ClientId"] = "aaaaaaaa-0000-0000-0000-000000000001",
|
||||
["EntraId:ClientSecret"] = "secret",
|
||||
}).Build();
|
||||
var registry = new EntraAppRegistry(configuration, NullLogger<EntraAppRegistry>.Instance);
|
||||
var tenantConfig = new Mock<TenantConfigurationService>(
|
||||
Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, cache)
|
||||
{ CallBase = false };
|
||||
var tokens = new Mock<GraphTokenService>(
|
||||
NullLogger<GraphTokenService>.Instance, Mock.Of<IHttpClientFactory>(), cache,
|
||||
configuration, registry, tenantConfig.Object)
|
||||
{ CallBase = false };
|
||||
tokens.Setup(t => t.GetAccessTokenAsync(TenantId, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(GraphTokenResult.Success("token"));
|
||||
|
||||
var detector = new Mock<IGraphFeatureDetector>();
|
||||
detector.Setup(d => d.HasPermissionAsync(TenantId, GraphAppPermissions.DeviceManagementManagedDevicesReadAll, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(permissionGranted);
|
||||
|
||||
var validator = new IntuneDeviceBindingValidator(
|
||||
NullLogger<IntuneDeviceBindingValidator>.Instance, factory.Object, cache, tokens.Object, detector.Object);
|
||||
return new Sut(validator, handler, cache, tokens, detector);
|
||||
}
|
||||
|
||||
private static async Task WaitUntil(Func<bool> condition)
|
||||
{
|
||||
var deadline = DateTime.UtcNow.AddSeconds(10);
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline)
|
||||
throw new TimeoutException("Background observation did not settle in time.");
|
||||
await Task.Delay(20);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool InFlight(MemoryCache cache)
|
||||
=> cache.TryGetValue(IntuneDeviceBindingValidator.BuildCacheKey(TenantId, DeviceId) + ":inflight", out _);
|
||||
|
||||
// ------------------------------------------------------------------ admitting lookups
|
||||
|
||||
[Fact]
|
||||
public async Task Admitting_Match_IsCached_SoTheNextRequestCostsNoGraphCall()
|
||||
{
|
||||
var sut = Build(permissionGranted: true, Respond(HttpStatusCode.OK, MatchBody));
|
||||
|
||||
var first = await sut.Validator.ValidateAsync(TenantId, DeviceId, OldCert, IntuneDeviceBindingRole.Admitting);
|
||||
var second = await sut.Validator.ValidateAsync(TenantId, DeviceId, OldCert, IntuneDeviceBindingRole.Admitting);
|
||||
|
||||
Assert.Equal(IntuneDeviceBindingOutcome.Match, first.Outcome);
|
||||
Assert.False(first.ServedFromCache);
|
||||
Assert.True(second.ServedFromCache);
|
||||
Assert.Single(sut.Handler.Requests);
|
||||
Assert.Equal("TESTSERIAL01", second.SerialNumber);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admitting_UsesAPointGetWithTheTelemetrySelect()
|
||||
{
|
||||
var sut = Build(permissionGranted: true);
|
||||
|
||||
await sut.Validator.ValidateAsync(TenantId, DeviceId.ToUpperInvariant(), OldCert, IntuneDeviceBindingRole.Admitting);
|
||||
|
||||
var uri = Uri.UnescapeDataString(Assert.Single(sut.Handler.Requests).RequestUri!.ToString());
|
||||
Assert.Contains($"/v1.0/deviceManagement/managedDevices/{DeviceId}?", uri);
|
||||
Assert.DoesNotContain("$filter", uri);
|
||||
foreach (var field in new[] { "managementState", "serialNumber", "managedDeviceOwnerType", "deviceEnrollmentType", "azureADRegistered" })
|
||||
Assert.Contains(field, uri);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admitting_NotFound_WithAnOldCertificate_IsDefinitiveAndCached()
|
||||
{
|
||||
var sut = Build(permissionGranted: true, Respond(HttpStatusCode.NotFound));
|
||||
|
||||
var result = await sut.Validator.ValidateAsync(TenantId, DeviceId, OldCert, IntuneDeviceBindingRole.Admitting);
|
||||
|
||||
Assert.Equal(IntuneDeviceBindingOutcome.NotFound, result.Outcome);
|
||||
Assert.Single(sut.Handler.Requests);
|
||||
Assert.Equal(IntuneDeviceBindingOutcome.NotFound, sut.Validator.TryGetCached(TenantId, DeviceId)?.Outcome);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admitting_NotFound_WithARecentCertificate_IsTransientAndNeverCached()
|
||||
{
|
||||
// The enrollment race: the device may not be visible in Graph yet. Caching the 404 would
|
||||
// keep a genuine device out for the whole negative TTL.
|
||||
var sut = Build(permissionGranted: true, Respond(HttpStatusCode.NotFound));
|
||||
|
||||
var result = await sut.Validator.ValidateAsync(TenantId, DeviceId, RecentCert, IntuneDeviceBindingRole.Admitting);
|
||||
|
||||
Assert.Equal(IntuneDeviceBindingOutcome.NotFoundRecentEnrollment, result.Outcome);
|
||||
Assert.True(result.IsTransient);
|
||||
Assert.Equal(2, sut.Handler.Requests.Count);
|
||||
Assert.Null(sut.Validator.TryGetCached(TenantId, DeviceId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admitting_RecentCertificate_ThenTheObjectAppears_IsAdmittedOnTheRetry()
|
||||
{
|
||||
var sut = Build(permissionGranted: true, Respond(HttpStatusCode.NotFound), Respond(HttpStatusCode.OK, MatchBody));
|
||||
|
||||
var result = await sut.Validator.ValidateAsync(TenantId, DeviceId, RecentCert, IntuneDeviceBindingRole.Admitting);
|
||||
|
||||
Assert.Equal(IntuneDeviceBindingOutcome.Match, result.Outcome);
|
||||
Assert.Equal(2, sut.Handler.Requests.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admitting_ForbiddenWithAFreshTokenToo_IsPermissionMissing()
|
||||
{
|
||||
var sut = Build(permissionGranted: false, Respond(HttpStatusCode.Forbidden), Respond(HttpStatusCode.Forbidden));
|
||||
|
||||
var result = await sut.Validator.ValidateAsync(TenantId, DeviceId, OldCert, IntuneDeviceBindingRole.Admitting);
|
||||
|
||||
Assert.Equal(IntuneDeviceBindingOutcome.PermissionMissing, result.Outcome);
|
||||
sut.Tokens.Verify(t => t.InvalidateTenant(TenantId), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admitting_RunsEvenWhenThePermissionWasNotDetected()
|
||||
{
|
||||
// An admin who just ran the grant script must not wait for the detector's token cache:
|
||||
// the admitting lookup goes to Graph and the 401/403 refresh picks up the new role.
|
||||
var sut = Build(permissionGranted: false, Respond(HttpStatusCode.Forbidden), Respond(HttpStatusCode.OK, MatchBody));
|
||||
|
||||
var result = await sut.Validator.ValidateAsync(TenantId, DeviceId, OldCert, IntuneDeviceBindingRole.Admitting);
|
||||
|
||||
Assert.Equal(IntuneDeviceBindingOutcome.Match, result.Outcome);
|
||||
sut.Detector.Verify(d => d.HasPermissionAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admitting_InvalidDeviceId_NeverReachesGraph()
|
||||
{
|
||||
var sut = Build(permissionGranted: true);
|
||||
|
||||
var result = await sut.Validator.ValidateAsync(TenantId, "not-a-guid", OldCert, IntuneDeviceBindingRole.Admitting);
|
||||
|
||||
Assert.Equal(IntuneDeviceBindingOutcome.NoDeviceIdInCert, result.Outcome);
|
||||
Assert.Empty(sut.Handler.Requests);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ observation
|
||||
|
||||
[Fact]
|
||||
public async Task Observe_WithoutThePermission_MakesNoGraphCall_AndAsksTheDetectorOncePerWindow()
|
||||
{
|
||||
var sut = Build(permissionGranted: false);
|
||||
|
||||
sut.Validator.ObserveInBackground(TenantId, DeviceId, OldCert, null);
|
||||
await WaitUntil(() => !InFlight(sut.Cache));
|
||||
|
||||
// Later requests of the same tenant stop at the cached "not granted" verdict.
|
||||
sut.Validator.ObserveInBackground(TenantId, DeviceId, OldCert, null);
|
||||
sut.Validator.ObserveInBackground(TenantId, "22222222-3333-4444-5555-666666666666", OldCert, null);
|
||||
await WaitUntil(() => !InFlight(sut.Cache));
|
||||
|
||||
Assert.Empty(sut.Handler.Requests);
|
||||
sut.Tokens.Verify(t => t.GetAccessTokenAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
sut.Detector.Verify(d => d.HasPermissionAsync(TenantId, GraphAppPermissions.DeviceManagementManagedDevicesReadAll, It.IsAny<CancellationToken>()), Times.Once);
|
||||
Assert.Null(sut.Validator.TryGetCached(TenantId, DeviceId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Observe_WithThePermission_FillsTheCacheInTheBackground()
|
||||
{
|
||||
var sut = Build(permissionGranted: true, Respond(HttpStatusCode.OK, MatchBody));
|
||||
|
||||
sut.Validator.ObserveInBackground(TenantId, DeviceId, OldCert, "session-1");
|
||||
await WaitUntil(() => sut.Validator.TryGetCached(TenantId, DeviceId) != null);
|
||||
|
||||
var observed = sut.Validator.TryGetCached(TenantId, DeviceId)!;
|
||||
Assert.Equal(IntuneDeviceBindingOutcome.Match, observed.Outcome);
|
||||
Assert.True(observed.ServedFromCache);
|
||||
Assert.Single(sut.Handler.Requests);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Observe_WhenAlreadyCached_DoesNothing()
|
||||
{
|
||||
var sut = Build(permissionGranted: true, Respond(HttpStatusCode.OK, MatchBody));
|
||||
await sut.Validator.ValidateAsync(TenantId, DeviceId, OldCert, IntuneDeviceBindingRole.Admitting);
|
||||
|
||||
sut.Validator.ObserveInBackground(TenantId, DeviceId, OldCert, null);
|
||||
|
||||
Assert.False(InFlight(sut.Cache));
|
||||
Assert.Single(sut.Handler.Requests);
|
||||
sut.Detector.Verify(d => d.HasPermissionAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Observe_TransientOutcome_KeepsACooldownInsteadOfALookupPerRequest()
|
||||
{
|
||||
// A recent certificate whose device is not visible yet caches nothing; without the cooldown
|
||||
// every request of that device would start a new Graph lookup.
|
||||
var sut = Build(permissionGranted: true, Respond(HttpStatusCode.NotFound));
|
||||
|
||||
sut.Validator.ObserveInBackground(TenantId, DeviceId, RecentCert, null);
|
||||
await WaitUntil(() => sut.Handler.Requests.Count == 2);
|
||||
await Task.Delay(100);
|
||||
|
||||
sut.Validator.ObserveInBackground(TenantId, DeviceId, RecentCert, null);
|
||||
await Task.Delay(100);
|
||||
|
||||
Assert.True(InFlight(sut.Cache));
|
||||
Assert.Equal(2, sut.Handler.Requests.Count);
|
||||
Assert.Null(sut.Validator.TryGetCached(TenantId, DeviceId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Observe_InvalidDeviceId_DoesNothing()
|
||||
{
|
||||
var sut = Build(permissionGranted: true);
|
||||
|
||||
sut.Validator.ObserveInBackground(TenantId, null, OldCert, null);
|
||||
|
||||
sut.Detector.Verify(d => d.HasPermissionAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ SecurityValidator chain
|
||||
|
||||
private static (SecurityValidator Validator, Mock<IntuneDeviceBindingValidator> Binding) BuildChain(TenantConfiguration config)
|
||||
{
|
||||
var configRepo = Mock.Of<IConfigRepository>();
|
||||
var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
|
||||
config.ManufacturerWhitelist = "*";
|
||||
config.ModelWhitelist = "*";
|
||||
|
||||
var configService = new Mock<TenantConfigurationService>(
|
||||
configRepo, Mock.Of<ILogger<TenantConfigurationService>>(), cache)
|
||||
{ CallBase = false };
|
||||
configService.Setup(x => x.TryGetConfigurationAsync(It.IsAny<string>())).ReturnsAsync((config, true));
|
||||
|
||||
var adminConfigService = new Mock<AdminConfigurationService>(
|
||||
configRepo, Mock.Of<ILogger<AdminConfigurationService>>(), cache)
|
||||
{ CallBase = false };
|
||||
adminConfigService.Setup(x => x.GetConfigurationAsync()).ReturnsAsync(new AdminConfiguration());
|
||||
|
||||
var binding = new Mock<IntuneDeviceBindingValidator>(
|
||||
NullLogger<IntuneDeviceBindingValidator>.Instance, Mock.Of<IHttpClientFactory>(), cache,
|
||||
null!, Mock.Of<IGraphFeatureDetector>())
|
||||
{ CallBase = false };
|
||||
|
||||
var validator = new SecurityValidator(
|
||||
configService.Object, adminConfigService.Object,
|
||||
new RateLimitService(cache, Mock.Of<ILogger<RateLimitService>>()),
|
||||
autopilotDeviceValidator: null!, corporateIdentifierValidator: null!,
|
||||
NullLogger.Instance,
|
||||
intuneDeviceBindingValidator: binding.Object);
|
||||
return (validator, binding);
|
||||
}
|
||||
|
||||
private static string CertTenant => CertTenantBindingTests.SampleCertTenantId.ToString();
|
||||
|
||||
private static void SetupAdmitting(Mock<IntuneDeviceBindingValidator> binding, IntuneDeviceBindingResult result)
|
||||
=> binding.Setup(b => b.ValidateAsync(CertTenant, DeviceId, It.IsAny<DateTimeOffset?>(), IntuneDeviceBindingRole.Admitting,
|
||||
It.IsAny<string?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(result);
|
||||
|
||||
[Fact]
|
||||
public async Task Chain_OnlyIntuneEnrollmentEnabled_PassesTheGate_AndAdmitsAnEnrolledDevice()
|
||||
{
|
||||
var (validator, binding) = BuildChain(new TenantConfiguration { ValidateIntuneDeviceBinding = true });
|
||||
SetupAdmitting(binding, new IntuneDeviceBindingResult
|
||||
{
|
||||
Outcome = IntuneDeviceBindingOutcome.Match, IntuneDeviceId = DeviceId,
|
||||
SerialNumber = "TESTSERIAL01", OwnerType = "personal", EnrollmentType = "windowsAzureADJoin",
|
||||
});
|
||||
var items = new Dictionary<object, object>();
|
||||
|
||||
var result = await validator.ValidateRequestAsync(
|
||||
CertTenantBindingTests.BuildRequestWithCert(CertTenantBindingTests.SampleCertBase64(), items), CertTenant);
|
||||
|
||||
Assert.True(result.IsValid, result.ErrorMessage + " " + result.Details);
|
||||
Assert.Equal(ValidatorType.IntuneEnrollment, result.ValidatedBy);
|
||||
Assert.Equal("IntuneEnrollment", items[RequestRowMarkers.DeviceValidationKey]);
|
||||
Assert.Equal("Match", items[RequestRowMarkers.CertDeviceBindingKey]);
|
||||
Assert.Equal("Admitting", items[RequestRowMarkers.CertDeviceBindingRoleKey]);
|
||||
Assert.Equal("true", items[RequestRowMarkers.CertDeviceSerialMatchKey]);
|
||||
Assert.Equal("personal", items[RequestRowMarkers.CertDeviceOwnerTypeKey]);
|
||||
Assert.Equal("windowsAzureADJoin", items[RequestRowMarkers.CertDeviceEnrollmentTypeKey]);
|
||||
// The admitting lookup already stamped the row; no second, observing lookup.
|
||||
binding.Verify(b => b.ObserveInBackground(It.IsAny<string>(), It.IsAny<string?>(), It.IsAny<DateTimeOffset?>(), It.IsAny<string?>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Chain_PassesTheCertificateNotBeforeToTheLookup()
|
||||
{
|
||||
var (validator, binding) = BuildChain(new TenantConfiguration { ValidateIntuneDeviceBinding = true });
|
||||
DateTimeOffset? seen = null;
|
||||
binding.Setup(b => b.ValidateAsync(CertTenant, DeviceId, It.IsAny<DateTimeOffset?>(), IntuneDeviceBindingRole.Admitting,
|
||||
It.IsAny<string?>(), It.IsAny<CancellationToken>()))
|
||||
.Callback<string, string?, DateTimeOffset?, IntuneDeviceBindingRole, string?, CancellationToken>((_, _, nb, _, _, _) => seen = nb)
|
||||
.ReturnsAsync(new IntuneDeviceBindingResult { Outcome = IntuneDeviceBindingOutcome.Match });
|
||||
|
||||
await validator.ValidateRequestAsync(
|
||||
CertTenantBindingTests.BuildRequestWithCert(CertTenantBindingTests.SampleCertBase64()), CertTenant);
|
||||
|
||||
Assert.Equal(new DateTimeOffset(2026, 5, 8, 12, 16, 49, TimeSpan.Zero), seen);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(IntuneDeviceBindingOutcome.NotFound)]
|
||||
[InlineData(IntuneDeviceBindingOutcome.NotManaged)]
|
||||
[InlineData(IntuneDeviceBindingOutcome.NoDeviceIdInCert)]
|
||||
public async Task Chain_DefinitiveMiss_IsA403(IntuneDeviceBindingOutcome outcome)
|
||||
{
|
||||
var (validator, binding) = BuildChain(new TenantConfiguration { ValidateIntuneDeviceBinding = true });
|
||||
SetupAdmitting(binding, new IntuneDeviceBindingResult { Outcome = outcome, ErrorMessage = "miss" });
|
||||
var items = new Dictionary<object, object>();
|
||||
|
||||
var result = await validator.ValidateRequestAsync(
|
||||
CertTenantBindingTests.BuildRequestWithCert(CertTenantBindingTests.SampleCertBase64(), items), CertTenant);
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, result.StatusCode);
|
||||
Assert.Equal(outcome.ToString(), items[RequestRowMarkers.CertDeviceBindingKey]);
|
||||
Assert.Equal(RequestRowMarkers.DeviceValidation.Rejected, items[RequestRowMarkers.DeviceValidationKey]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(IntuneDeviceBindingOutcome.NotFoundRecentEnrollment, 30)]
|
||||
[InlineData(IntuneDeviceBindingOutcome.Transient, 30)]
|
||||
[InlineData(IntuneDeviceBindingOutcome.PermissionMissing, 120)]
|
||||
public async Task Chain_NotYetDecidable_IsA503WithRetryAfter(IntuneDeviceBindingOutcome outcome, int retryAfter)
|
||||
{
|
||||
var (validator, binding) = BuildChain(new TenantConfiguration { ValidateIntuneDeviceBinding = true });
|
||||
SetupAdmitting(binding, new IntuneDeviceBindingResult { Outcome = outcome, ErrorMessage = "later" });
|
||||
|
||||
var result = await validator.ValidateRequestAsync(
|
||||
CertTenantBindingTests.BuildRequestWithCert(CertTenantBindingTests.SampleCertBase64()), CertTenant);
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, result.StatusCode);
|
||||
Assert.Equal(retryAfter, result.RetryAfterSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Chain_ToggleOff_NoAdmittingLookup_OnlyABackgroundObservation()
|
||||
{
|
||||
var (validator, binding) = BuildChain(new TenantConfiguration { AllowInsecureAgentRequests = true });
|
||||
var items = new Dictionary<object, object>();
|
||||
|
||||
var result = await validator.ValidateRequestAsync(
|
||||
CertTenantBindingTests.BuildRequestWithCert(CertTenantBindingTests.SampleCertBase64(), items), CertTenant);
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
binding.Verify(b => b.ValidateAsync(It.IsAny<string>(), It.IsAny<string?>(), It.IsAny<DateTimeOffset?>(),
|
||||
It.IsAny<IntuneDeviceBindingRole>(), It.IsAny<string?>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
binding.Verify(b => b.ObserveInBackground(CertTenant, DeviceId, It.IsAny<DateTimeOffset?>(), It.IsAny<string?>()), Times.Once);
|
||||
Assert.False(items.ContainsKey(RequestRowMarkers.CertDeviceBindingKey));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Chain_CachedObservation_IsStampedAsObserving_AndNeverRejects()
|
||||
{
|
||||
var (validator, binding) = BuildChain(new TenantConfiguration { AllowInsecureAgentRequests = true });
|
||||
binding.Setup(b => b.TryGetCached(CertTenant, DeviceId)).Returns(new IntuneDeviceBindingResult
|
||||
{
|
||||
Outcome = IntuneDeviceBindingOutcome.NotFound, SerialNumber = "OTHER-SERIAL",
|
||||
});
|
||||
var items = new Dictionary<object, object>();
|
||||
|
||||
var result = await validator.ValidateRequestAsync(
|
||||
CertTenantBindingTests.BuildRequestWithCert(CertTenantBindingTests.SampleCertBase64(), items), CertTenant);
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
Assert.Equal("NotFound", items[RequestRowMarkers.CertDeviceBindingKey]);
|
||||
Assert.Equal("Observing", items[RequestRowMarkers.CertDeviceBindingRoleKey]);
|
||||
Assert.Equal("false", items[RequestRowMarkers.CertDeviceSerialMatchKey]);
|
||||
binding.Verify(b => b.ObserveInBackground(It.IsAny<string>(), It.IsAny<string?>(), It.IsAny<DateTimeOffset?>(), It.IsAny<string?>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Chain_NothingEnabled_IsStillRejectedAtTheGate()
|
||||
{
|
||||
var (validator, _) = BuildChain(new TenantConfiguration());
|
||||
|
||||
var result = await validator.ValidateRequestAsync(
|
||||
CertTenantBindingTests.BuildRequestWithCert(CertTenantBindingTests.SampleCertBase64()), CertTenant);
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Equal("Device validation is required", result.ErrorMessage);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ gate + wire
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(TenantConfiguration.ValidateAutopilotDevice))]
|
||||
[InlineData(nameof(TenantConfiguration.ValidateCorporateIdentifier))]
|
||||
[InlineData(nameof(TenantConfiguration.ValidateDeviceAssociation))]
|
||||
[InlineData(nameof(TenantConfiguration.ValidateCloudPcDevice))]
|
||||
[InlineData(nameof(TenantConfiguration.ValidateIntuneDeviceBinding))]
|
||||
public void HasAnyDeviceValidation_EachMethodCountsAlone(string property)
|
||||
{
|
||||
var config = new TenantConfiguration();
|
||||
Assert.False(config.HasAnyDeviceValidation());
|
||||
|
||||
typeof(TenantConfiguration).GetProperty(property)!.SetValue(config, true);
|
||||
|
||||
Assert.True(config.HasAnyDeviceValidation());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HasAnyDeviceValidation_CoversEveryValidateFlag()
|
||||
{
|
||||
// A new Validate* flag that the gate does not know would leave its tenants locked out.
|
||||
var flags = typeof(TenantConfiguration).GetProperties()
|
||||
.Where(p => p.PropertyType == typeof(bool) && p.Name.StartsWith("Validate", StringComparison.Ordinal))
|
||||
.Select(p => p.Name)
|
||||
.ToList();
|
||||
|
||||
foreach (var flag in flags)
|
||||
{
|
||||
var config = new TenantConfiguration();
|
||||
typeof(TenantConfiguration).GetProperty(flag)!.SetValue(config, true);
|
||||
Assert.True(config.HasAnyDeviceValidation(), $"{flag} is not part of HasAnyDeviceValidation");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegisterWire_EveryValidatorTheBackendSends_ParsesInTheAgent()
|
||||
{
|
||||
// The backend writes enum names (ApiJsonOptions); the agent reads the same Shared model
|
||||
// with a plain JsonConvert.DeserializeObject. An agent built from this Shared therefore
|
||||
// parses every member — which is why a new member ships with an agent release first.
|
||||
foreach (var value in Enum.GetValues<ValidatorType>())
|
||||
{
|
||||
var json = JsonSerializer.Serialize(new RegisterSessionResponse { ValidatedBy = value }, ApiJsonOptions.Create());
|
||||
Assert.Contains($"\"validatedBy\":\"{value}\"", json);
|
||||
|
||||
var parsed = Newtonsoft.Json.JsonConvert.DeserializeObject<RegisterSessionResponse>(json);
|
||||
Assert.Equal(value, parsed!.ValidatedBy);
|
||||
}
|
||||
}
|
||||
|
||||
private enum ReleasedAgentValidatorType { Unknown = 0, AutopilotV1 = 1, CorporateIdentifier = 2, DeviceAssociation = 3, Bootstrap = 4, CloudPc = 5 }
|
||||
|
||||
private sealed class ReleasedAgentResponse
|
||||
{
|
||||
public ReleasedAgentValidatorType ValidatedBy { get; set; }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegisterWire_AnAgentWithoutTheMember_FailsTheRegistration()
|
||||
{
|
||||
// Why the release order matters: an agent that predates IntuneEnrollment throws on it,
|
||||
// and a failed parse counts as a failed registration. Agents self-update at every start,
|
||||
// so releasing the agent before the backend closes the gap.
|
||||
Assert.ThrowsAny<Newtonsoft.Json.JsonException>(() =>
|
||||
Newtonsoft.Json.JsonConvert.DeserializeObject<ReleasedAgentResponse>("{\"validatedBy\":\"IntuneEnrollment\"}"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("TESTSERIAL01", "testserial01", true)]
|
||||
[InlineData(" TESTSERIAL01 ", "TESTSERIAL01", true)]
|
||||
[InlineData("TESTSERIAL01", "OTHER", false)]
|
||||
[InlineData(null, "TESTSERIAL01", null)]
|
||||
[InlineData("TESTSERIAL01", "", null)]
|
||||
public void SerialMatch_ComparesTrimmedAndCaseInsensitive(string? header, string? intune, bool? expected)
|
||||
=> Assert.Equal(expected, RequestRowMarkers.SerialMatch(header, intune));
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Functions.Services.Backup;
|
||||
using AutopilotMonitor.Functions.Services.Maintenance;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Azure.Storage.Blobs.Specialized;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Single-flight of the platform maintenance run: the 2h timer and the manual trigger enter
|
||||
/// through one gate, so a second run is skipped instead of aggregating, cleaning up and
|
||||
/// backfilling the same tables in parallel — and a skip never looks like an active run.
|
||||
/// </summary>
|
||||
public class MaintenanceRunGateTests
|
||||
{
|
||||
private sealed class Harness
|
||||
{
|
||||
public Mock<MaintenanceRunLockStore> LockStore { get; }
|
||||
public Mock<BlobLeaseClient> Lease { get; } = new();
|
||||
public List<string> OpsEvents { get; } = new();
|
||||
public MaintenanceRunGate Sut { get; }
|
||||
|
||||
public Harness()
|
||||
{
|
||||
LockStore = new Mock<MaintenanceRunLockStore>(new SessionDeletionMaintenanceFunctionTests.MaintenanceBlobStub());
|
||||
LockStore.Setup(l => l.AcquireLeaseAsync(It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(Lease.Object);
|
||||
|
||||
var opsRepo = new Mock<IOpsEventRepository>();
|
||||
opsRepo.Setup(r => r.SaveOpsEventAsync(It.IsAny<OpsEventEntry>()))
|
||||
.Returns<OpsEventEntry>(e => { lock (OpsEvents) OpsEvents.Add(e.EventType); return Task.CompletedTask; });
|
||||
var adminConfig = new Mock<AdminConfigurationService>(
|
||||
Mock.Of<IConfigRepository>(), NullLogger<AdminConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
|
||||
var opsService = new OpsEventService(opsRepo.Object, NullLogger<OpsEventService>.Instance,
|
||||
TestNotifications.InertOpsAlertDispatch(adminConfig.Object));
|
||||
|
||||
Sut = new MaintenanceRunGate(LockStore.Object, opsService, NullLogger<MaintenanceRunGate>.Instance);
|
||||
}
|
||||
|
||||
public void HoldLease() =>
|
||||
LockStore.Setup(l => l.AcquireLeaseAsync(It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new LeaseHeldException("held", new Exception("409")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_held_lease_skips_the_run_and_never_reports_it_as_started()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.HoldLease();
|
||||
var ran = false;
|
||||
|
||||
var result = await h.Sut.RunExclusiveAsync("Timer", () => { ran = true; return Task.CompletedTask; });
|
||||
|
||||
Assert.False(result);
|
||||
Assert.False(ran);
|
||||
Assert.Equal(new[] { OpsEventTypes.MaintenanceSkippedLocked }, h.OpsEvents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Started_is_written_under_the_lease_before_the_body_and_the_lease_is_released_last()
|
||||
{
|
||||
var h = new Harness();
|
||||
var order = new List<string>();
|
||||
h.Lease.Setup(l => l.ReleaseAsync(It.IsAny<Azure.RequestConditions>(), It.IsAny<CancellationToken>()))
|
||||
.Callback(() => order.Add("release"))
|
||||
.ReturnsAsync(Mock.Of<Azure.Response<Azure.Storage.Blobs.Models.ReleasedObjectInfo>>());
|
||||
|
||||
var result = await h.Sut.RunExclusiveAsync("admin@example.com", () =>
|
||||
{
|
||||
order.Add($"body after [{string.Join(",", h.OpsEvents)}]");
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
Assert.True(result);
|
||||
Assert.Equal(new[] { $"body after [{OpsEventTypes.MaintenanceStarted}]", "release" }, order);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_lease_is_released_when_the_body_throws()
|
||||
{
|
||||
var h = new Harness();
|
||||
var released = false;
|
||||
h.Lease.Setup(l => l.ReleaseAsync(It.IsAny<Azure.RequestConditions>(), It.IsAny<CancellationToken>()))
|
||||
.Callback(() => released = true)
|
||||
.ReturnsAsync(Mock.Of<Azure.Response<Azure.Storage.Blobs.Models.ReleasedObjectInfo>>());
|
||||
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
h.Sut.RunExclusiveAsync("Timer", () => throw new InvalidOperationException("boom")));
|
||||
|
||||
Assert.True(released);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Probe_reports_an_active_run_while_the_lease_is_held()
|
||||
{
|
||||
var h = new Harness();
|
||||
h.HoldLease();
|
||||
|
||||
Assert.True(await h.Sut.IsRunActiveAsync());
|
||||
Assert.Empty(h.OpsEvents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Probe_releases_its_lease_and_reports_no_active_run()
|
||||
{
|
||||
var h = new Harness();
|
||||
var released = false;
|
||||
h.Lease.Setup(l => l.ReleaseAsync(It.IsAny<Azure.RequestConditions>(), It.IsAny<CancellationToken>()))
|
||||
.Callback(() => released = true)
|
||||
.ReturnsAsync(Mock.Of<Azure.Response<Azure.Storage.Blobs.Models.ReleasedObjectInfo>>());
|
||||
|
||||
Assert.False(await h.Sut.IsRunActiveAsync());
|
||||
Assert.True(released);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Probe_lets_a_failed_release_surface_so_nothing_is_queued_behind_a_stuck_lease()
|
||||
{
|
||||
// A queued run picked up seconds later would find the probe's own lease still held,
|
||||
// skip as "locked" and delete the message — the operator's run would silently vanish.
|
||||
var h = new Harness();
|
||||
h.Lease.Setup(l => l.ReleaseAsync(It.IsAny<Azure.RequestConditions>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new Azure.RequestFailedException(500, "storage down"));
|
||||
|
||||
await Assert.ThrowsAsync<Azure.RequestFailedException>(() => h.Sut.IsRunActiveAsync());
|
||||
}
|
||||
}
|
||||
+47
@@ -116,6 +116,53 @@ public class MaintenanceServiceExcessiveEventAutoActionTests
|
||||
Assert.False(MaintenanceService.IsAutoActionEligible(status));
|
||||
}
|
||||
|
||||
// ── Recount gate ──────────────────────────────────────────────────────────
|
||||
// The stored counter doubles on replayed batches, so every warn and every block is
|
||||
// decided on a recount. The gate keeps that Events-partition scan to candidates that
|
||||
// still have something to fire.
|
||||
|
||||
[Fact]
|
||||
public void HasPendingAction_WarnNotYetFired_IsPending()
|
||||
{
|
||||
Assert.True(MaintenanceService.HasPendingExcessiveEventAction(
|
||||
storedEventCount: 2001, SessionStatus.Succeeded, alreadyAlerted: false, alreadyAutoActioned: false,
|
||||
warnThreshold: 2000, autoMode: "Off", autoThreshold: 2500));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HasPendingAction_BlockNotYetFiredOnRunningSession_IsPending()
|
||||
{
|
||||
Assert.True(MaintenanceService.HasPendingExcessiveEventAction(
|
||||
storedEventCount: 2501, SessionStatus.InProgress, alreadyAlerted: true, alreadyAutoActioned: false,
|
||||
warnThreshold: 2000, autoMode: "Block", autoThreshold: 2500));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HasPendingAction_FinishedSessionAboveBlockThreshold_IsNotRescannedForever()
|
||||
{
|
||||
// Warned long ago, can never be blocked any more: without the eligibility term this
|
||||
// row would cost a full partition scan on every sweep until retention removes it.
|
||||
Assert.False(MaintenanceService.HasPendingExcessiveEventAction(
|
||||
storedEventCount: 9000, SessionStatus.Incomplete, alreadyAlerted: true, alreadyAutoActioned: false,
|
||||
warnThreshold: 2000, autoMode: "Block", autoThreshold: 2500));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HasPendingAction_BothAlreadyFired_IsNotPending()
|
||||
{
|
||||
Assert.False(MaintenanceService.HasPendingExcessiveEventAction(
|
||||
storedEventCount: 9000, SessionStatus.InProgress, alreadyAlerted: true, alreadyAutoActioned: true,
|
||||
warnThreshold: 2000, autoMode: "Block", autoThreshold: 2500));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HasPendingAction_WarnDisabledAndModeOff_IsNotPending()
|
||||
{
|
||||
Assert.False(MaintenanceService.HasPendingExcessiveEventAction(
|
||||
storedEventCount: 9000, SessionStatus.InProgress, alreadyAlerted: false, alreadyAutoActioned: false,
|
||||
warnThreshold: 0, autoMode: "Off", autoThreshold: 2500));
|
||||
}
|
||||
|
||||
// ── Status parsing feeding that gate ──────────────────────────────────────
|
||||
// The runaway query projects a subset of columns. SessionStatus.InProgress is ordinal 0,
|
||||
// so an unparsed Status would leave every row looking in-progress and the gate above
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
using System.Net;
|
||||
using AutopilotMonitor.Functions.DataAccess.TableStorage;
|
||||
using AutopilotMonitor.Functions.Functions.Admin;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.DataAccess;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Self-hosted MCP client registrations: storage round trip, wire parity, callback validation (the MCP proxy
|
||||
/// redirects authorization codes to the stored URL), the per-tenant cap, the operator switch (create refused,
|
||||
/// lookup 404, delete still possible) and the audit trail.
|
||||
/// </summary>
|
||||
public class McpClientRegistrationTests
|
||||
{
|
||||
private const string TenantA = "11111111-1111-1111-1111-111111111111";
|
||||
private const string TenantB = "22222222-2222-2222-2222-222222222222";
|
||||
private const string Callback = "https://chat.contoso.example/api/mcp/autopilot-monitor/oauth/callback";
|
||||
private static readonly DateTime Now = new(2026, 9, 24, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
// ── Storage and wire ────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Roundtrip_FullRow_SurvivesBuildAndMap()
|
||||
{
|
||||
var row = new McpClientRegistration
|
||||
{
|
||||
RegistrationId = "0123456789abcdef0123456789abcdef",
|
||||
TenantId = TenantA.ToUpperInvariant(),
|
||||
Name = "Team chat",
|
||||
RedirectUri = Callback,
|
||||
CreatedBy = "admin@contoso.example",
|
||||
CreatedAt = Now,
|
||||
};
|
||||
|
||||
var entity = TableMcpClientRegistrationRepository.Build(row);
|
||||
var back = TableMcpClientRegistrationRepository.Map(entity);
|
||||
|
||||
Assert.Equal(TableMcpClientRegistrationRepository.PartitionKey, entity.PartitionKey);
|
||||
Assert.Equal(row.RegistrationId, entity.RowKey);
|
||||
Assert.Equal(row.RegistrationId, back.RegistrationId);
|
||||
Assert.Equal(TenantA, back.TenantId); // lowercase: the offboarding wipe matches it
|
||||
Assert.Equal(row.Name, back.Name);
|
||||
Assert.Equal(row.RedirectUri, back.RedirectUri);
|
||||
Assert.Equal(row.CreatedBy, back.CreatedBy);
|
||||
Assert.Equal(Now, back.CreatedAt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TenantFilter_IsPartitionPlusLowercaseTenant()
|
||||
=> Assert.Equal($"PartitionKey eq 'registrations' and TenantId eq '{TenantA}'",
|
||||
TableMcpClientRegistrationRepository.BuildTenantFilter(TenantA.ToUpperInvariant()));
|
||||
|
||||
[Fact]
|
||||
public void ListResponse_WireShape()
|
||||
{
|
||||
var item = McpClientRegistrationFunction.ToItem(new McpClientRegistration
|
||||
{
|
||||
RegistrationId = "abc", TenantId = TenantA, Name = "Team chat", RedirectUri = Callback,
|
||||
CreatedBy = "admin@contoso.example", CreatedAt = Now,
|
||||
});
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new
|
||||
{
|
||||
enabled = true,
|
||||
maxRegistrations = 3,
|
||||
serverUrl = "https://mcp.autopilotmonitor.com/mcp",
|
||||
registrations = new[]
|
||||
{
|
||||
new { registrationId = "abc", clientId = "amc_abc", name = "Team chat", redirectUri = Callback, createdBy = "admin@contoso.example", createdUtc = Now },
|
||||
},
|
||||
},
|
||||
new McpClientRegistrationListResponse
|
||||
{
|
||||
Enabled = true, MaxRegistrations = 3, ServerUrl = "https://mcp.autopilotmonitor.com/mcp",
|
||||
Registrations = new[] { item },
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreateAndLookupResponses_WireShape()
|
||||
{
|
||||
var item = new McpClientRegistrationItem
|
||||
{
|
||||
RegistrationId = "abc", ClientId = "amc_abc", Name = "Team chat", RedirectUri = Callback,
|
||||
CreatedBy = "admin@contoso.example", CreatedUtc = Now,
|
||||
};
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new { registration = new { registrationId = "abc", clientId = "amc_abc", name = "Team chat", redirectUri = Callback, createdBy = "admin@contoso.example", createdUtc = Now } },
|
||||
new CreateMcpClientRegistrationResponse { Registration = item });
|
||||
ApiResponseWireParityTests.AssertWireIdentical(
|
||||
new { registrationId = "abc", tenantId = TenantA, redirectUri = Callback, name = "Team chat" },
|
||||
new McpClientRegistrationLookupResponse { RegistrationId = "abc", TenantId = TenantA, RedirectUri = Callback, Name = "Team chat" });
|
||||
}
|
||||
|
||||
// ── Validation ──────────────────────────────────────────────────────────────
|
||||
|
||||
[Theory]
|
||||
[InlineData(Callback)]
|
||||
[InlineData("http://localhost:3080/api/mcp/autopilot-monitor/oauth/callback")]
|
||||
[InlineData("http://127.0.0.1:3080/cb")]
|
||||
[InlineData("https://chat.contoso.example:8443/cb/")]
|
||||
public void AcceptableCallbacks(string uri) => Assert.Null(McpClientRegistrationService.ValidateRedirectUri(uri));
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("chat.contoso.example/cb")]
|
||||
[InlineData("http://chat.contoso.example/cb")] // http off loopback
|
||||
[InlineData("https://chat.contoso.example/cb?x=1")] // query
|
||||
[InlineData("https://chat.contoso.example/cb#frag")] // fragment
|
||||
[InlineData("https://*.contoso.example/cb")] // wildcard
|
||||
[InlineData("https://user:pw@chat.contoso.example/cb")]
|
||||
[InlineData("javascript:alert(1)")]
|
||||
[InlineData("ftp://chat.contoso.example/cb")]
|
||||
public void RejectedCallbacks(string uri) => Assert.NotNull(McpClientRegistrationService.ValidateRedirectUri(uri));
|
||||
|
||||
[Fact]
|
||||
public void OverlongCallback_IsRejected()
|
||||
=> Assert.NotNull(McpClientRegistrationService.ValidateRedirectUri("https://chat.contoso.example/" + new string('a', 1100)));
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
[InlineData("tab\there")]
|
||||
public void RejectedNames(string name) => Assert.NotNull(McpClientRegistrationService.ValidateName(name));
|
||||
|
||||
[Fact]
|
||||
public void OverlongName_IsRejected() => Assert.NotNull(McpClientRegistrationService.ValidateName(new string('n', 65)));
|
||||
|
||||
// ── Service: switch, cap, audit, tenant isolation ───────────────────────────
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
public required McpClientRegistrationService Sut { get; init; }
|
||||
public required Mock<IMcpClientRegistrationRepository> Repo { get; init; }
|
||||
public required Mock<IMaintenanceRepository> Audit { get; init; }
|
||||
}
|
||||
|
||||
private static Harness Build(bool enabled = true, int? tenantLimit = null)
|
||||
{
|
||||
var rows = new List<McpClientRegistration>();
|
||||
var repo = new Mock<IMcpClientRegistrationRepository>();
|
||||
repo.Setup(r => r.GetForTenantAsync(It.IsAny<string>()))
|
||||
.ReturnsAsync((string t) => rows.Where(r => r.TenantId == t.ToLowerInvariant()).ToList());
|
||||
repo.Setup(r => r.GetAsync(It.IsAny<string>())).ReturnsAsync((string id) => rows.FirstOrDefault(r => r.RegistrationId == id));
|
||||
repo.Setup(r => r.CreateAsync(It.IsAny<McpClientRegistration>())).Callback<McpClientRegistration>(rows.Add).ReturnsAsync(true);
|
||||
repo.Setup(r => r.DeleteAsync(It.IsAny<string>())).ReturnsAsync((string id) => rows.RemoveAll(r => r.RegistrationId == id) > 0);
|
||||
var audit = new Mock<IMaintenanceRepository>();
|
||||
audit.Setup(a => a.LogAuditEntryAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, string>?>()))
|
||||
.ReturnsAsync(true);
|
||||
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 { McpClientRegistrationEnabled = enabled });
|
||||
var configRepo = new Mock<IConfigRepository>();
|
||||
configRepo.Setup(r => r.GetTenantConfigurationAsync(It.IsAny<string>()))
|
||||
.ReturnsAsync((string t) => new TenantConfiguration { TenantId = t, McpClientRegistrationLimit = t == TenantA ? tenantLimit : null });
|
||||
var tenantConfig = new TenantConfigurationService(configRepo.Object, NullLogger<TenantConfigurationService>.Instance, cache);
|
||||
var sut = new McpClientRegistrationService(repo.Object, audit.Object, adminConfig.Object, tenantConfig, NullLogger<McpClientRegistrationService>.Instance);
|
||||
return new Harness { Sut = sut, Repo = repo, Audit = audit };
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_StoresARegistration_WithARandomHexId_AndAudits()
|
||||
{
|
||||
var h = Build();
|
||||
|
||||
var result = await h.Sut.CreateAsync(TenantA.ToUpperInvariant(), " Team chat ", Callback, "admin@contoso.example");
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, result.Status);
|
||||
var reg = result.Registration!;
|
||||
Assert.True(McpClientRegistrationService.IsRegistrationId(reg.RegistrationId));
|
||||
Assert.Equal(TenantA, reg.TenantId);
|
||||
Assert.Equal("Team chat", reg.Name);
|
||||
Assert.Equal($"amc_{reg.RegistrationId}", McpClientRegistrationService.ClientIdOf(reg.RegistrationId));
|
||||
h.Audit.Verify(a => a.LogAuditEntryAsync(TenantA, "CREATE", "McpClientRegistration", reg.RegistrationId, "admin@contoso.example",
|
||||
It.Is<Dictionary<string, string>?>(d => d != null && d["RedirectUri"] == Callback)), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_IsRefused_WhileTheSwitchIsOff()
|
||||
{
|
||||
var h = Build(enabled: false);
|
||||
|
||||
var result = await h.Sut.CreateAsync(TenantA, "Team chat", Callback, "admin@contoso.example");
|
||||
|
||||
Assert.Equal(HttpStatusCode.Forbidden, result.Status);
|
||||
h.Repo.Verify(r => r.CreateAsync(It.IsAny<McpClientRegistration>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_AllowsOneRegistrationByDefault_PerTenant()
|
||||
{
|
||||
var h = Build();
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, (await h.Sut.CreateAsync(TenantA, "chat", Callback, "a")).Status);
|
||||
var second = await h.Sut.CreateAsync(TenantA, "chat 2", "https://chat2.contoso.example/cb", "a");
|
||||
var otherTenant = await h.Sut.CreateAsync(TenantB, "chat", Callback, "b");
|
||||
|
||||
Assert.Equal(HttpStatusCode.Conflict, second.Status);
|
||||
Assert.Contains("raise the limit", second.Error);
|
||||
Assert.Equal(HttpStatusCode.Created, otherTenant.Status); // the limit and the duplicate check are per tenant
|
||||
Assert.Equal(1, await h.Sut.GetLimitAsync(TenantA));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AGlobalAdminOverride_RaisesTheLimit_AndDuplicatesStayRefused()
|
||||
{
|
||||
var h = Build(tenantLimit: 3);
|
||||
Assert.Equal(3, await h.Sut.GetLimitAsync(TenantA.ToUpperInvariant()));
|
||||
for (var i = 0; i < 3; i++)
|
||||
Assert.Equal(HttpStatusCode.Created, (await h.Sut.CreateAsync(TenantA, $"chat {i}", $"https://chat{i}.contoso.example/cb", "a")).Status);
|
||||
Assert.Equal(HttpStatusCode.Conflict, (await h.Sut.CreateAsync(TenantA, "chat 4", "https://chat4.contoso.example/cb", "a")).Status);
|
||||
|
||||
var dup = Build(tenantLimit: 3);
|
||||
await dup.Sut.CreateAsync(TenantA, "one", Callback, "a");
|
||||
Assert.Equal(HttpStatusCode.Conflict, (await dup.Sut.CreateAsync(TenantA, "two", Callback.ToUpperInvariant(), "a")).Status);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 1)]
|
||||
[InlineData(50, 10)]
|
||||
public async Task AnOutOfRangeOverride_IsClamped(int stored, int effective)
|
||||
=> Assert.Equal(effective, await Build(tenantLimit: stored).Sut.GetLimitAsync(TenantA));
|
||||
|
||||
[Fact]
|
||||
public async Task Create_ValidatesBeforeStoring()
|
||||
{
|
||||
var h = Build();
|
||||
Assert.Equal(HttpStatusCode.BadRequest, (await h.Sut.CreateAsync(TenantA, "x", "http://chat.contoso.example/cb", "a")).Status);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, (await h.Sut.CreateAsync(TenantA, "", Callback, "a")).Status);
|
||||
h.Repo.Verify(r => r.CreateAsync(It.IsAny<McpClientRegistration>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delete_OnlyTheOwnTenantsRegistration_AlsoWhileTheSwitchIsOff()
|
||||
{
|
||||
var h = Build();
|
||||
var reg = (await h.Sut.CreateAsync(TenantA, "Team chat", Callback, "a")).Registration!;
|
||||
|
||||
Assert.False(await h.Sut.DeleteAsync(TenantB, reg.RegistrationId, "b"));
|
||||
Assert.False(await h.Sut.DeleteAsync(TenantA, "not-an-id", "a"));
|
||||
Assert.True(await h.Sut.DeleteAsync(TenantA.ToUpperInvariant(), reg.RegistrationId, "a"));
|
||||
h.Audit.Verify(a => a.LogAuditEntryAsync(TenantA, "DELETE", "McpClientRegistration", reg.RegistrationId, "a", It.IsAny<Dictionary<string, string>?>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Lookup_AnswersOnlyWhileEnabled_AndOnlyForWellFormedIds()
|
||||
{
|
||||
var on = Build();
|
||||
var reg = (await on.Sut.CreateAsync(TenantA, "Team chat", Callback, "a")).Registration!;
|
||||
|
||||
Assert.NotNull(await on.Sut.LookupAsync(reg.RegistrationId));
|
||||
Assert.Null(await on.Sut.LookupAsync(reg.RegistrationId.ToUpperInvariant()));
|
||||
Assert.Null(await on.Sut.LookupAsync("../../etc"));
|
||||
|
||||
var off = Build(enabled: false);
|
||||
off.Repo.Setup(r => r.GetAsync(reg.RegistrationId)).ReturnsAsync(reg);
|
||||
Assert.Null(await off.Sut.LookupAsync(reg.RegistrationId));
|
||||
off.Repo.Verify(r => r.GetAsync(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
}
|
||||
+50
-35
@@ -7,47 +7,43 @@ namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the pure folds behind GET metrics/mcp-usage/organization (and its global twin): one item per
|
||||
/// account, the delegated (MSP) marker from the row's home tenant, the three windows (today / month / range),
|
||||
/// and the tenant's organization windows over every account.
|
||||
/// account, the three windows (today / month / range), and the tenant's organization windows over every
|
||||
/// account including the purchased-slot breakdown.
|
||||
/// </summary>
|
||||
public class McpOrganizationUsageAggregationTests
|
||||
{
|
||||
private const string Tenant = "11111111-1111-1111-1111-111111111111";
|
||||
private const string MspHome = "99999999-9999-9999-9999-999999999999";
|
||||
private const string Member = "aaaaaaaa-0000-0000-0000-000000000001";
|
||||
private const string MspAdmin = "bbbbbbbb-0000-0000-0000-000000000002";
|
||||
private const string OtherMember = "bbbbbbbb-0000-0000-0000-000000000002";
|
||||
|
||||
private static TenantUsageRecord Row(string user, string date, long count, string upn = "", string home = "", DateTime? last = null)
|
||||
=> new() { TenantId = Tenant, UserId = user, Date = date, RequestCount = count, UserPrincipalName = upn, HomeTenantId = home, LastRequestAt = last };
|
||||
private static TenantUsageRecord Row(string user, string date, long count, string upn = "", DateTime? last = null)
|
||||
=> new() { TenantId = Tenant, UserId = user, Date = date, RequestCount = count, UserPrincipalName = upn, LastRequestAt = last };
|
||||
|
||||
[Fact]
|
||||
public void Aggregate_MarksDelegatedAccounts_ByForeignHomeTenant()
|
||||
public void Aggregate_OneItemPerAccount_KeepsTheLatestUpn()
|
||||
{
|
||||
var rows = new[]
|
||||
{
|
||||
Row(Member, "20260902", 10, "alice@contoso.com"),
|
||||
Row(MspAdmin, "20260902", 40, "msp@partner.example", MspHome),
|
||||
Row(Member, "20260901", 10), // written before the UPN column existed
|
||||
Row(Member, "20260902", 5, "alice@contoso.com"),
|
||||
Row(OtherMember, "20260902", 40, "bob@contoso.com"),
|
||||
};
|
||||
|
||||
var items = McpUsageMetricsFunction.AggregateOrganizationUsage(rows, Tenant, "20260901", "20260902", "20260902", "20260901");
|
||||
var items = McpUsageMetricsFunction.AggregateOrganizationUsage(rows, "20260901", "20260902", "20260902", "20260901");
|
||||
|
||||
var msp = Assert.Single(items, i => i.UserId == MspAdmin);
|
||||
Assert.True(msp.Delegated);
|
||||
Assert.Equal(MspHome, msp.HomeTenantId);
|
||||
Assert.Equal("msp@partner.example", msp.UserPrincipalName);
|
||||
var member = Assert.Single(items, i => i.UserId == Member);
|
||||
Assert.False(member.Delegated);
|
||||
Assert.Null(member.HomeTenantId);
|
||||
Assert.Equal(2, items.Count);
|
||||
var alice = Assert.Single(items, i => i.UserId == Member);
|
||||
Assert.Equal("alice@contoso.com", alice.UserPrincipalName);
|
||||
Assert.Equal(15, alice.RequestsThisMonth);
|
||||
var bob = Assert.Single(items, i => i.UserId == OtherMember);
|
||||
Assert.Equal("bob@contoso.com", bob.UserPrincipalName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Aggregate_OwnTenantAsHome_IsNotDelegated()
|
||||
public void Aggregate_RowsWithoutUpn_LeaveItNull()
|
||||
{
|
||||
// Legacy/own rows may carry the tenant itself (or nothing) as home — both mean "own member".
|
||||
var rows = new[] { Row(Member, "20260902", 1, home: Tenant), Row(Member, "20260901", 1) };
|
||||
var items = McpUsageMetricsFunction.AggregateOrganizationUsage(rows, Tenant, "20260901", "20260902", "20260902", "20260901");
|
||||
var item = Assert.Single(items);
|
||||
Assert.False(item.Delegated);
|
||||
var rows = new[] { Row(Member, "20260902", 1), Row(Member, "20260901", 1) };
|
||||
var item = Assert.Single(McpUsageMetricsFunction.AggregateOrganizationUsage(rows, "20260901", "20260902", "20260902", "20260901"));
|
||||
Assert.Null(item.UserPrincipalName);
|
||||
}
|
||||
|
||||
@@ -62,7 +58,7 @@ public class McpOrganizationUsageAggregationTests
|
||||
Row(Member, "20260903", 7), // read window past the range end (never counted in range)
|
||||
};
|
||||
|
||||
var items = McpUsageMetricsFunction.AggregateOrganizationUsage(rows, Tenant, "20260815", "20260902", "20260902", "20260901");
|
||||
var items = McpUsageMetricsFunction.AggregateOrganizationUsage(rows, "20260815", "20260902", "20260902", "20260901");
|
||||
|
||||
var item = Assert.Single(items);
|
||||
Assert.Equal(5, item.RequestsToday);
|
||||
@@ -79,12 +75,12 @@ public class McpOrganizationUsageAggregationTests
|
||||
{
|
||||
Row(Member, "20260901", 3, last: newer),
|
||||
Row(Member, "20260902", 1, last: older),
|
||||
Row(MspAdmin, "20260902", 50, home: MspHome, last: older),
|
||||
Row(OtherMember, "20260902", 50, last: older),
|
||||
};
|
||||
|
||||
var items = McpUsageMetricsFunction.AggregateOrganizationUsage(rows, Tenant, "20260901", "20260902", "20260902", "20260901");
|
||||
var items = McpUsageMetricsFunction.AggregateOrganizationUsage(rows, "20260901", "20260902", "20260902", "20260901");
|
||||
|
||||
Assert.Equal(new[] { MspAdmin, Member }, items.Select(i => i.UserId));
|
||||
Assert.Equal(new[] { OtherMember, Member }, items.Select(i => i.UserId));
|
||||
Assert.Equal(newer, items[1].LastRequestAt);
|
||||
}
|
||||
|
||||
@@ -93,11 +89,11 @@ public class McpOrganizationUsageAggregationTests
|
||||
{
|
||||
var rows = new[]
|
||||
{
|
||||
Row(Member, "20260815", 100), // last month: neither window
|
||||
Row(Member, "20260901", 20), // month
|
||||
Row(Member, "20260902", 2), // today + month
|
||||
Row(MspAdmin, "20260902", 5, home: MspHome), // delegated reads count against the same windows
|
||||
Row(Member, "20260903", 7), // read window past today (range only)
|
||||
Row(Member, "20260815", 100), // last month: neither window
|
||||
Row(Member, "20260901", 20), // month
|
||||
Row(Member, "20260902", 2), // today + month
|
||||
Row(OtherMember, "20260902", 5), // another account counts against the same windows
|
||||
Row(Member, "20260903", 7), // read window past today (range only)
|
||||
};
|
||||
|
||||
var quota = McpUsageMetricsFunction.BuildOrganizationQuota(
|
||||
@@ -108,6 +104,25 @@ public class McpOrganizationUsageAggregationTests
|
||||
Assert.Equal(15000, quota.MonthlyLimit);
|
||||
Assert.Equal(7, quota.DailyUsed);
|
||||
Assert.Equal(27, quota.MonthlyUsed);
|
||||
// No purchased slot: the breakdown stays off the wire.
|
||||
Assert.Null(quota.PurchasedDelegatedSlots);
|
||||
Assert.Null(quota.SlotDailyLimit);
|
||||
Assert.Null(quota.SlotMonthlyLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OrganizationQuota_PurchasedSlots_CarryTheBreakdown()
|
||||
{
|
||||
// 3 000 + 3 × 900 = 5 700 — the limits arrive grown; the slot fields let the page show the sum.
|
||||
var quota = McpUsageMetricsFunction.BuildOrganizationQuota(
|
||||
new[] { Row(Member, "20260902", 3) },
|
||||
new McpQuotaService.TenantPlanLimits("pro", 5700, 114000, PurchasedDelegatedSlots: 3, SlotTenantDailyLimit: 900, SlotTenantMonthlyLimit: 18000),
|
||||
"20260902", "20260901");
|
||||
|
||||
Assert.Equal(5700, quota.DailyLimit);
|
||||
Assert.Equal(3, quota.PurchasedDelegatedSlots);
|
||||
Assert.Equal(900, quota.SlotDailyLimit);
|
||||
Assert.Equal(18000, quota.SlotMonthlyLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -115,11 +130,11 @@ public class McpOrganizationUsageAggregationTests
|
||||
{
|
||||
var rows = new[]
|
||||
{
|
||||
Row(Member, "20260815", 100), // before the range
|
||||
Row(Member, "20260815", 100), // before the range
|
||||
Row(Member, "20260902", 2),
|
||||
Row(MspAdmin, "20260902", 5, home: MspHome), // same day, delegated — one bar
|
||||
Row(OtherMember, "20260902", 5), // same day, another account — one bar
|
||||
Row(Member, "20260901", 20),
|
||||
Row(Member, "20260903", 7), // after the range (read window)
|
||||
Row(Member, "20260903", 7), // after the range (read window)
|
||||
};
|
||||
|
||||
var daily = McpUsageMetricsFunction.BuildOrganizationDaily(rows, "20260901", "20260902");
|
||||
|
||||
+32
-218
@@ -6,252 +6,77 @@ using Xunit;
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for the pure seams of <see cref="McpQuotaEnforcementMiddleware"/>: which tenant a request is
|
||||
/// charged to ("the budget follows the data"), the bound-narrowing isolation invariant, and the 429 texts
|
||||
/// that name whose budget is exhausted.
|
||||
/// Tests for the pure seams of <see cref="McpQuotaEnforcementMiddleware"/>: who bypasses the check (the Global
|
||||
/// Admin only — counted, never blocked) and the 429 texts that name whose window is exhausted. Every request is
|
||||
/// charged to the caller's HOME tenant ("the budget follows the delegating tenant"), so no seam names a target
|
||||
/// tenant any more.
|
||||
/// </summary>
|
||||
public class McpQuotaEnforcementMiddlewareTests
|
||||
{
|
||||
private const string Home = "aaaaaaaa-0000-0000-0000-000000000001";
|
||||
private const string TenantB = "bbbbbbbb-0000-0000-0000-000000000002";
|
||||
private const string TenantC = "cccccccc-0000-0000-0000-000000000003";
|
||||
private const string TenantD = "dddddddd-0000-0000-0000-000000000004";
|
||||
private static readonly DateTime Now = new(2026, 9, 2, 15, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
// ── ResolveChargeScope ─────────────────────────────────────────────────────────
|
||||
// ── IsExempt — the Global Admin runs, the Global Reader is quota'd ─────────────
|
||||
|
||||
[Fact]
|
||||
public void Member_ReadingOwnTenant_ChargesHome()
|
||||
public void GlobalAdmin_IsExempt_EvenOnAForeignTarget()
|
||||
{
|
||||
var ctx = new RequestContext { TenantId = Home, TargetTenantId = Home };
|
||||
var scope = McpQuotaEnforcementMiddleware.ResolveChargeScope(ctx, Home);
|
||||
Assert.Equal(McpChargeKind.Home, scope.Kind);
|
||||
Assert.Null(scope.TargetTenantId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Delegated_SingleManagedTarget_ChargesThatTarget()
|
||||
{
|
||||
var ctx = new RequestContext
|
||||
{
|
||||
TenantId = Home, TargetTenantId = TenantB, IsDelegatedReader = true,
|
||||
AllowedTenantIds = new[] { TenantB, TenantC },
|
||||
};
|
||||
var scope = McpQuotaEnforcementMiddleware.ResolveChargeScope(ctx, Home);
|
||||
Assert.Equal(McpChargeKind.SingleTarget, scope.Kind);
|
||||
Assert.Equal(TenantB, scope.TargetTenantId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Delegated_ReadingHomeTenant_ChargesHome()
|
||||
{
|
||||
// The subset tier admits a delegated caller for ?tenantId=<home> too (crossTenant=false) — that read
|
||||
// is the caller's OWN tenant and draws on its own budget.
|
||||
var ctx = new RequestContext
|
||||
{
|
||||
TenantId = Home, TargetTenantId = Home, IsDelegatedReader = true,
|
||||
AllowedTenantIds = new[] { TenantB },
|
||||
};
|
||||
var scope = McpQuotaEnforcementMiddleware.ResolveChargeScope(ctx, Home);
|
||||
Assert.Equal(McpChargeKind.Home, scope.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Delegated_TargetReachedThroughHomeChargedGroup_ChargesHome()
|
||||
{
|
||||
var ctx = new RequestContext
|
||||
{
|
||||
TenantId = Home, TargetTenantId = TenantC, IsDelegatedReader = true,
|
||||
AllowedTenantIds = new[] { TenantB, TenantC },
|
||||
HomeChargedTenantIds = new[] { TenantC },
|
||||
};
|
||||
var scope = McpQuotaEnforcementMiddleware.ResolveChargeScope(ctx, Home);
|
||||
Assert.Equal(McpChargeKind.Home, scope.Kind);
|
||||
Assert.Null(scope.TargetTenantId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Delegated_FleetAggregate_ChargesEveryManagedTenant()
|
||||
{
|
||||
var ctx = new RequestContext
|
||||
{
|
||||
TenantId = Home, TargetTenantId = Home, IsDelegatedReader = true, IsDelegatedAggregate = true,
|
||||
AllowedTenantIds = new[] { TenantB, TenantC },
|
||||
};
|
||||
var scope = McpQuotaEnforcementMiddleware.ResolveChargeScope(ctx, Home);
|
||||
Assert.Equal(McpChargeKind.BoundedAggregate, scope.Kind);
|
||||
Assert.Equal(new[] { TenantB, TenantC }, scope.ChargeMap!.Keys.OrderBy(k => k));
|
||||
Assert.Equal(new[] { TenantB }, scope.TargetsOf(new[] { TenantB }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Delegated_FleetAggregate_FoldsHomeChargedTenantsOntoHome()
|
||||
{
|
||||
var ctx = new RequestContext
|
||||
{
|
||||
TenantId = Home, TargetTenantId = Home, IsDelegatedReader = true, IsDelegatedAggregate = true,
|
||||
AllowedTenantIds = new[] { TenantB, TenantC, TenantD },
|
||||
HomeChargedTenantIds = new[] { TenantC, TenantD },
|
||||
};
|
||||
var scope = McpQuotaEnforcementMiddleware.ResolveChargeScope(ctx, Home);
|
||||
Assert.Equal(McpChargeKind.BoundedAggregate, scope.Kind);
|
||||
Assert.Equal(new[] { Home, TenantB }, scope.ChargeMap!.Keys.OrderBy(k => k));
|
||||
// Home is charged ONCE for both operator-managed tenants; they are served or dropped together.
|
||||
Assert.Equal(new[] { TenantC, TenantD }, scope.TargetsOf(new[] { Home }).OrderBy(t => t));
|
||||
Assert.Equal(new[] { TenantB }, scope.TargetsOf(new[] { TenantB }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Delegated_SubsetTierDirectoryListing_IsNotAnAggregate_ChargesHome()
|
||||
{
|
||||
// config/all: subset tier but TenantScoping.None → the policy middleware never marks it an aggregate.
|
||||
var ctx = new RequestContext
|
||||
{
|
||||
TenantId = Home, TargetTenantId = Home, IsDelegatedReader = true, IsDelegatedAggregate = false,
|
||||
AllowedTenantIds = new[] { TenantB, TenantC },
|
||||
};
|
||||
var scope = McpQuotaEnforcementMiddleware.ResolveChargeScope(ctx, Home);
|
||||
Assert.Equal(McpChargeKind.Home, scope.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GlobalAdmin_IsNeverDelegated_ResolvesHome()
|
||||
{
|
||||
// The policy middleware short-circuits delegated resolution for platform scope, so a GA reading
|
||||
// ?tenantId=<customer> carries no delegated flags — the charge scope is Home (and Invoke tracks
|
||||
// GA on home only, exempt from the check).
|
||||
// Platform operations must never be blocked by a budget; Invoke still counts the GA on home.
|
||||
var ctx = new RequestContext { TenantId = Home, TargetTenantId = TenantB, IsGlobalAdmin = true };
|
||||
var scope = McpQuotaEnforcementMiddleware.ResolveChargeScope(ctx, Home);
|
||||
Assert.Equal(McpChargeKind.Home, scope.Kind);
|
||||
}
|
||||
|
||||
// ── Narrow — ISOLATION INVARIANT ───────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public void Narrow_WithoutBound_LeavesContextUntouched()
|
||||
{
|
||||
// null = unbounded (GA/Reader). Narrowing must neither introduce a bound nor touch the context.
|
||||
var ctx = new RequestContext { TenantId = Home, AllowedTenantIds = null };
|
||||
var narrowed = McpQuotaEnforcementMiddleware.Narrow(ctx, new[] { TenantB }, new[] { TenantC });
|
||||
Assert.Same(ctx, narrowed);
|
||||
Assert.Null(narrowed.AllowedTenantIds);
|
||||
Assert.Null(narrowed.QuotaExcludedTenantIds);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(new[] { TenantB, TenantC }, new[] { TenantB }, new[] { TenantC })]
|
||||
[InlineData(new[] { TenantB, TenantC }, new string[0], new[] { TenantB, TenantC })]
|
||||
[InlineData(new[] { TenantB, TenantC }, new[] { TenantB, TenantC }, new string[0])]
|
||||
[InlineData(new[] { TenantB }, new[] { TenantB, TenantD }, new[] { TenantD })]
|
||||
[InlineData(new[] { TenantB, TenantC, TenantD }, new[] { TenantD, TenantB }, new[] { TenantC })]
|
||||
public void Narrow_NeverWidens_NeverNull(string[] bound, string[] admitted, string[] excluded)
|
||||
{
|
||||
var ctx = new RequestContext { TenantId = Home, AllowedTenantIds = bound, IsDelegatedReader = true };
|
||||
|
||||
var narrowed = McpQuotaEnforcementMiddleware.Narrow(ctx, admitted, excluded);
|
||||
|
||||
Assert.NotNull(narrowed.AllowedTenantIds);
|
||||
var boundSet = new HashSet<string>(bound, StringComparer.OrdinalIgnoreCase);
|
||||
Assert.All(narrowed.AllowedTenantIds!, t => Assert.Contains(t, boundSet));
|
||||
Assert.True(narrowed.AllowedTenantIds!.Count <= bound.Length);
|
||||
// A foreign tenant sneaking into "admitted" never widens the bound (TenantD ∉ bound in row 4).
|
||||
Assert.DoesNotContain(narrowed.AllowedTenantIds!, t => !boundSet.Contains(t));
|
||||
if (narrowed.QuotaExcludedTenantIds != null)
|
||||
Assert.All(narrowed.QuotaExcludedTenantIds, t => Assert.Contains(t, boundSet));
|
||||
// The rest of the context survives the copy.
|
||||
Assert.True(narrowed.IsDelegatedReader);
|
||||
Assert.Equal(Home, narrowed.TenantId);
|
||||
Assert.True(McpQuotaEnforcementMiddleware.IsExempt(ctx));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Narrow_EmptyAdmittedSet_PublishesEmptyBound_NotNull()
|
||||
public void GlobalReader_IsNotExempt()
|
||||
{
|
||||
// Empty ⇒ the repository serves an empty page. NEVER null (= all tenants).
|
||||
var ctx = new RequestContext { TenantId = Home, AllowedTenantIds = new[] { TenantB, TenantC } };
|
||||
var narrowed = McpQuotaEnforcementMiddleware.Narrow(ctx, Array.Empty<string>(), new[] { TenantB, TenantC });
|
||||
Assert.NotNull(narrowed.AllowedTenantIds);
|
||||
Assert.Empty(narrowed.AllowedTenantIds!);
|
||||
Assert.Equal(new[] { TenantB, TenantC }, narrowed.QuotaExcludedTenantIds!.OrderBy(t => t));
|
||||
// A customer-facing read role: it stays within its home tenant's windows like every member.
|
||||
var ctx = new RequestContext { TenantId = Home, TargetTenantId = TenantB, IsGlobalReader = true };
|
||||
Assert.False(McpQuotaEnforcementMiddleware.IsExempt(ctx));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Narrow_NothingExcluded_OmitsTheExcludedSet()
|
||||
public void Member_And_DelegatedReader_AreNotExempt()
|
||||
{
|
||||
var ctx = new RequestContext { TenantId = Home, AllowedTenantIds = new[] { TenantB, TenantC } };
|
||||
var narrowed = McpQuotaEnforcementMiddleware.Narrow(ctx, new[] { TenantB, TenantC }, Array.Empty<string>());
|
||||
Assert.Equal(2, narrowed.AllowedTenantIds!.Count);
|
||||
Assert.Null(narrowed.QuotaExcludedTenantIds);
|
||||
Assert.False(McpQuotaEnforcementMiddleware.IsExempt(new RequestContext { TenantId = Home, TargetTenantId = Home }));
|
||||
Assert.False(McpQuotaEnforcementMiddleware.IsExempt(new RequestContext
|
||||
{
|
||||
TenantId = Home, TargetTenantId = TenantB, IsDelegatedReader = true, AllowedTenantIds = new[] { TenantB },
|
||||
}));
|
||||
}
|
||||
|
||||
// ── BuildExceededResponse — whose budget ───────────────────────────────────────
|
||||
|
||||
private static McpQuotaDecision Blocked(string tenantPlan, string? target, long tenantDailyUsed = 300, int tenantDaily = 300)
|
||||
private static McpQuotaDecision Blocked(string tenantPlan, long tenantDailyUsed = 300, int tenantDaily = 300)
|
||||
=> McpQuotaService.BuildDecision(
|
||||
new McpPlanLimits("pro", 1000, 20000, tenantPlan, tenantDaily, 60000),
|
||||
dailyUsed: 5, monthlyUsed: 50, tenantDailyUsed: tenantDailyUsed, tenantMonthlyUsed: 400,
|
||||
Now, target);
|
||||
Now);
|
||||
|
||||
[Fact]
|
||||
public void ManagedCommunityTarget_NamesTheTenant_AndTheUpgradePath()
|
||||
public void OrganizationBlock_KeepsTheOrganizationWording()
|
||||
{
|
||||
var body = McpQuotaEnforcementMiddleware.BuildExceededResponse(Blocked("community", TenantB), "customer.example");
|
||||
|
||||
var body = McpQuotaEnforcementMiddleware.BuildExceededResponse(Blocked("community"));
|
||||
Assert.Equal("tenant", body.Level);
|
||||
Assert.Equal(TenantB, body.TargetTenantId);
|
||||
Assert.Contains("managed tenant 'customer.example'", body.Error);
|
||||
Assert.Contains("tenant plan 'community'", body.Error);
|
||||
Assert.Contains("Upgrading that tenant to Pro", body.Error);
|
||||
Assert.DoesNotContain("your organization", body.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ManagedTarget_WithoutLabel_FallsBackToTheId()
|
||||
{
|
||||
var body = McpQuotaEnforcementMiddleware.BuildExceededResponse(Blocked("community", TenantB));
|
||||
Assert.Contains($"managed tenant '{TenantB}'", body.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ManagedProTarget_OmitsTheUpgradeHint()
|
||||
{
|
||||
var body = McpQuotaEnforcementMiddleware.BuildExceededResponse(Blocked("pro", TenantB, 3000, 3000), "customer.example");
|
||||
Assert.Equal(TenantB, body.TargetTenantId);
|
||||
Assert.DoesNotContain("Upgrading", body.Error);
|
||||
Assert.Contains("shared by all its members and delegated admins", body.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OwnTenant_KeepsTheOrganizationWording_AndNoTarget()
|
||||
{
|
||||
var body = McpQuotaEnforcementMiddleware.BuildExceededResponse(Blocked("community", target: null));
|
||||
Assert.Null(body.TargetTenantId);
|
||||
Assert.Contains("of your organization", body.Error);
|
||||
Assert.Contains("tenant plan 'community'", body.Error);
|
||||
Assert.DoesNotContain("managed tenant", body.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OwnCommunityTenant_NamesTheUpgradePath()
|
||||
public void OrganizationBlock_OnCommunity_NamesTheUpgradePath()
|
||||
{
|
||||
// The quota is the upgrade lever: a member blocked by their own Community organization window is told
|
||||
// that Community is sized for occasional use and that Pro lifts it — Pro members never see the hint.
|
||||
var community = McpQuotaEnforcementMiddleware.BuildExceededResponse(Blocked("community", target: null));
|
||||
var community = McpQuotaEnforcementMiddleware.BuildExceededResponse(Blocked("community"));
|
||||
Assert.Contains("sized for occasional use", community.Error);
|
||||
Assert.Contains("upgrading your organization to Pro", community.Error);
|
||||
Assert.EndsWith("Resets at 2026-09-03T00:00:00Z.", community.Error);
|
||||
|
||||
var pro = McpQuotaEnforcementMiddleware.BuildExceededResponse(Blocked("pro", target: null, 3000, 3000));
|
||||
var pro = McpQuotaEnforcementMiddleware.BuildExceededResponse(Blocked("pro", 3000, 3000));
|
||||
Assert.DoesNotContain("upgrading", pro.Error);
|
||||
Assert.DoesNotContain("occasional use", pro.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ManagedCommunityTarget_SaysWhosePlanGoverns()
|
||||
{
|
||||
// The delegated admin must learn that the CUSTOMER's plan (not their own Pro/MSP plan) governs the window.
|
||||
var body = McpQuotaEnforcementMiddleware.BuildExceededResponse(Blocked("community", TenantB), "customer.example");
|
||||
Assert.Contains("on the Community plan", body.Error);
|
||||
Assert.Contains("its own plan governs this window, not yours", body.Error);
|
||||
Assert.Contains("Upgrading that tenant to Pro", body.Error);
|
||||
Assert.Contains("shared by all its members", pro.Error);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -272,25 +97,14 @@ public class McpQuotaEnforcementMiddlewareTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AllManagedTenantsExhausted_NamesTheCount_AndNoSingleTarget()
|
||||
public void UserLevelBlock_ReportsTheUserWindow()
|
||||
{
|
||||
var body = McpQuotaEnforcementMiddleware.BuildExceededResponse(Blocked("community", TenantB), exhaustedTenantCount: 3);
|
||||
Assert.Null(body.TargetTenantId);
|
||||
Assert.Equal("tenant", body.Level);
|
||||
Assert.Contains("all 3 managed tenants", body.Error);
|
||||
Assert.Contains("Earliest reset at 2026-09-03T00:00:00Z", body.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserLevelBlock_IgnoresTargetAndCount()
|
||||
{
|
||||
// The caller's OWN budget is exhausted — the target tenant is irrelevant and must not be named.
|
||||
var decision = McpQuotaService.BuildDecision(
|
||||
new McpPlanLimits("community", 100, 3000, "pro", 3000, 60000),
|
||||
dailyUsed: 100, monthlyUsed: 500, tenantDailyUsed: 1, tenantMonthlyUsed: 1, Now, TenantB);
|
||||
var body = McpQuotaEnforcementMiddleware.BuildExceededResponse(decision, "customer.example", exhaustedTenantCount: 2);
|
||||
Assert.Equal("user", body.Level);
|
||||
Assert.Null(body.TargetTenantId);
|
||||
dailyUsed: 100, monthlyUsed: 500, tenantDailyUsed: 1, tenantMonthlyUsed: 1, Now);
|
||||
var body = McpQuotaEnforcementMiddleware.BuildExceededResponse(decision);
|
||||
Assert.Equal(100, body.Limit);
|
||||
Assert.Equal(100, body.Used);
|
||||
Assert.Equal(
|
||||
"MCP daily request quota exceeded for plan 'community'. The Community plan is sized for occasional use; Pro raises your daily and monthly windows. Resets at 2026-09-03T00:00:00Z.",
|
||||
body.Error);
|
||||
|
||||
@@ -11,7 +11,8 @@ namespace AutopilotMonitor.Functions.Tests;
|
||||
/// <summary>
|
||||
/// Tests for <see cref="McpQuotaService"/>: window math (daily/monthly, reset times), plan
|
||||
/// precedence (per-user override → tenant edition; SectionUsagePlans definition → catalog
|
||||
/// fallback), and the fail-open contract on counter errors.
|
||||
/// fallback), the growth of both windows by purchased delegation slots, and the fail-open
|
||||
/// contract on counter errors.
|
||||
/// </summary>
|
||||
public class McpQuotaServiceTests
|
||||
{
|
||||
@@ -127,7 +128,9 @@ public class McpQuotaServiceTests
|
||||
IMemoryCache? cache = null,
|
||||
bool bound = true,
|
||||
Func<string?, TenantEdition>? editionResolver = null,
|
||||
Func<string?, string?>? tenantPlanOverrideResolver = null)
|
||||
Func<string?, string?>? tenantPlanOverrideResolver = null,
|
||||
Func<string?, int>? purchasedSlotsResolver = null,
|
||||
Func<string?, EditionResolution>? resolutionResolver = null)
|
||||
{
|
||||
var adminRepo = new Mock<IAdminRepository>();
|
||||
adminRepo.Setup(r => r.GetMcpUserAsync(It.IsAny<string>()))
|
||||
@@ -150,11 +153,15 @@ public class McpQuotaServiceTests
|
||||
var adminConfigService = new AdminConfigurationService(
|
||||
configRepo.Object, NullLogger<AdminConfigurationService>.Instance, cache);
|
||||
|
||||
var entitlements = resolutionResolver != null
|
||||
? new StubTenantEntitlementService(resolutionResolver, tenantPlanOverrideResolver, purchasedSlotsResolver)
|
||||
: new StubTenantEntitlementService(editionResolver ?? (_ => edition), tenantPlanOverrideResolver, purchasedSlotsResolver);
|
||||
|
||||
return new McpQuotaService(
|
||||
usageRepo.Object,
|
||||
mcpUserService,
|
||||
adminConfigService,
|
||||
new StubTenantEntitlementService(editionResolver ?? (_ => edition), tenantPlanOverrideResolver),
|
||||
entitlements,
|
||||
cache,
|
||||
NullLogger<McpQuotaService>.Instance,
|
||||
new TestTimeProvider(Now));
|
||||
@@ -338,25 +345,18 @@ public class McpQuotaServiceTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_DelegatedTarget_MspHomeOverride_LiftsTheCallerNotTheCustomer()
|
||||
public async Task Check_TenantOverride_ComposesWithPurchasedSlots()
|
||||
{
|
||||
// The MSP's home tenant carries the "msp" override; the managed Community customer does not.
|
||||
// The caller's own windows are lifted, the customer's organization window still bites.
|
||||
var repo = UsageRepo(("20260707", 1200));
|
||||
TenantRows(repo, Target, ("20260707", 300));
|
||||
var svc = Build(repo, planDefinitionsJson: MspPlanJson,
|
||||
editionResolver: HomeProTargetsCommunity,
|
||||
tenantPlanOverrideResolver: t => t == TenantId ? "msp" : null);
|
||||
// The "msp" definition carries no slot fields → the Pro catalog slot values grow its windows.
|
||||
var svc = Build(UsageRepo(("20260707", 1)), planDefinitionsJson: MspPlanJson,
|
||||
edition: TenantEdition.Pro, tenantPlanOverrideResolver: _ => "msp", purchasedSlotsResolver: _ => 2);
|
||||
|
||||
var d = await svc.CheckAsync(Oid, Upn, homeTenantId: TenantId, chargeTenantId: Target);
|
||||
var d = await svc.CheckAsync(Oid, Upn, TenantId);
|
||||
|
||||
Assert.False(d.Allowed);
|
||||
Assert.Equal("tenant", d.Level);
|
||||
Assert.Equal("msp", d.Plan);
|
||||
Assert.Equal(1500, d.DailyLimit);
|
||||
Assert.Equal("community", d.TenantPlan);
|
||||
Assert.Equal(300, d.TenantDailyLimit);
|
||||
Assert.Equal(Target, d.TargetTenantId);
|
||||
Assert.Equal(2100, d.DailyLimit); // 1500 + 2 × 300
|
||||
Assert.Equal("msp", d.TenantPlan);
|
||||
Assert.Equal(6800, d.TenantDailyLimit); // 5000 + 2 × 900
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -560,155 +560,176 @@ public class McpQuotaServiceTests
|
||||
repo.Verify(r => r.GetTenantUsageAsync(It.IsAny<string>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Exactly(2));
|
||||
}
|
||||
|
||||
// ── Delegated (MSP) reads: the budget follows the data ───────────────────────
|
||||
// The CHARGED tenant (the managed customer) supplies the organization windows and counters; the
|
||||
// caller's own windows still follow their HOME tenant's plan (and their per-user override).
|
||||
// ── Purchased delegation slots grow both windows ─────────────────────────────
|
||||
// The home tenant's windows (user AND organization) grow by purchased slots × per-slot value; the slot
|
||||
// values come from the governing plan definition, else the home edition's catalog. Community and
|
||||
// conferred Pro carry catalog slot values of 0, so a stray slot count grows nothing there.
|
||||
|
||||
private const string Target = "22222222-2222-2222-2222-222222222222";
|
||||
private const string Target2 = "33333333-3333-3333-3333-333333333333";
|
||||
private const string OtherOid = "00000000-0000-0000-0000-000000000002";
|
||||
|
||||
private static void TenantRows(Mock<IUserUsageRepository> repo, string tenantId, params (string Date, long Count)[] rows)
|
||||
=> repo.Setup(r => r.GetTenantUsageAsync(tenantId, It.IsAny<string?>(), It.IsAny<string?>()))
|
||||
.ReturnsAsync(rows.Select(r => new TenantUsageRecord
|
||||
{
|
||||
TenantId = tenantId,
|
||||
UserId = "some-member-or-msp",
|
||||
Date = r.Date,
|
||||
RequestCount = r.Count
|
||||
}).ToList());
|
||||
[Fact]
|
||||
public async Task Check_PurchasedSlots_GrowBothWindows()
|
||||
{
|
||||
// Pro home with 3 purchased slots: 1000 + 3 × 300 per account, 3000 + 3 × 900 for the organization.
|
||||
var svc = Build(UsageRepo(("20260707", 1)), edition: TenantEdition.Pro, purchasedSlotsResolver: _ => 3);
|
||||
|
||||
private static TenantEdition HomeProTargetsCommunity(string? tenantId)
|
||||
=> tenantId == TenantId ? TenantEdition.Pro : TenantEdition.Community;
|
||||
var d = await svc.CheckAsync(Oid, Upn, TenantId);
|
||||
|
||||
Assert.Equal(1900, d.DailyLimit);
|
||||
Assert.Equal(38000, d.MonthlyLimit);
|
||||
Assert.Equal(5700, d.TenantDailyLimit);
|
||||
Assert.Equal(114000, d.TenantMonthlyLimit);
|
||||
Assert.Equal(3, d.PurchasedDelegatedSlots);
|
||||
Assert.Equal(300, d.SlotDailyLimit);
|
||||
Assert.Equal(6000, d.SlotMonthlyLimit);
|
||||
Assert.Equal(900, d.SlotTenantDailyLimit);
|
||||
Assert.Equal(18000, d.SlotTenantMonthlyLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_DelegatedTarget_ChargesTheManagedTenantsPlanAndCounters()
|
||||
public async Task Check_IncludedSlotsOnly_NoGrowth()
|
||||
{
|
||||
// Pro MSP reads a Community customer whose organization window (300/day) other readers burned.
|
||||
var repo = UsageRepo(("20260707", 5));
|
||||
TenantRows(repo, Target, ("20260707", 300));
|
||||
var svc = Build(repo, editionResolver: HomeProTargetsCommunity);
|
||||
// A Pro tenant on its two included slots (purchased = 0) keeps the plain Pro windows.
|
||||
var svc = Build(UsageRepo(("20260707", 1)), edition: TenantEdition.Pro, purchasedSlotsResolver: _ => 0);
|
||||
|
||||
var d = await svc.CheckAsync(Oid, Upn, homeTenantId: TenantId, chargeTenantId: Target);
|
||||
var d = await svc.CheckAsync(Oid, Upn, TenantId);
|
||||
|
||||
Assert.Equal(1000, d.DailyLimit);
|
||||
Assert.Equal(3000, d.TenantDailyLimit);
|
||||
Assert.Equal(0, d.PurchasedDelegatedSlots);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_ConferredProHome_GrowsNothing_EvenWithASlotCount()
|
||||
{
|
||||
// Conferred Pro (managed by a Pro MSP, not Pro itself): the catalog slot values are 0, so even a slot
|
||||
// count leaking through (the entitlement service gates it to 0 anyway) grows neither window.
|
||||
var conferred = new EditionResolution(TenantEdition.Pro, EditionSource.Msp, OwnPro: false);
|
||||
var svc = Build(UsageRepo(("20260707", 1)), resolutionResolver: _ => conferred, purchasedSlotsResolver: _ => 3);
|
||||
|
||||
var d = await svc.CheckAsync(Oid, Upn, TenantId);
|
||||
|
||||
Assert.False(d.Allowed);
|
||||
Assert.Equal("tenant", d.Level);
|
||||
Assert.Equal("daily", d.Scope);
|
||||
Assert.Equal("community", d.TenantPlan);
|
||||
Assert.Equal(300, d.TenantDailyLimit);
|
||||
Assert.Equal(Target, d.TargetTenantId);
|
||||
// The caller's OWN windows still come from the Pro home tenant.
|
||||
Assert.Equal("pro", d.Plan);
|
||||
Assert.Equal(1000, d.DailyLimit);
|
||||
repo.Verify(r => r.GetTenantUsageAsync(TenantId, It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
|
||||
Assert.Equal(3000, d.TenantDailyLimit);
|
||||
Assert.Equal(0, d.SlotDailyLimit);
|
||||
Assert.Equal(0, d.SlotTenantDailyLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_DelegatedTarget_UserBudgetStillFollowsHome()
|
||||
public async Task Check_UserOverridePlan_StillGrowsWithTheHomeSlots()
|
||||
{
|
||||
// Community home (100/day) reading a Pro customer: the caller's own daily window bites first.
|
||||
var repo = UsageRepo(("20260707", 100));
|
||||
TenantRows(repo, Target, ("20260707", 1));
|
||||
var svc = Build(repo, editionResolver: t => t == Target ? TenantEdition.Pro : TenantEdition.Community);
|
||||
// The per-user "power" plan carries no slot fields → the HOME edition's catalog slot values apply,
|
||||
// so the override account grows with the tenant's purchased slots like everyone else.
|
||||
var json = """[{"name":"power","dailyRequestLimit":10000,"monthlyRequestLimit":100000,"description":""}]""";
|
||||
var svc = Build(UsageRepo(("20260707", 1)), planDefinitionsJson: json, edition: TenantEdition.Pro,
|
||||
mcpUserPlanOverride: "power", purchasedSlotsResolver: _ => 2);
|
||||
|
||||
var d = await svc.CheckAsync(Oid, Upn, homeTenantId: TenantId, chargeTenantId: Target);
|
||||
var d = await svc.CheckAsync(Oid, Upn, TenantId);
|
||||
|
||||
Assert.Equal("power", d.Plan);
|
||||
Assert.Equal(10600, d.DailyLimit);
|
||||
Assert.Equal(112000, d.MonthlyLimit);
|
||||
Assert.Equal(4800, d.TenantDailyLimit); // 3000 + 2 × 900 — the organization follows the tenant plan
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_SlotValues_DefinitionZero_DisablesTheGrowth()
|
||||
{
|
||||
var json = """[{"name":"pro","dailyRequestLimit":1000,"monthlyRequestLimit":20000,"slotDailyRequestLimit":0,"slotMonthlyRequestLimit":0,"slotTenantDailyRequestLimit":0,"slotTenantMonthlyRequestLimit":0,"description":""}]""";
|
||||
var svc = Build(UsageRepo(("20260707", 1)), planDefinitionsJson: json, edition: TenantEdition.Pro, purchasedSlotsResolver: _ => 5);
|
||||
|
||||
var d = await svc.CheckAsync(Oid, Upn, TenantId);
|
||||
|
||||
Assert.Equal(1000, d.DailyLimit);
|
||||
Assert.Equal(3000, d.TenantDailyLimit);
|
||||
Assert.Equal(5, d.PurchasedDelegatedSlots);
|
||||
Assert.Equal(0, d.SlotDailyLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_SlotValues_DefinitionSet_OverridesTheCatalog()
|
||||
{
|
||||
var json = """[{"name":"pro","dailyRequestLimit":1000,"monthlyRequestLimit":20000,"slotDailyRequestLimit":50,"slotMonthlyRequestLimit":500,"slotTenantDailyRequestLimit":100,"slotTenantMonthlyRequestLimit":1000,"description":""}]""";
|
||||
var svc = Build(UsageRepo(("20260707", 1)), planDefinitionsJson: json, edition: TenantEdition.Pro, purchasedSlotsResolver: _ => 2);
|
||||
|
||||
var d = await svc.CheckAsync(Oid, Upn, TenantId);
|
||||
|
||||
Assert.Equal(1100, d.DailyLimit);
|
||||
Assert.Equal(21000, d.MonthlyLimit);
|
||||
Assert.Equal(3200, d.TenantDailyLimit);
|
||||
Assert.Equal(62000, d.TenantMonthlyLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_SlotValues_DefinitionNull_UsesTheCatalog()
|
||||
{
|
||||
// A pre-existing definition without slot fields → the edition's catalog slot values.
|
||||
var json = """[{"name":"pro","dailyRequestLimit":1000,"monthlyRequestLimit":20000,"description":""}]""";
|
||||
var svc = Build(UsageRepo(("20260707", 1)), planDefinitionsJson: json, edition: TenantEdition.Pro, purchasedSlotsResolver: _ => 1);
|
||||
|
||||
var d = await svc.CheckAsync(Oid, Upn, TenantId);
|
||||
|
||||
Assert.Equal(1300, d.DailyLimit);
|
||||
Assert.Equal(3900, d.TenantDailyLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_LiftedWindow_StaysUnlimited_DespiteSlots()
|
||||
{
|
||||
// 0 = unlimited must never turn into "0 + slots × value" — a limit again. 30 000 requests today would
|
||||
// exceed any grown daily window (and the plain 20 000 monthly one) but stay under 20 000 + 4 × 6 000.
|
||||
var json = """[{"name":"pro","dailyRequestLimit":0,"monthlyRequestLimit":20000,"tenantDailyRequestLimit":0,"tenantMonthlyRequestLimit":60000,"description":""}]""";
|
||||
var svc = Build(UsageRepo(("20260707", 30000)), planDefinitionsJson: json, edition: TenantEdition.Pro, purchasedSlotsResolver: _ => 4);
|
||||
|
||||
var d = await svc.CheckAsync(Oid, Upn, TenantId);
|
||||
|
||||
Assert.True(d.Allowed);
|
||||
Assert.Equal(0, d.DailyLimit);
|
||||
Assert.Equal(0, d.TenantDailyLimit);
|
||||
Assert.Equal(44000, d.MonthlyLimit);
|
||||
Assert.Equal(30000, d.MonthlyUsed);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1000, 3, 300, 1900)]
|
||||
[InlineData(1000, 0, 300, 1000)]
|
||||
[InlineData(1000, 3, 0, 1000)]
|
||||
[InlineData(0, 3, 300, 0)]
|
||||
[InlineData(-1, 3, 300, -1)]
|
||||
public void Grow_AddsSlotsTimesValue_AndKeepsALiftedWindowLifted(int baseLimit, int slots, int perSlot, int expected)
|
||||
=> Assert.Equal(expected, McpQuotaService.Grow(baseLimit, slots, perSlot));
|
||||
|
||||
[Fact]
|
||||
public async Task Check_GrownWindow_IsTheEnforcedOne()
|
||||
{
|
||||
// Pro 1000 + 1 × 300 = 1300: the 1300th request of the day is the first blocked one.
|
||||
var below = Build(UsageRepo(("20260707", 1299)), edition: TenantEdition.Pro, purchasedSlotsResolver: _ => 1);
|
||||
Assert.True((await below.CheckAsync(Oid, Upn, TenantId)).Allowed);
|
||||
|
||||
var at = Build(UsageRepo(("20260707", 1300)), edition: TenantEdition.Pro, purchasedSlotsResolver: _ => 1);
|
||||
var d = await at.CheckAsync(Oid, Upn, TenantId);
|
||||
Assert.False(d.Allowed);
|
||||
Assert.Equal("daily", d.Scope);
|
||||
Assert.Equal("user", d.Level);
|
||||
Assert.Equal("community", d.Plan);
|
||||
Assert.Equal("pro", d.TenantPlan);
|
||||
Assert.Equal(Target, d.TargetTenantId);
|
||||
Assert.Equal(1300, d.ExceededLimit);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_OwnTenant_NamesNoTarget()
|
||||
{
|
||||
var svc = Build(UsageRepo(("20260707", 1)));
|
||||
var legacy = await svc.CheckAsync(Oid, Upn, TenantId);
|
||||
var explicitHome = await svc.CheckAsync(Oid, Upn, TenantId, TenantId);
|
||||
Assert.Null(legacy.TargetTenantId);
|
||||
Assert.Null(explicitHome.TargetTenantId);
|
||||
}
|
||||
// ── One tenant, many callers ─────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Check_TenantSnapshot_IsSharedAcrossCallersOfTheSameTenant()
|
||||
public async Task Check_TenantSnapshot_IsSharedAcrossMembersOfTheSameTenant()
|
||||
{
|
||||
// Two different callers charged to the same customer read its organization counters ONCE per TTL.
|
||||
var repo = UsageRepo(("20260707", 1));
|
||||
// Two members of one tenant read its organization counters ONCE per TTL.
|
||||
var repo = UsageRepo(new[] { ("20260707", 1L) }, tenantRows: new[] { ("20260707", 10L) });
|
||||
repo.Setup(r => r.GetUsageByUserAsync(OtherOid, It.IsAny<string?>(), It.IsAny<string?>()))
|
||||
.ReturnsAsync(new List<UserUsageRecord>());
|
||||
TenantRows(repo, Target, ("20260707", 10));
|
||||
var svc = Build(repo, editionResolver: HomeProTargetsCommunity);
|
||||
|
||||
await svc.CheckAsync(Oid, Upn, TenantId, Target);
|
||||
await svc.CheckAsync(OtherOid, "bob@contoso.com", TenantId, Target);
|
||||
|
||||
repo.Verify(r => r.GetTenantUsageAsync(Target, It.IsAny<string?>(), It.IsAny<string?>()), Times.Once);
|
||||
repo.Verify(r => r.GetUsageByUserAsync(It.IsAny<string>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckMany_ExcludesExhaustedTenants_AdmitsTheRest()
|
||||
{
|
||||
var repo = UsageRepo(("20260707", 1));
|
||||
TenantRows(repo, Target, ("20260707", 300));
|
||||
TenantRows(repo, Target2, ("20260707", 10));
|
||||
var svc = Build(repo, editionResolver: HomeProTargetsCommunity);
|
||||
|
||||
var r = await svc.CheckManyAsync(Oid, Upn, TenantId, new[] { Target, Target2 });
|
||||
|
||||
Assert.True(r.Allowed);
|
||||
Assert.Null(r.BlockingDecision);
|
||||
Assert.True(r.UserDecision.Allowed);
|
||||
Assert.Equal(new[] { Target2 }, r.AdmittedTenantIds);
|
||||
Assert.Equal(new[] { Target }, r.ExcludedTenantIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckMany_AllExhausted_BlocksWithTheEarliestReset()
|
||||
{
|
||||
var repo = UsageRepo(("20260707", 1));
|
||||
TenantRows(repo, Target, ("20260707", 300)); // daily window → resets tomorrow
|
||||
TenantRows(repo, Target2, ("20260701", 9000), ("20260707", 1)); // monthly window → resets on the 1st
|
||||
var svc = Build(repo, editionResolver: HomeProTargetsCommunity);
|
||||
|
||||
var r = await svc.CheckManyAsync(Oid, Upn, TenantId, new[] { Target, Target2 });
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Empty(r.AdmittedTenantIds);
|
||||
Assert.Equal(2, r.ExcludedTenantIds.Count);
|
||||
Assert.Equal("tenant", r.BlockingDecision!.Level);
|
||||
Assert.Equal("daily", r.BlockingDecision.Scope);
|
||||
Assert.Equal(new DateTime(2026, 7, 8, 0, 0, 0, DateTimeKind.Utc), r.BlockingDecision.ResetUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckMany_UserExhausted_SkipsEveryTenantRead()
|
||||
{
|
||||
var repo = UsageRepo(("20260707", 100)); // Community home: 100/day
|
||||
var svc = Build(repo);
|
||||
|
||||
var r = await svc.CheckManyAsync(Oid, Upn, TenantId, new[] { Target, Target2 });
|
||||
await svc.CheckAsync(Oid, Upn, TenantId);
|
||||
await svc.CheckAsync(OtherOid, "bob@contoso.com", TenantId);
|
||||
|
||||
Assert.False(r.Allowed);
|
||||
Assert.Equal("user", r.BlockingDecision!.Level);
|
||||
Assert.Equal(2, r.ExcludedTenantIds.Count);
|
||||
repo.Verify(r2 => r2.GetTenantUsageAsync(It.IsAny<string>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CheckMany_TenantReadFails_AdmitsThatTenant_FailOpen()
|
||||
{
|
||||
var repo = UsageRepo(("20260707", 1));
|
||||
repo.Setup(r => r.GetTenantUsageAsync(Target, It.IsAny<string?>(), It.IsAny<string?>()))
|
||||
.ThrowsAsync(new InvalidOperationException("storage down"));
|
||||
TenantRows(repo, Target2, ("20260707", 10));
|
||||
var svc = Build(repo, editionResolver: HomeProTargetsCommunity);
|
||||
|
||||
var r = await svc.CheckManyAsync(Oid, Upn, TenantId, new[] { Target, Target2 });
|
||||
|
||||
Assert.True(r.Allowed);
|
||||
Assert.Equal(new[] { Target, Target2 }, r.AdmittedTenantIds.OrderBy(t => t));
|
||||
Assert.Empty(r.ExcludedTenantIds);
|
||||
repo.Verify(r => r.GetTenantUsageAsync(TenantId, It.IsAny<string?>(), It.IsAny<string?>()), Times.Once);
|
||||
repo.Verify(r => r.GetUsageByUserAsync(It.IsAny<string>(), It.IsAny<string?>(), It.IsAny<string?>()), Times.Exactly(2));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -407,6 +407,12 @@ public class MetricsWireParityTests
|
||||
var tenantMonthlyLimit = 9000;
|
||||
long tenantDailyUsed = 120;
|
||||
long tenantMonthlyUsed = 4100;
|
||||
// Three purchased delegation slots: the limits above already grew by them; the breakdown rides along.
|
||||
int? purchasedDelegatedSlots = 3;
|
||||
int? slotDailyLimit = 300;
|
||||
int? slotMonthlyLimit = 6000;
|
||||
int? slotTenantDailyLimit = 900;
|
||||
int? slotTenantMonthlyLimit = 18000;
|
||||
var records = SampleUsageRecords(userId);
|
||||
|
||||
AssertParity(
|
||||
@@ -427,7 +433,12 @@ public class MetricsWireParityTests
|
||||
tenantDailyLimit,
|
||||
tenantMonthlyLimit,
|
||||
tenantDailyUsed,
|
||||
tenantMonthlyUsed
|
||||
tenantMonthlyUsed,
|
||||
purchasedDelegatedSlots,
|
||||
slotDailyLimit,
|
||||
slotMonthlyLimit,
|
||||
slotTenantDailyLimit,
|
||||
slotTenantMonthlyLimit
|
||||
},
|
||||
records
|
||||
},
|
||||
@@ -448,7 +459,12 @@ public class MetricsWireParityTests
|
||||
TenantDailyLimit = tenantDailyLimit,
|
||||
TenantMonthlyLimit = tenantMonthlyLimit,
|
||||
TenantDailyUsed = tenantDailyUsed,
|
||||
TenantMonthlyUsed = tenantMonthlyUsed
|
||||
TenantMonthlyUsed = tenantMonthlyUsed,
|
||||
PurchasedDelegatedSlots = purchasedDelegatedSlots,
|
||||
SlotDailyLimit = slotDailyLimit,
|
||||
SlotMonthlyLimit = slotMonthlyLimit,
|
||||
SlotTenantDailyLimit = slotTenantDailyLimit,
|
||||
SlotTenantMonthlyLimit = slotTenantMonthlyLimit
|
||||
},
|
||||
Records = records
|
||||
});
|
||||
@@ -457,10 +473,16 @@ public class MetricsWireParityTests
|
||||
[Fact]
|
||||
public void GetMyMcpUsageResponse_omits_null_upn_and_usagePlan()
|
||||
{
|
||||
// …and the slot breakdown, which is absent when no delegation slot was purchased.
|
||||
var userId = "7aa20c11-0002-4b7c-a1d2-52f3aaaa0008";
|
||||
string? upn = null;
|
||||
string? usagePlan = null;
|
||||
var effectivePlan = "free";
|
||||
int? purchasedDelegatedSlots = null;
|
||||
int? slotDailyLimit = null;
|
||||
int? slotMonthlyLimit = null;
|
||||
int? slotTenantDailyLimit = null;
|
||||
int? slotTenantMonthlyLimit = null;
|
||||
var records = new List<UserUsageRecord>();
|
||||
|
||||
AssertParity(
|
||||
@@ -481,7 +503,12 @@ public class MetricsWireParityTests
|
||||
tenantDailyLimit = 0,
|
||||
tenantMonthlyLimit = 0,
|
||||
tenantDailyUsed = 0L,
|
||||
tenantMonthlyUsed = 0L
|
||||
tenantMonthlyUsed = 0L,
|
||||
purchasedDelegatedSlots,
|
||||
slotDailyLimit,
|
||||
slotMonthlyLimit,
|
||||
slotTenantDailyLimit,
|
||||
slotTenantMonthlyLimit
|
||||
},
|
||||
records
|
||||
},
|
||||
@@ -672,7 +699,6 @@ public class MetricsWireParityTests
|
||||
{
|
||||
var tenantId = "7aa20c11-0002-4b7c-a1d2-52f3aaaa0001";
|
||||
var userId = "7aa20c11-0002-4b7c-a1d2-52f3aaaa0009";
|
||||
var homeTenantId = "7aa20c11-0002-4b7c-a1d2-52f3aaaa0002";
|
||||
var lastRequestAt = new DateTime(2026, 9, 2, 14, 5, 0, DateTimeKind.Utc);
|
||||
|
||||
AssertParity(
|
||||
@@ -686,9 +712,7 @@ public class MetricsWireParityTests
|
||||
new
|
||||
{
|
||||
userId,
|
||||
userPrincipalName = "msp@partner.example",
|
||||
delegated = true,
|
||||
homeTenantId,
|
||||
userPrincipalName = "admin@contoso.com",
|
||||
requestsToday = 4L,
|
||||
requestsThisMonth = 120L,
|
||||
requestsInRange = 120L,
|
||||
@@ -706,9 +730,7 @@ public class MetricsWireParityTests
|
||||
new()
|
||||
{
|
||||
UserId = userId,
|
||||
UserPrincipalName = "msp@partner.example",
|
||||
Delegated = true,
|
||||
HomeTenantId = homeTenantId,
|
||||
UserPrincipalName = "admin@contoso.com",
|
||||
RequestsToday = 4,
|
||||
RequestsThisMonth = 120,
|
||||
RequestsInRange = 120,
|
||||
@@ -719,13 +741,12 @@ public class MetricsWireParityTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMcpOrganizationUsageResponse_omits_null_upn_home_and_lastRequest()
|
||||
public void GetMcpOrganizationUsageResponse_omits_null_upn_and_lastRequest()
|
||||
{
|
||||
// A row written before the attribution columns existed: own member, no UPN, no timestamp.
|
||||
// A row written before the attribution columns existed: no UPN, no timestamp.
|
||||
var tenantId = "7aa20c11-0002-4b7c-a1d2-52f3aaaa0001";
|
||||
var userId = "7aa20c11-0002-4b7c-a1d2-52f3aaaa0009";
|
||||
string? userPrincipalName = null;
|
||||
string? homeTenantId = null;
|
||||
DateTime? lastRequestAt = null;
|
||||
|
||||
AssertParity(
|
||||
@@ -740,8 +761,6 @@ public class MetricsWireParityTests
|
||||
{
|
||||
userId,
|
||||
userPrincipalName,
|
||||
delegated = false,
|
||||
homeTenantId,
|
||||
requestsToday = 0L,
|
||||
requestsThisMonth = 3L,
|
||||
requestsInRange = 3L,
|
||||
@@ -756,11 +775,63 @@ public class MetricsWireParityTests
|
||||
DateTo = "20260902",
|
||||
Users = new List<McpOrganizationUsageItem>
|
||||
{
|
||||
new() { UserId = userId, Delegated = false, RequestsToday = 0, RequestsThisMonth = 3, RequestsInRange = 3 },
|
||||
new() { UserId = userId, RequestsToday = 0, RequestsThisMonth = 3, RequestsInRange = 3 },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetMcpOrganizationUsageResponse_quota_carries_the_slot_breakdown()
|
||||
{
|
||||
// Three purchased slots: 3 000 + 3 × 900 arrive as the grown limit; the breakdown lets the page show the sum.
|
||||
var tenantId = "7aa20c11-0002-4b7c-a1d2-52f3aaaa0001";
|
||||
var daily = new List<McpOrganizationDailyItem>
|
||||
{
|
||||
new() { Date = "20260901", Requests = 12 },
|
||||
new() { Date = "20260902", Requests = 7 },
|
||||
};
|
||||
|
||||
AssertParity(
|
||||
new
|
||||
{
|
||||
tenantId,
|
||||
dateFrom = "20260901",
|
||||
dateTo = "20260902",
|
||||
users = Array.Empty<object>(),
|
||||
quota = new
|
||||
{
|
||||
tenantPlan = "pro",
|
||||
dailyLimit = 5700,
|
||||
monthlyLimit = 114000,
|
||||
dailyUsed = 7L,
|
||||
monthlyUsed = 19L,
|
||||
purchasedDelegatedSlots = 3,
|
||||
slotDailyLimit = 900,
|
||||
slotMonthlyLimit = 18000,
|
||||
},
|
||||
daily,
|
||||
},
|
||||
new GetMcpOrganizationUsageResponse
|
||||
{
|
||||
TenantId = tenantId,
|
||||
DateFrom = "20260901",
|
||||
DateTo = "20260902",
|
||||
Users = new List<McpOrganizationUsageItem>(),
|
||||
Quota = new McpOrganizationQuotaNode
|
||||
{
|
||||
TenantPlan = "pro",
|
||||
DailyLimit = 5700,
|
||||
MonthlyLimit = 114000,
|
||||
DailyUsed = 7,
|
||||
MonthlyUsed = 19,
|
||||
PurchasedDelegatedSlots = 3,
|
||||
SlotDailyLimit = 900,
|
||||
SlotMonthlyLimit = 18000,
|
||||
},
|
||||
Daily = daily,
|
||||
});
|
||||
}
|
||||
|
||||
private static void AssertParity(object anonymousLiteral, IApiResponse typed)
|
||||
=> ApiResponseWireParityTests.AssertWireIdentical(anonymousLiteral, typed);
|
||||
}
|
||||
|
||||
@@ -40,6 +40,21 @@ public class MiddlewarePipelineOrderTests
|
||||
Assert.True(rateLimit < 0 || policy < rateLimit, "UserRateLimitMiddleware keys off the RequestContext the policy step resolves");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Client_app_binding_runs_between_authentication_and_policy_enforcement()
|
||||
{
|
||||
// It reads the principal the auth step stores and sets the cap marker the policy step resolves roles with.
|
||||
var src = ProgramSource();
|
||||
|
||||
var auth = src.IndexOf($"UseMiddleware<{nameof(AuthenticationMiddleware)}>()", System.StringComparison.Ordinal);
|
||||
var binding = src.IndexOf($"UseMiddleware<{nameof(ClientAppBindingMiddleware)}>()", System.StringComparison.Ordinal);
|
||||
var policy = src.IndexOf($"UseMiddleware<{nameof(PolicyEnforcementMiddleware)}>()", System.StringComparison.Ordinal);
|
||||
|
||||
Assert.True(binding >= 0, "ClientAppBindingMiddleware is not registered in Program.cs");
|
||||
Assert.True(auth < binding && binding < policy, "ClientAppBindingMiddleware must run after authentication and before policy enforcement");
|
||||
Assert.Equal(1, Count(src, $"UseMiddleware<{nameof(ClientAppBindingMiddleware)}>()"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Each_gate_middleware_is_registered_exactly_once()
|
||||
{
|
||||
|
||||
+6
-4
@@ -7,18 +7,20 @@ namespace AutopilotMonitor.Functions.Tests.Offboarding;
|
||||
/// <summary>
|
||||
/// Test double for <see cref="IOffboardFarewellEmailSender"/>. Records every invocation so
|
||||
/// the handler-side tests can assert "did the farewell send fire after History → Completed?"
|
||||
/// without booting the real mail provider client. Default = silent noop; set <see cref="ThrowOnSend"/>
|
||||
/// to simulate downstream failures and prove the handler's fail-soft contract.
|
||||
/// without booting the real mail provider client. Default = accepted (<see cref="Result"/> true);
|
||||
/// set <see cref="Result"/> false to simulate a refused send, or <see cref="ThrowOnSend"/> to
|
||||
/// simulate downstream failures and prove the handler's fail-soft contract.
|
||||
/// </summary>
|
||||
internal sealed class FakeOffboardFarewellEmailSender : IOffboardFarewellEmailSender
|
||||
{
|
||||
public readonly List<(string ToEmail, string DomainName, string TenantId)> Calls = new();
|
||||
public bool Result { get; set; } = true;
|
||||
public System.Exception? ThrowOnSend { get; set; }
|
||||
|
||||
public Task SendAsync(string toEmail, string domainName, string tenantId, CancellationToken ct = default)
|
||||
public Task<bool> SendAsync(string toEmail, string domainName, string tenantId, CancellationToken ct = default)
|
||||
{
|
||||
Calls.Add((toEmail, domainName, tenantId));
|
||||
if (ThrowOnSend is { } ex) throw ex;
|
||||
return Task.CompletedTask;
|
||||
return Task.FromResult(Result);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -414,7 +414,7 @@ public class OffboardingMarkerCleanupFunctionTests
|
||||
{
|
||||
}
|
||||
|
||||
public override Task<int> WipeByExactPartitionAsync(string tableName, string normalizedTenantId, CancellationToken ct = default)
|
||||
protected override Task<int> WipeByExactPartitionCoreAsync(string tableName, string normalizedTenantId, string filter, CancellationToken ct)
|
||||
{
|
||||
WipeCalls.Add((tableName, normalizedTenantId));
|
||||
if (ThrowOnNextWipe is { } ex)
|
||||
|
||||
+89
-13
@@ -383,6 +383,77 @@ public class TenantOffboardingHandlerDrainContractTests
|
||||
Times.Never(), "Drain-skip-gate must also bypass the enumerate+enqueue phase");
|
||||
}
|
||||
|
||||
// ── Farewell mail record (Side-effect 6) ────────────────────────────────────
|
||||
// The send fails soft and its success log never reaches Application Insights, so the ops
|
||||
// event is the only record of whether the departing customer got the farewell mail.
|
||||
|
||||
[Fact]
|
||||
public async Task Completed_WithCapturedAddress_ProviderAccepts_RecordsFarewellEmailSent()
|
||||
{
|
||||
var harness = Harness.New();
|
||||
harness.Repo.History[HistoryRowKey].NotificationEmail = "it@contoso.invalid";
|
||||
|
||||
await harness.Sut.HandleAsync(harness.Envelope(drainPollCount: 0));
|
||||
|
||||
Assert.Equal("Completed", harness.Repo.History[HistoryRowKey].Status);
|
||||
var call = Assert.Single(harness.Farewell.Calls);
|
||||
Assert.Equal(("it@contoso.invalid", "contoso.invalid", TenantId), call);
|
||||
var evt = Assert.Single(harness.OpsEvents, e => e.EventType.StartsWith("FarewellEmail", StringComparison.Ordinal));
|
||||
Assert.Equal(OpsEventTypes.FarewellEmailSent, evt.EventType);
|
||||
Assert.Equal(OpsEventSeverity.Info, evt.Severity);
|
||||
Assert.Equal(TenantId, evt.TenantId);
|
||||
Assert.Contains("it@contoso.invalid", evt.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Completed_WithoutCapturedAddress_RecordsFarewellEmailSkipped_AndNeverCallsSender()
|
||||
{
|
||||
var harness = Harness.New();
|
||||
harness.Repo.History[HistoryRowKey].NotificationEmail = null;
|
||||
|
||||
await harness.Sut.HandleAsync(harness.Envelope(drainPollCount: 0));
|
||||
|
||||
Assert.Equal("Completed", harness.Repo.History[HistoryRowKey].Status);
|
||||
Assert.Empty(harness.Farewell.Calls);
|
||||
var evt = Assert.Single(harness.OpsEvents, e => e.EventType.StartsWith("FarewellEmail", StringComparison.Ordinal));
|
||||
Assert.Equal(OpsEventTypes.FarewellEmailSkipped, evt.EventType);
|
||||
Assert.Equal(OpsEventSeverity.Warning, evt.Severity);
|
||||
Assert.Contains("no contact address", evt.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Completed_ProviderRefuses_RecordsFarewellEmailFailed()
|
||||
{
|
||||
var harness = Harness.New();
|
||||
harness.Repo.History[HistoryRowKey].NotificationEmail = "it@contoso.invalid";
|
||||
harness.Farewell.Result = false;
|
||||
|
||||
await harness.Sut.HandleAsync(harness.Envelope(drainPollCount: 0));
|
||||
|
||||
var evt = Assert.Single(harness.OpsEvents, e => e.EventType.StartsWith("FarewellEmail", StringComparison.Ordinal));
|
||||
Assert.Equal(OpsEventTypes.FarewellEmailFailed, evt.EventType);
|
||||
Assert.Equal(OpsEventSeverity.Error, evt.Severity);
|
||||
Assert.Contains("did not accept", evt.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Completed_SenderThrows_RecordsFarewellEmailFailed_AndStillCompletes()
|
||||
{
|
||||
// Fail-soft contract: the History row is already Completed when the mail goes out; a
|
||||
// throwing sender must neither propagate nor stop the TenantConfiguration delete after it.
|
||||
var harness = Harness.New();
|
||||
harness.Repo.History[HistoryRowKey].NotificationEmail = "it@contoso.invalid";
|
||||
harness.Farewell.ThrowOnSend = new HttpRequestException("simulated provider outage");
|
||||
|
||||
await harness.Sut.HandleAsync(harness.Envelope(drainPollCount: 0));
|
||||
|
||||
Assert.Equal("Completed", harness.Repo.History[HistoryRowKey].Status);
|
||||
Assert.Equal("Completed", harness.Repo.Markers[TenantId].Status);
|
||||
var evt = Assert.Single(harness.OpsEvents, e => e.EventType.StartsWith("FarewellEmail", StringComparison.Ordinal));
|
||||
Assert.Equal(OpsEventTypes.FarewellEmailFailed, evt.EventType);
|
||||
Assert.Contains("HttpRequestException", evt.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task History_AlreadyCompleted_IsNoOp()
|
||||
{
|
||||
@@ -436,6 +507,9 @@ public class TenantOffboardingHandlerDrainContractTests
|
||||
public CountingSafeWipeService SafeWipeProbe { get; } = new();
|
||||
public Mock<IMaintenanceRepository> Maintenance { get; } = new();
|
||||
public Mock<IConfigRepository> ConfigRepo { get; } = new();
|
||||
public FakeOffboardFarewellEmailSender Farewell { get; } = new();
|
||||
/// <summary>Every ops event the handler recorded, in order (the repository is a capturing mock).</summary>
|
||||
public List<OpsEventEntry> OpsEvents { get; } = new();
|
||||
public List<string> EnumeratorYields { get; } = new();
|
||||
public Exception? EnumeratorThrow { get; set; }
|
||||
|
||||
@@ -475,7 +549,7 @@ public class TenantOffboardingHandlerDrainContractTests
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, string>?>()))
|
||||
.ReturnsAsync(true);
|
||||
|
||||
var opsService = BuildRealOpsService();
|
||||
var opsService = BuildRealOpsService(h.OpsEvents);
|
||||
|
||||
var unusedTableStorage = new Mock<TableStorageService>(
|
||||
Mock.Of<TableServiceClient>(),
|
||||
@@ -494,7 +568,7 @@ public class TenantOffboardingHandlerDrainContractTests
|
||||
opsService,
|
||||
Mock.Of<ITenantCustomsArchiveRepository>(),
|
||||
h.ConfigRepo.Object,
|
||||
new FakeOffboardFarewellEmailSender(),
|
||||
h.Farewell,
|
||||
NullLogger<TenantOffboardingHandler>.Instance);
|
||||
|
||||
return h;
|
||||
@@ -578,10 +652,12 @@ public class TenantOffboardingHandlerDrainContractTests
|
||||
}, "\"0xFAKE_PTR_1\"");
|
||||
}
|
||||
|
||||
private static OpsEventService BuildRealOpsService()
|
||||
private static OpsEventService BuildRealOpsService(List<OpsEventEntry> captured)
|
||||
{
|
||||
var opsRepo = new Mock<IOpsEventRepository>();
|
||||
opsRepo.Setup(r => r.SaveOpsEventAsync(It.IsAny<OpsEventEntry>())).Returns(Task.CompletedTask);
|
||||
opsRepo.Setup(r => r.SaveOpsEventAsync(It.IsAny<OpsEventEntry>()))
|
||||
.Callback<OpsEventEntry>(captured.Add)
|
||||
.Returns(Task.CompletedTask);
|
||||
var memCache = new MemoryCache(new MemoryCacheOptions());
|
||||
var adminConfig = new Mock<AdminConfigurationService>(
|
||||
Mock.Of<IConfigRepository>(), NullLogger<AdminConfigurationService>.Instance, memCache);
|
||||
@@ -593,9 +669,9 @@ public class TenantOffboardingHandlerDrainContractTests
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="SafeWipeService"/> that records call counts without performing any storage IO.
|
||||
/// Tests use this to assert that fail-closed paths NEVER touch the wipe methods. Now that
|
||||
/// <see cref="SafeWipeService"/> exposes the wipe methods as <c>virtual</c>, the production
|
||||
/// dispatch lands here.
|
||||
/// Tests use this to assert that fail-closed paths NEVER touch the wipe methods. Only the
|
||||
/// protected cores are overridden, so the tenant-GUID guard of the public entry points still
|
||||
/// runs against whatever the handler passes in.
|
||||
/// </summary>
|
||||
private sealed class CountingSafeWipeService : SafeWipeService
|
||||
{
|
||||
@@ -610,37 +686,37 @@ public class TenantOffboardingHandlerDrainContractTests
|
||||
{
|
||||
}
|
||||
|
||||
public override Task<int> WipeByExactPartitionAsync(string tableName, string normalizedTenantId, CancellationToken ct = default)
|
||||
protected override Task<int> WipeByExactPartitionCoreAsync(string tableName, string normalizedTenantId, string filter, CancellationToken ct)
|
||||
{
|
||||
WipeCallCount++;
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public override Task<int> WipeByCompositePartitionRangeAsync(string tableName, string normalizedTenantId, CancellationToken ct = default)
|
||||
protected override Task<int> WipeByCompositePartitionRangeCoreAsync(string tableName, string normalizedTenantId, CancellationToken ct)
|
||||
{
|
||||
WipeCallCount++;
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public override Task<int> WipeByDiscriminatorAndTenantPropertyAsync(string tableName, string discriminator, string normalizedTenantId, CancellationToken ct = default)
|
||||
protected override Task<int> WipeByDiscriminatorAndTenantPropertyCoreAsync(string tableName, string discriminator, string normalizedTenantId, CancellationToken ct)
|
||||
{
|
||||
WipeCallCount++;
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public override Task<int> WipeByTenantIdPropertyAsync(string tableName, string normalizedTenantId, CancellationToken ct = default)
|
||||
protected override Task<int> WipeByTenantIdPropertyCoreAsync(string tableName, string normalizedTenantId, CancellationToken ct)
|
||||
{
|
||||
WipeCallCount++;
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public override Task<int> WipeByRowKeyAsync(string tableName, string normalizedTenantId, CancellationToken ct = default)
|
||||
protected override Task<int> WipeByRowKeyCoreAsync(string tableName, string normalizedTenantId, string filter, CancellationToken ct)
|
||||
{
|
||||
WipeCallCount++;
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public override Task<int> WipeBlobsByTenantPrefixAsync(string containerName, string normalizedTenantId, CancellationToken ct = default)
|
||||
protected override Task<int> WipeBlobsByTenantPrefixCoreAsync(string containerName, string normalizedTenantId, CancellationToken ct)
|
||||
{
|
||||
WipeCallCount++;
|
||||
return Task.FromResult(0);
|
||||
|
||||
+26
-6
@@ -320,6 +320,22 @@ public class TenantOffboardingHandlerOrderingTests
|
||||
Assert.Contains(Constants.TableNames.ScriptNameCache, harness.SafeWipeProbe.ExactPartitionWipes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostDrain_OwnedGroupWipe_AnchorsOnSelfServiceGroupId()
|
||||
{
|
||||
// The tenant's own self-service group lives under "msp-{tenantId}" — not a GUID. The wipe
|
||||
// must go through the owned-group entry points (tenant GUID in, group id derived inside);
|
||||
// handing the group id to a tenant-GUID entry point throws and poisons every offboarding.
|
||||
var harness = Harness.New();
|
||||
var ownedGroupId = Constants.TenantGroupIds.ForHomeTenant(TenantId);
|
||||
|
||||
await harness.Sut.HandleAsync(harness.Envelope());
|
||||
|
||||
Assert.Contains((Constants.TableNames.TenantGroups, ownedGroupId), harness.SafeWipeProbe.ExactPartitionAnchors);
|
||||
Assert.Contains((Constants.TableNames.TenantGroupAssignments, ownedGroupId), harness.SafeWipeProbe.RowKeyAnchors);
|
||||
Assert.Equal("Completed", harness.Repo.History[HistoryRowKey].Status);
|
||||
}
|
||||
|
||||
// ── Harness (copied minimal — only what these tests need) ───────────────────
|
||||
|
||||
private sealed class Harness
|
||||
@@ -470,12 +486,16 @@ public class TenantOffboardingHandlerOrderingTests
|
||||
new BlobStorageService(new BlobServiceClient("UseDevelopmentStorage=true"),
|
||||
NullLogger<BlobStorageService>.Instance, usesManagedIdentity: false),
|
||||
NullLogger<SafeWipeService>.Instance) { }
|
||||
public override Task<int> WipeByExactPartitionAsync(string t, string i, CancellationToken c = default) { WipeCallCount++; ExactPartitionWipes.Add(t); return Task.FromResult(0); }
|
||||
public override Task<int> WipeByCompositePartitionRangeAsync(string t, string i, CancellationToken c = default) { WipeCallCount++; return Task.FromResult(0); }
|
||||
public override Task<int> WipeByDiscriminatorAndTenantPropertyAsync(string t, string d, string i, CancellationToken c = default) { WipeCallCount++; return Task.FromResult(0); }
|
||||
public override Task<int> WipeByTenantIdPropertyAsync(string t, string i, CancellationToken c = default) { WipeCallCount++; PropertyOnlyWipes.Add(t); return Task.FromResult(0); }
|
||||
public override Task<int> WipeByRowKeyAsync(string t, string i, CancellationToken c = default) { WipeCallCount++; RowKeyWipes.Add(t); return Task.FromResult(0); }
|
||||
public override Task<int> WipeBlobsByTenantPrefixAsync(string c, string i, CancellationToken ct = default) { WipeCallCount++; return Task.FromResult(0); }
|
||||
/// <summary>(table, partition key) pairs of the exact-partition wipe — the anchor the delete would run against.</summary>
|
||||
public List<(string Table, string Anchor)> ExactPartitionAnchors { get; } = new();
|
||||
/// <summary>(table, row key) pairs of the RowKey-anchored wipe.</summary>
|
||||
public List<(string Table, string Anchor)> RowKeyAnchors { get; } = new();
|
||||
protected override Task<int> WipeByExactPartitionCoreAsync(string t, string pk, string filter, CancellationToken c) { WipeCallCount++; ExactPartitionWipes.Add(t); ExactPartitionAnchors.Add((t, pk)); return Task.FromResult(0); }
|
||||
protected override Task<int> WipeByCompositePartitionRangeCoreAsync(string t, string i, CancellationToken c) { WipeCallCount++; return Task.FromResult(0); }
|
||||
protected override Task<int> WipeByDiscriminatorAndTenantPropertyCoreAsync(string t, string d, string i, CancellationToken c) { WipeCallCount++; return Task.FromResult(0); }
|
||||
protected override Task<int> WipeByTenantIdPropertyCoreAsync(string t, string i, CancellationToken c) { WipeCallCount++; PropertyOnlyWipes.Add(t); return Task.FromResult(0); }
|
||||
protected override Task<int> WipeByRowKeyCoreAsync(string t, string rk, string filter, CancellationToken c) { WipeCallCount++; RowKeyWipes.Add(t); RowKeyAnchors.Add((t, rk)); return Task.FromResult(0); }
|
||||
protected override Task<int> WipeBlobsByTenantPrefixCoreAsync(string c, string i, CancellationToken ct) { WipeCallCount++; return Task.FromResult(0); }
|
||||
}
|
||||
|
||||
private sealed class NoopCustomsArchivingOrderingHandler : TenantOffboardingHandler
|
||||
|
||||
+130
-19
@@ -111,6 +111,71 @@ public class TenantOffboardingWorkerPoisonTests
|
||||
Assert.Equal("InProgress", harness.Repo.History[HistoryRowKey].Status);
|
||||
}
|
||||
|
||||
// ── Superseded dead letters ─────────────────────────────────────────────────
|
||||
//
|
||||
// A retry after a poisoned run is a new envelope, so nothing else ever removes the dead
|
||||
// letter of the failed run. The completed run sweeps it.
|
||||
|
||||
private const string OtherTenantId = "22222222-2222-2222-2222-222222222222";
|
||||
|
||||
[Fact]
|
||||
public async Task Completed_RemovesOnlyTheTenantsDeadLetters()
|
||||
{
|
||||
var harness = new Harness();
|
||||
harness.Repo.History[HistoryRowKey].Status = "Completed";
|
||||
var own = harness.AddDeadLetter(TenantId.ToUpperInvariant()); // tenant ids compare case-insensitively
|
||||
var foreign = harness.AddDeadLetter(OtherTenantId);
|
||||
var malformed = harness.AddDeadLetter(tenantId: null, bodyOverride: "{ not json at all");
|
||||
|
||||
await harness.InvokeHandleAsync();
|
||||
|
||||
Assert.Equal(new[] { own }, harness.PoisonDeletedIds);
|
||||
Assert.DoesNotContain(foreign, harness.PoisonDeletedIds);
|
||||
Assert.DoesNotContain(malformed, harness.PoisonDeletedIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Completed_SweepsPastTheFirstBatch()
|
||||
{
|
||||
var harness = new Harness();
|
||||
harness.Repo.History[HistoryRowKey].Status = "Completed";
|
||||
for (var i = 0; i < TenantOffboardingWorker.PoisonSweepBatchSize; i++)
|
||||
harness.AddDeadLetter(OtherTenantId);
|
||||
var own = harness.AddDeadLetter(TenantId);
|
||||
|
||||
await harness.InvokeHandleAsync();
|
||||
|
||||
Assert.Equal(new[] { own }, harness.PoisonDeletedIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NotCompleted_LeavesThePoisonQueueAlone()
|
||||
{
|
||||
// A pickup that finds the run Failed must not touch the dead letter — it is the only
|
||||
// queue-side trace of a failure nobody has resolved yet.
|
||||
var harness = new Harness();
|
||||
harness.Repo.History[HistoryRowKey].Status = "Failed";
|
||||
harness.AddDeadLetter(TenantId);
|
||||
|
||||
await harness.InvokeHandleAsync();
|
||||
|
||||
Assert.Equal(0, harness.PoisonReceiveCount);
|
||||
Assert.Empty(harness.PoisonDeletedIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Completed_SweepFailure_DoesNotFailTheRun()
|
||||
{
|
||||
// A throw here would keep the completed envelope on the main queue and finally move a
|
||||
// Completed run to poison.
|
||||
var harness = new Harness(poisonReceiveThrows: true);
|
||||
harness.Repo.History[HistoryRowKey].Status = "Completed";
|
||||
|
||||
await harness.InvokeHandleAsync();
|
||||
|
||||
Assert.Equal(1, harness.PoisonReceiveCount);
|
||||
}
|
||||
|
||||
// ── Harness ─────────────────────────────────────────────────────────────────
|
||||
|
||||
private sealed class Harness
|
||||
@@ -121,11 +186,38 @@ public class TenantOffboardingWorkerPoisonTests
|
||||
public Mock<QueueClient> PoisonQueue { get; } = new();
|
||||
public int PoisonSendCount { get; private set; }
|
||||
public int MainDeleteCount { get; private set; }
|
||||
public int PoisonReceiveCount { get; private set; }
|
||||
public List<string> PoisonDeletedIds { get; } = new();
|
||||
|
||||
public Harness(bool poisonSendThrows = false)
|
||||
// Poison-queue content for the sweep tests. A received message turns invisible, like the
|
||||
// real queue, so a second receive returns the next batch instead of the same one.
|
||||
private readonly List<QueueMessage> _deadLetters = new();
|
||||
private readonly HashSet<string> _hiddenDeadLetters = new();
|
||||
|
||||
public Harness(bool poisonSendThrows = false, bool poisonReceiveThrows = false)
|
||||
{
|
||||
SeedAudit();
|
||||
|
||||
PoisonQueue.Setup(q => q.ReceiveMessagesAsync(It.IsAny<int?>(), It.IsAny<TimeSpan?>(), It.IsAny<CancellationToken>()))
|
||||
.Returns<int?, TimeSpan?, CancellationToken>((max, _, _) =>
|
||||
{
|
||||
PoisonReceiveCount++;
|
||||
if (poisonReceiveThrows) throw new InvalidOperationException("simulated poison-queue 503");
|
||||
var batch = _deadLetters
|
||||
.Where(m => !_hiddenDeadLetters.Contains(m.MessageId))
|
||||
.Take(max ?? 1)
|
||||
.ToArray();
|
||||
foreach (var m in batch) _hiddenDeadLetters.Add(m.MessageId);
|
||||
return Task.FromResult(Response.FromValue(batch, new Mock<Response>().Object));
|
||||
});
|
||||
|
||||
PoisonQueue.Setup(q => q.DeleteMessageAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
|
||||
.Returns<string, string, CancellationToken>((id, _, _) =>
|
||||
{
|
||||
PoisonDeletedIds.Add(id);
|
||||
return Task.FromResult(new Mock<Response>().Object);
|
||||
});
|
||||
|
||||
// Cascade-handler dependencies. The handler is real — it talks to FakeRepo +
|
||||
// OpsEvent + (unused) other deps. Only MarkEnvelopeFailedFromPoisonAsync is
|
||||
// exercised, so most deps are noise.
|
||||
@@ -160,24 +252,43 @@ public class TenantOffboardingWorkerPoisonTests
|
||||
}
|
||||
|
||||
public QueueMessage BuildMessage(int dequeueCount, string? bodyOverride = null)
|
||||
{
|
||||
var envelope = new TenantOffboardingEnvelope
|
||||
{
|
||||
TenantId = TenantId,
|
||||
HistoryPartitionKey = Constants.OffboardingPartitionKeys.History,
|
||||
HistoryRowKey = HistoryRowKey,
|
||||
InitiatedBy = "alice@contoso.invalid",
|
||||
InitiatedAt = DateTime.UtcNow.AddMinutes(-1),
|
||||
EnqueuedAt = DateTime.UtcNow,
|
||||
DrainPollCount = 0,
|
||||
};
|
||||
return QueuesModelFactory.QueueMessage(
|
||||
=> QueuesModelFactory.QueueMessage(
|
||||
messageId: Guid.NewGuid().ToString(),
|
||||
popReceipt: "fake-receipt",
|
||||
body: new BinaryData(bodyOverride ?? JsonConvert.SerializeObject(envelope)),
|
||||
body: new BinaryData(bodyOverride ?? JsonConvert.SerializeObject(BuildEnvelope(TenantId))),
|
||||
dequeueCount: dequeueCount);
|
||||
|
||||
/// <summary>Puts a dead letter into the poison queue and returns its message id.</summary>
|
||||
public string AddDeadLetter(string? tenantId, string? bodyOverride = null)
|
||||
{
|
||||
var msg = QueuesModelFactory.QueueMessage(
|
||||
messageId: Guid.NewGuid().ToString(),
|
||||
popReceipt: "fake-receipt",
|
||||
body: new BinaryData(bodyOverride ?? JsonConvert.SerializeObject(BuildEnvelope(tenantId!))),
|
||||
dequeueCount: 1);
|
||||
_deadLetters.Add(msg);
|
||||
return msg.MessageId;
|
||||
}
|
||||
|
||||
public Task InvokeHandleAsync()
|
||||
{
|
||||
var method = typeof(TenantOffboardingWorker)
|
||||
.GetMethod("HandleAsync", BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
Assert.NotNull(method);
|
||||
return (Task)method!.Invoke(Worker, new object[] { BuildEnvelope(TenantId), default(CancellationToken) })!;
|
||||
}
|
||||
|
||||
private static TenantOffboardingEnvelope BuildEnvelope(string tenantId) => new()
|
||||
{
|
||||
TenantId = tenantId,
|
||||
HistoryPartitionKey = Constants.OffboardingPartitionKeys.History,
|
||||
HistoryRowKey = HistoryRowKey,
|
||||
InitiatedBy = "alice@contoso.invalid",
|
||||
InitiatedAt = DateTime.UtcNow.AddMinutes(-1),
|
||||
EnqueuedAt = DateTime.UtcNow,
|
||||
DrainPollCount = 0,
|
||||
};
|
||||
|
||||
public Task InvokeMoveToPoisonAsync(QueueMessage msg)
|
||||
{
|
||||
// MoveToPoisonAsync is private — invoke via reflection. Avoids spinning up the
|
||||
@@ -288,10 +399,10 @@ public class TenantOffboardingWorkerPoisonTests
|
||||
new BlobStorageService(new BlobServiceClient("UseDevelopmentStorage=true"),
|
||||
NullLogger<BlobStorageService>.Instance, usesManagedIdentity: false),
|
||||
NullLogger<SafeWipeService>.Instance) { }
|
||||
public override Task<int> WipeByExactPartitionAsync(string t, string i, CancellationToken c = default) => Task.FromResult(0);
|
||||
public override Task<int> WipeByCompositePartitionRangeAsync(string t, string i, CancellationToken c = default) => Task.FromResult(0);
|
||||
public override Task<int> WipeByDiscriminatorAndTenantPropertyAsync(string t, string d, string i, CancellationToken c = default) => Task.FromResult(0);
|
||||
public override Task<int> WipeByTenantIdPropertyAsync(string t, string i, CancellationToken c = default) => Task.FromResult(0);
|
||||
public override Task<int> WipeBlobsByTenantPrefixAsync(string c, string i, CancellationToken ct = default) => Task.FromResult(0);
|
||||
protected override Task<int> WipeByExactPartitionCoreAsync(string t, string i, string filter, CancellationToken c) => Task.FromResult(0);
|
||||
protected override Task<int> WipeByCompositePartitionRangeCoreAsync(string t, string i, CancellationToken c) => Task.FromResult(0);
|
||||
protected override Task<int> WipeByDiscriminatorAndTenantPropertyCoreAsync(string t, string d, string i, CancellationToken c) => Task.FromResult(0);
|
||||
protected override Task<int> WipeByTenantIdPropertyCoreAsync(string t, string i, CancellationToken c) => Task.FromResult(0);
|
||||
protected override Task<int> WipeBlobsByTenantPrefixCoreAsync(string c, string i, CancellationToken ct) => Task.FromResult(0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,6 +116,23 @@ public class OffboardingFiltersTests
|
||||
Assert.DoesNotContain("PartitionKey", filter);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OwnedGroupFilters_AnchorOnTheDerivedSelfServiceGroupId()
|
||||
{
|
||||
Assert.Equal($"PartitionKey eq 'msp-{ValidTenant}'", OffboardingFilters.OwnedGroupPartition(ValidTenant));
|
||||
Assert.Equal($"RowKey eq 'msp-{ValidTenant}'", OffboardingFilters.OwnedGroupRowKey(ValidTenant));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not-a-guid")]
|
||||
[InlineData("msp-11111111-1111-1111-1111-111111111111")] // the group id itself is not an input
|
||||
[InlineData("")]
|
||||
public void OwnedGroupFilters_ThrowForNonGuid(string input)
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => OffboardingFilters.OwnedGroupPartition(input));
|
||||
Assert.Throws<ArgumentException>(() => OffboardingFilters.OwnedGroupRowKey(input));
|
||||
}
|
||||
|
||||
// ── Injection neutralization (defense in depth even after EnsureValidGuid) ──
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the "since release" semantics of the platform-stats recompute: every cumulative
|
||||
/// counter is a monotonic high-water-mark. The tables the recompute scans are pruned by
|
||||
/// retention, so a raw recompute only sees the retention window — persisting that verbatim
|
||||
/// regressed the public landing-page figures after every cleanup.
|
||||
/// </summary>
|
||||
public class PlatformStatsMonotonicTests
|
||||
{
|
||||
private static readonly DateTime Now = new(2026, 07, 11, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
[Fact]
|
||||
public void Cumulative_counters_never_regress_below_persisted_values()
|
||||
{
|
||||
// Retention pruned old sessions: the recompute sees far less than the persisted
|
||||
// counters accumulated. Every cumulative figure must keep its high-water-mark.
|
||||
var existing = new PlatformStats
|
||||
{
|
||||
TotalEnrollments = 50_000,
|
||||
SuccessfulEnrollments = 40_000,
|
||||
TotalEventsProcessed = 9_000_000,
|
||||
TotalUsers = 800,
|
||||
TotalTenants = 120,
|
||||
UniqueDeviceModels = 450,
|
||||
IssuesDetected = 6_500,
|
||||
TotalSignedUpTenants = 150
|
||||
};
|
||||
|
||||
var stats = MaintenanceService.BuildMonotonicPlatformStats(
|
||||
recomputedEnrollments: 7_000,
|
||||
recomputedSuccessful: 6_000,
|
||||
recomputedEvents: 1_200_000,
|
||||
recomputedUsers: 90,
|
||||
recomputedActiveTenants: 80,
|
||||
recomputedUniqueModels: 200,
|
||||
signedUpTenants: 155,
|
||||
existing: existing,
|
||||
nowUtc: Now);
|
||||
|
||||
Assert.Equal(50_000, stats.TotalEnrollments);
|
||||
Assert.Equal(40_000, stats.SuccessfulEnrollments);
|
||||
Assert.Equal(9_000_000, stats.TotalEventsProcessed);
|
||||
Assert.Equal(800, stats.TotalUsers);
|
||||
Assert.Equal(120, stats.TotalTenants);
|
||||
Assert.Equal(450, stats.UniqueDeviceModels);
|
||||
Assert.Equal(6_500, stats.IssuesDetected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Recompute_raises_counters_when_live_data_exceeds_persisted_values()
|
||||
{
|
||||
// Self-heal: lost increments (fire-and-forget failures, pre-feature history) are
|
||||
// recovered as long as the sessions are still within retention.
|
||||
var existing = new PlatformStats
|
||||
{
|
||||
TotalEnrollments = 1_000,
|
||||
SuccessfulEnrollments = 700,
|
||||
TotalEventsProcessed = 100_000,
|
||||
TotalUsers = 50,
|
||||
TotalTenants = 10,
|
||||
UniqueDeviceModels = 30
|
||||
};
|
||||
|
||||
var stats = MaintenanceService.BuildMonotonicPlatformStats(
|
||||
recomputedEnrollments: 1_500,
|
||||
recomputedSuccessful: 1_100,
|
||||
recomputedEvents: 250_000,
|
||||
recomputedUsers: 80,
|
||||
recomputedActiveTenants: 14,
|
||||
recomputedUniqueModels: 42,
|
||||
signedUpTenants: 20,
|
||||
existing: existing,
|
||||
nowUtc: Now);
|
||||
|
||||
Assert.Equal(1_500, stats.TotalEnrollments);
|
||||
Assert.Equal(1_100, stats.SuccessfulEnrollments);
|
||||
Assert.Equal(250_000, stats.TotalEventsProcessed);
|
||||
Assert.Equal(80, stats.TotalUsers);
|
||||
Assert.Equal(14, stats.TotalTenants);
|
||||
Assert.Equal(42, stats.UniqueDeviceModels);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SignedUpTenants_is_current_state_and_may_drop()
|
||||
{
|
||||
// Deliberate exception: TenantConfiguration is not retention-pruned, so its count is
|
||||
// authoritative — a drop reflects real offboarding, not data loss.
|
||||
var existing = new PlatformStats { TotalSignedUpTenants = 150 };
|
||||
|
||||
var stats = MaintenanceService.BuildMonotonicPlatformStats(
|
||||
recomputedEnrollments: 0, recomputedSuccessful: 0, recomputedEvents: 0,
|
||||
recomputedUsers: 0, recomputedActiveTenants: 0, recomputedUniqueModels: 0,
|
||||
signedUpTenants: 140,
|
||||
existing: existing,
|
||||
nowUtc: Now);
|
||||
|
||||
Assert.Equal(140, stats.TotalSignedUpTenants);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void First_run_without_persisted_row_uses_recomputed_values()
|
||||
{
|
||||
var stats = MaintenanceService.BuildMonotonicPlatformStats(
|
||||
recomputedEnrollments: 10,
|
||||
recomputedSuccessful: 8,
|
||||
recomputedEvents: 500,
|
||||
recomputedUsers: 3,
|
||||
recomputedActiveTenants: 2,
|
||||
recomputedUniqueModels: 4,
|
||||
signedUpTenants: 5,
|
||||
existing: null,
|
||||
nowUtc: Now);
|
||||
|
||||
Assert.Equal(10, stats.TotalEnrollments);
|
||||
Assert.Equal(8, stats.SuccessfulEnrollments);
|
||||
Assert.Equal(500, stats.TotalEventsProcessed);
|
||||
Assert.Equal(3, stats.TotalUsers);
|
||||
Assert.Equal(2, stats.TotalTenants);
|
||||
Assert.Equal(4, stats.UniqueDeviceModels);
|
||||
Assert.Equal(0, stats.IssuesDetected);
|
||||
Assert.Equal(5, stats.TotalSignedUpTenants);
|
||||
Assert.Equal(Now, stats.LastFullCompute);
|
||||
Assert.Equal(Now, stats.LastUpdated);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the "since release" semantics of the platform-stats rollup: a cumulative counter is
|
||||
/// the persisted total plus the growth of its source since the previous run. A total derived
|
||||
/// from an absolute figure stops moving for good once that figure shrinks below it — retention
|
||||
/// prunes sessions, offboarding deletes a tenant's counters — which froze the public
|
||||
/// landing-page figures while enrollments kept arriving.
|
||||
/// </summary>
|
||||
public class PlatformStatsRollupTests
|
||||
{
|
||||
private static readonly DateTime Now = new(2026, 07, 11, 12, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private static PlatformRollupSources Sources(long enrollments, long successful = 0, long events = 0, long tenants = 0, long models = 0)
|
||||
=> new()
|
||||
{
|
||||
TotalEnrollments = enrollments,
|
||||
SuccessfulEnrollments = successful,
|
||||
TotalEventsProcessed = events,
|
||||
ActiveTenants = tenants,
|
||||
SeenDeviceModels = models
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Counters_grow_by_the_source_delta_although_the_source_is_far_below_the_total()
|
||||
{
|
||||
// The freeze scenario: the persisted total (19 312) is above anything the source can
|
||||
// show, yet 40 enrollments arrived since the last run. Max(source, total) never moves.
|
||||
var existing = new PlatformStats
|
||||
{
|
||||
TotalEnrollments = 19_312,
|
||||
SuccessfulEnrollments = 10_289,
|
||||
TotalEventsProcessed = 5_779_212,
|
||||
TotalTenants = 84,
|
||||
UniqueDeviceModels = 486
|
||||
};
|
||||
|
||||
var stats = MaintenanceService.BuildPlatformStatsRollup(
|
||||
existing,
|
||||
baseline: Sources(14_540, successful: 10_240, events: 4_000_000, tenants: 80, models: 430),
|
||||
sources: Sources(14_580, successful: 10_275, events: 4_012_000, tenants: 81, models: 433),
|
||||
recomputedUsers: 0, signedUpTenants: 0, nowUtc: Now);
|
||||
|
||||
Assert.Equal(19_352, stats.TotalEnrollments);
|
||||
Assert.Equal(10_324, stats.SuccessfulEnrollments);
|
||||
Assert.Equal(5_791_212, stats.TotalEventsProcessed);
|
||||
Assert.Equal(85, stats.TotalTenants);
|
||||
Assert.Equal(489, stats.UniqueDeviceModels);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_shrunken_source_never_lowers_the_total_and_the_next_run_counts_again()
|
||||
{
|
||||
// Offboarding deleted a tenant's counters (−3 000) while 20 enrollments arrived: the
|
||||
// delta of this interval is clamped, the baseline follows, the next interval is exact.
|
||||
var existing = new PlatformStats { TotalEnrollments = 50_000 };
|
||||
var afterOffboarding = Sources(37_020);
|
||||
|
||||
var clamped = MaintenanceService.BuildPlatformStatsRollup(
|
||||
existing, baseline: Sources(40_000), sources: afterOffboarding,
|
||||
recomputedUsers: 0, signedUpTenants: 0, nowUtc: Now);
|
||||
Assert.Equal(50_000, clamped.TotalEnrollments);
|
||||
|
||||
var next = MaintenanceService.BuildPlatformStatsRollup(
|
||||
clamped, baseline: afterOffboarding, sources: Sources(37_055),
|
||||
recomputedUsers: 0, signedUpTenants: 0, nowUtc: Now);
|
||||
Assert.Equal(50_035, next.TotalEnrollments);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void First_run_without_a_baseline_treats_the_source_as_a_lower_bound_only()
|
||||
{
|
||||
// No baseline yet: whatever the sources show is already contained in the persisted
|
||||
// totals (or exceeds them and heals them) — it must never be added on top.
|
||||
var existing = new PlatformStats { TotalEnrollments = 19_312, SuccessfulEnrollments = 10_289 };
|
||||
|
||||
var stats = MaintenanceService.BuildPlatformStatsRollup(
|
||||
existing, baseline: null, sources: Sources(21_687, successful: 10_275),
|
||||
recomputedUsers: 0, signedUpTenants: 0, nowUtc: Now);
|
||||
|
||||
Assert.Equal(21_687, stats.TotalEnrollments);
|
||||
Assert.Equal(10_289, stats.SuccessfulEnrollments);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void First_run_without_a_persisted_row_starts_from_the_sources()
|
||||
{
|
||||
var stats = MaintenanceService.BuildPlatformStatsRollup(
|
||||
existing: null, baseline: null,
|
||||
sources: Sources(10, successful: 8, events: 500, tenants: 2, models: 4),
|
||||
recomputedUsers: 3, signedUpTenants: 5, nowUtc: Now);
|
||||
|
||||
Assert.Equal(10, stats.TotalEnrollments);
|
||||
Assert.Equal(8, stats.SuccessfulEnrollments);
|
||||
Assert.Equal(500, stats.TotalEventsProcessed);
|
||||
Assert.Equal(3, stats.TotalUsers);
|
||||
Assert.Equal(2, stats.TotalTenants);
|
||||
Assert.Equal(4, stats.UniqueDeviceModels);
|
||||
Assert.Equal(0, stats.IssuesDetected);
|
||||
Assert.Equal(5, stats.TotalSignedUpTenants);
|
||||
Assert.Equal(Now, stats.LastFullCompute);
|
||||
Assert.Equal(Now, stats.LastUpdated);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Users_stay_a_high_water_mark_and_issues_are_carried_over()
|
||||
{
|
||||
var existing = new PlatformStats { TotalUsers = 800, IssuesDetected = 6_500 };
|
||||
|
||||
var pruned = MaintenanceService.BuildPlatformStatsRollup(
|
||||
existing, baseline: Sources(0), sources: Sources(0),
|
||||
recomputedUsers: 90, signedUpTenants: 0, nowUtc: Now);
|
||||
Assert.Equal(800, pruned.TotalUsers);
|
||||
Assert.Equal(6_500, pruned.IssuesDetected);
|
||||
|
||||
var grown = MaintenanceService.BuildPlatformStatsRollup(
|
||||
existing, baseline: Sources(0), sources: Sources(0),
|
||||
recomputedUsers: 950, signedUpTenants: 0, nowUtc: Now);
|
||||
Assert.Equal(950, grown.TotalUsers);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SignedUpTenants_is_current_state_and_may_drop()
|
||||
{
|
||||
// Deliberate exception: TenantConfiguration is not retention-pruned, so its count is
|
||||
// authoritative — a drop reflects real offboarding, not data loss.
|
||||
var existing = new PlatformStats { TotalSignedUpTenants = 150 };
|
||||
|
||||
var stats = MaintenanceService.BuildPlatformStatsRollup(
|
||||
existing, baseline: Sources(0), sources: Sources(0),
|
||||
recomputedUsers: 0, signedUpTenants: 140, nowUtc: Now);
|
||||
|
||||
Assert.Equal(140, stats.TotalSignedUpTenants);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Azure;
|
||||
using Azure.Data.Tables;
|
||||
using AutopilotMonitor.Functions.Services;
|
||||
using AutopilotMonitor.Shared;
|
||||
using AutopilotMonitor.Shared.Models;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace AutopilotMonitor.Functions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Storage side of the platform rollup: the platform row is merged with the ETag it was read
|
||||
/// with and never carries IssuesDetected, the tenant floors land in one write, and the reads
|
||||
/// that feed the rollup baseline are scoped to exactly the rows they mean.
|
||||
/// </summary>
|
||||
public class PlatformStatsStorageTests
|
||||
{
|
||||
private const string Tenant = "11111111-1111-1111-1111-111111111111";
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
public Mock<TableClient> Table { get; } = new();
|
||||
public List<string> Filters { get; } = new();
|
||||
public List<List<TableTransactionAction>> Submitted { get; } = new();
|
||||
public Func<string, TableEntity[]> RowsFor { get; set; } = _ => Array.Empty<TableEntity>();
|
||||
public Queue<Exception> SubmitFailures { get; } = new();
|
||||
public TableStorageService Sut { get; }
|
||||
|
||||
public Harness()
|
||||
{
|
||||
Table.Setup(c => c.QueryAsync<TableEntity>(It.IsAny<string>(), It.IsAny<int?>(), It.IsAny<IEnumerable<string>>(), It.IsAny<CancellationToken>()))
|
||||
.Returns((string filter, int? _, IEnumerable<string> _, CancellationToken _) =>
|
||||
{
|
||||
Filters.Add(filter);
|
||||
var page = Page<TableEntity>.FromValues(RowsFor(filter), null, Mock.Of<Response>());
|
||||
return AsyncPageable<TableEntity>.FromPages(new[] { page });
|
||||
});
|
||||
Table.Setup(c => c.SubmitTransactionAsync(It.IsAny<IEnumerable<TableTransactionAction>>(), It.IsAny<CancellationToken>()))
|
||||
.Returns<IEnumerable<TableTransactionAction>, CancellationToken>((actions, _) =>
|
||||
{
|
||||
var snapshot = actions.ToList();
|
||||
Submitted.Add(snapshot);
|
||||
if (SubmitFailures.Count > 0) throw SubmitFailures.Dequeue();
|
||||
var inner = (IReadOnlyList<Response>)snapshot.Select(_ => Mock.Of<Response>()).ToList();
|
||||
return Task.FromResult(Response.FromValue(inner, Mock.Of<Response>()));
|
||||
});
|
||||
|
||||
var service = new Mock<TableServiceClient>();
|
||||
service.Setup(s => s.GetTableClient(Constants.TableNames.PlatformStats)).Returns(Table.Object);
|
||||
Sut = new TableStorageService(service.Object, NullLogger<TableStorageService>.Instance);
|
||||
}
|
||||
}
|
||||
|
||||
private static TableEntity PlatformRow(long enrollments, long issues, string etag)
|
||||
{
|
||||
var row = new TableEntity("global", "current") { ["TotalEnrollments"] = enrollments, ["IssuesDetected"] = issues };
|
||||
row.ETag = new ETag(etag);
|
||||
return row;
|
||||
}
|
||||
|
||||
private static TableEntity BaselineRow(long enrollments)
|
||||
=> new("global", "rollup-baseline") { ["TotalEnrollments"] = enrollments };
|
||||
|
||||
// ---------- rollup write ----------
|
||||
|
||||
[Fact]
|
||||
public async Task Rollup_merges_the_platform_row_with_its_read_etag_and_leaves_IssuesDetected_alone()
|
||||
{
|
||||
var h = new Harness { RowsFor = _ => new[] { PlatformRow(19_312, issues: 35_000, etag: "e1"), BaselineRow(21_000) } };
|
||||
PlatformRollupSources? seenBaseline = null;
|
||||
|
||||
var result = await h.Sut.RollupPlatformStatsAsync(
|
||||
(existing, baseline) =>
|
||||
{
|
||||
seenBaseline = baseline;
|
||||
return new PlatformStats { TotalEnrollments = existing!.TotalEnrollments + 40, IssuesDetected = existing.IssuesDetected };
|
||||
},
|
||||
new PlatformRollupSources { TotalEnrollments = 21_040 });
|
||||
|
||||
Assert.Equal(21_000, seenBaseline!.TotalEnrollments);
|
||||
Assert.Equal(19_352, result!.TotalEnrollments);
|
||||
Assert.Equal("PartitionKey eq 'global'", Assert.Single(h.Filters));
|
||||
|
||||
var batch = Assert.Single(h.Submitted);
|
||||
var platform = batch.Single(a => a.Entity.RowKey == "current");
|
||||
Assert.Equal(TableTransactionActionType.UpdateMerge, platform.ActionType);
|
||||
Assert.Equal(new ETag("e1"), platform.ETag);
|
||||
Assert.Equal(19_352L, ((TableEntity)platform.Entity).GetInt64("TotalEnrollments"));
|
||||
Assert.False(((TableEntity)platform.Entity).ContainsKey("IssuesDetected"),
|
||||
"a write-back of IssuesDetected undoes every increment that landed since the read");
|
||||
|
||||
var baselineWrite = batch.Single(a => a.Entity.RowKey == "rollup-baseline");
|
||||
Assert.Equal(TableTransactionActionType.UpsertReplace, baselineWrite.ActionType);
|
||||
Assert.Equal(21_040L, ((TableEntity)baselineWrite.Entity).GetInt64("TotalEnrollments"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Rollup_re_reads_and_re_merges_when_the_platform_row_changed_in_between()
|
||||
{
|
||||
var reads = 0;
|
||||
var h = new Harness
|
||||
{
|
||||
RowsFor = _ => ++reads == 1
|
||||
? new[] { PlatformRow(19_312, issues: 1, etag: "e1"), BaselineRow(100) }
|
||||
: new[] { PlatformRow(21_800, issues: 2, etag: "e2"), BaselineRow(100) } // corrected in between
|
||||
};
|
||||
h.SubmitFailures.Enqueue(new RequestFailedException(412, "precondition failed"));
|
||||
|
||||
var result = await h.Sut.RollupPlatformStatsAsync(
|
||||
(existing, _) => new PlatformStats { TotalEnrollments = existing!.TotalEnrollments + 5 },
|
||||
new PlatformRollupSources { TotalEnrollments = 105 });
|
||||
|
||||
Assert.Equal(21_805, result!.TotalEnrollments);
|
||||
Assert.Equal(2, h.Submitted.Count);
|
||||
Assert.Equal(new ETag("e2"), h.Submitted[1].Single(a => a.Entity.RowKey == "current").ETag);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Rollup_adds_a_missing_platform_row_instead_of_upserting_it()
|
||||
{
|
||||
var h = new Harness();
|
||||
|
||||
await h.Sut.RollupPlatformStatsAsync(
|
||||
(existing, baseline) =>
|
||||
{
|
||||
Assert.Null(existing);
|
||||
Assert.Null(baseline);
|
||||
return new PlatformStats { TotalEnrollments = 10 };
|
||||
},
|
||||
new PlatformRollupSources { TotalEnrollments = 10 });
|
||||
|
||||
var platform = Assert.Single(h.Submitted).Single(a => a.Entity.RowKey == "current");
|
||||
Assert.Equal(TableTransactionActionType.Add, platform.ActionType);
|
||||
Assert.True(((TableEntity)platform.Entity).ContainsKey("IssuesDetected"));
|
||||
}
|
||||
|
||||
// ---------- tenant counters ----------
|
||||
|
||||
private static (Mock<TableClient> Table, TableStorageService Sut, List<(TableEntity Entity, ETag ETag, TableUpdateMode Mode)> Updates) TenantRowHarness(TableEntity row)
|
||||
{
|
||||
var table = new Mock<TableClient>();
|
||||
table.Setup(t => t.GetEntityAsync<TableEntity>(Tenant, "current", It.IsAny<IEnumerable<string>>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(Response.FromValue(row, Mock.Of<Response>()));
|
||||
var updates = new List<(TableEntity, ETag, TableUpdateMode)>();
|
||||
table.Setup(t => t.UpdateEntityAsync(It.IsAny<TableEntity>(), It.IsAny<ETag>(), It.IsAny<TableUpdateMode>(), It.IsAny<CancellationToken>()))
|
||||
.Returns<TableEntity, ETag, TableUpdateMode, CancellationToken>((e, tag, mode, _) => { updates.Add((e, tag, mode)); return Task.FromResult(Mock.Of<Response>()); });
|
||||
var service = new Mock<TableServiceClient>();
|
||||
service.Setup(s => s.GetTableClient(Constants.TableNames.PlatformStats)).Returns(table.Object);
|
||||
return (table, new TableStorageService(service.Object, NullLogger<TableStorageService>.Instance), updates);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Floors_raise_only_the_counters_below_their_floor_in_one_merge()
|
||||
{
|
||||
var row = new TableEntity(Tenant, "current") { ["TotalEnrollments"] = 500L, ["SuccessfulEnrollments"] = 10L };
|
||||
row.ETag = new ETag("t1");
|
||||
var (_, sut, updates) = TenantRowHarness(row);
|
||||
|
||||
var inPlace = await sut.EnsureTenantStatFloorsAsync(Tenant, new Dictionary<string, long>
|
||||
{
|
||||
["TotalEnrollments"] = 120, // below the counter: retention pruned, must not lower
|
||||
["SuccessfulEnrollments"] = 90, // above: heal
|
||||
["TotalEventsProcessed"] = 30_000 // field missing on the row: seed
|
||||
});
|
||||
|
||||
Assert.True(inPlace);
|
||||
var update = Assert.Single(updates);
|
||||
Assert.Equal(new ETag("t1"), update.ETag);
|
||||
Assert.Equal(TableUpdateMode.Merge, update.Mode);
|
||||
Assert.False(update.Entity.ContainsKey("TotalEnrollments"));
|
||||
Assert.Equal(90L, update.Entity.GetInt64("SuccessfulEnrollments"));
|
||||
Assert.Equal(30_000L, update.Entity.GetInt64("TotalEventsProcessed"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Floors_already_met_write_nothing_and_still_count_as_in_place()
|
||||
{
|
||||
var row = new TableEntity(Tenant, "current") { ["TotalEnrollments"] = 500L };
|
||||
row.ETag = new ETag("t1");
|
||||
var (_, sut, updates) = TenantRowHarness(row);
|
||||
|
||||
var inPlace = await sut.EnsureTenantStatFloorsAsync(Tenant, new Dictionary<string, long> { ["TotalEnrollments"] = 120 });
|
||||
|
||||
Assert.True(inPlace);
|
||||
Assert.Empty(updates);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Floors_that_cannot_be_written_report_false()
|
||||
{
|
||||
var row = new TableEntity(Tenant, "current") { ["TotalEnrollments"] = 1L };
|
||||
row.ETag = new ETag("t1");
|
||||
var (table, sut, _) = TenantRowHarness(row);
|
||||
table.Setup(t => t.UpdateEntityAsync(It.IsAny<TableEntity>(), It.IsAny<ETag>(), It.IsAny<TableUpdateMode>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new RequestFailedException(500, "storage down"));
|
||||
|
||||
Assert.False(await sut.EnsureTenantStatFloorsAsync(Tenant, new Dictionary<string, long> { ["TotalEnrollments"] = 120 }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Increment_adds_to_the_one_field()
|
||||
{
|
||||
var row = new TableEntity(Tenant, "current") { ["TotalEnrollments"] = 500L, ["TotalEventsProcessed"] = 1_000L };
|
||||
row.ETag = new ETag("t1");
|
||||
var (_, sut, updates) = TenantRowHarness(row);
|
||||
|
||||
await sut.IncrementTenantStatAsync(Tenant, "TotalEventsProcessed", 37);
|
||||
|
||||
var update = Assert.Single(updates);
|
||||
Assert.Equal(1_037L, update.Entity.GetInt64("TotalEventsProcessed"));
|
||||
Assert.False(update.Entity.ContainsKey("TotalEnrollments"), "the patch must not carry fields it did not change");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task All_tenant_stats_read_the_tenant_rows_only()
|
||||
{
|
||||
var h = new Harness
|
||||
{
|
||||
RowsFor = _ => new[]
|
||||
{
|
||||
new TableEntity(Tenant, "current") { ["TotalEnrollments"] = 7L, ["SuccessfulEnrollments"] = 5L, ["TotalEventsProcessed"] = 900L },
|
||||
}
|
||||
};
|
||||
|
||||
var stats = Assert.Single(await h.Sut.GetAllTenantStatsAsync());
|
||||
|
||||
Assert.Equal("RowKey eq 'current' and PartitionKey ne 'global'", Assert.Single(h.Filters));
|
||||
Assert.Equal(7, stats.TotalEnrollments);
|
||||
Assert.Equal(5, stats.SuccessfulEnrollments);
|
||||
Assert.Equal(900, stats.TotalEventsProcessed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_failing_tenant_stats_read_throws_instead_of_reporting_zero()
|
||||
{
|
||||
// Zero would become the rollup baseline and the next run would count every tenant
|
||||
// counter as growth a second time.
|
||||
var h = new Harness { RowsFor = _ => throw new RequestFailedException(503, "busy") };
|
||||
|
||||
await Assert.ThrowsAsync<RequestFailedException>(() => h.Sut.GetAllTenantStatsAsync());
|
||||
}
|
||||
|
||||
// ---------- seen device models ----------
|
||||
|
||||
[Fact]
|
||||
public async Task Seen_models_adds_only_unknown_models_and_returns_the_size_of_the_set()
|
||||
{
|
||||
var known = TableStorageService.SeenDeviceModelRowKey("LENOVO ThinkPad T14 Gen 6");
|
||||
var h = new Harness { RowsFor = _ => new[] { new TableEntity("models", known), new TableEntity("models", "PRUNEDMODELHASH") } };
|
||||
|
||||
var size = await h.Sut.RecordSeenDeviceModelsAsync(new[]
|
||||
{
|
||||
"lenovo thinkpad t14 gen 6", // known, different casing
|
||||
"HP EliteBook 840 14 inch G10/#1", // new, with characters a table key cannot hold
|
||||
" ",
|
||||
});
|
||||
|
||||
Assert.Equal(3, size);
|
||||
Assert.Equal("PartitionKey eq 'models'", Assert.Single(h.Filters));
|
||||
var added = Assert.Single(Assert.Single(h.Submitted));
|
||||
Assert.Equal("models", added.Entity.PartitionKey);
|
||||
Assert.Equal("HP EliteBook 840 14 inch G10/#1", ((TableEntity)added.Entity).GetString("Model"));
|
||||
Assert.Matches("^[0-9A-F]{64}$", added.Entity.RowKey);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Security.Claims;
|
||||
using AutopilotMonitor.Functions.Functions.Admin;
|
||||
using AutopilotMonitor.Functions.Functions.Config;
|
||||
using AutopilotMonitor.Functions.Middleware;
|
||||
using AutopilotMonitor.Functions.Security;
|
||||
@@ -937,13 +938,10 @@ public class PolicyEnforcementMiddlewareTests
|
||||
Assert.False(rc.IsGlobalReader);
|
||||
Assert.NotNull(rc.AllowedTenantIds);
|
||||
Assert.Contains(TenantB.ToLowerInvariant(), rc.AllowedTenantIds!);
|
||||
// …and it is the DATA aggregate the MCP quota layer may narrow (charged per managed tenant).
|
||||
Assert.True(rc.IsDelegatedAggregate);
|
||||
Assert.Null(rc.HomeChargedTenantIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delegated_GlobalSessions_WithTenantId_IsADrill_NotAnAggregate()
|
||||
public async Task Delegated_GlobalSessions_WithTenantId_IsADrill()
|
||||
{
|
||||
const string upn = "msp@partner.example";
|
||||
var h = BuildHarness();
|
||||
@@ -955,15 +953,12 @@ public class PolicyEnforcementMiddlewareTests
|
||||
var rc = result.Context!;
|
||||
Assert.True(rc.IsDelegatedReader);
|
||||
Assert.Equal(TenantB, rc.TargetTenantId);
|
||||
Assert.False(rc.IsDelegatedAggregate);
|
||||
Assert.Null(rc.HomeChargedTenantIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delegated_ConfigAll_IsADirectoryListing_NotAnAggregate()
|
||||
public async Task Delegated_ConfigAll_IsADirectoryListing_AdmittedAndBounded()
|
||||
{
|
||||
// Subset tier with TenantScoping.None: admitted + bounded, but no data fan-out — the quota layer
|
||||
// charges it to the caller's home tenant, never to the managed tenants.
|
||||
// Subset tier with TenantScoping.None: admitted + bounded, but no data fan-out.
|
||||
const string upn = "msp@partner.example";
|
||||
var h = BuildHarness();
|
||||
h.AsDelegated(TenantB);
|
||||
@@ -974,54 +969,6 @@ public class PolicyEnforcementMiddlewareTests
|
||||
var rc = result.Context!;
|
||||
Assert.True(rc.IsDelegatedReader);
|
||||
Assert.NotNull(rc.AllowedTenantIds);
|
||||
Assert.False(rc.IsDelegatedAggregate);
|
||||
}
|
||||
|
||||
private static void AsHomeChargedGroupMember(Harness h, string groupId, string upn, params string[] tenantIds)
|
||||
{
|
||||
h.Repo.Setup(r => r.GetGroupAssignmentsForUpnAsync(It.IsAny<string>()))
|
||||
.ReturnsAsync(new List<TenantGroupAssignment>
|
||||
{
|
||||
new() { Upn = upn, GroupId = groupId, Role = Constants.DelegatedRoles.DelegatedReader, IsEnabled = true, AssignedBy = "ga@vendor.example" },
|
||||
});
|
||||
h.Repo.Setup(r => r.GetGroupMembershipAsync(groupId))
|
||||
.ReturnsAsync(new TenantGroupMembership
|
||||
{
|
||||
GroupId = groupId,
|
||||
TenantIds = tenantIds.Select(t => t.ToLowerInvariant()).ToList(),
|
||||
ChargeHomeTenantQuota = true,
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delegated_HomeChargedGroup_MarksTheDrillTarget()
|
||||
{
|
||||
const string upn = "ops@vendor.example";
|
||||
var h = BuildHarness();
|
||||
AsHomeChargedGroupMember(h, "grp-managed-service", upn, TenantB);
|
||||
|
||||
var result = await h.Middleware.DecideAsync("GET", "/api/global/sessions", TenantB, AuthedPrincipal(TenantA, upn));
|
||||
|
||||
Assert.True(result.Allowed);
|
||||
var rc = result.Context!;
|
||||
Assert.True(rc.IsDelegatedReader);
|
||||
Assert.Equal(new[] { TenantB.ToLowerInvariant() }, rc.HomeChargedTenantIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Delegated_HomeChargedGroup_MarksTheAggregateMembers()
|
||||
{
|
||||
const string upn = "ops@vendor.example";
|
||||
var h = BuildHarness();
|
||||
AsHomeChargedGroupMember(h, "grp-managed-service", upn, TenantB);
|
||||
|
||||
var result = await h.Middleware.DecideAsync("GET", "/api/global/sessions", null, AuthedPrincipal(TenantA, upn));
|
||||
|
||||
Assert.True(result.Allowed);
|
||||
var rc = result.Context!;
|
||||
Assert.True(rc.IsDelegatedAggregate);
|
||||
Assert.Contains(TenantB.ToLowerInvariant(), rc.AllowedTenantIds!);
|
||||
Assert.Equal(new[] { TenantB.ToLowerInvariant() }, rc.HomeChargedTenantIds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -1677,6 +1624,82 @@ public class PolicyEnforcementMiddlewareTests
|
||||
h.ConfigRepo.Verify(r => r.GetTenantConfigurationAsync(It.IsAny<string>()), Times.Never);
|
||||
}
|
||||
|
||||
// ── Offboarding tombstone vs. the farewell feedback route (AllowedDuringOffboarding) ──────
|
||||
// The offboard endpoint tombstones the tenant (Disabled=true, offboarding reason) BEFORE it answers
|
||||
// 202, so the departing admin submits the farewell feedback from an already-suspended tenant. That
|
||||
// one route opts out of the tombstone gate; every other route and every other suspension stay closed.
|
||||
|
||||
private static void AsOffboardingTombstone(Harness h, string tenantId) =>
|
||||
AsSuspended(h, tenantId, reason: TenantOffboardFunction.OffboardingDisabledReason);
|
||||
|
||||
[Fact]
|
||||
public async Task OffboardingTombstone_FeedbackRoute_IsAllowed_ForDepartingTenantAdmin()
|
||||
{
|
||||
const string upn = "admin@contoso.com";
|
||||
var h = BuildHarness();
|
||||
h.AsTenantAdmin(TenantA, upn);
|
||||
AsOffboardingTombstone(h, TenantA);
|
||||
|
||||
var result = await h.Middleware.DecideAsync(
|
||||
"POST", $"/api/tenants/{TenantA}/offboard/feedback", null, AuthedPrincipal(TenantA, upn));
|
||||
|
||||
Assert.True(result.Allowed);
|
||||
Assert.Equal(TenantA, result.Context!.TargetTenantId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OffboardingTombstone_OtherRoutes_StayForbidden()
|
||||
{
|
||||
// The opt-out is per route: the same tombstone still closes the rest of the API.
|
||||
const string upn = "admin@contoso.com";
|
||||
var h = BuildHarness();
|
||||
h.AsTenantAdmin(TenantA, upn);
|
||||
AsOffboardingTombstone(h, TenantA);
|
||||
|
||||
var read = await h.Middleware.DecideAsync("GET", "/api/sessions", null, AuthedPrincipal(TenantA, upn));
|
||||
var write = await h.Middleware.DecideAsync("DELETE", $"/api/tenants/{TenantA}/offboard", null, AuthedPrincipal(TenantA, upn));
|
||||
|
||||
Assert.False(read.Allowed);
|
||||
Assert.Equal("TenantSuspended", read.ErrorCode);
|
||||
Assert.Equal(TenantOffboardFunction.OffboardingDisabledReason, read.ErrorMessage);
|
||||
Assert.False(write.Allowed);
|
||||
Assert.Equal("TenantSuspended", write.ErrorCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OperatorSuspension_FeedbackRoute_StaysForbidden()
|
||||
{
|
||||
// The opt-out is for the offboarding tombstone only: a tenant an operator suspended (any other
|
||||
// reason) cannot reach the feedback route either — nothing in the flag grants access.
|
||||
const string upn = "admin@contoso.com";
|
||||
var h = BuildHarness();
|
||||
h.AsTenantAdmin(TenantA, upn);
|
||||
AsSuspended(h, TenantA, reason: "Abuse investigation");
|
||||
|
||||
var result = await h.Middleware.DecideAsync(
|
||||
"POST", $"/api/tenants/{TenantA}/offboard/feedback", null, AuthedPrincipal(TenantA, upn));
|
||||
|
||||
Assert.False(result.Allowed);
|
||||
Assert.Equal("TenantSuspended", result.ErrorCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task OffboardingTombstone_FeedbackRoute_NonMember_StillNeedsTenantAdmin()
|
||||
{
|
||||
// Policy tier is untouched by the flag: a plain member (no tenant admin role) is denied by the
|
||||
// TenantAdminOrGA tier before the suspension gate is even reached.
|
||||
const string upn = "viewer@contoso.com";
|
||||
var h = BuildHarness();
|
||||
AsOffboardingTombstone(h, TenantA);
|
||||
|
||||
var result = await h.Middleware.DecideAsync(
|
||||
"POST", $"/api/tenants/{TenantA}/offboard/feedback", null, AuthedPrincipal(TenantA, upn));
|
||||
|
||||
Assert.False(result.Allowed);
|
||||
Assert.Equal(403, result.StatusCode);
|
||||
Assert.NotEqual("TenantSuspended", result.ErrorCode);
|
||||
}
|
||||
|
||||
// ── Tenant MCP switch (TenantConfiguration.McpDisabled) — the per-request half ────────────
|
||||
// The MCP front door (McpUserService) already denies a caller whose home tenant is closed; this gate
|
||||
// is what makes the switch hold per request (front-door verdicts are cached) and what keeps a closed
|
||||
@@ -1769,7 +1792,6 @@ public class PolicyEnforcementMiddlewareTests
|
||||
Assert.True(mcp.Allowed);
|
||||
Assert.NotNull(mcp.Context!.AllowedTenantIds);
|
||||
Assert.Empty(mcp.Context!.AllowedTenantIds!);
|
||||
Assert.True(mcp.Context!.IsDelegatedAggregate);
|
||||
Assert.Contains(TenantB.ToLowerInvariant(), portal.Context!.AllowedTenantIds!);
|
||||
}
|
||||
|
||||
|
||||
@@ -71,4 +71,67 @@ public class QueryParamGuardTests
|
||||
"Baseline entries without a TryParse any more — remove them (the ratchet only shrinks):\n " +
|
||||
string.Join("\n ", stale));
|
||||
}
|
||||
|
||||
// ── One source of the query collection ──────────────────────────────────────────────
|
||||
// `req.Query` IS `HttpUtility.ParseQueryString(req.Url.Query)`, cached per request (the
|
||||
// fact below pins that against a worker update). A second spelling of the same call is
|
||||
// only a pattern for the next function to copy, so the request query is read through
|
||||
// `req.Query` and ParseQueryString stays for strings that are not the request's query.
|
||||
|
||||
private static readonly Regex ParseQueryStringCall = new(@"\bParseQueryString\(", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>ParseQueryString over something other than the request query: file → why.</summary>
|
||||
private static readonly IReadOnlyDictionary<string, string> ParseQueryStringBaseline = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["Functions/Config/GetTenantConfigurationFunction.cs"] = "ShouldRedact takes the raw query string so the redaction decision is unit-testable without a request",
|
||||
["Functions/Diagnostics/GetDiagnosticsUploadUrlFunction.cs"] = "query of the tenant's stored SAS URL",
|
||||
["Services/Diagnostics/SasPermissionParser.cs"] = "query of a SAS URL",
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void The_request_query_is_read_through_req_Query_only()
|
||||
{
|
||||
var root = FunctionsRoot();
|
||||
var offenders = new List<string>();
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
var files = Directory.EnumerateFiles(root, "*.cs", SearchOption.AllDirectories)
|
||||
.Select(p => Path.GetRelativePath(root, p).Replace('\\', '/'))
|
||||
.Where(rel => !rel.StartsWith("bin/", StringComparison.Ordinal) && !rel.StartsWith("obj/", StringComparison.Ordinal))
|
||||
.OrderBy(p => p, StringComparer.Ordinal);
|
||||
|
||||
foreach (var rel in files)
|
||||
{
|
||||
if (!ParseQueryStringCall.IsMatch(File.ReadAllText(Path.Combine(root, rel)))) continue;
|
||||
seen.Add(rel);
|
||||
if (!ParseQueryStringBaseline.ContainsKey(rel)) offenders.Add(rel);
|
||||
}
|
||||
|
||||
Assert.True(offenders.Count == 0,
|
||||
"HttpUtility.ParseQueryString in the Functions project — read the request query through " +
|
||||
"req.Query, or add the file to the baseline with what it parses instead:\n " + string.Join("\n ", offenders));
|
||||
|
||||
var stale = ParseQueryStringBaseline.Keys.Where(k => !seen.Contains(k)).ToList();
|
||||
Assert.True(stale.Count == 0,
|
||||
"Baseline entries without a ParseQueryString any more — remove them:\n " + string.Join("\n ", stale));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Req_Query_is_ParseQueryString_over_the_request_url()
|
||||
{
|
||||
var url = new Uri("https://localhost/api/x?a=1&a=2&b=%20x%2B&c&=orphan&D=Case");
|
||||
var req = new Moq.Mock<Microsoft.Azure.Functions.Worker.Http.HttpRequestData>(
|
||||
Moq.Mock.Of<Microsoft.Azure.Functions.Worker.FunctionContext>()) { CallBase = true };
|
||||
req.SetupGet(r => r.Url).Returns(url);
|
||||
|
||||
var viaRequest = req.Object.Query;
|
||||
var viaHelper = System.Web.HttpUtility.ParseQueryString(url.Query);
|
||||
|
||||
Assert.Equal(viaHelper.AllKeys, viaRequest.AllKeys);
|
||||
foreach (var key in viaHelper.AllKeys)
|
||||
Assert.Equal(viaHelper.GetValues(key), viaRequest.GetValues(key));
|
||||
Assert.Equal("1,2", viaRequest["a"]); // repeated key: comma-joined on both paths
|
||||
Assert.Equal(" x+", viaRequest["b"]);
|
||||
Assert.Same(viaRequest, req.Object.Query); // parsed once per request
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user