Compare commits

...

8 Commits

Author SHA1 Message Date
Oliver Kieselbach fa31872903 fix(agent,engine,web): keep the due time as the deadline stamp; draw timeout verdicts hollow in the Network Timeline (D-238 revised)
Revises 14b185db after the pre-release review. The fleet measurement (30 days,
all tenants) showed 87 of 821 sessions with a sleep episode had their verdict
inside the episode — 59 of them one tenant's self-deploying devices closed two
minutes before the device-only detection came due and reopened 5–7 days later.
Stamping the firing clock would have turned those outages into session
duration and pushed the tenant's mean duration from minutes to days.

- OnDeadlineFired posts OccurredAtUtc = DueAtUtc again; the due time stays in the
  payload and the two stale-fire guards keep reading it (any stamp stays safe).
- Network Timeline: a timeout verdict (helloOutcome timeout, device-only detection
  window) is drawn as a hollow marker "Completed (timeout)" with a legend line and a
  plain-language tooltip — a wait expired, nothing observed on the device; the
  Asleep block is never split at it. finalizing_grace alone is not an indicator.
- Session Info standby note clips to the two WhiteGlove spans when the card shows
  the combined WhiteGlove duration; the dedup key is consumed only by a usable
  observation (review findings).
- Stale comments describing the firing-clock contract corrected.

Tests: DeadlineFireTimeStampTests (reducer stays correct for any stamp),
EnrollmentOrchestratorTests (due-time stamp + payload), networkTimelineModel
timeout markers (3), standby windows, WhiteGlove windows.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 01:55:31 +02:00
Oliver Kieselbach b08b79eafe test(mcp): revert_tenant_config backupId is required — schema and description pin (D-240 review)
Left out of e43d916c's explicit file list by mistake; part of the same change.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 01:47:31 +02:00
Oliver Kieselbach e43d916c24 fix(mcp): spec gates, secret-safe error text, enforced response cap, payload-coupled pageSize, client cancellation (D-239, D-240)
Request gates: an Origin other than the server's own is refused with 403 before any token
work (spec MUST); a token the backend rejects is answered 401 + WWW-Authenticate
error="invalid_token" instead of a final 403. The auth.ts header now names the
backend-audience token forwarding as a deliberate deviation (D-239) instead of calling
it spec-conformant.

Secrets: the per-argument echo policy travels in the tool-call context, so toolError's
"Parameters used" block masks update_tenant_config.fields the same way the log line
does. revert_tenant_config requires backupId (a retried revert without one restored the
snapshot the previous revert had just created). /oauth/token relays Entra errors through
an allowlist (error, capped description, error_codes). OAuthStateSigningKey is required
in production (B-uba).

Results: toolResultText enforces the response cap — a page above it is refused with an
overflow answer naming the pageSize that fits (from this page's bytes per row), never
rows or a nextLink; the telemetry logs the size the page would have had (B-zhp).
query_raw_events with DataJson in the effective projection defaults to 50 rows and
refuses more than 100 before the backend runs (30-day measurement: p90 3.3 KB, outliers
21-29 KB per row) (B-s2y). The caller context carries the request's cancellation signal:
apiFetch, the retry wait and the timeout fallback stop when the client goes away, and the
tool_call line logs cancelled instead of an error.

Tests: 9 new files (origin guard both eras over HTTP, 401 + cancellation, apiFetch abort,
arg policy in error text, signing key, token error body, overflow, raw-events pageSize,
telemetry overflow/cancelled); vitest 844 green, tsc 0.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 01:47:10 +02:00
Oliver Kieselbach 14b185db35 fix(agent,engine,web): a deadline decision is stamped with the firing clock, never the due time (D-238)
A HelloSafety deadline due during Modern Standby fired after wake but was stamped
with its due time, so enrollment_complete and CompletedAt landed inside the sleep
window: the Network Timeline drew "Completed" in the middle of the Asleep block
and three views named three different standby durations.

- OnDeadlineFired posts OccurredAtUtc = FiredAtUtc and carries the due time under
  SignalPayloadKeys.DeadlineDueAtUtc; the stale-fire guards (RealmJoin re-arm,
  SelfDeploying guard C) identify the incarnation via DecisionEngine.DeadlineDueAtUtc,
  which falls back to the signal time for pre-key signal logs.
- SignalSerializer renders Date-tokenized payload strings as ISO-8601 round-trip text
  instead of the culture-formatted JValue.ToString() (a replayed deadlineDueAtUtc came
  back as "4/20/2026 9:55:00 AM").
- Web: the Session Info standby note is clipped to the same window as the duration
  next to it (lib/standby.ts) and printed with seconds, matching the attribution chip.

Tests: DeadlineFireTimeStampTests (late HelloSafety fire, guard C, RealmJoin re-arm,
helper fallback), SerializationTests date-like payload round-trip,
EnrollmentOrchestratorTests late fire, lib/__tests__/standby.test.ts.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 01:05:16 +02:00
Oliver Kieselbach baa51102fd feat(web,backend,mcp): app rows without a terminal state become Incomplete instead of running forever (D-237)
An app still installing when the session's observation ended has no terminal
event and never will. The session page ticked Date.now() - startedAt for it
("11h 39m" on a session that finished hours ago), and its AppInstallSummaries
row stayed InProgress forever - ranked behind failures in the app's session
list and counted in totalInstalls with no named bucket.

Web: applyObservationEnd marks such rows Incomplete once the session is
terminal (isTerminalStatus), bounded by session.lastEventAt; the panel shows a
slate Incomplete badge and the watched span as a lower bound, the "active"
pill excludes them, and the download panel carries the parallel flag. Covers
every historic session without a backfill.

Backend: CloseOpenAppInstallsForSessionAsync closes InProgress rows without a
CompletedAt as Incomplete - at the terminal seam, again on the ingest batch
that carries agent_shutting_down for a terminal session (rows opened after
the verdict), and from the 30-day sweep. The sticky-status reconcile keeps
Incomplete against a late progress-only batch and lets a real terminal win.
App metrics and app analytics disclose the bucket (incomplete,
totalIncomplete) outside the failure rate; manifest and wire types
regenerated.

MCP: get_session_summary coverage gains an apps block and a gaps line naming
the apps the agent's last app_tracking_summary still listed as installing or
downloading, terminal sessions only.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 00:02:24 +02:00
Oliver Kieselbach 5577f5e7e5 feat(rules): rule submissions — retention (withdrawn 30d, declined 90d), contact email, pending-first tenant list, operator hard delete (D-236 amended)
Closed submissions leave through the daily maintenance sweep (RuleSubmissionRetention, one place for rule and test); pending/approved/published never. The submit dialog takes an optional contact email (a UPN is not always a mailbox), stored for the reviewer and never published. The tenant list shows pending rows by default with the rest behind Show all, and the contribute button shows for every writer, also before the first custom rule exists. DELETE global/rule-submissions/{id} (GlobalAdminOnly, MCP delete_rule_submission) removes test/demo rows for operator and tenant alike. Bumps internal and .claude/commands gitlinks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-09 23:27:25 +02:00
Oliver Kieselbach 61892592e4 feat(rules): community rule submissions — submit custom rules from the portal, review via GA page or MCP, publish by repo commit + reseed (D-236)
Tenant admins submit references to their own gather/analyze rules; the server freezes the rule, records pre-flight findings and fire stats, and stores it under a 12-character id (RuleSubmissions, SessionReports layout). Attribution is the submitter's frozen choice (anonymous by default) and becomes the published author. Review (approve with reserved id / decline with comment) through /admin/reports/rule-submissions or the MCP tools list_rule_submissions, get_rule_submission, review_rule_submission, reseed_rules_from_github; published is derived from the global catalog, never stored. Analyze rules now get the same server-side author stamp as gather rules; ANALYZE-ID-001 carries author Community. Privacy page names the credit; bumps internal and .claude/commands gitlinks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-09 22:53:32 +02:00
Oliver Kieselbach 1e2ca46946 chore: bump internal gitlink (ESP-004 released, B-kfu)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 17:40:23 +02:00
123 changed files with 7615 additions and 208 deletions
+1 -1
Submodule infra updated: 55a8eaf929...742249e7e3
+1
View File
@@ -5,6 +5,7 @@
"description": "Detects when a certificate with the configured subject is missing from the local machine personal store (LocalMachine\\My). Requires the gather rule GATHER-ID-002 (machine cert store inventory) to be enabled — the check runs against its gather_machine_cert_store output. A missing certificate may indicate that MDM enrollment certificate provisioning or SCEP certificate deployment failed.",
"severity": "warning",
"category": "identity",
"author": "Community",
"isCommunity": true,
"enabled": false,
"evaluateOn": [
+1
View File
@@ -2806,6 +2806,7 @@
"description": "Detects when a certificate with the configured subject is missing from the local machine personal store (LocalMachine\\My). Requires the gather rule GATHER-ID-002 (machine cert store inventory) to be enabled — the check runs against its gather_machine_cert_store output. A missing certificate may indicate that MDM enrollment certificate provisioning or SCEP certificate deployment failed.",
"severity": "warning",
"category": "identity",
"author": "Community",
"isCommunity": true,
"enabled": false,
"evaluateOn": [
@@ -265,6 +265,42 @@ namespace AutopilotMonitor.Agent.V2.Core.Tests.Orchestration
sut.Stop();
}
[Fact]
public void Deadline_fired_late_keeps_the_due_time_as_stamp_and_carries_it_in_the_payload()
{
// A deadline that was due while the device slept (or the agent was down) fires only
// afterwards. The signal keeps the due time as OccurredAtUtc (D-238: the outage must not
// become session duration) and repeats it in the payload so the stale-fire guards
// identify the incarnation independently of the stamp.
using var rig = new EnrollmentOrchestratorRig(At);
var sut = rig.Build();
sut.Start();
var dueAt = At.AddMinutes(-5);
var scheduler = GetScheduler(sut);
scheduler.Schedule(new ActiveDeadline(
name: "hello_safety",
dueAtUtc: dueAt,
firesSignalKind: DecisionSignalKind.DeadlineFired,
firesPayload: new Dictionary<string, string> { [SignalPayloadKeys.Deadline] = "hello_safety" }));
var signalLog = GetSignalLog(sut);
Assert.True(SpinWait.SpinUntil(() => ContainsDeadlineFired(signalLog), 3000));
DecisionSignal? fired = null;
foreach (var sig in signalLog.ReadAll())
{
if (sig.Kind == DecisionSignalKind.DeadlineFired) { fired = sig; break; }
}
Assert.NotNull(fired);
Assert.Equal(dueAt, fired!.OccurredAtUtc);
Assert.NotNull(fired.Payload);
Assert.Equal("hello_safety", fired.Payload![SignalPayloadKeys.Deadline]);
Assert.Equal(dueAt.ToString("O"), fired.Payload[SignalPayloadKeys.DeadlineDueAtUtc]);
sut.Stop();
}
// ========================================================================= Quarantine
[Fact]
@@ -9,9 +9,11 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
/// <para>
/// The orchestrator consumes this event and translates it into a synthetic
/// <c>DeadlineFired</c>-<see cref="AutopilotMonitor.DecisionCore.Signals.DecisionSignal"/>
/// whose <c>OccurredAtUtc</c> equals the deadline's <see cref="ActiveDeadline.DueAtUtc"/>,
/// not the wall-clock firing time — so replay stays deterministic even if the agent
/// restarts long after the deadline has passed.
/// whose <c>OccurredAtUtc</c> equals the deadline's <see cref="ActiveDeadline.DueAtUtc"/>
/// (the policy instant the wait expired), with the due time repeated in the payload. The
/// firing clock is deliberately NOT the stamp: a timer due during Modern Standby or a
/// reboot fires only afterwards, and the outage would otherwise become session duration
/// (D-238).
/// </para>
/// </summary>
public sealed class DeadlineFiredEventArgs : EventArgs
@@ -1,6 +1,7 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
@@ -1159,7 +1160,7 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
var evidence = new Evidence(
kind: EvidenceKind.Synthetic,
identifier: e.Deadline.Name,
summary: $"deadline '{e.Deadline.Name}' fired at {e.Deadline.DueAtUtc:O}");
summary: $"deadline '{e.Deadline.Name}' due {e.Deadline.DueAtUtc:O} fired at {e.FiredAtUtc:O}");
// The reducer reads the deadline name under SignalPayloadKeys.Deadline
// (see HandleDeadlineFiredV1 in DecisionEngine.Shared). Forward the
@@ -1180,7 +1181,15 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
payload[SignalPayloadKeys.Deadline] = e.Deadline.Name;
}
// OccurredAtUtc = DueAtUtc (not firedAt) — replay-determinism per DeadlineFiredEventArgs doc.
// OccurredAtUtc = DueAtUtc, not the firing clock (D-238). Every effect of the
// resulting step (phase_transition, enrollment_complete) is stamped with the signal
// time; a timer that came due during Modern Standby or a reboot fires only afterwards,
// and the firing clock would make the verdict — and the session duration — grow by
// the whole outage (measured: days for devices closed right after provisioning).
// The due time also travels in the payload so the stale-fire guards identify the
// deadline incarnation independently of the stamp.
payload[SignalPayloadKeys.DeadlineDueAtUtc] = e.Deadline.DueAtUtc.ToString("O", CultureInfo.InvariantCulture);
_ingress.Post(
kind: DecisionSignalKind.DeadlineFired,
occurredAtUtc: e.Deadline.DueAtUtc,
@@ -39,7 +39,8 @@ namespace AutopilotMonitor.Agent.V2.Core.Orchestration
/// <summary>
/// Wird vom Timer-Thread geraised, wenn ein Deadline fällig wird. Subscriber
/// ist typischerweise der Orchestrator, der daraus ein synthetisches
/// <c>DeadlineFired</c>-Signal mit <c>OccurredAtUtc = deadline.DueAtUtc</c> erzeugt.
/// <c>DeadlineFired</c>-Signal mit <c>OccurredAtUtc = deadline.DueAtUtc</c> erzeugt; die
/// Fälligkeit reist zusätzlich im Payload (<c>SignalPayloadKeys.DeadlineDueAtUtc</c>).
/// </summary>
event EventHandler<DeadlineFiredEventArgs>? Fired;
@@ -0,0 +1,191 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using AutopilotMonitor.DecisionCore.Engine;
using AutopilotMonitor.DecisionCore.Signals;
using AutopilotMonitor.DecisionCore.State;
using Xunit;
namespace AutopilotMonitor.DecisionCore.Tests
{
/// <summary>
/// The reducer identifies a deadline incarnation through the due time carried in the
/// payload (<see cref="SignalPayloadKeys.DeadlineDueAtUtc"/>), never through the signal
/// time: the host stamps <c>DeadlineFired</c> with the due time (D-238), but the guards
/// must stay correct for any stamp — a late fire after Modern Standby or a restart, a
/// replayed signal, or a future switch to the firing clock. Without the key they fall back
/// to the signal time (pre-key signal logs, where the two were equal by contract).
/// </summary>
public sealed class DeadlineFireTimeStampTests
{
private static readonly DateTime T0 = new DateTime(2026, 9, 9, 6, 31, 0, DateTimeKind.Utc);
private static DecisionSignal MakeSignal(
long ordinal,
DecisionSignalKind kind,
DateTime occurredAtUtc,
IReadOnlyDictionary<string, string>? payload = null) =>
new DecisionSignal(
sessionSignalOrdinal: ordinal,
sessionTraceOrdinal: ordinal,
kind: kind,
kindSchemaVersion: 1,
occurredAtUtc: occurredAtUtc,
sourceOrigin: "test",
evidence: new Evidence(EvidenceKind.Synthetic, $"t-{kind}-{ordinal}", $"synthetic {kind}"),
payload: payload);
/// <summary>What the host posts: name plus due time, OccurredAtUtc = firing clock.</summary>
private static Dictionary<string, string> FiredPayload(string deadlineName, DateTime dueAtUtc) =>
new Dictionary<string, string>
{
[SignalPayloadKeys.Deadline] = deadlineName,
[SignalPayloadKeys.DeadlineDueAtUtc] = dueAtUtc.ToString("O", CultureInfo.InvariantCulture),
};
// ============================================================== helper
[Fact]
public void DeadlineDueAtUtc_reads_the_payload_and_falls_back_to_the_signal_time()
{
var due = T0.AddMinutes(5);
var fired = T0.AddMinutes(9);
var withKey = MakeSignal(1, DecisionSignalKind.DeadlineFired, fired, FiredPayload(DeadlineNames.HelloSafety, due));
Assert.Equal(due, DecisionEngine.DeadlineDueAtUtc(withKey));
Assert.Equal(DateTimeKind.Utc, DecisionEngine.DeadlineDueAtUtc(withKey).Kind);
var withoutKey = MakeSignal(2, DecisionSignalKind.DeadlineFired, fired,
new Dictionary<string, string> { [SignalPayloadKeys.Deadline] = DeadlineNames.HelloSafety });
Assert.Equal(fired, DecisionEngine.DeadlineDueAtUtc(withoutKey));
var garbage = MakeSignal(3, DecisionSignalKind.DeadlineFired, fired,
new Dictionary<string, string> { [SignalPayloadKeys.DeadlineDueAtUtc] = "not-a-time" });
Assert.Equal(fired, DecisionEngine.DeadlineDueAtUtc(garbage));
}
// ============================================================== Classic: standby at the Hello prompt
[Fact]
public void Late_HelloSafety_fire_stamps_the_resolution_and_the_grace_window_from_the_firing_clock()
{
// Session ac5660b8 shape: ESP exits, the user leaves the device at the Hello prompt, it
// enters Modern Standby, HelloSafety is due during the sleep and fires ~3 min late after
// wake. Fed with the firing clock as signal time, the reducer must stamp the Hello
// timeout fact, the Finalizing step and the FinalizingGrace due time from that time —
// the stamp policy is the host's choice (D-238), the reducer follows the signal.
var engine = new DecisionEngine();
var state = DecisionState.CreateInitial("sess-standby", "tenant", T0);
state = engine.Reduce(state, MakeSignal(0, DecisionSignalKind.SessionStarted, T0)).NewState;
state = engine.Reduce(state, MakeSignal(1, DecisionSignalKind.EspPhaseChanged, T0.AddMinutes(1),
new Dictionary<string, string> { [SignalPayloadKeys.EspPhase] = "AccountSetup" })).NewState;
state = engine.Reduce(state, MakeSignal(2, DecisionSignalKind.AccountSetupProvisioningComplete, T0.AddMinutes(2))).NewState;
state = engine.Reduce(state, MakeSignal(3, DecisionSignalKind.DesktopArrived, T0.AddMinutes(3))).NewState;
var espExit = T0.AddMinutes(6).AddSeconds(50.2144855);
state = engine.Reduce(state, MakeSignal(4, DecisionSignalKind.EspExiting, espExit)).NewState;
var helloSafety = Assert.Single(state.Deadlines, d => d.Name == DeadlineNames.HelloSafety);
Assert.Equal(espExit.AddSeconds(300), helloSafety.DueAtUtc);
// Timer fires after wake, 2m 54s past due.
var firedAt = helloSafety.DueAtUtc.AddSeconds(174);
var finalizing = engine.Reduce(state, MakeSignal(5, DecisionSignalKind.DeadlineFired, firedAt,
FiredPayload(DeadlineNames.HelloSafety, helloSafety.DueAtUtc)));
Assert.True(finalizing.Transition.Taken);
Assert.Equal(SessionStage.Finalizing, finalizing.NewState.Stage);
Assert.Equal("Timeout", finalizing.NewState.HelloOutcome!.Value);
Assert.Equal(firedAt, finalizing.NewState.HelloResolvedUtc!.Value);
var grace = Assert.Single(finalizing.NewState.Deadlines, d => d.Name == DeadlineNames.FinalizingGrace);
Assert.Equal(firedAt.AddSeconds(5), grace.DueAtUtc);
// The chained grace fires on time and completes; nothing carries the old due time.
var completed = engine.Reduce(finalizing.NewState, MakeSignal(6, DecisionSignalKind.DeadlineFired, grace.DueAtUtc,
FiredPayload(DeadlineNames.FinalizingGrace, grace.DueAtUtc)));
Assert.Equal(SessionStage.Completed, completed.NewState.Stage);
Assert.Equal(SessionOutcome.EnrollmentComplete, completed.NewState.Outcome);
Assert.Contains(completed.Effects, e =>
e.Kind == DecisionEffectKind.EmitEventTimelineEntry
&& e.Parameters != null
&& e.Parameters.TryGetValue("eventType", out var et) && et == "enrollment_complete");
}
// ============================================================== SelfDeploying guard C
[Fact]
public void SelfDeploying_guard_C_matches_the_incarnation_by_payload_due_time_not_by_firing_clock()
{
var engine = new DecisionEngine();
var state = DecisionState.CreateInitial("sd-late", "t", T0);
state = engine.Reduce(state, MakeSignal(0, DecisionSignalKind.SessionStarted, T0)).NewState;
state = engine.Reduce(state, MakeSignal(1, DecisionSignalKind.EspPhaseChanged, T0.AddMinutes(1),
new Dictionary<string, string> { [SignalPayloadKeys.EspPhase] = "DeviceSetup" })).NewState;
state = engine.Reduce(state, MakeSignal(2, DecisionSignalKind.DeviceSetupProvisioningComplete, T0.AddMinutes(3))).NewState;
var armed = Assert.Single(state.Deadlines, d => d.Name == DeadlineNames.DeviceOnlyEspDetection);
Assert.Equal(T0.AddMinutes(8), armed.DueAtUtc);
// A stale fire of an OLDER incarnation (due T+5) arriving late: dead-end, deadline kept.
var stale = engine.Reduce(state, MakeSignal(3, DecisionSignalKind.DeadlineFired, T0.AddMinutes(12),
FiredPayload(DeadlineNames.DeviceOnlyEspDetection, T0.AddMinutes(5))));
Assert.False(stale.Transition.Taken);
Assert.Equal("device_only_esp_detection_stale_due_at_mismatch", stale.Transition.DeadEndReason);
Assert.Single(stale.NewState.Deadlines, d => d.Name == DeadlineNames.DeviceOnlyEspDetection);
// The real fire, 4 min late (standby), carries the armed due time: terminal.
var real = engine.Reduce(stale.NewState, MakeSignal(4, DecisionSignalKind.DeadlineFired, T0.AddMinutes(12),
FiredPayload(DeadlineNames.DeviceOnlyEspDetection, armed.DueAtUtc)));
Assert.True(real.Transition.Taken);
Assert.Equal(SessionStage.Completed, real.NewState.Stage);
}
// ============================================================== RealmJoin re-arm guard
[Fact]
public void RealmJoin_rearm_guard_compares_the_payload_due_time_not_the_firing_clock()
{
var engine = new DecisionEngine();
var state = DecisionState.CreateInitial("rj-late", "t", T0);
state = engine.Reduce(state, MakeSignal(0, DecisionSignalKind.SessionStarted, T0)).NewState;
state = engine.Reduce(state, MakeSignal(1, DecisionSignalKind.EspPhaseChanged, T0.AddMinutes(1),
new Dictionary<string, string> { [SignalPayloadKeys.EspPhase] = "DeviceSetup" })).NewState;
state = engine.Reduce(state, MakeSignal(2, DecisionSignalKind.EspPhaseChanged, T0.AddMinutes(2),
new Dictionary<string, string> { [SignalPayloadKeys.EspPhase] = "AccountSetup" })).NewState;
state = engine.Reduce(state, MakeSignal(3, DecisionSignalKind.EspExiting, T0.AddMinutes(3))).NewState;
state = engine.Reduce(state, MakeSignal(4, DecisionSignalKind.HelloResolved, T0.AddMinutes(4),
new Dictionary<string, string> { [SignalPayloadKeys.HelloOutcome] = "Success" })).NewState;
state = engine.Reduce(state, MakeSignal(5, DecisionSignalKind.RealmJoinDetected, T0.AddMinutes(5),
new Dictionary<string, string> { [DecisionEngine.RealmJoinPayloadKeys.DeploymentPhase] = "100" })).NewState;
state = engine.Reduce(state, MakeSignal(6, DecisionSignalKind.DesktopArrived, T0.AddMinutes(6))).NewState;
var first = Assert.Single(state.Deadlines, d => d.Name == DeadlineNames.RealmJoinTimeout);
// Simulate the activity-based re-arm: the armed incarnation is now due later.
var rearmedDue = first.DueAtUtc.AddMinutes(25);
var rearmed = state.ToBuilder()
.CancelDeadline(DeadlineNames.RealmJoinTimeout)
.AddDeadline(new ActiveDeadline(
name: DeadlineNames.RealmJoinTimeout,
dueAtUtc: rearmedDue,
firesSignalKind: DecisionSignalKind.DeadlineFired,
firesPayload: new Dictionary<string, string> { [SignalPayloadKeys.Deadline] = DeadlineNames.RealmJoinTimeout }))
.Build();
// The OLD incarnation's fire arrives late — after the re-armed due time on the clock.
// Only the payload due time identifies it as superseded.
var firedAt = rearmedDue.AddMinutes(1);
var stale = engine.Reduce(rearmed, MakeSignal(7, DecisionSignalKind.DeadlineFired, firedAt,
FiredPayload(DeadlineNames.RealmJoinTimeout, first.DueAtUtc)));
Assert.False(stale.Transition.Taken);
Assert.Equal("realmjoin_timeout_stale_superseded_by_rearm", stale.Transition.DeadEndReason);
Assert.Null(stale.NewState.RealmJoinFacts.Outcome);
// The re-armed incarnation's own fire, same firing clock: timeout is applied.
var real = engine.Reduce(stale.NewState, MakeSignal(8, DecisionSignalKind.DeadlineFired, firedAt,
FiredPayload(DeadlineNames.RealmJoinTimeout, rearmedDue)));
Assert.True(real.Transition.Taken);
Assert.Equal("Timeout", real.NewState.RealmJoinFacts.Outcome!.Value);
Assert.Equal(SessionStage.Finalizing, real.NewState.Stage);
}
}
}
@@ -706,7 +706,7 @@ namespace AutopilotMonitor.DecisionCore.Tests
var deadline = Assert.Single(signalStep.NewState.Deadlines, d => d.Name == DeadlineNames.DeviceOnlyEspDetection);
Assert.Equal(T0.AddMinutes(7), deadline.DueAtUtc);
// DeadlineFired (OccurredAtUtc = DueAtUtc per scheduler contract) → terminal.
// DeadlineFired at the due time (no payload due key → helper falls back to the signal time) → terminal.
var step = engine.Reduce(signalStep.NewState, MakeSignal(3, DecisionSignalKind.DeadlineFired, T0.AddMinutes(7),
new Dictionary<string, string> { [SignalPayloadKeys.Deadline] = DeadlineNames.DeviceOnlyEspDetection }));
@@ -443,8 +443,9 @@ namespace AutopilotMonitor.DecisionCore.Tests
{
// Cancel-then-rearm race: old deadline (DueAt=T+8) fires queued; before processing,
// DeviceSetupProvisioningComplete arrives (signal at T+10) → cancel+rearm to DueAt=T+15.
// The queued OLD fire (OccurredAtUtc=T+8) arrives. Guard C must dead-end WITHOUT
// cancelling the new deadline.
// The queued OLD fire arrives carrying its due time T+8 (no payload key here, so the
// helper falls back to the signal time). Guard C must dead-end WITHOUT cancelling the
// new deadline.
var engine = new DecisionEngine();
var state = PrimeDeviceSetup(engine, DecisionState.CreateInitial("sd-11", "t", T0));
@@ -467,7 +468,7 @@ namespace AutopilotMonitor.DecisionCore.Tests
firesPayload: new Dictionary<string, string> { [SignalPayloadKeys.Deadline] = DeadlineNames.DeviceOnlyEspDetection }));
state = rearmedBuilder.Build();
// OLD queued fire arrives with OccurredAtUtc=T+8 — mismatches new deadline at T+15.
// OLD queued fire arrives with due time T+8 — mismatches the new deadline at T+15.
var step = engine.Reduce(state, MakeSignal(99, DecisionSignalKind.DeadlineFired, T0.AddMinutes(8),
new Dictionary<string, string> { [SignalPayloadKeys.Deadline] = DeadlineNames.DeviceOnlyEspDetection }));
@@ -54,6 +54,37 @@ namespace AutopilotMonitor.DecisionCore.Tests
Assert.Equal("AccountSetup", roundtripped.Payload!["phase"]);
}
[Fact]
public void SignalSerializer_roundtrip_keeps_date_like_payload_strings_verbatim()
{
// The shared reader tokenizes ISO-8601 strings as dates; the string dictionaries must
// still come back as the round-trip text the writer produced, never culture-formatted
// (the DeadlineFired due time is parsed back with the "o" format on replay).
var due = new DateTime(2026, 4, 20, 9, 55, 0, DateTimeKind.Utc);
var original = new DecisionSignal(
sessionSignalOrdinal: 7,
sessionTraceOrdinal: 7,
kind: DecisionSignalKind.DeadlineFired,
kindSchemaVersion: 1,
occurredAtUtc: due.AddMinutes(5),
sourceOrigin: "DeadlineScheduler",
evidence: new Evidence(
kind: EvidenceKind.Synthetic,
identifier: "hello_safety",
summary: "deadline fired",
derivationInputs: new Dictionary<string, string> { ["armedAt"] = "2026-04-20T09:50:00.0000000Z" }),
payload: new Dictionary<string, string>
{
["deadline"] = "hello_safety",
["deadlineDueAtUtc"] = due.ToString("O"),
});
var roundtripped = SignalSerializer.Deserialize(SignalSerializer.Serialize(original));
Assert.Equal("2026-04-20T09:55:00.0000000Z", roundtripped.Payload!["deadlineDueAtUtc"]);
Assert.Equal("2026-04-20T09:50:00.0000000Z", roundtripped.Evidence.DerivationInputs!["armedAt"]);
}
[Fact]
public void SignalSerializer_Deserialize_MissingEvidence_throws()
{
@@ -0,0 +1,206 @@
using System.Net;
using System.Security.Claims;
using System.Text;
using AutopilotMonitor.Functions.Functions.Rules;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.DataAccess;
using AutopilotMonitor.Shared.Models;
using Azure.Core.Serialization;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Newtonsoft.Json;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// Analyze twin of <see cref="GatherRulesFunctionAuthorEndpointTests"/>: the rule Author is
/// stamped from the caller's JWT on create, on a PUT-upsert of an unknown rule and on the
/// template copy, and a true update keeps the original creator over editor and body.
/// Before this pin, custom analyze rules were created as "Autopilot Monitor" and the edit
/// path let the browser choose the author.
/// </summary>
public class AnalyzeRulesFunctionAuthorEndpointTests
{
private const string TenantId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
private const string RuleId = "ANALYZE-CUSTOM-777";
private const string TemplateRuleId = "ANALYZE-SEC-004";
private sealed class FakeHttpResponseData : HttpResponseData
{
public FakeHttpResponseData(FunctionContext context) : base(context) { }
public override HttpStatusCode StatusCode { get; set; } = HttpStatusCode.OK;
public override HttpHeadersCollection Headers { get; set; } = new();
public override Stream Body { get; set; } = new MemoryStream();
public override HttpCookies Cookies { get; } = new Mock<HttpCookies>().Object;
}
private static FunctionContext BuildContext(ClaimsPrincipal? principal)
{
var services = new ServiceCollection();
services.AddOptions();
services.Configure<WorkerOptions>(o => o.Serializer =
new JsonObjectSerializer(ApiJsonOptions.Create()));
var provider = services.BuildServiceProvider();
var items = new Dictionary<object, object>();
if (principal != null)
{
items["ClaimsPrincipal"] = principal;
}
var context = new Mock<FunctionContext>();
context.SetupGet(c => c.Items).Returns(items);
context.SetupGet(c => c.InstanceServices).Returns(provider);
return context.Object;
}
private static HttpRequestData BuildRequest(ClaimsPrincipal? principal, object body)
{
var context = BuildContext(principal);
var req = new Mock<HttpRequestData>(context);
req.SetupGet(r => r.Headers).Returns(new HttpHeadersCollection());
req.SetupGet(r => r.Body).Returns(
new MemoryStream(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(body))));
req.Setup(r => r.CreateResponse()).Returns(() => new FakeHttpResponseData(context));
return req.Object;
}
private static ClaimsPrincipal Principal(params (string Type, string Value)[] claims)
=> new(new ClaimsIdentity(claims.Select(c => new Claim(c.Type, c.Value)), "TestAuth"));
private static ClaimsPrincipal AlicePrincipal()
=> Principal(("tid", TenantId), ("name", "Alice Admin"), ("upn", "alice@contoso.com"));
private static (AnalyzeRulesFunction function, List<AnalyzeRule> stored) BuildFunction(
AnalyzeRule? existingTenantRule = null, AnalyzeRule? globalRule = null)
{
var repo = new Mock<IRuleRepository>(MockBehavior.Loose);
var stored = new List<AnalyzeRule>();
repo.Setup(r => r.AnalyzeRuleExistsAsync(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(false);
repo.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(
globalRule == null ? new List<AnalyzeRule>() : new List<AnalyzeRule> { globalRule });
repo.Setup(r => r.GetAnalyzeRulesAsync(TenantId)).ReturnsAsync(
existingTenantRule == null ? new List<AnalyzeRule>() : new List<AnalyzeRule> { existingTenantRule });
repo.Setup(r => r.GetRuleStatesAsync(TenantId)).ReturnsAsync(new Dictionary<string, RuleState>());
repo.Setup(r => r.StoreRuleStateAsync(TenantId, It.IsAny<string>(), It.IsAny<RuleState>())).ReturnsAsync(true);
repo.Setup(r => r.StoreAnalyzeRuleAsync(It.IsAny<AnalyzeRule>(), TenantId))
.Callback<AnalyzeRule, string>((rule, _) => stored.Add(rule))
.ReturnsAsync(true);
var service = new AnalyzeRuleService(repo.Object, NullLogger<AnalyzeRuleService>.Instance);
return (new AnalyzeRulesFunction(NullLogger<AnalyzeRulesFunction>.Instance, service), stored);
}
private static AnalyzeRule SpoofedPayload() => new()
{
RuleId = RuleId,
Title = "Proxy PAC unreachable",
Description = "Custom",
Severity = "warning",
Category = "network",
Explanation = "The PAC file could not be fetched.",
IsBuiltIn = false,
IsCommunity = false,
Enabled = true,
Author = "Spoofed Author",
Conditions = new List<RuleCondition>
{
new() { Signal = "pac_failed", Source = "event_type", EventType = "network_pac_failed", Required = true }
},
};
[Fact]
public async Task CreateRule_stamps_author_from_jwt_not_from_body()
{
var (function, stored) = BuildFunction();
var req = BuildRequest(AlicePrincipal(), SpoofedPayload());
var response = await function.CreateRule(req);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var written = Assert.Single(stored);
Assert.Equal("Alice Admin", written.Author);
}
[Fact]
public async Task CreateRule_falls_back_to_product_name_without_identifying_claims()
{
var (function, stored) = BuildFunction();
var req = BuildRequest(Principal(("tid", TenantId)), SpoofedPayload());
var response = await function.CreateRule(req);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var written = Assert.Single(stored);
Assert.Equal("Autopilot Monitor", written.Author);
}
[Fact]
public async Task UpdateRule_upsert_of_unknown_rule_stamps_author_from_jwt()
{
var (function, stored) = BuildFunction(existingTenantRule: null);
var req = BuildRequest(AlicePrincipal(), SpoofedPayload());
var response = await function.UpdateRule(req, RuleId);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var written = Assert.Single(stored);
Assert.Equal("Alice Admin", written.Author);
}
[Fact]
public async Task UpdateRule_true_update_keeps_original_author_over_editor_and_body()
{
var existing = SpoofedPayload();
existing.Author = "Original Creator";
existing.CreatedAt = new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc);
var (function, stored) = BuildFunction(existing);
var req = BuildRequest(
Principal(("tid", TenantId), ("name", "Bob Editor")), SpoofedPayload());
var response = await function.UpdateRule(req, RuleId);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var written = Assert.Single(stored);
Assert.Equal("Original Creator", written.Author);
Assert.Equal(existing.CreatedAt, written.CreatedAt);
}
[Fact]
public async Task CreateFromTemplate_stamps_the_copying_admin_not_the_template_author()
{
var template = new AnalyzeRule
{
RuleId = TemplateRuleId,
Title = "AutoLogon enabled for an unexpected user",
Description = "Template",
Severity = "warning",
Category = "security",
Explanation = "Template",
IsBuiltIn = true,
Author = "Autopilot Monitor",
Conditions = new List<RuleCondition>
{
new() { Signal = "autologon", Source = "event_type", EventType = "autologon_analysis", Operator = "equals", Value = "PLACEHOLDER", Required = true }
},
TemplateVariables = new List<TemplateVariable>
{
new() { Name = "allowed", Label = "Allowed", ConditionIndex = 0, Field = "value" }
},
};
var (function, stored) = BuildFunction(globalRule: template);
var req = BuildRequest(AlicePrincipal(), new { variables = new Dictionary<string, string> { ["allowed"] = "KIOSK-1" } });
var response = await function.CreateFromTemplate(req, TemplateRuleId);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var written = Assert.Single(stored);
Assert.Equal("Alice Admin", written.Author);
Assert.Equal(TemplateRuleId, written.DerivedFromTemplateRuleId);
}
}
@@ -0,0 +1,63 @@
using Azure.Data.Tables;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.Models;
using Xunit;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// Observation-end closure of app rows: a row still InProgress when the session's observation
/// ended becomes "Incomplete" (terminal, non-failure, outcome unknown). Pins the pure per-row
/// predicate behind <see cref="TableStorageService.CloseOpenAppInstallsForSessionAsync"/> and
/// the disclosed bucket in the app-metrics payload.
/// </summary>
public class AppInstallIncompleteCloseTests
{
private static TableEntity Row(string? status, DateTimeOffset? completedAt = null)
{
var row = new TableEntity("tenant", "session_App");
if (status != null) row["Status"] = status;
if (completedAt.HasValue) row["CompletedAt"] = completedAt.Value;
return row;
}
[Theory]
[InlineData("InProgress")]
[InlineData("")]
[InlineData(null)]
public void ShouldClose_OpenRow(string? status)
=> Assert.True(TableStorageService.ShouldCloseAsIncomplete(Row(status)));
[Theory]
[InlineData("Succeeded")]
[InlineData("Failed")]
[InlineData("Incomplete")]
public void ShouldClose_LeavesTerminalRowsAlone(string status)
=> Assert.False(TableStorageService.ShouldCloseAsIncomplete(Row(status)));
[Fact]
public void ShouldClose_NeverClosesARowWithAnEnd()
{
// Out-of-order arrival can leave a CompletedAt on a row whose status batch is late —
// an end is an end.
Assert.False(TableStorageService.ShouldCloseAsIncomplete(Row("InProgress", DateTimeOffset.UtcNow)));
}
[Fact]
public void AppMetrics_DisclosesIncompleteOutsideTheRate()
{
var payload = MetricsMath.BuildAppMetricsPayload(new[]
{
new AppInstallSummary { AppName = "App", Status = "Succeeded", TerminalState = "Installed", DurationSeconds = 30 },
new AppInstallSummary { AppName = "App", Status = "Failed", TerminalState = "Error", DurationSeconds = 30 },
new AppInstallSummary { AppName = "App", Status = "Incomplete" },
});
var group = Assert.Single(payload.TopFailingApps);
Assert.Equal(3, group.TotalInstalls);
Assert.Equal(1, group.Incomplete);
Assert.Equal(50.0, group.FailureRate);
Assert.Equal(1, payload.TotalIncomplete);
}
}
@@ -155,6 +155,30 @@ public class AppInstallTerminalStateAndReconcileTests
Assert.Equal("Succeeded", summary.Status);
}
[Fact]
public void Reconcile_IncompleteIsSticky_AgainstLateProgressBatch()
{
// Closed by the observation-end step; a straggling started/progress batch must not reopen it.
var existing = new TableEntity("tenant", "session_App") { ["Status"] = "Incomplete" };
var summary = new AppInstallSummary { AppName = "App", Status = "InProgress", StartedAt = T0 };
TableStorageService.ReconcileAppInstallSummaryWithExisting(summary, existing);
Assert.Equal("Incomplete", summary.Status);
}
[Fact]
public void Reconcile_RealTerminalOverridesIncomplete()
{
// The completion arrived after the close step: real evidence beats the hedge.
var existing = new TableEntity("tenant", "session_App") { ["Status"] = "Incomplete" };
var summary = new AppInstallSummary { AppName = "App", Status = "Succeeded", StartedAt = T0 };
TableStorageService.ReconcileAppInstallSummaryWithExisting(summary, existing);
Assert.Equal("Succeeded", summary.Status);
}
[Fact]
public void Reconcile_Q4Guard_DoesNotFireWithoutStoredCompletedAt()
{
@@ -0,0 +1,530 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.DataAccess;
using AutopilotMonitor.Shared.Models;
using AutopilotMonitor.Shared.Pagination;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// The pure pieces of <see cref="RuleSubmissionService"/> (id suggestion, repo file, snapshot
/// stripping, attribution shape) and the review state machine against mocked repositories.
/// </summary>
public class RuleSubmissionServiceTests
{
private const string TenantId = "11111111-1111-1111-1111-111111111111";
// ── id suggestion ───────────────────────────────────────────────────────
[Fact]
public void Suggest_is_max_plus_one_and_never_fills_a_gap()
{
// 001 and 003 exist, 002 is a retired id — the next is 004, not 002.
var taken = new[] { "ANALYZE-NET-001", "ANALYZE-NET-003", "ANALYZE-APP-018", "GATHER-NET-009" };
Assert.Equal("ANALYZE-NET-004", RuleSubmissionService.SuggestPublishedRuleId("analyze", "network", taken));
}
[Fact]
public void Suggest_starts_at_001_for_an_empty_category_and_maps_the_kind_convention()
{
Assert.Equal("ANALYZE-NET-001", RuleSubmissionService.SuggestPublishedRuleId("analyze", "network", Array.Empty<string>()));
Assert.Equal("GATHER-DEVICE-001", RuleSubmissionService.SuggestPublishedRuleId("gather", "device", Array.Empty<string>()));
Assert.Equal("ANALYZE-DEV-001", RuleSubmissionService.SuggestPublishedRuleId("analyze", "device", Array.Empty<string>()));
Assert.Equal("ANALYZE-ENRL-001", RuleSubmissionService.SuggestPublishedRuleId("analyze", "enrollment", Array.Empty<string>()));
Assert.Equal("GATHER-ENROLL-001", RuleSubmissionService.SuggestPublishedRuleId("gather", "enrollment", Array.Empty<string>()));
}
[Fact]
public void Suggest_is_case_insensitive_over_taken_ids()
{
Assert.Equal("ANALYZE-SEC-008", RuleSubmissionService.SuggestPublishedRuleId("analyze", "security", new[] { "analyze-sec-007" }));
}
[Fact]
public void Suggest_falls_back_to_the_upper_cased_category_when_unmapped()
{
Assert.Equal("ANALYZE-OFFICE-001", RuleSubmissionService.SuggestPublishedRuleId("analyze", "office", Array.Empty<string>()));
}
// ── freeze + repo file ──────────────────────────────────────────────────
private static AnalyzeRule CustomAnalyzeRule() => new()
{
RuleId = "ANALYZE-CUSTOM-003",
Title = "Proxy PAC unreachable",
Description = "PAC download fails",
Severity = "warning",
Category = "network",
Version = "1.2.0",
Author = "Alice Admin",
Enabled = false,
IsBuiltIn = false,
IsCommunity = false,
Provenance = "embedded",
MarkSessionAsFailed = true,
Notify = true,
NotifyChannelIds = new List<string> { "chan-1" },
DerivedFromTemplateRuleId = "ANALYZE-SEC-004",
Explanation = "The PAC file could not be fetched.",
Conditions = new List<RuleCondition>
{
new() { Signal = "pac_failed", Source = "event_type", EventType = "network_pac_failed", Required = true },
},
CreatedAt = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc),
UpdatedAt = new DateTime(2026, 2, 1, 0, 0, 0, DateTimeKind.Utc),
};
[Fact]
public void Freeze_strips_server_and_tenant_fields_and_keeps_the_rule()
{
var json = RuleSubmissionService.FreezeRule(CustomAnalyzeRule());
var node = JsonNode.Parse(json)!.AsObject();
foreach (var stripped in new[] { "isBuiltIn", "provenance", "createdAt", "updatedAt", "markSessionAsFailed", "notifyDefault", "notify", "notifyChannelIds" })
Assert.False(node.ContainsKey(stripped), $"{stripped} must not be frozen");
Assert.Equal("ANALYZE-CUSTOM-003", node["ruleId"]!.GetValue<string>());
Assert.Equal("Alice Admin", node["author"]!.GetValue<string>());
Assert.Equal("ANALYZE-SEC-004", node["derivedFromTemplateRuleId"]!.GetValue<string>());
Assert.Single(node["conditions"]!.AsArray());
}
[Fact]
public void RepoFile_carries_schema_pointer_assigned_id_credit_and_community_flag_in_repo_order()
{
var s = new RuleSubmission
{
RuleKind = RuleSubmissionKinds.Analyze,
RuleJson = RuleSubmissionService.FreezeRule(CustomAnalyzeRule()),
AttributionName = RuleAttributionModes.AnonymousAuthor,
};
var file = RuleSubmissionService.BuildRepoFile(s, "ANALYZE-NET-002");
Assert.Equal("rules/analyze/ANALYZE-NET-002.json", file.Path);
Assert.EndsWith("\n", file.Content);
var node = JsonNode.Parse(file.Content)!.AsObject();
var keys = node.Select(kv => kv.Key).ToList();
Assert.Equal(new[] { "$schema", "ruleId", "title", "description", "severity", "category", "version", "author", "enabled", "isCommunity" }, keys.Take(10));
Assert.Equal("../schema/analyze-rule.schema.json", node["$schema"]!.GetValue<string>());
Assert.Equal("ANALYZE-NET-002", node["ruleId"]!.GetValue<string>());
Assert.Equal("Community contribution", node["author"]!.GetValue<string>());
Assert.True(node["isCommunity"]!.GetValue<bool>());
// Analyze rules ship enabled — the tenant's own toggle state does not travel.
Assert.True(node["enabled"]!.GetValue<bool>());
Assert.False(node.ContainsKey("derivedFromTemplateRuleId"));
Assert.False(node.ContainsKey("isBuiltIn"));
Assert.Contains("\"explanation\": \"The PAC file could not be fetched.\"", file.Content);
}
[Fact]
public void RepoFile_for_a_gather_rule_ships_disabled_and_without_severity()
{
var gather = new GatherRule
{
RuleId = "GATHER-CUSTOM-001",
Title = "BIOS config",
Description = "Reads the BIOS registry block",
Category = "device",
Enabled = true,
IsBuiltIn = false,
CollectorType = "registry",
Target = "HKLM\\SOFTWARE\\Vendor\\BIOS",
Trigger = "startup",
OutputEventType = "gather_bios_config",
};
var s = new RuleSubmission
{
RuleKind = RuleSubmissionKinds.Gather,
RuleJson = RuleSubmissionService.FreezeRule(gather),
AttributionName = "Contoso IT",
};
var file = RuleSubmissionService.BuildRepoFile(s, "GATHER-DEVICE-009");
Assert.Equal("rules/gather/GATHER-DEVICE-009.json", file.Path);
var node = JsonNode.Parse(file.Content)!.AsObject();
Assert.Equal("../schema/gather-rule.schema.json", node["$schema"]!.GetValue<string>());
Assert.False(node["enabled"]!.GetValue<bool>());
Assert.Equal("Contoso IT", node["author"]!.GetValue<string>());
Assert.False(node.ContainsKey("severity"));
// No \u escaping of the backslash-heavy registry path beyond JSON's own rules.
Assert.Contains("HKLM\\\\SOFTWARE\\\\Vendor\\\\BIOS", file.Content);
}
// ── attribution ─────────────────────────────────────────────────────────
[Theory]
[InlineData("Alice A.")]
[InlineData("Contoso IT & Ops (EMEA)")]
[InlineData("Zoë Müller-Lüdenscheidt")]
public void AttributionName_accepts_names(string name)
=> Assert.Equal(name, RuleSubmissionService.ValidateAttributionName(name));
[Theory]
[InlineData("")]
[InlineData("<script>")]
[InlineData("https://example.com")]
[InlineData("line\nbreak")]
public void AttributionName_rejects_markup_urls_and_control_characters(string name)
=> Assert.Throws<ArgumentException>(() => RuleSubmissionService.ValidateAttributionName(name));
[Theory]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData(" alice@contoso.com ", "alice@contoso.com")]
public void Email_is_trimmed_or_null(string? input, string? expected)
=> Assert.Equal(expected, RuleSubmissionService.NormalizeEmail(input));
[Theory]
[InlineData("alice")]
[InlineData("@contoso.com")]
[InlineData("alice@")]
[InlineData("a@b@c")]
[InlineData("alice @contoso.com")]
public void Email_rejects_non_addresses(string input)
=> Assert.Throws<ArgumentException>(() => RuleSubmissionService.NormalizeEmail(input));
// ── review state machine ────────────────────────────────────────────────
private static (RuleSubmissionService service, Mock<IRuleSubmissionRepository> repo) Build(
RuleSubmission row, IEnumerable<string>? globalAnalyzeIds = null, IEnumerable<string>? reservedIds = null)
{
var repo = new Mock<IRuleSubmissionRepository>(MockBehavior.Loose);
repo.Setup(r => r.GetAsync(row.SubmissionId)).ReturnsAsync(row);
repo.Setup(r => r.UpdateAsync(It.IsAny<RuleSubmission>())).ReturnsAsync(true);
repo.Setup(r => r.GetReservedPublishedRuleIdsAsync())
.ReturnsAsync(new HashSet<string>(reservedIds ?? Array.Empty<string>(), StringComparer.OrdinalIgnoreCase));
var rules = new Mock<IRuleRepository>(MockBehavior.Loose);
rules.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(
(globalAnalyzeIds ?? Array.Empty<string>()).Select(id => new AnalyzeRule { RuleId = id, IsBuiltIn = true }).ToList());
rules.Setup(r => r.GetGatherRulesAsync("global")).ReturnsAsync(new List<GatherRule>());
var metrics = new Mock<IMetricsRepository>(MockBehavior.Loose);
var config = new Mock<TenantConfigurationService>(MockBehavior.Loose,
Mock.Of<IConfigRepository>(), NullLogger<TenantConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
var service = new RuleSubmissionService(repo.Object, rules.Object, metrics.Object, config.Object,
NullLogger<RuleSubmissionService>.Instance);
return (service, repo);
}
private static RuleSubmission PendingRow() => new()
{
SubmissionId = "a1b2c3d4e5f6",
BatchId = "b",
TenantId = TenantId,
RuleKind = RuleSubmissionKinds.Analyze,
SourceRuleId = "ANALYZE-CUSTOM-003",
Title = "Proxy PAC unreachable",
Category = "network",
RuleJson = RuleSubmissionService.FreezeRule(CustomAnalyzeRule()),
SubmittedBy = "alice@contoso.com",
SubmittedByName = "Alice Admin",
SubmittedAt = DateTime.UtcNow,
Status = RuleSubmissionStatuses.Pending,
};
[Fact]
public async Task Approve_requires_a_reserved_id_of_the_same_kind()
{
var (service, _) = Build(PendingRow());
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
new ReviewRuleSubmissionRequest { Decision = "approve" }, "ga@example.com"));
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-CUSTOM-009" }, "ga@example.com"));
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "GATHER-NET-002" }, "ga@example.com"));
}
[Fact]
public async Task Approve_refuses_an_id_taken_by_the_catalog_or_another_approval()
{
var (service, _) = Build(PendingRow(), globalAnalyzeIds: new[] { "ANALYZE-NET-001" }, reservedIds: new[] { "ANALYZE-NET-002" });
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ReviewAsync("a1b2c3d4e5f6",
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-NET-001" }, "ga@example.com"));
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ReviewAsync("a1b2c3d4e5f6",
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-NET-002" }, "ga@example.com"));
}
[Fact]
public async Task Approve_stores_id_comment_adaptation_flag_and_reviewer()
{
var (service, repo) = Build(PendingRow());
RuleSubmission? written = null;
repo.Setup(r => r.UpdateAsync(It.IsAny<RuleSubmission>())).Callback<RuleSubmission>(s => written = s).ReturnsAsync(true);
var result = await service.ReviewAsync("a1b2c3d4e5f6",
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-NET-003", ReviewComment = "Taken, will generalise the title.", WillBeAdapted = true },
"ga@example.com");
Assert.Same(result, written);
Assert.Equal(RuleSubmissionStatuses.Approved, result.Status);
Assert.Equal("ANALYZE-NET-003", result.PublishedRuleId);
Assert.True(result.WillBeAdapted);
Assert.Equal("Taken, will generalise the title.", result.ReviewComment);
Assert.Equal("ga@example.com", result.ReviewedBy);
Assert.NotNull(result.ReviewedAt);
}
[Fact]
public async Task Decline_requires_a_comment_and_clears_the_published_id()
{
var row = PendingRow();
row.Status = RuleSubmissionStatuses.Approved;
row.PublishedRuleId = "ANALYZE-NET-003";
var (service, _) = Build(row);
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
new ReviewRuleSubmissionRequest { Decision = "decline" }, "ga@example.com"));
var result = await service.ReviewAsync("a1b2c3d4e5f6",
new ReviewRuleSubmissionRequest { Decision = "decline", ReviewComment = "Too tenant-specific." }, "ga@example.com");
Assert.Equal(RuleSubmissionStatuses.Declined, result.Status);
Assert.Null(result.PublishedRuleId);
Assert.False(result.WillBeAdapted);
}
[Fact]
public async Task Published_is_derived_and_final()
{
var row = PendingRow();
row.Status = RuleSubmissionStatuses.Approved;
row.PublishedRuleId = "ANALYZE-NET-003";
var (service, _) = Build(row, globalAnalyzeIds: new[] { "ANALYZE-NET-003" });
var items = await service.ToItemsAsync(new[] { row });
Assert.Equal(RuleSubmissionStatuses.Published, items[0].Status);
Assert.Equal(RuleSubmissionStatuses.Approved, row.Status);
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ReviewAsync("a1b2c3d4e5f6",
new ReviewRuleSubmissionRequest { Decision = "decline", ReviewComment = "too late" }, "ga@example.com"));
}
[Fact]
public async Task Approved_but_unpublished_stays_approved_on_the_wire()
{
var row = PendingRow();
row.Status = RuleSubmissionStatuses.Approved;
row.PublishedRuleId = "ANALYZE-NET-003";
var (service, _) = Build(row, globalAnalyzeIds: new[] { "ANALYZE-NET-001" });
var items = await service.ToItemsAsync(new[] { row });
Assert.Equal(RuleSubmissionStatuses.Approved, items[0].Status);
}
[Fact]
public async Task Withdraw_only_pending_and_only_own_tenant()
{
var row = PendingRow();
var (service, _) = Build(row);
Assert.False(await service.WithdrawAsync("22222222-2222-2222-2222-222222222222", "a1b2c3d4e5f6", crossTenantAllowed: false));
Assert.True(await service.WithdrawAsync(TenantId, "a1b2c3d4e5f6", crossTenantAllowed: false));
Assert.Equal(RuleSubmissionStatuses.Withdrawn, row.Status);
await Assert.ThrowsAsync<InvalidOperationException>(() => service.WithdrawAsync(TenantId, "a1b2c3d4e5f6", crossTenantAllowed: false));
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ReviewAsync("a1b2c3d4e5f6",
new ReviewRuleSubmissionRequest { Decision = "approve", PublishedRuleId = "ANALYZE-NET-003" }, "ga@example.com"));
}
[Fact]
public async Task Operator_delete_passes_through_to_the_repository()
{
var (service, repo) = Build(PendingRow());
repo.Setup(r => r.DeleteAsync("a1b2c3d4e5f6")).ReturnsAsync(true);
Assert.True(await service.DeleteAsync("a1b2c3d4e5f6"));
repo.Verify(r => r.DeleteAsync("a1b2c3d4e5f6"), Times.Once);
}
[Fact]
public async Task Unknown_decision_is_a_bad_request()
{
var (service, _) = Build(PendingRow());
await Assert.ThrowsAsync<ArgumentException>(() => service.ReviewAsync("a1b2c3d4e5f6",
new ReviewRuleSubmissionRequest { Decision = "maybe" }, "ga@example.com"));
}
[Fact]
public async Task Detail_returns_the_typed_rule_suggested_id_and_repo_file()
{
var (service, _) = Build(PendingRow(), globalAnalyzeIds: new[] { "ANALYZE-NET-001" });
var detail = await service.GetDetailAsync("a1b2c3d4e5f6");
Assert.NotNull(detail);
Assert.NotNull(detail!.AnalyzeRule);
Assert.Null(detail.GatherRule);
Assert.Equal("ANALYZE-CUSTOM-003", detail.AnalyzeRule!.RuleId);
Assert.False(detail.AnalyzeRule.IsBuiltIn);
Assert.Equal("ANALYZE-NET-002", detail.SuggestedPublishedRuleId);
Assert.Equal("rules/analyze/ANALYZE-NET-002.json", detail.RepoFile!.Path);
}
// ── submit ──────────────────────────────────────────────────────────────
private static (RuleSubmissionService service, List<RuleSubmission> stored) BuildForSubmit(
List<AnalyzeRule> tenantAnalyze, List<RuleSubmission>? existing = null, TenantConfiguration? config = null)
{
var stored = new List<RuleSubmission>();
var repo = new Mock<IRuleSubmissionRepository>(MockBehavior.Loose);
repo.Setup(r => r.GetForTenantAsync(TenantId)).ReturnsAsync(existing ?? new List<RuleSubmission>());
repo.Setup(r => r.AddAsync(It.IsAny<RuleSubmission>())).Callback<RuleSubmission>(stored.Add).ReturnsAsync(true);
repo.Setup(r => r.GetReservedPublishedRuleIdsAsync()).ReturnsAsync(new HashSet<string>());
var rules = new Mock<IRuleRepository>(MockBehavior.Loose);
rules.Setup(r => r.GetAnalyzeRulesAsync(TenantId)).ReturnsAsync(tenantAnalyze);
rules.Setup(r => r.GetGatherRulesAsync(TenantId)).ReturnsAsync(new List<GatherRule>());
rules.Setup(r => r.GetAnalyzeRulesAsync("global")).ReturnsAsync(new List<AnalyzeRule>());
rules.Setup(r => r.GetGatherRulesAsync("global")).ReturnsAsync(new List<GatherRule>());
var metrics = new Mock<IMetricsRepository>(MockBehavior.Loose);
metrics.Setup(m => m.GetRuleStatsAsync(TenantId, It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<string?>(), It.IsAny<int>()))
.ReturnsAsync(new List<RuleStatsEntry>
{
new() { RuleId = "ANALYZE-CUSTOM-003", FireCount = 4, SessionsEvaluated = 40, EvaluationCount = 41 },
new() { RuleId = "ANALYZE-CUSTOM-003", FireCount = 1, SessionsEvaluated = 10, EvaluationCount = 10 },
new() { RuleId = "ANALYZE-CUSTOM-999", FireCount = 99, SessionsEvaluated = 99, EvaluationCount = 99 },
});
var configRepo = new Mock<IConfigRepository>(MockBehavior.Loose);
var configService = new Mock<TenantConfigurationService>(MockBehavior.Loose, configRepo.Object,
NullLogger<TenantConfigurationService>.Instance, new MemoryCache(new MemoryCacheOptions()));
configService.Setup(c => c.GetConfigurationIfExistsAsync(TenantId)).ReturnsAsync(config);
var service = new RuleSubmissionService(repo.Object, rules.Object, metrics.Object, configService.Object,
NullLogger<RuleSubmissionService>.Instance);
return (service, stored);
}
private static SubmitRuleSubmissionsRequest Request(params string[] ruleIds) => new()
{
TenantId = TenantId,
Items = ruleIds.Select(id => new RuleSubmissionItemRef { Kind = "analyze", RuleId = id }).ToList(),
Comment = "Fires when the PAC download fails during ESP.",
AttributionMode = RuleAttributionModes.Anonymous,
};
[Fact]
public async Task Submit_freezes_the_tenant_rule_records_findings_and_fire_stats()
{
var (service, stored) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() });
var created = await service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003"), "alice@contoso.com", "Alice Admin");
var s = Assert.Single(created);
Assert.Same(s, Assert.Single(stored));
Assert.Equal(12, s.SubmissionId.Length);
Assert.Equal(12, s.BatchId.Length);
Assert.Equal(RuleSubmissionStatuses.Pending, s.Status);
Assert.Equal("Community contribution", s.AttributionName);
Assert.Null(s.ContactEmail);
Assert.Equal("Proxy PAC unreachable", s.Title);
Assert.Equal("network", s.Category);
Assert.Equal("ANALYZE-SEC-004", s.DerivedFromTemplateRuleId);
Assert.Contains(s.ValidationFindings, f => f.Level == "info" && f.Message.Contains("ANALYZE-SEC-004"));
Assert.DoesNotContain(s.ValidationFindings, f => f.Level == "error");
Assert.Equal(5, s.SourceFireStats!.FireCount);
Assert.Equal(50, s.SourceFireStats.SessionsEvaluated);
Assert.DoesNotContain("isBuiltIn", s.RuleJson);
}
[Fact]
public async Task Submit_rejects_built_in_and_unknown_rules_without_storing_anything()
{
var builtIn = CustomAnalyzeRule();
builtIn.RuleId = "ANALYZE-NET-001";
builtIn.IsBuiltIn = true;
var (service, stored) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule(), builtIn });
var ex = await Assert.ThrowsAsync<ArgumentException>(() =>
service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003", "ANALYZE-NET-001", "ANALYZE-CUSTOM-404"), "alice@contoso.com", "Alice Admin"));
Assert.Contains("ANALYZE-NET-001", ex.Message);
Assert.Contains("ANALYZE-CUSTOM-404", ex.Message);
Assert.Empty(stored);
}
[Fact]
public async Task Submit_rejects_a_rule_whose_draft_validation_fails()
{
var broken = CustomAnalyzeRule();
broken.Conditions = new List<RuleCondition>();
var (service, stored) = BuildForSubmit(new List<AnalyzeRule> { broken });
var ex = await Assert.ThrowsAsync<ArgumentException>(() =>
service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003"), "alice@contoso.com", "Alice Admin"));
Assert.Contains("at least one condition", ex.Message);
Assert.Empty(stored);
}
[Fact]
public async Task Submit_refuses_a_second_pending_submission_of_the_same_rule()
{
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() }, existing: new List<RuleSubmission> { PendingRow() });
await Assert.ThrowsAsync<InvalidOperationException>(() =>
service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003"), "alice@contoso.com", "Alice Admin"));
}
[Fact]
public async Task Submit_enforces_the_daily_cap()
{
var existing = Enumerable.Range(0, RuleSubmissionService.MaxSubmissionsPerTenantPerDay)
.Select(i => { var r = PendingRow(); r.SourceRuleId = $"OTHER-{i}"; r.Status = RuleSubmissionStatuses.Declined; return r; })
.ToList();
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() }, existing);
await Assert.ThrowsAsync<InvalidOperationException>(() =>
service.SubmitAsync(TenantId, Request("ANALYZE-CUSTOM-003"), "alice@contoso.com", "Alice Admin"));
}
[Fact]
public async Task Submit_organization_attribution_uses_the_company_name_and_fails_without_one()
{
var withName = new TenantConfiguration { TenantId = TenantId, DomainName = "contoso.example", CompanyName = "Contoso Ltd." };
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() }, config: withName);
var request = Request("ANALYZE-CUSTOM-003");
request.AttributionMode = RuleAttributionModes.Organization;
var created = await service.SubmitAsync(TenantId, request, "alice@contoso.com", "Alice Admin");
Assert.Equal("Contoso Ltd.", created[0].AttributionName);
var (noConfig, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() }, config: null);
await Assert.ThrowsAsync<ArgumentException>(() => noConfig.SubmitAsync(TenantId, request, "alice@contoso.com", "Alice Admin"));
}
[Fact]
public async Task Submit_stores_the_contact_email_when_given()
{
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() });
var request = Request("ANALYZE-CUSTOM-003");
request.Email = " alice.reply@contoso.com ";
var created = await service.SubmitAsync(TenantId, request, "alice@contoso.com", "Alice Admin");
Assert.Equal("alice.reply@contoso.com", created[0].ContactEmail);
}
[Fact]
public async Task Submit_person_attribution_freezes_the_requested_name()
{
var (service, _) = BuildForSubmit(new List<AnalyzeRule> { CustomAnalyzeRule() });
var request = Request("ANALYZE-CUSTOM-003");
request.AttributionMode = RuleAttributionModes.Person;
request.AttributionName = " Alice A. ";
var created = await service.SubmitAsync(TenantId, request, "alice@contoso.com", "Alice Admin");
Assert.Equal("Alice A.", created[0].AttributionName);
Assert.Equal(RuleAttributionModes.Person, created[0].AttributionMode);
}
}
@@ -0,0 +1,136 @@
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// Wire pins for the rule-submission responses (typed from the start — the anonymous side is
/// the literal a client sees, so a reordered or renamed property fails here first).
/// </summary>
public class RuleSubmissionsWireParityTests
{
private static readonly DateTime T0 = new(2026, 9, 9, 10, 30, 0, DateTimeKind.Utc);
private static RuleSubmissionItem Item() => new()
{
SubmissionId = "a1b2c3d4e5f6",
BatchId = "0f0e0d0c0b0a",
TenantId = "11111111-1111-1111-1111-111111111111",
RuleKind = "analyze",
SourceRuleId = "ANALYZE-CUSTOM-003",
Title = "Proxy PAC unreachable",
Category = "network",
Comment = "Fires when the PAC download fails.",
SubmittedBy = "alice@contoso.com",
SubmittedByName = "Alice Admin",
ContactEmail = "alice.reply@contoso.com",
AttributionMode = "anonymous",
AttributionName = "Community contribution",
SubmittedAt = T0,
Status = "approved",
ValidationFindings = new List<RuleSubmissionFinding> { new() { Level = "info", Message = "Derived from template ANALYZE-SEC-004" } },
SourceFireStats = new RuleSubmissionFireStats { Days = 30, FireCount = 42, SessionsEvaluated = 310, EvaluationCount = 312 },
ReviewedBy = "ga@example.com",
ReviewedAt = T0.AddDays(1),
ReviewComment = "Taken.",
WillBeAdapted = true,
PublishedRuleId = "ANALYZE-NET-002",
DerivedFromTemplateRuleId = "ANALYZE-SEC-004",
};
private static object ItemLiteral() => new
{
submissionId = "a1b2c3d4e5f6",
batchId = "0f0e0d0c0b0a",
tenantId = "11111111-1111-1111-1111-111111111111",
ruleKind = "analyze",
sourceRuleId = "ANALYZE-CUSTOM-003",
title = "Proxy PAC unreachable",
category = "network",
comment = "Fires when the PAC download fails.",
submittedBy = "alice@contoso.com",
submittedByName = "Alice Admin",
contactEmail = "alice.reply@contoso.com",
attributionMode = "anonymous",
attributionName = "Community contribution",
submittedAt = T0,
status = "approved",
validationFindings = new List<object> { new { level = "info", message = "Derived from template ANALYZE-SEC-004" } },
sourceFireStats = new { days = 30, fireCount = 42, sessionsEvaluated = 310, evaluationCount = 312 },
reviewedBy = "ga@example.com",
reviewedAt = T0.AddDays(1),
reviewComment = "Taken.",
willBeAdapted = true,
publishedRuleId = "ANALYZE-NET-002",
derivedFromTemplateRuleId = "ANALYZE-SEC-004",
};
[Fact]
public void Submit_response_shape()
{
ApiResponseWireParityTests.AssertWireIdentical(
new { success = true, message = "Rule submitted for review.", batchId = "0f0e0d0c0b0a", submissions = new List<object> { ItemLiteral() } },
new SubmitRuleSubmissionsResponse { Success = true, Message = "Rule submitted for review.", BatchId = "0f0e0d0c0b0a", Submissions = new List<RuleSubmissionItem> { Item() } });
}
[Fact]
public void List_nonPaged_has_no_nextLink_key()
{
ApiResponseWireParityTests.AssertWireIdentical(
new { success = true, count = 1, submissions = new List<object> { ItemLiteral() } },
new RuleSubmissionListResponse { Success = true, Count = 1, Submissions = new List<RuleSubmissionItem> { Item() } });
}
[Fact]
public void List_paged_carries_nextLink()
{
ApiResponseWireParityTests.AssertWireIdentical(
new { success = true, count = 1, submissions = new List<object> { ItemLiteral() }, nextLink = "/api/global/rule-submissions?pageSize=20&continuation=abc" },
new RuleSubmissionListResponse { Success = true, Count = 1, Submissions = new List<RuleSubmissionItem> { Item() }, NextLink = "/api/global/rule-submissions?pageSize=20&continuation=abc" });
}
[Fact]
public void List_last_page_drops_the_nextLink_key()
{
ApiResponseWireParityTests.AssertWireIdentical(
new { success = true, count = 0, submissions = new List<object>() },
new RuleSubmissionListResponse { Success = true, Count = 0, Submissions = new List<RuleSubmissionItem>(), NextLink = null });
}
[Fact]
public void Detail_shape_with_analyze_rule_omits_the_gather_slot()
{
var rule = new AnalyzeRule
{
RuleId = "ANALYZE-CUSTOM-003", Title = "Proxy PAC unreachable", Description = "d", Severity = "warning", Category = "network",
Explanation = "e", IsBuiltIn = false, Conditions = new List<RuleCondition>(),
};
var typed = new RuleSubmissionDetailResponse
{
Success = true,
Submission = Item(),
AnalyzeRule = rule,
LiveFireStats = new RuleSubmissionFireStats { Days = 30, FireCount = 1, SessionsEvaluated = 2, EvaluationCount = 3 },
SuggestedPublishedRuleId = "ANALYZE-NET-002",
RepoFile = new RuleSubmissionRepoFile { Path = "rules/analyze/ANALYZE-NET-002.json", Content = "{}\n" },
};
ApiResponseWireParityTests.AssertWireIdentical(
new
{
success = true,
submission = ItemLiteral(),
analyzeRule = rule,
liveFireStats = new { days = 30, fireCount = 1, sessionsEvaluated = 2, evaluationCount = 3 },
suggestedPublishedRuleId = "ANALYZE-NET-002",
repoFile = new { path = "rules/analyze/ANALYZE-NET-002.json", content = "{}\n" },
},
typed);
}
[Fact]
public void Review_response_shape()
{
ApiResponseWireParityTests.AssertWireIdentical(
new { success = true, message = "Submission approved.", submission = ItemLiteral() },
new ReviewRuleSubmissionResponse { Success = true, Message = "Submission approved.", Submission = Item() });
}
}
@@ -88,6 +88,12 @@ public sealed class SharedManifestParityTests
["webhookProviderTypes"] = EnumMap<WebhookProviderType>(),
["annotationLanes"] = AnnotationLanes.All,
["annotationVerdicts"] = AnnotationVerdicts.All,
// Community rule submissions: kinds, effective statuses (incl. the derived "published"),
// attribution modes and reviewer decisions — the MCP tool schemas enumerate these.
["ruleSubmissionKinds"] = RuleSubmissionKinds.All,
["ruleSubmissionStatuses"] = RuleSubmissionStatuses.All,
["ruleAttributionModes"] = RuleAttributionModes.All,
["ruleSubmissionDecisions"] = RuleSubmissionDecisions.All,
// Ops vocabularies. Declaration order kept for severities — it IS the ladder
// (Info < Warning < Error < Critical), and the MCP renders it in that order.
["opsEventCategories"] = ConstStrings(typeof(OpsEventCategory)),
@@ -0,0 +1,195 @@
using AutopilotMonitor.Functions.DataAccess.TableStorage;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Shared.Models;
namespace AutopilotMonitor.Functions.Tests;
/// <summary>
/// Round-trip pins for the RuleSubmissions Store/Map pair (memory:
/// feedback_table_storage_serialization — every new field in <see cref="RuleSubmission"/>
/// MUST be exercised in Store+Map so silent drops surface here), plus the key and filter shapes.
/// </summary>
public class TableRuleSubmissionRepositoryTests
{
private const string TenantId = "11111111-1111-1111-1111-111111111111";
private static RuleSubmission Full() => new()
{
SubmissionId = "a1b2c3d4e5f6",
BatchId = "0f0e0d0c0b0a",
TenantId = TenantId,
RuleKind = RuleSubmissionKinds.Analyze,
SourceRuleId = "ANALYZE-CUSTOM-003",
Title = "Proxy PAC unreachable",
Category = "network",
RuleJson = "{\"ruleId\":\"ANALYZE-CUSTOM-003\",\"title\":\"Proxy PAC unreachable\"}",
Comment = "Fires when the PAC download fails during ESP.",
SubmittedBy = "alice@contoso.com",
SubmittedByName = "Alice Admin",
ContactEmail = "alice.reply@contoso.com",
AttributionMode = RuleAttributionModes.Person,
AttributionName = "Alice A.",
SubmittedAt = new DateTime(2026, 9, 9, 10, 30, 0, DateTimeKind.Utc),
Status = RuleSubmissionStatuses.Approved,
ValidationFindings = new List<RuleSubmissionFinding>
{
new() { Level = "info", Message = "Derived from template ANALYZE-SEC-004" },
},
SourceFireStats = new RuleSubmissionFireStats { Days = 30, FireCount = 42, SessionsEvaluated = 310, EvaluationCount = 312 },
ReviewedBy = "ga@example.com",
ReviewedAt = new DateTime(2026, 9, 10, 8, 0, 0, DateTimeKind.Utc),
ReviewComment = "Taken, generalised for the community.",
WillBeAdapted = true,
PublishedRuleId = "ANALYZE-NET-002",
DerivedFromTemplateRuleId = "ANALYZE-SEC-004",
};
[Fact]
public void Roundtrip_all_fields_survive_store_and_map()
{
var original = Full();
var mapped = TableRuleSubmissionRepository.MapSubmission(
TableRuleSubmissionRepository.StoreSubmission(original));
Assert.Equal(original.SubmissionId, mapped.SubmissionId);
Assert.Equal(original.BatchId, mapped.BatchId);
Assert.Equal(original.TenantId, mapped.TenantId);
Assert.Equal(original.RuleKind, mapped.RuleKind);
Assert.Equal(original.SourceRuleId, mapped.SourceRuleId);
Assert.Equal(original.Title, mapped.Title);
Assert.Equal(original.Category, mapped.Category);
Assert.Equal(original.RuleJson, mapped.RuleJson);
Assert.Equal(original.Comment, mapped.Comment);
Assert.Equal(original.SubmittedBy, mapped.SubmittedBy);
Assert.Equal(original.SubmittedByName, mapped.SubmittedByName);
Assert.Equal(original.ContactEmail, mapped.ContactEmail);
Assert.Equal(original.AttributionMode, mapped.AttributionMode);
Assert.Equal(original.AttributionName, mapped.AttributionName);
Assert.Equal(original.SubmittedAt, mapped.SubmittedAt);
Assert.Equal(original.Status, mapped.Status);
Assert.Single(mapped.ValidationFindings);
Assert.Equal("info", mapped.ValidationFindings[0].Level);
Assert.Equal(original.ValidationFindings[0].Message, mapped.ValidationFindings[0].Message);
Assert.NotNull(mapped.SourceFireStats);
Assert.Equal(42, mapped.SourceFireStats!.FireCount);
Assert.Equal(310, mapped.SourceFireStats.SessionsEvaluated);
Assert.Equal(312, mapped.SourceFireStats.EvaluationCount);
Assert.Equal(30, mapped.SourceFireStats.Days);
Assert.Equal(original.ReviewedBy, mapped.ReviewedBy);
Assert.Equal(original.ReviewedAt, mapped.ReviewedAt);
Assert.Equal(original.ReviewComment, mapped.ReviewComment);
Assert.True(mapped.WillBeAdapted);
Assert.Equal(original.PublishedRuleId, mapped.PublishedRuleId);
Assert.Equal(original.DerivedFromTemplateRuleId, mapped.DerivedFromTemplateRuleId);
}
[Fact]
public void Roundtrip_pending_row_keeps_nulls_null()
{
var original = Full();
original.Status = RuleSubmissionStatuses.Pending;
original.Comment = null;
original.ContactEmail = null;
original.SourceFireStats = null;
original.ValidationFindings = new List<RuleSubmissionFinding>();
original.ReviewedBy = null;
original.ReviewedAt = null;
original.ReviewComment = null;
original.WillBeAdapted = false;
original.PublishedRuleId = null;
original.DerivedFromTemplateRuleId = null;
var mapped = TableRuleSubmissionRepository.MapSubmission(
TableRuleSubmissionRepository.StoreSubmission(original));
Assert.Null(mapped.Comment);
Assert.Null(mapped.ContactEmail);
Assert.Null(mapped.SourceFireStats);
Assert.Empty(mapped.ValidationFindings);
Assert.Null(mapped.ReviewedBy);
Assert.Null(mapped.ReviewedAt);
Assert.Null(mapped.ReviewComment);
Assert.False(mapped.WillBeAdapted);
Assert.Null(mapped.PublishedRuleId);
Assert.Null(mapped.DerivedFromTemplateRuleId);
}
[Fact]
public void Store_uses_the_single_partition_and_an_inverted_tick_row_key()
{
var s = Full();
var entity = TableRuleSubmissionRepository.StoreSubmission(s);
Assert.Equal("submissions", entity.PartitionKey);
Assert.Equal($"{RowKeyCodec.InvertedTicks(s.SubmittedAt)}_{s.SubmissionId}", entity.RowKey);
}
[Fact]
public void Newer_submission_sorts_first()
{
var older = Full();
var newer = Full();
newer.SubmittedAt = older.SubmittedAt.AddMinutes(5);
var olderKey = TableRuleSubmissionRepository.StoreSubmission(older).RowKey;
var newerKey = TableRuleSubmissionRepository.StoreSubmission(newer).RowKey;
Assert.True(string.CompareOrdinal(newerKey, olderKey) < 0);
}
[Fact]
public void Map_tolerates_a_corrupt_json_column()
{
var entity = TableRuleSubmissionRepository.StoreSubmission(Full());
entity["ValidationFindingsJson"] = "{not json";
entity["SourceFireStatsJson"] = "[]";
var mapped = TableRuleSubmissionRepository.MapSubmission(entity);
Assert.Empty(mapped.ValidationFindings);
Assert.Null(mapped.SourceFireStats);
}
// ── retention rule (shared by the sweep and this pin) ──
private static readonly DateTime Now = new(2026, 12, 1, 12, 0, 0, DateTimeKind.Utc);
[Theory]
[InlineData("withdrawn", 29, false)]
[InlineData("withdrawn", 30, true)]
[InlineData("declined", 89, false)]
[InlineData("declined", 90, true)]
[InlineData("pending", 400, false)]
[InlineData("approved", 400, false)]
public void Retention_expires_only_closed_rows_at_their_window(string status, int ageDays, bool expired)
{
var s = Full();
s.Status = status;
s.SubmittedAt = Now.AddDays(-ageDays);
s.ReviewedAt = status == "declined" ? Now.AddDays(-ageDays) : null;
Assert.Equal(expired, RuleSubmissionRetention.IsExpired(s, Now));
}
[Fact]
public void Retention_of_a_declined_row_counts_from_the_decision_not_the_submission()
{
var s = Full();
s.Status = RuleSubmissionStatuses.Declined;
s.SubmittedAt = Now.AddDays(-200);
s.ReviewedAt = Now.AddDays(-10);
Assert.False(RuleSubmissionRetention.IsExpired(s, Now));
}
[Theory]
[InlineData(null, null, "PartitionKey eq 'submissions'")]
[InlineData("t'1", null, "PartitionKey eq 'submissions' and TenantId eq 't''1'")]
[InlineData(null, "pending", "PartitionKey eq 'submissions' and Status eq 'pending'")]
[InlineData("t1", "approved", "PartitionKey eq 'submissions' and TenantId eq 't1' and Status eq 'approved'")]
public void Filter_escapes_and_composes(string? tenantId, string? status, string expected)
{
Assert.Equal(expected, TableRuleSubmissionRepository.BuildFilter(tenantId, status));
}
}
@@ -184,6 +184,7 @@ public class TypedContractCompletionWireParityTests
totalInstalls = 4,
totalSkipped = 1,
totalUnmeasured = 1,
totalIncomplete = 0,
totalCollisionExcluded = 0,
slowestApps = new[]
{
@@ -195,6 +196,7 @@ public class TypedContractCompletionWireParityTests
skipped = 1,
unmeasured = 1,
failed = 1,
incomplete = 0,
failureRate = 33.3,
avgDurationSeconds = 120.0,
maxDurationSeconds = 240,
@@ -225,6 +227,7 @@ public class TypedContractCompletionWireParityTests
TotalInstalls = 4,
TotalSkipped = 1,
TotalUnmeasured = 1,
TotalIncomplete = 0,
TotalCollisionExcluded = 0,
SlowestApps = new[]
{
@@ -236,6 +239,7 @@ public class TypedContractCompletionWireParityTests
Skipped = 1,
Unmeasured = 1,
Failed = 1,
Incomplete = 0,
FailureRate = 33.3,
AvgDurationSeconds = 120.0,
MaxDurationSeconds = 240,
@@ -684,6 +688,7 @@ public class TypedContractCompletionWireParityTests
skipped = 0,
unmeasured = 0,
failed = 0,
incomplete = 0,
failureRate = 0.0,
avgDurationSeconds = 0.0,
p95DurationSeconds = 0,
@@ -715,6 +720,7 @@ public class TypedContractCompletionWireParityTests
Skipped = 0,
Unmeasured = 0,
Failed = 0,
Incomplete = 0,
FailureRate = 0.0,
AvgDurationSeconds = 0.0,
P95DurationSeconds = 0,
@@ -34,6 +34,7 @@ namespace AutopilotMonitor.Functions.DataAccess
services.AddSingleton<ISessionAnnotationRepository, TableSessionAnnotationRepository>();
services.AddSingleton<IBootstrapRepository, TableBootstrapRepository>();
services.AddSingleton<INotificationRepository, TableNotificationRepository>();
services.AddSingleton<IRuleSubmissionRepository, TableRuleSubmissionRepository>();
services.AddSingleton<ITenantNotificationRepository, TableTenantNotificationRepository>();
services.AddSingleton<ISlaTenantStatusRepository, TableSlaTenantStatusRepository>();
// What's new notifier watermark (single platform row in the AdminConfiguration table).
@@ -142,6 +142,9 @@ namespace AutopilotMonitor.Functions.DataAccess.TableStorage
public Task ResolveEspBlockingForSessionAsync(string tenantId, string sessionId)
=> _storage.ResolveEspBlockingForSessionAsync(tenantId, sessionId);
public Task<int> CloseOpenAppInstallsForSessionAsync(string tenantId, string sessionId)
=> _storage.CloseOpenAppInstallsForSessionAsync(tenantId, sessionId);
public Task<bool> SaveTimeAttributionAggregateAsync(TimeAttributionDailyAggregate aggregate)
=> _storage.SaveTimeAttributionAggregateAsync(aggregate);
@@ -0,0 +1,294 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Pagination;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared;
using AutopilotMonitor.Shared.DataAccess;
using AutopilotMonitor.Shared.Models;
using AutopilotMonitor.Shared.Pagination;
using Azure;
using Azure.Data.Tables;
using Microsoft.Extensions.Logging;
namespace AutopilotMonitor.Functions.DataAccess.TableStorage
{
/// <summary>
/// Table-storage implementation of <see cref="IRuleSubmissionRepository"/>.
/// PK = <see cref="PartitionKey"/> for every tenant, RK = inverted ticks + id (newest first).
/// </summary>
public class TableRuleSubmissionRepository : IRuleSubmissionRepository
{
internal const string PartitionKey = "submissions";
private readonly TableClient _tableClient;
private readonly ILogger<TableRuleSubmissionRepository> _logger;
public TableRuleSubmissionRepository(TableStorageService storage, ILogger<TableRuleSubmissionRepository> logger)
{
_tableClient = storage.GetTableClient(Constants.TableNames.RuleSubmissions);
_logger = logger;
}
public async Task<bool> AddAsync(RuleSubmission submission)
{
try
{
await _tableClient.AddEntityAsync(StoreSubmission(submission));
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to store rule submission {SubmissionId}", submission.SubmissionId);
return false;
}
}
public async Task<RuleSubmission?> GetAsync(string submissionId)
{
var entity = await FindEntityAsync(submissionId);
return entity == null ? null : MapSubmission(entity);
}
public async Task<List<RuleSubmission>> GetForTenantAsync(string tenantId)
{
var results = new List<RuleSubmission>();
try
{
await foreach (var entity in _tableClient.QueryAsync<TableEntity>(filter: BuildFilter(tenantId, status: null)))
{
results.Add(MapSubmission(entity));
}
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
_logger.LogDebug("RuleSubmissions table does not exist yet, returning empty list");
}
return results;
}
public async Task<RawPage<RuleSubmission>> GetPageAsync(string? tenantId, string? status, int pageSize, string? continuation)
{
if (pageSize < 1) throw new ArgumentOutOfRangeException(nameof(pageSize));
try
{
var (entities, nextRawToken) = await AzureTablesPaginator.FetchPageAsync<TableEntity>(
client: _tableClient,
filter: BuildFilter(tenantId, status),
pageSize: pageSize,
continuation: continuation);
var page = new List<RuleSubmission>(entities.Count);
foreach (var entity in entities) page.Add(MapSubmission(entity));
// RowKey is the inverted tick of SubmittedAt — newest first by construction.
return new RawPage<RuleSubmission>(page, nextRawToken);
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
_logger.LogDebug("RuleSubmissions table does not exist yet, returning empty page");
return RawPage<RuleSubmission>.Empty;
}
}
public async Task<bool> UpdateAsync(RuleSubmission submission)
{
var existing = await FindEntityAsync(submission.SubmissionId);
if (existing == null)
{
_logger.LogWarning("UpdateAsync: rule submission {SubmissionId} not found", submission.SubmissionId);
return false;
}
var entity = StoreSubmission(submission);
entity.RowKey = existing.RowKey;
entity.ETag = existing.ETag;
try
{
// If-Match on the ETag: two reviewers deciding the same submission cannot both win.
await _tableClient.UpdateEntityAsync(entity, existing.ETag, TableUpdateMode.Replace);
return true;
}
catch (RequestFailedException ex) when (ex.Status == 412)
{
_logger.LogWarning("UpdateAsync: rule submission {SubmissionId} changed underneath the reviewer", submission.SubmissionId);
return false;
}
}
public async Task<HashSet<string>> GetReservedPublishedRuleIdsAsync()
{
var ids = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
try
{
await foreach (var entity in _tableClient.QueryAsync<TableEntity>(
filter: BuildFilter(tenantId: null, status: RuleSubmissionStatuses.Approved),
select: new[] { "PublishedRuleId" }))
{
var id = entity.GetString("PublishedRuleId");
if (!string.IsNullOrEmpty(id)) ids.Add(id!);
}
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
_logger.LogDebug("RuleSubmissions table does not exist yet");
}
return ids;
}
public async Task<int> DeleteExpiredAsync(DateTime nowUtc)
{
var deleted = 0;
try
{
// The expiry rule is the shared RuleSubmissionRetention, so the sweep and its
// test cannot disagree; only the two closed statuses are scanned.
foreach (var status in new[] { RuleSubmissionStatuses.Withdrawn, RuleSubmissionStatuses.Declined })
{
var expired = new List<TableEntity>();
await foreach (var entity in _tableClient.QueryAsync<TableEntity>(filter: BuildFilter(tenantId: null, status)))
{
if (RuleSubmissionRetention.IsExpired(MapSubmission(entity), nowUtc)) expired.Add(entity);
}
foreach (var entity in expired)
{
try
{
await _tableClient.DeleteEntityAsync(entity.PartitionKey, entity.RowKey);
deleted++;
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
// Already gone — a parallel sweep or a tenant offboarding won the race.
}
}
}
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
_logger.LogDebug("RuleSubmissions table does not exist yet");
}
return deleted;
}
public async Task<bool> DeleteAsync(string submissionId)
{
var existing = await FindEntityAsync(submissionId);
if (existing == null) return false;
try
{
await _tableClient.DeleteEntityAsync(existing.PartitionKey, existing.RowKey);
return true;
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
return false;
}
}
private async Task<TableEntity?> FindEntityAsync(string submissionId)
{
try
{
await foreach (var entity in _tableClient.QueryAsync<TableEntity>(
filter: $"PartitionKey eq '{PartitionKey}' and SubmissionId eq '{Escape(submissionId)}'"))
{
return entity;
}
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
_logger.LogDebug("RuleSubmissions table does not exist yet");
}
return null;
}
internal static string BuildFilter(string? tenantId, string? status)
{
var filter = $"PartitionKey eq '{PartitionKey}'";
if (!string.IsNullOrEmpty(tenantId)) filter += $" and TenantId eq '{Escape(tenantId!)}'";
if (!string.IsNullOrEmpty(status)) filter += $" and Status eq '{Escape(status!)}'";
return filter;
}
private static string Escape(string value) => value.Replace("'", "''");
// ── Store / Map ─────────────────────────────────────────────────────────
// internal static: pinned by round-trip unit tests — every property must survive
// Store→Map, so any new field lands in BOTH methods plus the test.
internal static TableEntity StoreSubmission(RuleSubmission s) =>
new(PartitionKey, $"{RowKeyCodec.InvertedTicks(s.SubmittedAt)}_{s.SubmissionId}")
{
["SubmissionId"] = s.SubmissionId,
["BatchId"] = s.BatchId,
["TenantId"] = s.TenantId,
["RuleKind"] = s.RuleKind,
["SourceRuleId"] = s.SourceRuleId,
["Title"] = s.Title,
["Category"] = s.Category,
["RuleJson"] = s.RuleJson,
["Comment"] = s.Comment ?? string.Empty,
["SubmittedBy"] = s.SubmittedBy,
["SubmittedByName"] = s.SubmittedByName,
["ContactEmail"] = s.ContactEmail ?? string.Empty,
["AttributionMode"] = s.AttributionMode,
["AttributionName"] = s.AttributionName,
["SubmittedAt"] = s.SubmittedAt,
["Status"] = s.Status,
["ValidationFindingsJson"] = JsonSerializer.Serialize(s.ValidationFindings),
["SourceFireStatsJson"] = s.SourceFireStats == null ? string.Empty : JsonSerializer.Serialize(s.SourceFireStats),
["ReviewedBy"] = s.ReviewedBy ?? string.Empty,
["ReviewedAt"] = s.ReviewedAt,
["ReviewComment"] = s.ReviewComment ?? string.Empty,
["WillBeAdapted"] = s.WillBeAdapted,
["PublishedRuleId"] = s.PublishedRuleId ?? string.Empty,
["DerivedFromTemplateRuleId"] = s.DerivedFromTemplateRuleId ?? string.Empty,
};
internal static RuleSubmission MapSubmission(TableEntity e) => new()
{
SubmissionId = e.GetString("SubmissionId") ?? string.Empty,
BatchId = e.GetString("BatchId") ?? string.Empty,
TenantId = e.GetString("TenantId") ?? string.Empty,
RuleKind = e.GetString("RuleKind") ?? string.Empty,
SourceRuleId = e.GetString("SourceRuleId") ?? string.Empty,
Title = e.GetString("Title") ?? string.Empty,
Category = e.GetString("Category") ?? string.Empty,
RuleJson = e.GetString("RuleJson") ?? string.Empty,
Comment = NullIfEmpty(e.GetString("Comment")),
SubmittedBy = e.GetString("SubmittedBy") ?? string.Empty,
SubmittedByName = e.GetString("SubmittedByName") ?? string.Empty,
ContactEmail = NullIfEmpty(e.GetString("ContactEmail")),
AttributionMode = e.GetString("AttributionMode") ?? RuleAttributionModes.Anonymous,
AttributionName = e.GetString("AttributionName") ?? RuleAttributionModes.AnonymousAuthor,
SubmittedAt = e.GetDateTimeOffset("SubmittedAt")?.UtcDateTime ?? DateTime.MinValue,
Status = e.GetString("Status") ?? RuleSubmissionStatuses.Pending,
ValidationFindings = DeserializeOrDefault<List<RuleSubmissionFinding>>(e.GetString("ValidationFindingsJson")) ?? new List<RuleSubmissionFinding>(),
SourceFireStats = DeserializeOrDefault<RuleSubmissionFireStats>(e.GetString("SourceFireStatsJson")),
ReviewedBy = NullIfEmpty(e.GetString("ReviewedBy")),
ReviewedAt = e.GetDateTimeOffset("ReviewedAt")?.UtcDateTime,
ReviewComment = NullIfEmpty(e.GetString("ReviewComment")),
WillBeAdapted = e.GetBoolean("WillBeAdapted") ?? false,
PublishedRuleId = NullIfEmpty(e.GetString("PublishedRuleId")),
DerivedFromTemplateRuleId = NullIfEmpty(e.GetString("DerivedFromTemplateRuleId")),
};
private static T? DeserializeOrDefault<T>(string? json) where T : class
{
if (string.IsNullOrEmpty(json)) return null;
try
{
return JsonSerializer.Deserialize<T>(json!);
}
catch (JsonException)
{
// A corrupt column must not hide the submission itself.
return null;
}
}
private static string? NullIfEmpty(string? value) => string.IsNullOrEmpty(value) ? null : value;
}
}
@@ -101,6 +101,13 @@ namespace AutopilotMonitor.Functions.DataAccess.TableStorage
// complete. Positive evidence only (listed ⇒ EspBlocking=true, absent ⇒ stays
// unknown). Idempotent + fail-soft like the counter reconcile above.
await _storage.ResolveEspBlockingForSessionAsync(tenantId, sessionId);
// Observation end: app rows still InProgress on a terminal session never get a
// terminal event — close them as Incomplete (outcome unknown, not a failure).
// Early for the ingest path (verdict batch, the agent may still be watching),
// never wrong in the end state: a real terminal arriving later still wins via
// the sticky-status reconcile, and the shutdown batch re-runs the close for rows
// opened after the verdict. Idempotent + fail-soft.
await _storage.CloseOpenAppInstallsForSessionAsync(tenantId, sessionId);
// F1 PR2: compute + persist the time-attribution breakdown once, now that the
// terminal write stamped CompletedAt/DurationSeconds and the event stream is
@@ -291,6 +291,7 @@ namespace AutopilotMonitor.Functions.Functions.Apps
var measured = installed.Where(MetricsMath.HasMeasuredDuration).ToList();
var succeeded = installed.Count;
var failed = summaries.Count(s => s.Status == "Failed");
var incomplete = summaries.Count(s => s.Status == "Incomplete");
var failureRate = MetricsMath.TerminalFailureRatePct(failed, succeeded);
var avgDurationSeconds = measured.Count > 0 ? Math.Round(measured.Average(s => s.DurationSeconds), 0) : 0;
var p95DurationSeconds = Percentile(measured.Select(s => s.DurationSeconds).ToList(), 0.95);
@@ -423,6 +424,7 @@ namespace AutopilotMonitor.Functions.Functions.Apps
Skipped = skipped,
Unmeasured = installed.Count - measured.Count,
Failed = failed,
Incomplete = incomplete,
FailureRate = failureRate,
AvgDurationSeconds = avgDurationSeconds,
P95DurationSeconds = p95DurationSeconds,
@@ -55,6 +55,10 @@ namespace AutopilotMonitor.Functions.Functions.Rules
return await req.BadRequestAsync("Invalid rule data");
}
// Author is stamped from the creator's token, never from the payload
// (anti-spoof), and stays immutable through every later update.
rule.Author = TenantHelper.GetUserDisplayName(req) ?? "Autopilot Monitor";
try
{
var success = await _ruleService.CreateRuleAsync(tenantId, rule);
@@ -88,6 +92,11 @@ namespace AutopilotMonitor.Functions.Functions.Rules
rule.RuleId = ruleId;
// Same anti-spoof stamp as CreateRule: on a true update the service replaces
// this with the original author (immutable attribution), but a full-payload PUT
// that upserts a rule with no existing row must not store the payload's author.
rule.Author = TenantHelper.GetUserDisplayName(req) ?? "Autopilot Monitor";
try
{
var success = await _ruleService.UpdateRuleAsync(tenantId, rule);
@@ -124,7 +133,8 @@ namespace AutopilotMonitor.Functions.Functions.Rules
try
{
var newRule = await _ruleService.CreateFromTemplateAsync(tenantId, ruleId, variables);
var author = TenantHelper.GetUserDisplayName(req) ?? "Autopilot Monitor";
var newRule = await _ruleService.CreateFromTemplateAsync(tenantId, ruleId, variables, author);
var response = req.CreateResponse(HttpStatusCode.Created);
await response.WriteAsJsonAsync(new CreateAnalyzeRuleFromTemplateResponse { Success = true, Rule = newRule, Message = "Custom rule created from template" });
@@ -0,0 +1,52 @@
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.Models;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
{
/// <summary>
/// Operator hard delete of a submission (test/demo rows, or a tenant's request). The row
/// vanishes from both lists; a published rule in the repo is untouched.
/// </summary>
public class DeleteGlobalRuleSubmissionFunction
{
private readonly ILogger<DeleteGlobalRuleSubmissionFunction> _logger;
private readonly RuleSubmissionService _service;
public DeleteGlobalRuleSubmissionFunction(ILogger<DeleteGlobalRuleSubmissionFunction> logger, RuleSubmissionService service)
{
_logger = logger;
_service = service;
}
[Function("DeleteGlobalRuleSubmission")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "global/rule-submissions/{submissionId}")] HttpRequestData req,
string submissionId)
{
try
{
// Authentication + GlobalAdminOnly authorization enforced by PolicyEnforcementMiddleware
var user = TenantHelper.GetUserIdentifier(req);
if (string.IsNullOrWhiteSpace(submissionId)) return await req.BadRequestAsync("submissionId is required.");
var existing = await _service.GetAsync(submissionId);
if (existing == null) return await req.NotFoundAsync("Submission not found.");
if (!await _service.DeleteAsync(submissionId)) return await req.NotFoundAsync("Submission not found.");
// Warning on purpose: an operator delete is rare and must be visible in App Insights.
_logger.LogWarning("Rule submission {SubmissionId} ({RuleId}, tenant {TenantId}, status {Status}) deleted by {User}",
submissionId, existing.SourceRuleId, existing.TenantId, existing.Status, user);
return await req.OkAsync(new SuccessMessageResponse { Success = true, Message = "Submission deleted." });
}
catch (Exception ex)
{
return await req.InternalServerErrorAsync(_logger, ex, "DeleteGlobalRuleSubmission");
}
}
}
}
@@ -0,0 +1,41 @@
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Services;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
{
/// <summary>One submission with the frozen rule, live fire stats, the suggested id and the repo file.</summary>
public class GetGlobalRuleSubmissionFunction
{
private readonly ILogger<GetGlobalRuleSubmissionFunction> _logger;
private readonly RuleSubmissionService _service;
public GetGlobalRuleSubmissionFunction(ILogger<GetGlobalRuleSubmissionFunction> logger, RuleSubmissionService service)
{
_logger = logger;
_service = service;
}
[Function("GetGlobalRuleSubmission")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "global/rule-submissions/{submissionId}")] HttpRequestData req,
string submissionId)
{
try
{
// Authentication + GlobalReadOrAdmin authorization enforced by PolicyEnforcementMiddleware
if (string.IsNullOrWhiteSpace(submissionId)) return await req.BadRequestAsync("submissionId is required.");
var detail = await _service.GetDetailAsync(submissionId);
if (detail == null) return await req.NotFoundAsync("Submission not found.");
return await req.OkAsync(detail);
}
catch (Exception ex)
{
return await req.InternalServerErrorAsync(_logger, ex, "GetGlobalRuleSubmission");
}
}
}
}
@@ -0,0 +1,77 @@
using System.Web;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Pagination;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.Models;
using AutopilotMonitor.Shared.Pagination;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
{
/// <summary>Operator list across tenants: <c>?tenantId=</c> and <c>?status=</c> are server-side filters, paging as for session reports.</summary>
public class GetGlobalRuleSubmissionsFunction
{
private readonly ILogger<GetGlobalRuleSubmissionsFunction> _logger;
private readonly RuleSubmissionService _service;
public GetGlobalRuleSubmissionsFunction(ILogger<GetGlobalRuleSubmissionsFunction> logger, RuleSubmissionService service)
{
_logger = logger;
_service = service;
}
[Function("GetGlobalRuleSubmissions")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "global/rule-submissions")] HttpRequestData req)
{
try
{
// Authentication + GlobalReadOrAdmin authorization enforced by PolicyEnforcementMiddleware
var callerTenantId = TenantHelper.GetTenantId(req);
var query = HttpUtility.ParseQueryString(req.Url.Query ?? string.Empty);
var parsed = RuleSubmissionsPagination.ParseQuery(query);
if (parsed.Error != null) return await req.BadRequestAsync(parsed.Error);
var pageSize = parsed.PageSize ?? RuleSubmissionsPagination.DefaultPageSize;
string? azureToken = null;
if (parsed.Continuation != null)
{
if (!RuleSubmissionsPagination.TryAcceptContinuation(
parsed.Continuation, callerTenantId, parsed.FilterTenantId, parsed.FilterStatus,
out azureToken, out var rejectReason))
{
_logger.LogWarning("GetGlobalRuleSubmissions: continuation rejected ({Reason})", rejectReason);
return await req.BadRequestAsync($"Invalid continuation token ({rejectReason}). Restart pagination from the first page.");
}
}
var page = await _service.GetPageAsync(parsed.FilterTenantId, parsed.FilterStatus, pageSize, azureToken);
var items = await _service.ToItemsAsync(page.Items);
string? nextLink = null;
if (!string.IsNullOrEmpty(page.NextRawToken))
{
var fp = RuleSubmissionsPagination.Fingerprint(callerTenantId, parsed.FilterTenantId, parsed.FilterStatus);
var wireToken = ContinuationToken.Encode(page.NextRawToken!, callerTenantId, fp);
nextLink = RuleSubmissionsPagination.BuildNextLink(pageSize, wireToken, parsed.FilterTenantId, parsed.FilterStatus);
}
return await req.OkAsync(new RuleSubmissionListResponse
{
Success = true,
Count = items.Count,
Submissions = items,
NextLink = nextLink,
});
}
catch (Exception ex)
{
return await req.InternalServerErrorAsync(_logger, ex, "GetGlobalRuleSubmissions");
}
}
}
}
@@ -0,0 +1,41 @@
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.Models;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
{
/// <summary>The submitting tenant's own submissions, newest first, with the effective status.</summary>
public class GetRuleSubmissionsFunction
{
private readonly ILogger<GetRuleSubmissionsFunction> _logger;
private readonly RuleSubmissionService _service;
public GetRuleSubmissionsFunction(ILogger<GetRuleSubmissionsFunction> logger, RuleSubmissionService service)
{
_logger = logger;
_service = service;
}
[Function("GetRuleSubmissions")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "rules/submissions")] HttpRequestData req)
{
try
{
// Authentication + TenantAdminOrGA authorization enforced by PolicyEnforcementMiddleware.
// Always the JWT tenant — a GA reads foreign tenants through global/rule-submissions?tenantId=.
var tenantId = req.GetRequestContext().TenantId;
var rows = await _service.GetForTenantAsync(tenantId);
var items = await _service.ToItemsAsync(rows);
return await req.OkAsync(new RuleSubmissionListResponse { Success = true, Count = items.Count, Submissions = items });
}
catch (Exception ex)
{
return await req.InternalServerErrorAsync(_logger, ex, "GetRuleSubmissions");
}
}
}
}
@@ -0,0 +1,92 @@
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.Models;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
{
/// <summary>The reviewer's decision (portal or MCP). The submitter is told through a tenant notification.</summary>
public class ReviewRuleSubmissionFunction
{
private readonly ILogger<ReviewRuleSubmissionFunction> _logger;
private readonly RuleSubmissionService _service;
private readonly TenantNotificationService _tenantNotifications;
public ReviewRuleSubmissionFunction(
ILogger<ReviewRuleSubmissionFunction> logger,
RuleSubmissionService service,
TenantNotificationService tenantNotifications)
{
_logger = logger;
_service = service;
_tenantNotifications = tenantNotifications;
}
[Function("ReviewRuleSubmission")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = "global/rule-submissions/{submissionId}")] HttpRequestData req,
string submissionId)
{
try
{
// Authentication + GlobalAdminOnly authorization enforced by PolicyEnforcementMiddleware
var reviewer = TenantHelper.GetUserIdentifier(req);
if (string.IsNullOrWhiteSpace(submissionId)) return await req.BadRequestAsync("submissionId is required.");
var read = await req.ReadAsync<ReviewRuleSubmissionRequest>();
if (read.Error != null) return read.Error;
RuleSubmission updated;
try
{
updated = await _service.ReviewAsync(submissionId, read.Value!, reviewer);
}
catch (KeyNotFoundException ex)
{
return await req.NotFoundAsync(ex.Message);
}
catch (ArgumentException ex)
{
return await req.BadRequestAsync(ex.Message);
}
catch (InvalidOperationException ex)
{
return await req.ConflictAsync(ex.Message);
}
var approved = updated.Status == RuleSubmissionStatuses.Approved;
var title = approved
? $"Rule submission approved: {updated.SourceRuleId}"
: $"Rule submission declined: {updated.SourceRuleId}";
var message = approved
? (updated.WillBeAdapted
? $"\"{updated.Title}\" will be published as {updated.PublishedRuleId} after a small adaptation for the community."
: $"\"{updated.Title}\" will be published as {updated.PublishedRuleId}.")
: $"\"{updated.Title}\" was not accepted for the community pool.";
if (!string.IsNullOrEmpty(updated.ReviewComment)) message += $" Reviewer: {updated.ReviewComment}";
// Best effort; the submissions list carries the same facts.
_ = _tenantNotifications.CreateNotificationAsync(
updated.TenantId, "rule_submission_decided", title, message,
href: updated.RuleKind == RuleSubmissionKinds.Analyze ? "/analyze-rules" : "/gather-rules");
_logger.LogInformation("Rule submission {SubmissionId} {Status} by {Reviewer} (published id {PublishedRuleId})",
submissionId, updated.Status, reviewer, updated.PublishedRuleId ?? "-");
var item = (await _service.ToItemsAsync(new[] { updated }))[0];
return await req.OkAsync(new ReviewRuleSubmissionResponse
{
Success = true,
Message = approved ? "Submission approved." : "Submission declined.",
Submission = item,
});
}
catch (Exception ex)
{
return await req.InternalServerErrorAsync(_logger, ex, "ReviewRuleSubmission");
}
}
}
}
@@ -0,0 +1,137 @@
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Security;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.DataAccess;
using AutopilotMonitor.Shared.Models;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
{
/// <summary>
/// A tenant admin submits one or more of the tenant's custom rules for the community pool.
/// The body carries only rule references; the service freezes the rules server-side.
/// </summary>
public class SubmitRuleSubmissionsFunction
{
private readonly ILogger<SubmitRuleSubmissionsFunction> _logger;
private readonly RuleSubmissionService _service;
private readonly IMaintenanceRepository _maintenanceRepo;
private readonly TelegramNotificationService _telegram;
private readonly GlobalNotificationService _globalNotifications;
public SubmitRuleSubmissionsFunction(
ILogger<SubmitRuleSubmissionsFunction> logger,
RuleSubmissionService service,
IMaintenanceRepository maintenanceRepo,
TelegramNotificationService telegram,
GlobalNotificationService globalNotifications)
{
_logger = logger;
_service = service;
_maintenanceRepo = maintenanceRepo;
_telegram = telegram;
_globalNotifications = globalNotifications;
}
[Function("SubmitRuleSubmissions")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "rules/submissions")] HttpRequestData req)
{
try
{
// Authentication + TenantAdminOrGA authorization enforced by PolicyEnforcementMiddleware
var requestCtx = req.GetRequestContext();
var tenantId = requestCtx.TenantId;
var userIdentifier = requestCtx.UserPrincipalName;
var read = await req.ReadAsync<SubmitRuleSubmissionsRequest>(262_144);
if (read.Error != null) return read.Error;
var request = read.Value!;
// Same tenant-tamper gate as the session report: non-GAs submit for their JWT
// tenant only; a GA may submit on behalf of a foreign tenant and must name it.
if (!requestCtx.IsGlobalAdmin)
{
if (!string.IsNullOrEmpty(request.TenantId)
&& !string.Equals(request.TenantId, tenantId, StringComparison.OrdinalIgnoreCase))
{
_logger.LogWarning(
"SubmitRuleSubmissions: BLOCKED cross-tenant body for non-GA user={User} jwtTenant={JwtTenant} bodyTenant={BodyTenant}",
userIdentifier, tenantId, request.TenantId);
return await req.ForbiddenAsync("Body tenantId must match your authenticated tenant.");
}
request.TenantId = tenantId;
}
else if (string.IsNullOrEmpty(request.TenantId))
{
return await req.BadRequestAsync("tenantId is required in body for Global Admin submissions.");
}
if (!SecurityValidator.IsValidGuid(request.TenantId))
return await req.BadRequestAsync("Invalid tenantId.");
var displayName = TenantHelper.GetUserDisplayName(req) ?? userIdentifier;
List<RuleSubmission> created;
try
{
created = await _service.SubmitAsync(request.TenantId, request, userIdentifier, displayName);
}
catch (ArgumentException ex)
{
return await req.BadRequestAsync(ex.Message);
}
catch (InvalidOperationException ex)
{
return await req.ConflictAsync(ex.Message);
}
if (!requestCtx.IsGlobalAdmin)
{
foreach (var s in created)
{
await _maintenanceRepo.LogAuditEntryAsync(
request.TenantId, "CREATE", "RuleSubmission", s.SubmissionId, userIdentifier,
new Dictionary<string, string>
{
{ "Action", "SubmitRuleSubmission" },
{ "RuleKind", s.RuleKind },
{ "RuleId", s.SourceRuleId },
{ "BatchId", s.BatchId },
{ "AttributionMode", s.AttributionMode },
{ "HasComment", (s.Comment != null).ToString() },
});
}
}
// Operator notifications — best effort, one per rule so every id has its own deep link.
foreach (var s in created)
{
_ = _telegram.SendRuleSubmissionAsync(s.SubmissionId, request.TenantId, userIdentifier, s.RuleKind, s.SourceRuleId, s.Title, s.Comment ?? string.Empty);
_ = _globalNotifications.CreateNotificationAsync(
"rule_submission",
$"Rule submission {s.SubmissionId}",
$"{s.SourceRuleId} \"{s.Title}\" ({s.RuleKind}) — {userIdentifier} (Tenant: {request.TenantId})",
href: $"/admin/reports/rule-submissions?submissionId={Uri.EscapeDataString(s.SubmissionId)}");
}
_logger.LogInformation("Rule submissions stored: {Count} rule(s), batch {BatchId}, tenant {TenantId}, by {User}",
created.Count, created[0].BatchId, request.TenantId, userIdentifier);
var items = await _service.ToItemsAsync(created);
return await req.OkAsync(new SubmitRuleSubmissionsResponse
{
Success = true,
Message = created.Count == 1 ? "Rule submitted for review." : $"{created.Count} rules submitted for review.",
BatchId = created[0].BatchId,
Submissions = items,
});
}
catch (Exception ex)
{
return await req.InternalServerErrorAsync(_logger, ex, "SubmitRuleSubmissions");
}
}
}
}
@@ -0,0 +1,55 @@
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Services;
using AutopilotMonitor.Shared.Models;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
namespace AutopilotMonitor.Functions.Functions.Rules.Submissions
{
/// <summary>The submitter takes a pending submission back. The row stays (status withdrawn) for the audit trail.</summary>
public class WithdrawRuleSubmissionFunction
{
private readonly ILogger<WithdrawRuleSubmissionFunction> _logger;
private readonly RuleSubmissionService _service;
public WithdrawRuleSubmissionFunction(ILogger<WithdrawRuleSubmissionFunction> logger, RuleSubmissionService service)
{
_logger = logger;
_service = service;
}
[Function("WithdrawRuleSubmission")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "rules/submissions/{submissionId}")] HttpRequestData req,
string submissionId)
{
try
{
// Authentication + TenantAdminOrGA authorization enforced by PolicyEnforcementMiddleware
var requestCtx = req.GetRequestContext();
if (string.IsNullOrWhiteSpace(submissionId)) return await req.BadRequestAsync("submissionId is required.");
bool withdrawn;
try
{
// A foreign tenant's submission answers 404 for a non-GA — the row's existence is not theirs to learn.
withdrawn = await _service.WithdrawAsync(requestCtx.TenantId, submissionId, crossTenantAllowed: requestCtx.IsGlobalAdmin);
}
catch (InvalidOperationException ex)
{
return await req.ConflictAsync(ex.Message);
}
if (!withdrawn) return await req.NotFoundAsync("Submission not found.");
_logger.LogInformation("Rule submission {SubmissionId} withdrawn by {User}", submissionId, requestCtx.UserPrincipalName);
return await req.OkAsync(new SuccessMessageResponse { Success = true, Message = "Submission withdrawn." });
}
catch (Exception ex)
{
return await req.InternalServerErrorAsync(_logger, ex, "WithdrawRuleSubmission");
}
}
}
}
@@ -10,8 +10,8 @@ public static class MetricsMath
/// <summary>
/// App-install failure rate over finished installs only: Failed / (Failed + Succeeded), one
/// decimal, 0 when nothing finished. The same outcome-quota convention as the enrollment
/// success rate — "InProgress" rows (still installing, or orphaned by a session that died
/// mid-install) never dilute the rate. Shared by the app-metrics payload and the Apps
/// success rate — "InProgress" rows (still installing) and "Incomplete" rows (observation
/// ended before any outcome) never dilute the rate. Shared by the app-metrics payload and the Apps
/// dashboard aggregations so the definition can't drift between panes.
/// </summary>
public static double TerminalFailureRatePct(int failed, int succeeded)
@@ -94,6 +94,8 @@ public static class MetricsMath
var installed = succeededAll.Where(s => !IsSkipTerminalState(s)).ToList();
var measured = installed.Where(HasMeasuredDuration).ToList();
var failed = g.Where(s => s.Status == "Failed").ToList();
// Observation ended before any outcome — disclosed, outside the rate and the durations.
var incomplete = g.Count(s => s.Status == "Incomplete");
var total = g.Count();
// DoAggregator is the single source for the DO rollup: it filters rows that actually
@@ -109,6 +111,7 @@ public static class MetricsMath
Skipped = skipped.Count,
Unmeasured = installed.Count - measured.Count,
Failed = failed.Count,
Incomplete = incomplete,
// Skips leave the rate (they are not attempts); legacy rows stay in it.
FailureRate = TerminalFailureRatePct(failed.Count, installed.Count),
AvgDurationSeconds = measured.Count > 0 ? Math.Round(measured.Average(s => s.DurationSeconds), 0) : 0,
@@ -151,6 +154,7 @@ public static class MetricsMath
TotalInstalls = summaryList.Count,
TotalSkipped = appGroups.Sum(a => a.Skipped),
TotalUnmeasured = appGroups.Sum(a => a.Unmeasured),
TotalIncomplete = appGroups.Sum(a => a.Incomplete),
TotalCollisionExcluded = totalCollisionExcluded,
SlowestApps = slowestApps,
TopFailingApps = topFailingApps,
@@ -0,0 +1,92 @@
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Text;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Shared.Pagination;
namespace AutopilotMonitor.Functions.Pagination
{
/// <summary>
/// Pure helpers for the <c>GET /api/global/rule-submissions</c> pagination surface — the
/// SessionReportsPagination contract with a second server-side filter (<c>status</c>). Both
/// filters are bound into the continuation fingerprint so a token issued for one view cannot
/// resume another.
/// </summary>
public static class RuleSubmissionsPagination
{
public const int DefaultPageSize = 200;
public static string Fingerprint(string callerTenantId, string? filterTenantId, string? filterStatus) =>
ContinuationToken.ComputeFingerprint(new[]
{
new KeyValuePair<string, string?>("scope", "rule-submissions"),
new KeyValuePair<string, string?>("tenantId", callerTenantId),
new KeyValuePair<string, string?>("filterTenantId", filterTenantId),
new KeyValuePair<string, string?>("filterStatus", filterStatus),
});
public sealed class Parsed
{
public string? FilterTenantId { get; init; }
public string? FilterStatus { get; init; }
public int? PageSize { get; init; }
public string? Continuation { get; init; }
public string? Error { get; init; }
}
public static Parsed ParseQuery(NameValueCollection? query)
{
var filterTenantIdRaw = query?["tenantId"];
var filterStatusRaw = query?["status"];
var pageSizeRaw = query?["pageSize"];
var continuationRaw = query?["continuation"];
if (!QueryParams.TryPageSize(pageSizeRaw, out var pageSize, out var pageSizeError))
return new Parsed { Error = pageSizeError };
if (!string.IsNullOrEmpty(filterStatusRaw)
&& System.Array.IndexOf(Shared.Models.RuleSubmissionStatuses.Stored, filterStatusRaw) < 0)
{
return new Parsed { Error = $"status must be one of: {string.Join(", ", Shared.Models.RuleSubmissionStatuses.Stored)}" };
}
var continuation = pageSize.HasValue && !string.IsNullOrEmpty(continuationRaw)
? continuationRaw
: null;
return new Parsed
{
FilterTenantId = string.IsNullOrEmpty(filterTenantIdRaw) ? null : filterTenantIdRaw,
FilterStatus = string.IsNullOrEmpty(filterStatusRaw) ? null : filterStatusRaw,
PageSize = pageSize,
Continuation = continuation,
};
}
public static bool TryAcceptContinuation(
string raw,
string callerTenantId,
string? filterTenantId,
string? filterStatus,
out string azureToken,
out string? rejectReason)
{
var fp = Fingerprint(callerTenantId, filterTenantId, filterStatus);
return ContinuationToken.TryDecode(raw, callerTenantId, fp, out azureToken, out rejectReason);
}
public static string BuildNextLink(int pageSize, string wireContinuation, string? filterTenantId, string? filterStatus)
{
var sb = new StringBuilder("/api/global/rule-submissions");
sb.Append('?');
sb.Append("pageSize=").Append(pageSize.ToString(CultureInfo.InvariantCulture));
sb.Append("&continuation=").Append(System.Uri.EscapeDataString(wireContinuation));
if (!string.IsNullOrEmpty(filterTenantId))
sb.Append("&tenantId=").Append(System.Uri.EscapeDataString(filterTenantId!));
if (!string.IsNullOrEmpty(filterStatus))
sb.Append("&status=").Append(System.Uri.EscapeDataString(filterStatus!));
return sb.ToString();
}
}
}
@@ -318,6 +318,7 @@ builder.Services.AddSingleton<AutopilotMonitor.Functions.Services.Diagnostics.Di
builder.Services.AddSingleton<AutopilotMonitor.Functions.Services.Diagnostics.DiagnosticsBlobCascadeDeleter>();
builder.Services.AddSingleton<AutopilotMonitor.Functions.Services.Diagnostics.SessionReportDiagnosticsArchiveCopier>();
builder.Services.AddSingleton<SessionReportService>();
builder.Services.AddSingleton<RuleSubmissionService>();
builder.Services.AddSingleton<BootstrapSessionService>();
// Queue producers + handlers. Consumers are [QueueTrigger] functions under Functions/Queue/
@@ -354,6 +354,11 @@ public static class EndpointAccessPolicyCatalog
// troubleshooting action, not a config change — a support-driven Operator may use it.
// Viewer and the read-only Global Reader stay excluded (the tier admits no Viewer/Reader).
new("POST", "diagnostics/files", EndpointPolicy.TenantAdminOrOperator),
// Community rule submissions: the tenant admin submits references to own custom rules
// (frozen server-side), lists and withdraws them for the JWT tenant only.
new("POST", "rules/submissions", EndpointPolicy.TenantAdminOrGA),
new("GET", "rules/submissions", EndpointPolicy.TenantAdminOrGA),
new("DELETE", "rules/submissions/{submissionId}", EndpointPolicy.TenantAdminOrGA),
new("DELETE", "sessions/{sessionId}", EndpointPolicy.TenantAdminOrGA, TenantScoping.QueryParam),
new("GET", "tenants/{tenantId}/admins", EndpointPolicy.TenantAdminOrGA, TenantScoping.RouteParam),
new("POST", "tenants/{tenantId}/admins", EndpointPolicy.TenantAdminOrGA, TenantScoping.RouteParam),
@@ -513,6 +518,11 @@ public static class EndpointAccessPolicyCatalog
new("POST", "global/session-reports/download-ticket", EndpointPolicy.GlobalReadOrAdmin),
new("GET", "global/session-reports/download-url", EndpointPolicy.GlobalReadOrAdmin),
new("PATCH", "global/session-reports/{reportId}/note", EndpointPolicy.GlobalAdminOnly),
// Community rule submissions, operator side: cross-tenant read (Global Reader included), decision GA-only.
new("GET", "global/rule-submissions", EndpointPolicy.GlobalReadOrAdmin, TenantScoping.QueryParam),
new("GET", "global/rule-submissions/{submissionId}", EndpointPolicy.GlobalReadOrAdmin),
new("PATCH", "global/rule-submissions/{submissionId}", EndpointPolicy.GlobalAdminOnly),
new("DELETE", "global/rule-submissions/{submissionId}", EndpointPolicy.GlobalAdminOnly),
// Flywheel evaluation stream: all annotation lanes across tenants (verdict/rule filters).
new("GET", "global/session-annotations", EndpointPolicy.GlobalReadOrAdmin, TenantScoping.QueryParam),
new("GET", "global/rules/gather", EndpointPolicy.GlobalReadOrAdmin, TenantScoping.QueryParam),
@@ -322,6 +322,16 @@ namespace AutopilotMonitor.Functions.Services
rule.Notify = null;
}
var existing = (await _ruleRepo.GetAnalyzeRulesAsync(tenantId))
.FirstOrDefault(r => r.RuleId == rule.RuleId && !r.IsBuiltIn && !r.IsCommunity);
if (existing != null)
{
rule.CreatedAt = existing.CreatedAt;
// Author is stamped from the creator's token at create time and is
// immutable afterwards — updates (incl. cross-tenant GA edits) keep it.
rule.Author = existing.Author;
}
rule.UpdatedAt = DateTime.UtcNow;
return await _ruleRepo.StoreAnalyzeRuleAsync(rule, tenantId);
}
@@ -333,7 +343,8 @@ namespace AutopilotMonitor.Functions.Services
public async Task<AnalyzeRule> CreateFromTemplateAsync(
string tenantId,
string templateRuleId,
Dictionary<string, string> variableValues)
Dictionary<string, string> variableValues,
string? author = null)
{
var allRules = await GetAllRulesForTenantAsync(tenantId);
var template = allRules.FirstOrDefault(r => r.RuleId == templateRuleId);
@@ -370,6 +381,8 @@ namespace AutopilotMonitor.Functions.Services
customRule.RuleId = $"{templateRuleId}-CUSTOM";
customRule.IsBuiltIn = false;
customRule.IsCommunity = false;
// The copy is the tenant's rule, not the template author's.
customRule.Author = string.IsNullOrWhiteSpace(author) ? "Autopilot Monitor" : author!;
customRule.Enabled = true;
customRule.DerivedFromTemplateRuleId = templateRuleId;
customRule.TemplateVariables = new List<TemplateVariable>();
@@ -92,6 +92,9 @@ namespace AutopilotMonitor.Functions.Services
classification.HasCompletionEvidenceCandidate = true;
break;
case "agent_shutting_down":
// Every shutdown ends this agent run's observation; the max-lifetime
// flavour additionally carries the verdict mapping below.
classification.AgentShutdownEvent = evt;
if (IsMaxLifetimeAgentShutdown(evt))
classification.AgentMaxLifetimeShutdownEvent = evt;
break;
@@ -705,6 +708,14 @@ namespace AutopilotMonitor.Functions.Services
public EnrollmentEvent? EspFailureEvent { get; set; }
public EnrollmentEvent? SessionStalledEvent { get; set; }
/// <summary>
/// Any <c>agent_shutting_down</c> in the batch — the agent's last word for this run.
/// After the status write, a terminal session closes its still-open app rows on this
/// batch: apps that started after the verdict (the agent keeps watching after
/// enrollment_complete) got their row only after the terminal seam had already run.
/// </summary>
public EnrollmentEvent? AgentShutdownEvent { get; set; }
/// <summary>
/// <c>agent_shutting_down</c> with <c>Data.reason == "max_lifetime"</c> — the V2
/// watchdog shutdown that deliberately carries no enrollment verdict. Mapped to a
@@ -276,6 +276,21 @@ namespace AutopilotMonitor.Functions.Services
updatedSession?.AgentVersion, skewScan);
}
// Observation end: the batch carrying agent_shutting_down is the agent's last word.
// On a terminal session an app row still InProgress now will never get a terminal
// event — close it as Incomplete. The terminal seam already did this on the verdict
// batch; this re-run catches rows opened after the verdict (the IME keeps installing
// and the agent keeps watching after enrollment_complete). Non-terminal sessions
// (reboot shutdown, WhiteGlove part 1) keep their rows open. Idempotent + fail-soft.
if (classification.AgentShutdownEvent != null
&& updatedSession != null
&& (updatedSession.Status == SessionStatus.Succeeded
|| updatedSession.Status == SessionStatus.Failed
|| updatedSession.Status == SessionStatus.Incomplete))
{
await _metricsRepo.CloseOpenAppInstallsForSessionAsync(request.TenantId, request.SessionId);
}
// Auto-analyze fan-out: enqueue a queue message instead of running fire-and-forget
// Task.Run inside the function. The previous in-function approach could be killed
// mid-flight by Functions scale-in (HTTP 200 returned → worker unloaded → rules
@@ -328,7 +328,12 @@ namespace AutopilotMonitor.Functions.Services
// Idempotent, positive-evidence-only; also heals sessions that went
// terminal before the resolution seam existed (hadNoRow backfill).
if (eventCountMoved || hadNoRow)
{
await _metricsRepo.ResolveEspBlockingForSessionAsync(session.TenantId, session.SessionId);
// Same late-batch reasoning: an app row opened after the agent's
// shutdown batch was never closed — the sweep is its self-heal.
await _metricsRepo.CloseOpenAppInstallsForSessionAsync(session.TenantId, session.SessionId);
}
}
if (breakdown == null)
@@ -1045,6 +1050,20 @@ namespace AutopilotMonitor.Functions.Services
_logger.LogWarning(ex, "Failed to cleanup old tenant notifications");
}
try
{
// Closed community rule submissions: withdrawn 30d, declined 90d (RuleSubmissionRetention);
// pending/approved/published rows are never swept.
var deleted = await _ruleSubmissionRepo.DeleteExpiredAsync(now);
if (deleted > 0)
_logger.LogInformation("Rule submissions cleanup: deleted {Count} closed rows (withdrawn {WithdrawnDays}d / declined {DeclinedDays}d)",
deleted, RuleSubmissionRetention.WithdrawnDays, RuleSubmissionRetention.DeclinedDays);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to cleanup closed rule submissions");
}
try
{
var deleted = await _hardwareRejectionTracker.DeleteOlderThanAsync(now.AddDays(-hardwareRejectionRetentionDays));
@@ -41,6 +41,7 @@ namespace AutopilotMonitor.Functions.Services
private readonly INotificationRepository _notificationRepo;
private readonly ITenantNotificationRepository _tenantNotificationRepo;
private readonly IHardwareRejectionNotificationTracker _hardwareRejectionTracker;
private readonly IRuleSubmissionRepository _ruleSubmissionRepo;
private readonly IDelegationInvitationRepository _delegationInvitationRepo;
private readonly DataAccess.TableStorage.BackupJobsRepository _backupJobsRepo;
private readonly OpsEventService _opsEventService;
@@ -75,6 +76,7 @@ namespace AutopilotMonitor.Functions.Services
INotificationRepository notificationRepo,
ITenantNotificationRepository tenantNotificationRepo,
IHardwareRejectionNotificationTracker hardwareRejectionTracker,
IRuleSubmissionRepository ruleSubmissionRepo,
IDelegationInvitationRepository delegationInvitationRepo,
DataAccess.TableStorage.BackupJobsRepository backupJobsRepo,
OpsEventService opsEventService,
@@ -103,6 +105,7 @@ namespace AutopilotMonitor.Functions.Services
_opsEventRepo = opsEventRepo;
_notificationRepo = notificationRepo;
_tenantNotificationRepo = tenantNotificationRepo;
_ruleSubmissionRepo = ruleSubmissionRepo;
_hardwareRejectionTracker = hardwareRejectionTracker;
_delegationInvitationRepo = delegationInvitationRepo;
_backupJobsRepo = backupJobsRepo;
@@ -141,6 +141,7 @@ namespace AutopilotMonitor.Functions.Services.Offboarding
{
(Constants.TableNames.BootstrapSessions, "CodeLookup"),
(Constants.TableNames.SessionReports, "reports"),
(Constants.TableNames.RuleSubmissions, "submissions"),
};
// Plan §6.3.2 — Variant C (TenantId property only).
@@ -0,0 +1,559 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using AutopilotMonitor.Functions.Functions.Rules;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Shared.DataAccess;
using AutopilotMonitor.Shared.Models;
using AutopilotMonitor.Shared.Pagination;
using Microsoft.Extensions.Logging;
namespace AutopilotMonitor.Functions.Services
{
/// <summary>
/// Community rule submissions: freezes a tenant's custom rule at submit time, records the
/// pre-flight findings and fire telemetry, and carries the review through to the repo file.
/// Publishing itself is a repository commit plus reseed — this service never writes the
/// global rule partition; <c>published</c> is derived from the catalog on every read.
/// </summary>
public class RuleSubmissionService
{
public const int MaxRuleJsonLength = 32_000;
public const int MaxSubmissionsPerTenantPerDay = 10;
public const int FireStatsDays = 30;
/// <summary>The credit text is published in the repo, so it is a name and nothing else.</summary>
private static readonly Regex AttributionNameShape = new(@"^[\p{L}\p{N} .,'&()\-]{1,64}$", RegexOptions.CultureInvariant);
/// <summary>Rule fields that belong to the server or the tenant, never to a frozen or published rule.</summary>
private static readonly string[] StrippedFields =
{
"isBuiltIn", "provenance", "createdAt", "updatedAt",
"markSessionAsFailed", "notifyDefault", "notify", "notifyChannelIds",
};
private static readonly JsonSerializerOptions RepoFileOptions = new()
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};
// The dominant convention per kind in rules/ (ANALYZE-APP vs GATHER-APPS …); an unmapped
// category falls back to its upper-cased name, which the reviewer can overrule.
private static readonly Dictionary<string, string> AnalyzeCategoryCodes = new(StringComparer.OrdinalIgnoreCase)
{
["apps"] = "APP", ["device"] = "DEV", ["enrollment"] = "ENRL", ["esp"] = "ESP",
["identity"] = "ID", ["network"] = "NET", ["security"] = "SEC",
};
private static readonly Dictionary<string, string> GatherCategoryCodes = new(StringComparer.OrdinalIgnoreCase)
{
["apps"] = "APPS", ["device"] = "DEVICE", ["enrollment"] = "ENROLL", ["esp"] = "ESP",
["identity"] = "ID", ["network"] = "NET",
};
private readonly IRuleSubmissionRepository _submissions;
private readonly IRuleRepository _ruleRepo;
private readonly IMetricsRepository _metricsRepo;
private readonly TenantConfigurationService _configService;
private readonly ILogger<RuleSubmissionService> _logger;
public RuleSubmissionService(
IRuleSubmissionRepository submissions,
IRuleRepository ruleRepo,
IMetricsRepository metricsRepo,
TenantConfigurationService configService,
ILogger<RuleSubmissionService> logger)
{
_submissions = submissions;
_ruleRepo = ruleRepo;
_metricsRepo = metricsRepo;
_configService = configService;
_logger = logger;
}
// ── Submit ──────────────────────────────────────────────────────────────
/// <summary>
/// Freezes and stores every referenced rule. All-or-nothing: a pre-flight error on any
/// item rejects the whole batch (<see cref="ArgumentException"/>), so a tenant never ends
/// up with half a submission. <see cref="InvalidOperationException"/> = conflict (open
/// duplicate, daily cap).
/// </summary>
public async Task<List<RuleSubmission>> SubmitAsync(
string tenantId, SubmitRuleSubmissionsRequest request, string submittedBy, string submittedByName)
{
if (request.Items == null || request.Items.Count == 0)
throw new ArgumentException("At least one rule is required.");
if (request.Items.Count > SubmitRuleSubmissionsRequest.MaxItems)
throw new ArgumentException($"At most {SubmitRuleSubmissionsRequest.MaxItems} rules per submission.");
if (request.Comment != null && request.Comment.Length > SubmitRuleSubmissionsRequest.MaxCommentLength)
throw new ArgumentException($"Comment exceeds {SubmitRuleSubmissionsRequest.MaxCommentLength} characters.");
var attributionName = await ResolveAttributionNameAsync(tenantId, request.AttributionMode, request.AttributionName);
var contactEmail = NormalizeEmail(request.Email);
var distinct = request.Items
.Select(i => (Kind: i.Kind?.Trim().ToLowerInvariant() ?? string.Empty, RuleId: i.RuleId?.Trim() ?? string.Empty))
.Distinct()
.ToList();
foreach (var (kind, ruleId) in distinct)
{
if (!RuleSubmissionKinds.IsKnown(kind))
throw new ArgumentException($"Unknown rule kind '{kind}'.");
if (string.IsNullOrEmpty(ruleId))
throw new ArgumentException("ruleId is required for every item.");
}
var existing = await _submissions.GetForTenantAsync(tenantId);
var since = DateTime.UtcNow.AddDays(-1);
if (existing.Count(s => s.SubmittedAt >= since) + distinct.Count > MaxSubmissionsPerTenantPerDay)
throw new InvalidOperationException($"At most {MaxSubmissionsPerTenantPerDay} rule submissions per tenant and day.");
var analyzeRules = distinct.Any(d => d.Kind == RuleSubmissionKinds.Analyze)
? await _ruleRepo.GetAnalyzeRulesAsync(tenantId) : new List<AnalyzeRule>();
var gatherRules = distinct.Any(d => d.Kind == RuleSubmissionKinds.Gather)
? await _ruleRepo.GetGatherRulesAsync(tenantId) : new List<GatherRule>();
var now = DateTime.UtcNow;
var batchId = NewId();
var prepared = new List<RuleSubmission>(distinct.Count);
var errors = new List<string>();
foreach (var (kind, ruleId) in distinct)
{
if (existing.Any(s => s.Status == RuleSubmissionStatuses.Pending
&& s.RuleKind == kind
&& string.Equals(s.SourceRuleId, ruleId, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"Rule '{ruleId}' already has a pending submission.");
var submission = new RuleSubmission
{
SubmissionId = NewId(),
BatchId = batchId,
TenantId = tenantId,
RuleKind = kind,
SourceRuleId = ruleId,
Comment = string.IsNullOrWhiteSpace(request.Comment) ? null : request.Comment!.Trim(),
SubmittedBy = submittedBy,
SubmittedByName = submittedByName,
ContactEmail = contactEmail,
AttributionMode = request.AttributionMode,
AttributionName = attributionName,
SubmittedAt = now,
Status = RuleSubmissionStatuses.Pending,
};
var findings = new List<RuleSubmissionFinding>();
if (kind == RuleSubmissionKinds.Analyze)
{
var rule = analyzeRules.FirstOrDefault(r => string.Equals(r.RuleId, ruleId, StringComparison.OrdinalIgnoreCase)
&& !r.IsBuiltIn && !r.IsCommunity);
if (rule == null) { errors.Add($"{ruleId}: not a custom analyze rule of this tenant."); continue; }
submission.Title = rule.Title ?? string.Empty;
submission.Category = rule.Category ?? string.Empty;
submission.DerivedFromTemplateRuleId = rule.DerivedFromTemplateRuleId;
submission.RuleJson = FreezeRule(rule);
foreach (var e in DryRunAnalyzeRuleFunction.ValidateDraftRule(rule))
findings.Add(new RuleSubmissionFinding { Level = "error", Message = e });
if (!string.IsNullOrEmpty(rule.DerivedFromTemplateRuleId))
findings.Add(new RuleSubmissionFinding { Level = "info", Message = $"Derived from template {rule.DerivedFromTemplateRuleId} — usually a filled-in copy rather than a new detection." });
}
else
{
var rule = gatherRules.FirstOrDefault(r => string.Equals(r.RuleId, ruleId, StringComparison.OrdinalIgnoreCase)
&& !r.IsBuiltIn && !r.IsCommunity);
if (rule == null) { errors.Add($"{ruleId}: not a custom gather rule of this tenant."); continue; }
submission.Title = rule.Title ?? string.Empty;
submission.Category = rule.Category ?? string.Empty;
submission.RuleJson = FreezeRule(rule);
if (string.IsNullOrWhiteSpace(rule.CollectorType)) findings.Add(new RuleSubmissionFinding { Level = "error", Message = "collectorType is required" });
if (string.IsNullOrWhiteSpace(rule.Target)) findings.Add(new RuleSubmissionFinding { Level = "error", Message = "target is required" });
if (string.IsNullOrWhiteSpace(rule.Trigger)) findings.Add(new RuleSubmissionFinding { Level = "error", Message = "trigger is required" });
if (string.IsNullOrWhiteSpace(rule.OutputEventType)) findings.Add(new RuleSubmissionFinding { Level = "error", Message = "outputEventType is required" });
var scopeError = GatherRulesFunction.ValidateScopeAndEmitMode(rule);
if (scopeError != null) findings.Add(new RuleSubmissionFinding { Level = "error", Message = scopeError });
findings.Add(new RuleSubmissionFinding { Level = "info", Message = "Collector guardrails are enforced on the device; the full allowlist check runs in the MCP validate_rule tool." });
}
if (submission.RuleJson.Length > MaxRuleJsonLength)
findings.Add(new RuleSubmissionFinding { Level = "error", Message = $"rule document exceeds {MaxRuleJsonLength} characters" });
var itemErrors = findings.Where(f => f.Level == "error").Select(f => $"{ruleId}: {f.Message}").ToList();
if (itemErrors.Count > 0) { errors.AddRange(itemErrors); continue; }
submission.ValidationFindings = findings;
submission.SourceFireStats = await GetFireStatsAsync(tenantId, kind, ruleId);
prepared.Add(submission);
}
if (errors.Count > 0)
throw new ArgumentException("Submission rejected: " + string.Join(" | ", errors));
foreach (var submission in prepared)
{
if (!await _submissions.AddAsync(submission))
throw new InvalidOperationException("Failed to store the submission.");
}
return prepared;
}
private async Task<string> ResolveAttributionNameAsync(string tenantId, string? mode, string? requestedName)
{
switch (mode)
{
case RuleAttributionModes.Anonymous:
return RuleAttributionModes.AnonymousAuthor;
case RuleAttributionModes.Organization:
{
var config = await _configService.GetConfigurationIfExistsAsync(tenantId);
var name = config?.CompanyName;
if (string.IsNullOrWhiteSpace(name)) name = config?.DomainName;
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("No organization name is known for this tenant — set the company name in the tenant settings or choose another attribution.");
return ValidateAttributionName(name!.Trim());
}
case RuleAttributionModes.Person:
if (string.IsNullOrWhiteSpace(requestedName))
throw new ArgumentException("attributionName is required for the person attribution.");
return ValidateAttributionName(requestedName!.Trim());
default:
throw new ArgumentException($"attributionMode must be one of: {string.Join(", ", RuleAttributionModes.All)}.");
}
}
/// <summary>Trimmed, or null when empty; the shape check is deliberately loose (exactly one @ with something on both sides, no whitespace, at most 254 characters).</summary>
internal static string? NormalizeEmail(string? email)
{
var trimmed = email?.Trim();
if (string.IsNullOrEmpty(trimmed)) return null;
var at = trimmed!.IndexOf('@');
if (trimmed.Length > SubmitRuleSubmissionsRequest.MaxEmailLength
|| at <= 0
|| at != trimmed.LastIndexOf('@')
|| at == trimmed.Length - 1
|| trimmed.Any(char.IsWhiteSpace))
throw new ArgumentException("email is not a valid address.");
return trimmed;
}
internal static string ValidateAttributionName(string name)
{
if (!AttributionNameShape.IsMatch(name))
throw new ArgumentException("attributionName may only contain letters, digits, spaces and . , ' & ( ) - (1–64 characters).");
return name;
}
/// <summary>Wire JSON of the rule minus server and tenant fields — what the reviewer sees and what ships.</summary>
internal static string FreezeRule<T>(T rule)
{
var node = JsonSerializer.SerializeToNode(rule, ApiJsonOptions.Create()) as JsonObject
?? throw new InvalidOperationException("Rule did not serialize to an object.");
foreach (var field in StrippedFields) node.Remove(field);
return node.ToJsonString();
}
private async Task<RuleSubmissionFireStats?> GetFireStatsAsync(string tenantId, string kind, string ruleId)
{
try
{
var end = DateTime.UtcNow;
var start = end.AddDays(-FireStatsDays);
var entries = await _metricsRepo.GetRuleStatsAsync(
tenantId, start.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
end.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), kind);
var mine = entries.Where(e => string.Equals(e.RuleId, ruleId, StringComparison.OrdinalIgnoreCase)).ToList();
return new RuleSubmissionFireStats
{
Days = FireStatsDays,
FireCount = mine.Sum(e => e.FireCount),
SessionsEvaluated = mine.Sum(e => e.SessionsEvaluated),
EvaluationCount = mine.Sum(e => e.EvaluationCount),
};
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Fire stats unavailable for {RuleId} (tenant {TenantId})", ruleId, tenantId);
return null;
}
}
// ── Read ────────────────────────────────────────────────────────────────
public Task<RuleSubmission?> GetAsync(string submissionId) => _submissions.GetAsync(submissionId);
public Task<List<RuleSubmission>> GetForTenantAsync(string tenantId) => _submissions.GetForTenantAsync(tenantId);
public Task<RawPage<RuleSubmission>> GetPageAsync(string? tenantId, string? status, int pageSize, string? continuation)
=> _submissions.GetPageAsync(tenantId, status, pageSize, continuation);
/// <summary>Projects rows to the wire shape with the effective status (<c>published</c> derived from the catalog).</summary>
public async Task<List<RuleSubmissionItem>> ToItemsAsync(IEnumerable<RuleSubmission> rows)
{
var list = rows.ToList();
HashSet<string>? globalAnalyze = null, globalGather = null;
if (list.Any(s => s.Status == RuleSubmissionStatuses.Approved && !string.IsNullOrEmpty(s.PublishedRuleId)))
{
globalAnalyze = (await _ruleRepo.GetAnalyzeRulesAsync("global")).Select(r => r.RuleId).ToHashSet(StringComparer.OrdinalIgnoreCase);
globalGather = (await _ruleRepo.GetGatherRulesAsync("global")).Select(r => r.RuleId).ToHashSet(StringComparer.OrdinalIgnoreCase);
}
return list.Select(s => ToItem(s, IsPublished(s, globalAnalyze, globalGather))).ToList();
}
private static bool IsPublished(RuleSubmission s, HashSet<string>? globalAnalyze, HashSet<string>? globalGather)
{
if (s.Status != RuleSubmissionStatuses.Approved || string.IsNullOrEmpty(s.PublishedRuleId)) return false;
var set = s.RuleKind == RuleSubmissionKinds.Analyze ? globalAnalyze : globalGather;
return set != null && set.Contains(s.PublishedRuleId!);
}
internal static RuleSubmissionItem ToItem(RuleSubmission s, bool published) => new()
{
SubmissionId = s.SubmissionId,
BatchId = s.BatchId,
TenantId = s.TenantId,
RuleKind = s.RuleKind,
SourceRuleId = s.SourceRuleId,
Title = s.Title,
Category = s.Category,
Comment = s.Comment,
SubmittedBy = s.SubmittedBy,
SubmittedByName = s.SubmittedByName,
ContactEmail = s.ContactEmail,
AttributionMode = s.AttributionMode,
AttributionName = s.AttributionName,
SubmittedAt = s.SubmittedAt,
Status = published ? RuleSubmissionStatuses.Published : s.Status,
ValidationFindings = s.ValidationFindings,
SourceFireStats = s.SourceFireStats,
ReviewedBy = s.ReviewedBy,
ReviewedAt = s.ReviewedAt,
ReviewComment = s.ReviewComment,
WillBeAdapted = s.WillBeAdapted,
PublishedRuleId = s.PublishedRuleId,
DerivedFromTemplateRuleId = s.DerivedFromTemplateRuleId,
};
/// <summary>Everything the reviewer (human or AI) needs for one submission.</summary>
public async Task<RuleSubmissionDetailResponse?> GetDetailAsync(string submissionId)
{
var s = await _submissions.GetAsync(submissionId);
if (s == null) return null;
var item = (await ToItemsAsync(new[] { s }))[0];
var response = new RuleSubmissionDetailResponse { Success = true, Submission = item };
if (s.RuleKind == RuleSubmissionKinds.Analyze)
{
var rule = JsonSerializer.Deserialize<AnalyzeRule>(s.RuleJson, ApiJsonOptions.Read);
if (rule != null) { rule.IsBuiltIn = false; rule.IsCommunity = false; }
response.AnalyzeRule = rule;
}
else
{
var rule = JsonSerializer.Deserialize<GatherRule>(s.RuleJson, ApiJsonOptions.Read);
if (rule != null) { rule.IsBuiltIn = false; rule.IsCommunity = false; }
response.GatherRule = rule;
}
response.LiveFireStats = await GetFireStatsAsync(s.TenantId, s.RuleKind, s.SourceRuleId);
response.SuggestedPublishedRuleId = s.PublishedRuleId ?? await SuggestPublishedRuleIdAsync(s.RuleKind, s.Category);
var fileId = s.PublishedRuleId ?? response.SuggestedPublishedRuleId;
if (!string.IsNullOrEmpty(fileId))
response.RepoFile = BuildRepoFile(s, fileId!);
return response;
}
// ── Review ──────────────────────────────────────────────────────────────
/// <summary>
/// Applies a reviewer decision. Transitions: pending → approved | declined; approved → declined
/// while not yet published. <see cref="KeyNotFoundException"/> = unknown id,
/// <see cref="ArgumentException"/> = bad input, <see cref="InvalidOperationException"/> = conflict.
/// </summary>
public async Task<RuleSubmission> ReviewAsync(string submissionId, ReviewRuleSubmissionRequest request, string reviewedBy)
{
var s = await _submissions.GetAsync(submissionId) ?? throw new KeyNotFoundException("Submission not found.");
var comment = string.IsNullOrWhiteSpace(request.ReviewComment) ? null : request.ReviewComment!.Trim();
if (comment != null && comment.Length > ReviewRuleSubmissionRequest.MaxReviewCommentLength)
throw new ArgumentException($"reviewComment exceeds {ReviewRuleSubmissionRequest.MaxReviewCommentLength} characters.");
var published = (await ToItemsAsync(new[] { s }))[0].Status == RuleSubmissionStatuses.Published;
if (published)
throw new InvalidOperationException("The rule is already published; the submission is final.");
if (s.Status == RuleSubmissionStatuses.Withdrawn)
throw new InvalidOperationException("The submitter withdrew this submission.");
switch (request.Decision)
{
case RuleSubmissionDecisions.Approve:
{
if (s.Status != RuleSubmissionStatuses.Pending)
throw new InvalidOperationException($"Only a pending submission can be approved (status: {s.Status}).");
var publishedRuleId = request.PublishedRuleId?.Trim();
if (string.IsNullOrEmpty(publishedRuleId))
throw new ArgumentException("publishedRuleId is required to approve.");
await ValidatePublishedRuleIdAsync(s, publishedRuleId!);
s.Status = RuleSubmissionStatuses.Approved;
s.PublishedRuleId = publishedRuleId;
s.WillBeAdapted = request.WillBeAdapted ?? false;
break;
}
case RuleSubmissionDecisions.Decline:
{
if (s.Status != RuleSubmissionStatuses.Pending && s.Status != RuleSubmissionStatuses.Approved)
throw new InvalidOperationException($"Cannot decline a submission in status {s.Status}.");
if (comment == null)
throw new ArgumentException("reviewComment is required to decline — the submitter sees it.");
s.Status = RuleSubmissionStatuses.Declined;
s.PublishedRuleId = null;
s.WillBeAdapted = false;
break;
}
default:
throw new ArgumentException($"decision must be one of: {string.Join(", ", RuleSubmissionDecisions.All)}.");
}
s.ReviewComment = comment;
s.ReviewedBy = reviewedBy;
s.ReviewedAt = DateTime.UtcNow;
if (!await _submissions.UpdateAsync(s))
throw new InvalidOperationException("The submission changed underneath this review; reload and retry.");
return s;
}
private async Task ValidatePublishedRuleIdAsync(RuleSubmission s, string publishedRuleId)
{
var kindPrefix = s.RuleKind == RuleSubmissionKinds.Analyze ? "ANALYZE-" : "GATHER-";
if (!RuleIdPolicy.IsReservedBuiltInId(publishedRuleId)
|| !publishedRuleId.StartsWith(kindPrefix, StringComparison.OrdinalIgnoreCase)
|| !Regex.IsMatch(publishedRuleId, @"^[A-Z]+-[A-Z]+-\d{3}$"))
throw new ArgumentException($"publishedRuleId must be {kindPrefix}<CATEGORY>-<NNN> in the reserved built-in namespace (upper case, three digits).");
var taken = await GetTakenIdsAsync(s.RuleKind);
if (taken.Contains(publishedRuleId))
throw new InvalidOperationException($"Rule id '{publishedRuleId}' is already taken (catalog, global partition or another approved submission).");
}
/// <summary>Tenant-side withdrawal; only while pending. False when there is nothing to withdraw.</summary>
public async Task<bool> WithdrawAsync(string tenantId, string submissionId, bool crossTenantAllowed)
{
var s = await _submissions.GetAsync(submissionId);
if (s == null) return false;
if (!crossTenantAllowed && !string.Equals(s.TenantId, tenantId, StringComparison.OrdinalIgnoreCase)) return false;
if (s.Status != RuleSubmissionStatuses.Pending)
throw new InvalidOperationException($"Only a pending submission can be withdrawn (status: {s.Status}).");
s.Status = RuleSubmissionStatuses.Withdrawn;
return await _submissions.UpdateAsync(s);
}
/// <summary>
/// Operator hard delete — the row disappears from the operator list and the tenant's list
/// alike. Not part of normal operations: for test and demo submissions, or on a tenant's request.
/// </summary>
public Task<bool> DeleteAsync(string submissionId) => _submissions.DeleteAsync(submissionId);
/// <summary>Daily retention sweep of closed submissions (see <see cref="RuleSubmissionRetention"/>).</summary>
public Task<int> SweepExpiredAsync(DateTime nowUtc) => _submissions.DeleteExpiredAsync(nowUtc);
// ── Id suggestion + repo file ───────────────────────────────────────────
private async Task<HashSet<string>> GetTakenIdsAsync(string kind)
{
var taken = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (kind == RuleSubmissionKinds.Analyze)
{
foreach (var r in BuiltInAnalyzeRules.GetAll()) taken.Add(r.RuleId);
foreach (var r in await _ruleRepo.GetAnalyzeRulesAsync("global")) taken.Add(r.RuleId);
}
else
{
foreach (var r in BuiltInGatherRules.GetAll()) taken.Add(r.RuleId);
foreach (var r in await _ruleRepo.GetGatherRulesAsync("global")) taken.Add(r.RuleId);
}
foreach (var id in await _submissions.GetReservedPublishedRuleIdsAsync()) taken.Add(id);
return taken;
}
public async Task<string> SuggestPublishedRuleIdAsync(string kind, string category)
=> SuggestPublishedRuleId(kind, category, await GetTakenIdsAsync(kind));
/// <summary>
/// Max + 1 within <c>{KIND}-{CODE}-</c> over every taken id. Gaps are retired ids that may
/// return (RuleIdPolicy) and are never reused.
/// </summary>
internal static string SuggestPublishedRuleId(string kind, string category, IEnumerable<string> takenIds)
{
var codes = kind == RuleSubmissionKinds.Analyze ? AnalyzeCategoryCodes : GatherCategoryCodes;
var code = codes.TryGetValue(category ?? string.Empty, out var mapped)
? mapped
: Regex.Replace((category ?? "MISC").ToUpperInvariant(), "[^A-Z]", "");
if (code.Length == 0) code = "MISC";
var prefix = (kind == RuleSubmissionKinds.Analyze ? "ANALYZE-" : "GATHER-") + code + "-";
var max = 0;
foreach (var id in takenIds)
{
if (!id.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue;
if (int.TryParse(id.Substring(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out var n) && n > max)
max = n;
}
return prefix + (max + 1).ToString("D3", CultureInfo.InvariantCulture);
}
/// <summary>
/// The file that ships the rule: schema pointer first, the assigned id, the chosen credit,
/// <c>isCommunity</c>, and <c>enabled</c> after the built-in convention (analyze rules ship
/// on, gather rules opt-in because they cost device work). Lineage to the tenant's template
/// copy is dropped.
/// </summary>
internal static RuleSubmissionRepoFile BuildRepoFile(RuleSubmission s, string publishedRuleId)
{
var frozen = JsonNode.Parse(s.RuleJson) as JsonObject
?? throw new InvalidOperationException("Frozen rule is not an object.");
var isAnalyze = s.RuleKind == RuleSubmissionKinds.Analyze;
var ordered = new JsonObject
{
["$schema"] = isAnalyze ? "../schema/analyze-rule.schema.json" : "../schema/gather-rule.schema.json",
["ruleId"] = publishedRuleId,
};
foreach (var head in isAnalyze
? new[] { "title", "description", "severity", "category", "version" }
: new[] { "title", "description", "category", "version" })
{
if (frozen.TryGetPropertyValue(head, out var value)) ordered[head] = value?.DeepClone();
}
ordered["author"] = s.AttributionName;
ordered["enabled"] = isAnalyze;
ordered["isCommunity"] = true;
foreach (var kv in frozen)
{
if (ordered.ContainsKey(kv.Key)) continue;
if (kv.Key == "derivedFromTemplateRuleId") continue;
if (Array.IndexOf(StrippedFields, kv.Key) >= 0) continue;
ordered[kv.Key] = kv.Value?.DeepClone();
}
var folder = isAnalyze ? "analyze" : "gather";
return new RuleSubmissionRepoFile
{
Path = $"rules/{folder}/{publishedRuleId}.json",
Content = ordered.ToJsonString(RepoFileOptions) + "\n",
};
}
private static string NewId() => Guid.NewGuid().ToString("N").Substring(0, 12);
}
}
@@ -253,9 +253,11 @@ namespace AutopilotMonitor.Functions.Services
// Status "InProgress" — a real (non-sentinel) value that Merge-mode would
// happily write over a row the terminal batch already closed. Only another
// terminal observation may change a terminal status (Failed→Succeeded on a
// successful retry stays legal).
// successful retry stays legal). Incomplete (observation-end close step) is
// terminal for the same purpose: a straggling progress-only batch must not
// reopen it, while a real terminal observation still wins.
var existingStatus = existing.GetString("Status");
if ((existingStatus == "Succeeded" || existingStatus == "Failed") &&
if ((existingStatus == "Succeeded" || existingStatus == "Failed" || existingStatus == "Incomplete") &&
summary.Status != "Succeeded" && summary.Status != "Failed")
{
summary.Status = existingStatus;
@@ -525,6 +527,66 @@ namespace AutopilotMonitor.Functions.Services
return sets.Contains(appId);
}
/// <summary>
/// Closes the session's app rows that never reached a terminal state: Status
/// "InProgress" (or missing) with no CompletedAt becomes "Incomplete" — terminal,
/// non-failure, outcome unknown. Runs at the terminal seam, again after the batch that
/// carries the agent's shutdown (rows opened after the verdict), and from the 30-day
/// sweep. Idempotent + fail-soft; a real terminal arriving later still wins through the
/// sticky-status reconcile. Returns the number of rows closed.
/// </summary>
public async Task<int> CloseOpenAppInstallsForSessionAsync(string tenantId, string sessionId)
{
try
{
SecurityValidator.EnsureValidGuid(tenantId, nameof(tenantId));
SecurityValidator.EnsureValidGuid(sessionId, nameof(sessionId));
var tableClient = _tableServiceClient.GetTableClient(Constants.TableNames.AppInstallSummaries);
var filter = $"PartitionKey eq '{tenantId}' and RowKey ge '{sessionId}_' and RowKey lt '{sessionId}`'";
var query = tableClient.QueryAsync<TableEntity>(
filter: filter,
select: new[] { "PartitionKey", "RowKey", "Status", "CompletedAt" });
var closed = 0;
await foreach (var row in query)
{
if (!ShouldCloseAsIncomplete(row)) continue;
var update = new TableEntity(row.PartitionKey, row.RowKey)
{
["Status"] = "Incomplete"
};
await tableClient.UpsertEntityAsync(update, TableUpdateMode.Merge);
closed++;
}
if (closed > 0)
_logger.LogInformation(
"Session {SessionId}: closed {Count} app rows as Incomplete (no terminal state when observation ended)",
sessionId, closed);
return closed;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Closing open app rows failed for session {SessionId} (fail-soft)", sessionId);
return 0;
}
}
/// <summary>
/// Pure per-row predicate behind <see cref="CloseOpenAppInstallsForSessionAsync"/> —
/// internal static so the contract is pinned by unit tests: only a row that is still
/// open (Status missing, empty or "InProgress", no CompletedAt) closes; every terminal
/// row, including an already-closed Incomplete one, is left alone (idempotency).
/// </summary>
internal static bool ShouldCloseAsIncomplete(TableEntity row)
{
if (row.GetDateTimeOffset("CompletedAt").HasValue) return false;
var status = row.GetString("Status");
return string.IsNullOrEmpty(status) || status == "InProgress";
}
/// <summary>
/// Gets app install summaries for a tenant (fleet-level metrics). When <paramref name="sinceUtc"/>
/// is supplied, a server-side <c>StartedAt ge</c> filter is applied so a windowed view (e.g. the
@@ -104,6 +104,42 @@ namespace AutopilotMonitor.Functions.Services
}
}
/// <summary>
/// Sends a Telegram notification when a tenant admin submits a custom rule for the
/// community pool. The submission id comes first — it is the handle for the review.
/// Best-effort — silently no-ops if the webhook URL is not configured.
/// </summary>
public async Task SendRuleSubmissionAsync(string submissionId, string tenantId, string submittedBy, string ruleKind, string ruleId, string title, string comment)
{
try
{
var webhookUrl = await GetWebhookUrlAsync();
if (string.IsNullOrWhiteSpace(webhookUrl))
{
_logger.LogDebug("Telegram webhook URL not configured — skipping rule submission notification");
return;
}
var commentLine = string.IsNullOrWhiteSpace(comment) ? "" : $"\nComment: {comment}";
var payload = new
{
chat_id = "-1003632442830",
text = $"New Rule Submission {submissionId}\nRule: {ruleId} \"{title}\" ({ruleKind})\nTenantID: {tenantId}\nBy: {submittedBy}{commentLine}"
};
var json = JsonConvert.SerializeObject(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _http.PostAsync(webhookUrl, content);
if (response.IsSuccessStatusCode)
_logger.LogInformation("Telegram rule submission notification sent for {SubmissionId}", submissionId);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to send Telegram rule submission notification for {SubmissionId}", submissionId);
}
}
/// <summary>
/// Sends a Telegram notification when a tenant admin submits a diag-files-only report
/// (no session context). Best-effort — silently no-ops if the webhook URL is not configured.
@@ -35,6 +35,8 @@ public static class TenantNotificationAudienceCatalog
["rule_frequency_regression"] = NotificationAudience.Admin,
// App-version duration regression radar: packaging/rollout is an admin concern.
["app_version_duration_regression"] = NotificationAudience.Admin,
// Community rule submission decided (approved/declined): only admins submit, only admins act.
["rule_submission_decided"] = NotificationAudience.Admin,
};
public static NotificationAudience Resolve(string? type)
@@ -0,0 +1,139 @@
/**
* Two request-gate contracts (2026-09-10):
* - a token the backend refuses (401) is answered 401 + WWW-Authenticate error="invalid_token"
* (spec: invalid or expired tokens MUST receive 401), cached like a deny, never 403 "not enabled";
* - the caller context carries a cancellation signal that fires when the client closes the request
* before the response is written (Streamable HTTP: closing the response stream cancels the request).
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import type { Request, Response, NextFunction } from 'express';
import { accessGuard } from '../access-guard.js';
import { getCallerSignal } from '../client.js';
function makeToken(claims: Record<string, unknown>): string {
const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url');
const payload = Buffer.from(JSON.stringify(claims)).toString('base64url');
return `${header}.${payload}.sig`;
}
let seed = 0;
/** A fresh, unexpired token per call — the guard caches verdicts per UPN+token. */
function request(): Request {
seed += 1;
const token = makeToken({ upn: `user${seed}@contoso.com`, exp: Math.floor(Date.now() / 1000) + 3600 });
return {
headers: { host: 'mcp.example.com', authorization: `Bearer ${token}` },
protocol: 'https',
body: { jsonrpc: '2.0', method: 'tools/list', id: 1 },
} as unknown as Request;
}
interface Outcome {
nextCalled: boolean;
status: number | null;
body: unknown;
headers: Record<string, string>;
/** The caller context's signal, read INSIDE next(). */
signal?: AbortSignal;
res: { writableFinished: boolean };
/** Emits the response's 'close' event the way Node does when the socket goes away. */
close: () => void;
}
function run(req: Request): Promise<Outcome> {
return new Promise((resolve) => {
const headers: Record<string, string> = {};
const closeHandlers: Array<() => void> = [];
let status: number | null = null;
let settled = false;
const state = { writableFinished: false };
const close = () => closeHandlers.forEach((h) => h());
const finish = (o: Omit<Outcome, 'res' | 'close'>) => {
if (settled) return;
settled = true;
resolve({ ...o, res: state, close });
};
const res = {
get writableFinished() { return state.writableFinished; },
setHeader(name: string, value: string) { headers[name] = String(value); return this; },
status(code: number) { status = code; return this; },
json(payload: unknown) { finish({ nextCalled: false, status, body: payload, headers }); return this; },
on(event: string, handler: () => void) { if (event === 'close') closeHandlers.push(handler); return this; },
} as unknown as Response;
const next: NextFunction = () => finish({ nextCalled: true, status, body: undefined, headers, signal: getCallerSignal() });
accessGuard(req, res, next);
setTimeout(() => finish({ nextCalled: false, status, body: undefined, headers }), 2_000);
});
}
function stubBackend(status: number, body: unknown) {
const fn = vi.fn(async () => ({ status, text: async () => JSON.stringify(body) } as unknown as Response));
vi.stubGlobal('fetch', fn);
return fn;
}
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe('accessGuard — a backend 401 becomes 401 + challenge', () => {
it('answers 401 with error="invalid_token" and the backend reason, not 403', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
stubBackend(401, { error: 'Token signature is invalid', code: 'unauthorized' });
const out = await run(request());
expect(out.nextCalled).toBe(false);
expect(out.status).toBe(401);
expect(out.headers['WWW-Authenticate']).toContain('error="invalid_token"');
expect(out.headers['WWW-Authenticate']).toContain('oauth-protected-resource/mcp');
expect(out.body).toMatchObject({ error: 'Invalid token', reason: 'Token signature is invalid' });
});
it('caches the rejection per token: a replay costs no second backend call and stays 401', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
const fetchMock = stubBackend(401, { error: 'Token expired' });
const req = request();
const first = await run(req);
const second = await run(req);
expect(first.status).toBe(401);
expect(second.status).toBe(401);
expect(second.headers['WWW-Authenticate']).toContain('error="invalid_token"');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('keeps a 401 without an envelope body at 401 with a generic reason', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
stubBackend(401, 'Unauthorized');
const out = await run(request());
expect(out.status).toBe(401);
expect(out.body).toMatchObject({ reason: 'The backend rejected the token' });
});
it('keeps a genuine authorization deny (200, allowed:false) at 403 without a challenge', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
stubBackend(200, { allowed: false, upn: 'x', accessGrant: '', reason: 'not on the MCP allowlist' });
const out = await run(request());
expect(out.status).toBe(403);
expect(out.headers['WWW-Authenticate']).toBeUndefined();
});
});
describe('accessGuard — cancellation signal', () => {
it('hands the caller context a signal that fires when the client closes the request early', async () => {
stubBackend(200, { allowed: true, upn: 'x', accessGrant: 'ok' });
const out = await run(request());
expect(out.nextCalled).toBe(true);
expect(out.signal).toBeInstanceOf(AbortSignal);
expect(out.signal?.aborted).toBe(false);
out.close();
expect(out.signal?.aborted).toBe(true);
});
it('does not fire when the response completed normally before the socket closed', async () => {
stubBackend(200, { allowed: true, upn: 'x', accessGrant: 'ok' });
const out = await run(request());
out.res.writableFinished = true;
out.close();
expect(out.signal?.aborted).toBe(false);
});
});
@@ -45,6 +45,7 @@ function runGuard(req: Request): Promise<Outcome> {
setHeader() { return this as Response; },
status(code: number) { statusCode = code; return this as Response; },
json() { done({ nextCalled: false, status: statusCode }); return this as Response; },
on() { return this as Response; },
};
const next: NextFunction = () => done({ nextCalled: true, status: statusCode });
accessGuard(req, res as Response, next);
@@ -68,6 +68,10 @@ function mockRes(): CapturedRes {
captured.body = payload;
return this as Response;
},
// The guard subscribes to 'close' for the cancellation signal; nothing here ever emits it.
on() {
return this as Response;
},
};
captured.res = res as Response;
return captured;
@@ -0,0 +1,59 @@
/**
* Client cancellation reaches the backend: the caller context's signal (aborted by the access
* guard when the client closes the request) is folded into every apiFetch attempt and into the
* automatic 429/503 retry wait, so an abandoned tool call stops its backend work at once.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { apiFetch, runWithCaller } from '../client.js';
afterEach(() => vi.restoreAllMocks());
function caller(signal: AbortSignal) {
return { token: 'test-token', isGlobalAdmin: true, isGlobalReader: false, signal };
}
describe('apiFetch — caller cancellation', () => {
it("aborts the in-flight backend fetch when the caller's signal fires", async () => {
let seen: AbortSignal | undefined;
vi.spyOn(globalThis, 'fetch').mockImplementation((_url, init) => new Promise<Response>((_resolve, reject) => {
seen = init?.signal ?? undefined;
seen?.addEventListener('abort', () => reject(seen?.reason), { once: true });
}));
const controller = new AbortController();
const pending = runWithCaller(caller(controller.signal), () => apiFetch<unknown>('/api/sessions'));
expect(seen).toBeDefined();
expect(seen?.aborted).toBe(false);
controller.abort();
await expect(pending).rejects.toMatchObject({ name: 'AbortError' });
expect(seen?.aborted).toBe(true);
});
it('ends the automatic retry wait at once on cancellation instead of sleeping out Retry-After', async () => {
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: false,
status: 429,
headers: { get: (name: string) => (name.toLowerCase() === 'retry-after' ? '5' : null) },
text: async () => '',
} as unknown as Response);
const controller = new AbortController();
const started = Date.now();
const pending = runWithCaller(caller(controller.signal), () => apiFetch<unknown>('/api/sessions'));
setTimeout(() => controller.abort(), 20);
await expect(pending).rejects.toMatchObject({ name: 'AbortError' });
expect(Date.now() - started).toBeLessThan(2000);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('keeps the plain per-attempt timeout when the caller context carries no signal', async () => {
let seen: AbortSignal | undefined;
vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
seen = init?.signal ?? undefined;
return { ok: true, status: 200, headers: { get: () => null }, text: async () => '{"ok":true}' } as unknown as Response;
});
await runWithCaller({ token: 'test-token', isGlobalAdmin: true }, () => apiFetch<unknown>('/api/sessions'));
expect(seen).toBeDefined();
expect(seen?.aborted).toBe(false);
});
});
@@ -0,0 +1,49 @@
/**
* The per-argument echo policy a tool declares at its withToolTelemetry call site governs BOTH
* sinks that quote the arguments: the tool_call log line and the "Parameters used" block of an
* error result (whose first lines the log quotes). Without this, a clear-text config value masked
* in the args summary still reached the container log through the error text.
*/
import { describe, it, expect } from 'vitest';
import { toolError } from '../tools/error-handler.js';
import { createToolCallContext, runWithToolCallContext } from '../client.js';
const TENANT = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
const SECRET = 'https://hooks.example/services/secret-token-123';
function errorText(result: unknown): string {
return (result as { content: Array<{ text: string }> }).content[0].text;
}
describe('toolError — parameter echo honours the call\'s ArgPolicy', () => {
it("renders only the field NAMES of a 'keys' argument, so no config value enters the error text", () => {
const args = { tenantId: TENANT, fields: { teamsWebhookUrl: SECRET, dataRetentionDays: 4242 }, reason: 'rotate' };
const result = runWithToolCallContext(
createToolCallContext('update_tenant_config', 'cid', { fields: 'keys' }),
() => toolError('update_tenant_config', args, new Error('boom')),
);
const text = errorText(result);
expect(text).toContain('**Parameters used**');
expect(text).toContain('fields: teamsWebhookUrl,dataRetentionDays');
expect(text).toContain('reason: rotate');
expect(text).not.toContain(SECRET);
expect(text).not.toContain('4242');
});
it("omits a 'drop' argument entirely", () => {
const result = runWithToolCallContext(
createToolCallContext('t', 'cid', { secret: 'drop' }),
() => toolError('t', { secret: 'hunter2', q: 'x' }, new Error('boom')),
);
expect(errorText(result)).not.toContain('hunter2');
expect(errorText(result)).not.toContain('secret');
expect(errorText(result)).toContain('q: x');
});
it('renders values verbatim (size-capped) without a policy — the pre-existing behaviour', () => {
const text = errorText(toolError('search_sessions', { status: 'failed', pageSize: 50, days: null }, new Error('boom')));
expect(text).toContain('status: failed');
expect(text).toContain('pageSize: 50');
expect(text).not.toContain('days');
});
});
@@ -101,6 +101,7 @@ describe('revert_tenant_config — request shape', () => {
apiFetchMock.mockResolvedValueOnce({ success: true });
await captureToolHandlers(true, true).revert_tenant_config({
tenantId: TENANT,
backupId: '20260910T000000Z_abcd1234',
reason: 'undo bad change',
});
@@ -108,7 +109,7 @@ describe('revert_tenant_config — request shape', () => {
expect(path).toBe(`/api/config/${TENANT}/revert`);
expect(options.method).toBe('POST');
expect(JSON.parse(options.body as string)).toEqual({
backupId: undefined,
backupId: '20260910T000000Z_abcd1234',
includeProtectedFields: false,
reason: 'undo bad change',
});
@@ -0,0 +1,97 @@
/**
* The Origin gate in front of the dual-era MCP entry, driven over loopback HTTP the way index.ts
* mounts it (express.json → originGuard → handler): a foreign Origin is refused with 403 on a 2025
* initialize and on a 2026-07-28 request alike; the server's own origin and no Origin pass.
*/
import { describe, it, expect, beforeAll, afterAll, vi, afterEach } from 'vitest';
import express from 'express';
import type { Server } from 'node:http';
import { createMcpRequestHandler } from '../mcp-http.js';
import { createServerForCaller, type ServerDeps } from '../mcp-server-factory.js';
import { runWithCaller } from '../client.js';
import { originGuard } from '../origin-guard.js';
const DEPS: ServerDeps = { serverVersion: '0.0.0-test', knowledgeBase: undefined, eventTypeIndex: undefined, docs: undefined };
let httpServer: Server;
let url: URL;
beforeAll(async () => {
const app = express();
app.use('/mcp', express.json({ limit: '256kb' }));
app.use('/mcp', originGuard);
const handler = createMcpRequestHandler(() => createServerForCaller(DEPS), {});
app.post('/mcp', (req, res) =>
runWithCaller({ token: 'test-token', isGlobalAdmin: true, isGlobalReader: false, upn: 'caller@contoso.com' }, () => handler(req, res)),
);
await new Promise<void>((resolve) => {
httpServer = app.listen(0, '127.0.0.1', () => resolve());
});
const addr = httpServer.address();
if (typeof addr !== 'object' || addr === null) throw new Error('no address');
url = new URL(`http://127.0.0.1:${addr.port}/mcp`);
});
afterAll(async () => {
await new Promise<void>((resolve) => httpServer.close(() => resolve()));
});
afterEach(() => vi.restoreAllMocks());
const LEGACY_INITIALIZE = {
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'origin-test', version: '1.0.0' } },
};
const MODERN_TOOLS_LIST = {
jsonrpc: '2.0',
id: 1,
method: 'tools/list',
params: {
_meta: {
'io.modelcontextprotocol/protocolVersion': '2026-07-28',
'io.modelcontextprotocol/clientInfo': { name: 'origin-test', version: '1.0.0' },
'io.modelcontextprotocol/clientCapabilities': {},
},
},
};
function post(body: unknown, headers: Record<string, string>): Promise<Response> {
return fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...headers },
body: JSON.stringify(body),
});
}
describe('Origin gate on /mcp — both protocol eras', () => {
it('refuses a foreign Origin on a 2025 initialize: 403 + JSON-RPC error without id, and a log line', async () => {
const log = vi.spyOn(console, 'error').mockImplementation(() => {});
const res = await post(LEGACY_INITIALIZE, { origin: 'https://attacker.example' });
expect(res.status).toBe(403);
expect(await res.json()).toMatchObject({ jsonrpc: '2.0', error: { code: -32600 }, id: null });
expect(log).toHaveBeenCalledWith(expect.stringContaining('403 origin-rejected origin=https://attacker.example method=initialize'));
});
it('refuses a foreign Origin on a 2026-07-28 request', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
const res = await post(MODERN_TOOLS_LIST, {
origin: 'https://attacker.example',
'mcp-protocol-version': '2026-07-28',
'mcp-method': 'tools/list',
});
expect(res.status).toBe(403);
});
it("serves the server's own origin", async () => {
const res = await post(LEGACY_INITIALIZE, { origin: url.origin, 'mcp-protocol-version': '2025-11-25' });
expect(res.status).toBe(200);
});
it('serves a request without Origin (every non-browser client)', async () => {
const res = await post(LEGACY_INITIALIZE, { 'mcp-protocol-version': '2025-11-25' });
expect(res.status).toBe(200);
});
});
@@ -0,0 +1,36 @@
/**
* OAuthStateSigningKey boot guard: production refuses to boot without the key (the signed
* client_ids and the OAuth state derive from it and must survive restarts and replicas); the
* per-process random fallback exists for development and tests only; a short key fails everywhere.
*/
import { describe, it, expect } from 'vitest';
// oauth.ts throws at import unless the Entra client id is present.
process.env.AUTOPILOT_ENTRA_CLIENT_ID ??= '00000000-0000-0000-0000-000000000000';
const { loadSigningKey } = await import('../oauth.js');
const KEY = Buffer.alloc(32, 7).toString('base64');
describe('loadSigningKey', () => {
it('decodes a valid base64 key of 32+ bytes in production', () => {
expect(loadSigningKey(KEY, 'production').length).toBe(32);
});
it('refuses to boot in production without a key', () => {
expect(() => loadSigningKey(undefined, 'production')).toThrow('OAuthStateSigningKey is not set');
expect(() => loadSigningKey('', 'production')).toThrow('OAuthStateSigningKey is not set');
});
it('falls back to a fresh random key outside production', () => {
const a = loadSigningKey(undefined, 'test');
const b = loadSigningKey(undefined, undefined);
expect(a.length).toBe(32);
expect(b.length).toBe(32);
expect(a.equals(b)).toBe(false);
});
it('rejects a key shorter than 32 bytes in every environment', () => {
expect(() => loadSigningKey(Buffer.alloc(16).toString('base64'), 'test')).toThrow('32 bytes');
expect(() => loadSigningKey('not base64 at all', 'production')).toThrow('32 bytes');
});
});
@@ -0,0 +1,61 @@
/**
* /oauth/token relays Entra's error body through an allowlist: the OAuth error code, the human
* message (cut before the trace-id tail, capped) and the numeric AADSTS codes. Trace, correlation,
* timestamp, error_uri and claims never reach an unauthenticated caller (review R-5).
*/
import { describe, it, expect } from 'vitest';
// oauth.ts throws at import unless the Entra client id is present.
process.env.AUTOPILOT_ENTRA_CLIENT_ID ??= '00000000-0000-0000-0000-000000000000';
const { sanitizeTokenErrorBody } = await import('../oauth.js');
const ENTRA_INVALID_GRANT = {
error: 'invalid_grant',
error_description:
'AADSTS70008: The provided authorization code or refresh token has expired due to inactivity. ' +
'Send a new interactive authorization request for this user and resource. Trace ID: 5d1a2b3c-0000-4000-8000-000000000000\r\n' +
'Correlation ID: 7e9f0a1b-0000-4000-8000-000000000000\r\nTimestamp: 2026-09-10 00:00:00Z',
error_codes: [70008],
timestamp: '2026-09-10 00:00:00Z',
trace_id: '5d1a2b3c-0000-4000-8000-000000000000',
correlation_id: '7e9f0a1b-0000-4000-8000-000000000000',
error_uri: 'https://login.microsoftonline.com/error?code=70008',
claims: '{"access_token":{"capolids":{"essential":true,"values":["x"]}}}',
};
describe('sanitizeTokenErrorBody', () => {
it('keeps the OAuth error, the message before the trace tail, and the numeric codes only', () => {
expect(sanitizeTokenErrorBody(ENTRA_INVALID_GRANT)).toEqual({
error: 'invalid_grant',
error_description:
'AADSTS70008: The provided authorization code or refresh token has expired due to inactivity. ' +
'Send a new interactive authorization request for this user and resource.',
error_codes: [70008],
});
});
it('never carries trace, correlation, timestamp, error_uri or claims', () => {
const out = sanitizeTokenErrorBody(ENTRA_INVALID_GRANT);
for (const key of ['trace_id', 'correlation_id', 'timestamp', 'error_uri', 'claims']) expect(out).not.toHaveProperty(key);
expect(JSON.stringify(out)).not.toContain('5d1a2b3c');
expect(JSON.stringify(out)).not.toContain('7e9f0a1b');
});
it('maps an unknown error code to invalid_request', () => {
expect(sanitizeTokenErrorBody({ error: 'something_entra_specific', error_description: 'x' }).error).toBe('invalid_request');
});
it('caps a long description', () => {
const out = sanitizeTokenErrorBody({ error: 'invalid_request', error_description: 'y'.repeat(1000) });
expect((out.error_description as string).length).toBe(303);
expect(out.error_description as string).toMatch(/\.\.\.$/);
});
it('tolerates a non-object body and non-numeric codes', () => {
expect(sanitizeTokenErrorBody('not json')).toEqual({ error: 'invalid_request' });
expect(sanitizeTokenErrorBody({ error: 'invalid_client', error_codes: ['7000218', 7000218] })).toEqual({
error: 'invalid_client',
error_codes: [7000218],
});
});
});
@@ -0,0 +1,91 @@
/**
* Origin gate on /mcp (spec 2026-07-28 Streamable HTTP "Security & Endpoint": a present, invalid
* Origin MUST be answered 403). Non-browser clients send no Origin and pass; only the server's own
* origin passes with one; everything else — foreign hosts, scheme downgrades, suffix tricks, the
* opaque `null` — is refused before any token work.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import type { Request, Response } from 'express';
import { isAllowedOrigin, originGuard } from '../origin-guard.js';
const SELF = 'https://mcp.example.com';
describe('isAllowedOrigin', () => {
it('passes a request without Origin (every non-browser MCP client)', () => {
expect(isAllowedOrigin(undefined, SELF)).toBe(true);
});
it("accepts the server's own origin, port-normalised and case-insensitive on the host", () => {
expect(isAllowedOrigin('https://mcp.example.com', SELF)).toBe(true);
expect(isAllowedOrigin('https://MCP.example.com:443', SELF)).toBe(true);
});
it.each([
'https://evil.example',
'http://mcp.example.com',
'https://mcp.example.com.evil.example',
'https://mcp.example.com:8443',
'null',
'not a url',
'',
])('rejects a present, invalid Origin: %j', (origin) => {
expect(isAllowedOrigin(origin, SELF)).toBe(false);
});
});
describe('originGuard middleware', () => {
afterEach(() => vi.restoreAllMocks());
function run(origin?: string) {
const req = {
headers: { host: 'mcp.example.com', ...(origin !== undefined ? { origin } : {}) },
protocol: 'https',
body: { jsonrpc: '2.0', method: 'tools/list', id: 1 },
} as unknown as Request;
let status: number | null = null;
let body: unknown;
const res = {
status(code: number) { status = code; return this; },
json(payload: unknown) { body = payload; return this; },
} as unknown as Response;
const next = vi.fn();
originGuard(req, res, next);
return { status: status as number | null, body, next };
}
it('lets a request without Origin through untouched', () => {
const { status, next } = run();
expect(next).toHaveBeenCalledOnce();
expect(status).toBeNull();
});
it("lets the server's own origin through", () => {
const { status, next } = run('https://mcp.example.com');
expect(next).toHaveBeenCalledOnce();
expect(status).toBeNull();
});
it('answers 403 with a JSON-RPC error without id for a foreign origin, and logs it', () => {
const log = vi.spyOn(console, 'error').mockImplementation(() => {});
const { status, body, next } = run('https://attacker.example');
expect(next).not.toHaveBeenCalled();
expect(status).toBe(403);
expect(body).toEqual({ jsonrpc: '2.0', error: { code: -32600, message: 'Origin not allowed' }, id: null });
expect(log).toHaveBeenCalledWith(expect.stringContaining('[mcp-auth] 403 origin-rejected origin=https://attacker.example method=tools/list'));
});
it('treats the opaque "null" origin as present and invalid', () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
const { status, next } = run('null');
expect(next).not.toHaveBeenCalled();
expect(status).toBe(403);
});
it('renders a hostile origin value log-safe (control characters replaced, length capped)', () => {
const log = vi.spyOn(console, 'error').mockImplementation(() => {});
run('https://x.example/\r\nINJECTED' + 'a'.repeat(500));
const line = log.mock.calls[0][0] as string;
expect(line).not.toContain('\n');
expect(line.length).toBeLessThan(320);
});
});
@@ -0,0 +1,123 @@
/**
* query_raw_events pageSize follows the effective projection: a page that carries DataJson is
* bounded by rows × payload (measured p90 3.3 KB, outliers 21-29 KB per row), so it gets a
* smaller default and a ceiling of 100, refused BEFORE the backend does the work; a lean page
* keeps the schema's 1000. A nextLink is judged by its echoed fields.
*
* The handler reaches the backend through scanWithTimeoutFallback (client.ts), so that is the
* seam the test observes: its first argument is the path the backend would receive.
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
const { scanMock } = vi.hoisted(() => ({ scanMock: vi.fn() }));
vi.mock('../client.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../client.js')>();
return { ...actual, scanWithTimeoutFallback: scanMock };
});
import { registerAdminTools, rawEventsPayloadIncluded, RAW_EVENTS_PAYLOAD_PAGE_DEFAULT, RAW_EVENTS_PAYLOAD_PAGE_MAX } from '../tools/admin.js';
import { DEFAULT_FIRST_PAGE_SIZE } from '../client.js';
type Handler = (args: Record<string, unknown>) => Promise<{ content: Array<{ text: string }>; isError?: boolean }>;
function queryRawEvents(): Handler {
const handlers: Record<string, Handler> = {};
const fake = { registerTool: (name: string, _def: unknown, handler: Handler) => { handlers[name] = handler; } };
registerAdminTools(fake as never, true, true, false);
return handlers.query_raw_events;
}
const PAGE = { count: 1, events: [{ EventType: 'app_install_failed' }] };
function sentPath(): string {
return scanMock.mock.calls[0][0] as string;
}
function sentPageSize(): string | null {
const path = sentPath();
return new URLSearchParams(path.slice(path.indexOf('?') + 1)).get('pageSize');
}
const FULL_ROWS_NEXTLINK = '/api/raw/events?eventType=app_install_failed&pageSize=1000&continuation=c1';
const LEAN_NEXTLINK = '/api/raw/events?eventType=app_install_failed&fields=EventType%2CSeverity%2COccurredUtc&pageSize=1000&continuation=c1';
describe('rawEventsPayloadIncluded', () => {
it('follows an explicit fields list, case-insensitively', () => {
expect(rawEventsPayloadIncluded('PartitionKey,DataJson', undefined, false)).toBe(true);
expect(rawEventsPayloadIncluded('EventType, datajson', undefined, false)).toBe(true);
expect(rawEventsPayloadIncluded('EventType,Message', undefined, true)).toBe(false);
});
it('a filtered first page without fields carries the payload; an unfiltered one is lean by default', () => {
expect(rawEventsPayloadIncluded(undefined, undefined, true)).toBe(true);
expect(rawEventsPayloadIncluded(undefined, undefined, false)).toBe(false);
});
it('judges a nextLink by its echoed fields — none echoed means full rows', () => {
expect(rawEventsPayloadIncluded(undefined, FULL_ROWS_NEXTLINK, false)).toBe(true);
expect(rawEventsPayloadIncluded(undefined, LEAN_NEXTLINK, false)).toBe(false);
expect(rawEventsPayloadIncluded(undefined, '/api/raw/events?fields=EventType%2CDataJson&continuation=c1', false)).toBe(true);
});
});
describe('query_raw_events — pageSize follows the payload projection', () => {
beforeEach(() => {
scanMock.mockReset();
scanMock.mockResolvedValue(PAGE);
});
it('refuses pageSize 1000 on a filtered read (full rows) before any backend call', async () => {
const result = await queryRawEvents()({ eventType: 'app_install_failed', pageSize: 1000 });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain(`exceeds the maximum of ${RAW_EVENTS_PAYLOAD_PAGE_MAX}`);
expect(scanMock).not.toHaveBeenCalled();
});
it('refuses an explicit DataJson projection above the ceiling', async () => {
const result = await queryRawEvents()({ fields: 'EventType,DataJson', pageSize: RAW_EVENTS_PAYLOAD_PAGE_MAX + 1 });
expect(result.isError).toBe(true);
expect(scanMock).not.toHaveBeenCalled();
});
it('accepts the ceiling itself with the payload', async () => {
const result = await queryRawEvents()({ eventType: 'app_install_failed', pageSize: RAW_EVENTS_PAYLOAD_PAGE_MAX });
expect(result.isError).toBeUndefined();
expect(sentPageSize()).toBe(String(RAW_EVENTS_PAYLOAD_PAGE_MAX));
});
it('keeps the large page for a lean projection', async () => {
const result = await queryRawEvents()({ eventType: 'app_install_failed', fields: 'EventType,Severity,OccurredUtc', pageSize: 1000 });
expect(result.isError).toBeUndefined();
expect(sentPageSize()).toBe('1000');
});
it('defaults a payload page to the smaller size and a lean page to the tool default', async () => {
await queryRawEvents()({ eventType: 'app_install_failed' });
expect(sentPageSize()).toBe(String(RAW_EVENTS_PAYLOAD_PAGE_DEFAULT));
scanMock.mockClear();
await queryRawEvents()({});
expect(sentPageSize()).toBe(String(DEFAULT_FIRST_PAGE_SIZE));
});
it('refuses a nextLink whose embedded pageSize exceeds the ceiling for full rows', async () => {
const result = await queryRawEvents()({ continuation: FULL_ROWS_NEXTLINK });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('overrides the value embedded in a nextLink');
expect(scanMock).not.toHaveBeenCalled();
});
it('lets an explicit smaller pageSize override the nextLink and pass', async () => {
const result = await queryRawEvents()({ continuation: FULL_ROWS_NEXTLINK, pageSize: RAW_EVENTS_PAYLOAD_PAGE_MAX });
expect(result.isError).toBeUndefined();
expect(sentPath()).toContain('continuation=c1');
expect(sentPageSize()).toBe(String(RAW_EVENTS_PAYLOAD_PAGE_MAX));
});
it('keeps the embedded 1000 of a lean nextLink', async () => {
const result = await queryRawEvents()({ continuation: LEAN_NEXTLINK });
expect(result.isError).toBeUndefined();
expect(sentPageSize()).toBe('1000');
});
});
@@ -0,0 +1,41 @@
/**
* revert_tenant_config takes an explicit backupId — no "latest" default. Every revert snapshots
* the current state first, so a retried revert without an id would restore the snapshot the
* previous revert had just created and undo it. With a fixed id the same call is a no-op twice.
*/
import { describe, it, expect, vi } from 'vitest';
import { z } from 'zod';
vi.mock('../client.js', async (importOriginal) => ({
...(await importOriginal<typeof import('../client.js')>()),
apiFetch: vi.fn(),
}));
import { registerAdminTools } from '../tools/admin.js';
interface ToolDef { description: string; inputSchema: Record<string, z.ZodTypeAny> }
function definitionOf(tool: string): ToolDef {
let found: ToolDef | undefined;
const fake = { registerTool: (name: string, def: ToolDef) => { if (name === tool) found = def; } };
registerAdminTools(fake as never, true, true, false);
if (!found) throw new Error(`${tool} not registered`);
return found;
}
const TENANT = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
describe('revert_tenant_config — backupId is required', () => {
it('rejects a revert without backupId or with an empty one; accepts a named snapshot', () => {
const schema = z.object(definitionOf('revert_tenant_config').inputSchema);
expect(schema.safeParse({ tenantId: TENANT, reason: 'undo' }).success).toBe(false);
expect(schema.safeParse({ tenantId: TENANT, reason: 'undo', backupId: '' }).success).toBe(false);
expect(schema.safeParse({ tenantId: TENANT, reason: 'undo', backupId: '20260910T000000Z_abcd1234' }).success).toBe(true);
});
it('explains the rule in the description and no longer advertises a latest default', () => {
const { description } = definitionOf('revert_tenant_config');
expect(description).toContain('backupId is required');
expect(description).not.toContain('latest by default');
});
});
@@ -254,6 +254,36 @@ describe('buildSessionCoverage — diagnostics package', () => {
});
});
describe('buildSessionCoverage — apps without a terminal state', () => {
// The shutdown emit of the termination handler: what was still in flight when the agent left.
const shutdownSummary = ev('app_tracking_summary', 900, { installingNames: ['Suite'], downloadingNames: [], pendingNames: ['Other'] });
it("names the apps still in flight in the agent's last summary on a terminal session", () => {
const c = buildSessionCoverage({ startedAt: at(0), status: 'Succeeded' }, [
ev('agent_started', 5),
ev('app_tracking_summary', 300, { installingNames: ['Early'], downloadingNames: ['Later'] }),
shutdownSummary,
]);
expect(c.apps).toEqual({ stillInstalling: ['Suite'], stillDownloading: [] });
expect(c.gaps).toEqual([expect.stringContaining('1 app(s) still installing when the agent stopped observing (Suite)')]);
});
it('reports nothing while the session is still live, even with apps in flight', () => {
const c = buildSessionCoverage({ startedAt: at(0), status: 'InProgress' }, [ev('agent_started', 5), shutdownSummary]);
expect(c.apps).toEqual({ stillInstalling: [], stillDownloading: [] });
expect(c.gaps).toEqual([]);
});
it("stays silent when the last summary has nothing in flight (apps that never started are the starved rule's finding)", () => {
const c = buildSessionCoverage({ startedAt: at(0), status: 'Failed' }, [
ev('agent_started', 5),
ev('app_tracking_summary', 900, { installingNames: [], pendingNames: ['Other'] }),
]);
expect(c.apps).toEqual({ stillInstalling: [], stillDownloading: [] });
expect(c.gaps).toEqual([]);
});
});
describe('coverage wiring', () => {
it('SUMMARY_EVENT_FIELDS carries every coverage slice, as data.<key> entries only', () => {
const fields = SUMMARY_EVENT_FIELDS.split(',');
@@ -271,6 +301,7 @@ describe('coverage wiring', () => {
'agent_started', 'agent_late_start', 'historic_ime_replay_detected', 'ime_tracker_degraded', 'ime_pattern_hits',
'collector_degraded', 'spool_pressure_detected', 'telemetry_upload_poisoned', 'telemetry_upload_blocked',
'ingress_backpressure', 'disk_space_low', 'diagnostics_collecting', 'diagnostics_uploaded', 'diagnostics_upload_failed',
'app_tracking_summary',
];
expect([...COVERAGE_EVENT_TYPES].sort()).toEqual([...consulted].sort());
});
@@ -0,0 +1,66 @@
/**
* The tool_call line under the two 2026-09-10 result contracts: an overflow answer (page refused
* by toolResultText) is logged at the size the page WOULD have had and as overCap; a call the
* client abandoned is logged as cancelled, never as an error.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
async function loadTelemetry() {
vi.resetModules();
vi.stubEnv('MCP_TOOL_LOGGING', 'true');
return await import('../telemetry.js');
}
function lastLoggedJson(spy: ReturnType<typeof vi.spyOn>): Record<string, unknown> {
expect(spy).toHaveBeenCalled();
return JSON.parse(spy.mock.calls[spy.mock.calls.length - 1][0] as string) as Record<string, unknown>;
}
afterEach(() => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
describe('withToolTelemetry — overflow and cancellation', () => {
it('logs an overflow answer at the size the page would have had, as overCap and isError', async () => {
const { withToolTelemetry } = await loadTelemetry();
const { toolResultText } = await import('../tools/shared.js');
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
const page = { events: Array.from({ length: 50 }, (_, i) => ({ i, payload: 'x'.repeat(200) })) };
const result = await withToolTelemetry('query_raw_events', { eventType: 'x' }, () => toolResultText(page, 1_000));
expect(result.isError).toBe(true);
const line = lastLoggedJson(spy);
expect(line.overCap).toBe(true);
expect(line.isError).toBe(true);
expect(line.resultChars).toBe(JSON.stringify(page).length);
expect(String(line.errorMessage)).toContain('"overflow":true');
});
it('logs a call the client abandoned as cancelled, not as an error', async () => {
const { withToolTelemetry } = await loadTelemetry();
const { runWithCaller } = await import('../client.js');
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
const controller = new AbortController();
await runWithCaller({ token: 't', isGlobalAdmin: true, signal: controller.signal }, () =>
withToolTelemetry('get_session', { sessionId: 's' }, () => {
controller.abort();
return { isError: true, content: [{ type: 'text', text: '**Timeout in get_session**' }] };
}),
);
const line = lastLoggedJson(spy);
expect(line.cancelled).toBe(true);
expect(line.isError).toBe(false);
expect(line.errorMessage).toBeUndefined();
});
it('leaves a completed call without a cancelled field', async () => {
const { withToolTelemetry } = await loadTelemetry();
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
await withToolTelemetry('get_session', { sessionId: 's' }, () => ({ content: [{ type: 'text', text: '{}' }] }));
expect(lastLoggedJson(spy)).not.toHaveProperty('cancelled');
});
});
@@ -0,0 +1,83 @@
/**
* The response-size cap is enforced, not advisory: a page above the tool's cap is never sent —
* the answer is an error naming what the page held and the exact pageSize that fits, computed from
* THIS page's bytes per row. The oversized page's nextLink is withheld (following it would skip
* rows), and the telemetry marker carries the size the page would have had.
*/
import { describe, it, expect } from 'vitest';
import { toolResultText, OVERFLOW_META_KEY } from '../tools/shared.js';
const CAP = 10_000;
function rows(n: number, payloadChars: number): Array<{ id: number; payload: string }> {
return Array.from({ length: n }, (_, i) => ({ id: i, payload: 'x'.repeat(payloadChars) }));
}
function bodyOf(result: { content: Array<{ text: string }> }): Record<string, unknown> {
return JSON.parse(result.content[0].text) as Record<string, unknown>;
}
describe('toolResultText — hard cap', () => {
it('sends a page under the cap unchanged, with the size hint and no overflow marker', () => {
const data = { count: 3, events: rows(3, 100), nextLink: '/api/x?continuation=abc' };
const r = toolResultText(data, CAP);
expect(r.isError).toBeUndefined();
expect(bodyOf(r)).toEqual(data);
expect(r._meta['anthropic/maxResultSizeChars']).toBe(CAP);
expect(r._meta[OVERFLOW_META_KEY]).toBeUndefined();
});
it('refuses a page over the cap: no rows, no nextLink, the pageSize that fits, the marker', () => {
const data = { count: 100, events: rows(100, 500), nextLink: '/api/x?continuation=abc' };
const chars = JSON.stringify(data).length;
const r = toolResultText(data, CAP);
expect(r.isError).toBe(true);
const body = bodyOf(r);
expect(body.overflow).toBe(true);
expect(body.responseChars).toBe(chars);
expect(body.maxResultSizeChars).toBe(CAP);
expect(body.rowsField).toBe('events');
expect(body.rowsFetched).toBe(100);
expect(body.rowsThatFit).toBe(Math.floor((CAP * 0.9) / (chars / 100)));
expect(body.rowsThatFit as number).toBeGreaterThanOrEqual(1);
expect(body.rowsThatFit as number).toBeLessThan(100);
expect(body.events).toBeUndefined();
expect(body.nextLink).toBeUndefined();
expect(body.advice).toContain(`pageSize=${body.rowsThatFit}`);
expect(r.content[0].text.length).toBeLessThan(CAP);
expect(r._meta[OVERFLOW_META_KEY]).toEqual({ responseChars: chars });
expect(r._meta['anthropic/maxResultSizeChars']).toBe(CAP);
});
it('gives an honest advice: a re-send at rowsThatFit lands under the cap', () => {
const fit = bodyOf(toolResultText({ events: rows(100, 500) }, CAP)).rowsThatFit as number;
const again = toolResultText({ events: rows(fit, 500) }, CAP);
expect(again.isError).toBeUndefined();
});
it('never advises fewer than one row', () => {
const body = bodyOf(toolResultText({ events: rows(2, CAP) }, CAP));
expect(body.rowsThatFit).toBe(1);
});
it('gives only narrowing advice when the page carries no list', () => {
const body = bodyOf(toolResultText({ blob: 'x'.repeat(CAP + 1) }, CAP));
expect(body.overflow).toBe(true);
expect(body.rowsThatFit).toBeUndefined();
expect(body.rowsField).toBeUndefined();
expect(body.advice).toContain('Narrow the query');
});
it('does not project a pageSize from a one-element list (the KQL tables[] shape)', () => {
const body = bodyOf(toolResultText({ tables: [{ name: 'PrimaryResult', rows: rows(50, 300) }] }, CAP));
expect(body.overflow).toBe(true);
expect(body.rowsThatFit).toBeUndefined();
});
it('picks the largest top-level list when a page carries several', () => {
const body = bodyOf(toolResultText({ warnings: ['a', 'b'], sessions: rows(60, 400) }, CAP));
expect(body.rowsField).toBe('sessions');
expect(body.rowsFetched).toBe(60);
});
});
@@ -110,6 +110,8 @@ describe('role catalog snapshot — privilege-leak guard', () => {
// fails — that failure is the deliberate prompt to decide its role placement.
const GA_FULL = [
'annotate_session',
// Community rule submission write surface (strictGa): operator hard delete.
'delete_rule_submission',
'get_agent_efficiency_metrics',
'get_api_usage',
'get_app_install_metrics',
@@ -132,6 +134,8 @@ describe('role catalog snapshot — privilege-leak guard', () => {
'get_platform_metrics',
'get_resource',
'get_rule_stats',
// Platform scope (GA + Global Reader): one community rule submission with its frozen rule.
'get_rule_submission',
'get_session',
'get_session_diagnostics',
'get_session_events',
@@ -151,6 +155,8 @@ describe('role catalog snapshot — privilege-leak guard', () => {
'get_verdict_calibration',
'get_vulnerability_summary',
'list_blocked_devices',
// Platform scope (GA + Global Reader): community rule submissions across tenants.
'list_rule_submissions',
'list_session_annotations',
'list_session_reports',
'list_tables',
@@ -162,7 +168,10 @@ describe('role catalog snapshot — privilege-leak guard', () => {
'query_raw_events',
'query_raw_sessions',
'query_table',
// Community rule submission write surface (strictGa): the publish step and the decision.
'reseed_rules_from_github',
'revert_tenant_config',
'review_rule_submission',
'search_events',
'search_knowledge',
'search_sessions',
@@ -200,12 +209,17 @@ describe('role catalog snapshot — privilege-leak guard', () => {
// reads annotations (list_session_annotations) but never writes the GA lane.
const ANNOTATION_WRITE_GA_STRICT = ['annotate_session'];
// Community rule submission write surface: strictGa only — a read-only Global Reader
// lists and reads submissions but never decides one or triggers the reseed that publishes.
const RULE_SUBMISSION_WRITE_GA_STRICT = ['delete_rule_submission', 'reseed_rules_from_github', 'review_rule_submission'];
// Platform-only tools: a non-platform caller (tenant or delegated) gets no
// cross-fleet aggregate surface at all. Superset of RAW_GA_STRICT and
// CONFIG_WRITE_GA_STRICT (those are also platform-only) plus the curated
// cross-tenant aggregates.
const PLATFORM_ONLY = [
'annotate_session',
'delete_rule_submission',
'get_agent_efficiency_metrics',
'get_api_usage',
'get_deployment_state',
@@ -213,11 +227,13 @@ describe('role catalog snapshot — privilege-leak guard', () => {
'get_ime_pattern_health',
'get_ops_events',
'get_platform_metrics',
'get_rule_submission',
'get_session_report_download',
'get_tenant_config',
'get_tenant_config_schema',
'get_verdict_calibration',
'list_blocked_devices',
'list_rule_submissions',
'list_session_annotations',
'list_session_reports',
'list_tables',
@@ -225,7 +241,9 @@ describe('role catalog snapshot — privilege-leak guard', () => {
'list_tenants',
'query_backend_logs',
'query_table',
'reseed_rules_from_github',
'revert_tenant_config',
'review_rule_submission',
'update_tenant_config',
];
@@ -246,7 +264,7 @@ describe('role catalog snapshot — privilege-leak guard', () => {
it('Global Reader = GA minus the secret-bearing raw tools, the config-write surface and the annotation write (strictGa split)', () => {
expect(registeredToolNames(true, false)).toEqual(
without(GA_FULL, [...RAW_GA_STRICT, ...CONFIG_WRITE_GA_STRICT, ...ANNOTATION_WRITE_GA_STRICT]));
without(GA_FULL, [...RAW_GA_STRICT, ...CONFIG_WRITE_GA_STRICT, ...ANNOTATION_WRITE_GA_STRICT, ...RULE_SUBMISSION_WRITE_GA_STRICT]));
});
it('tenant user = GA minus all platform-only tools', () => {
@@ -265,6 +283,7 @@ describe('role catalog snapshot — privilege-leak guard', () => {
['RAW_GA_STRICT', RAW_GA_STRICT],
['CONFIG_WRITE_GA_STRICT', CONFIG_WRITE_GA_STRICT],
['ANNOTATION_WRITE_GA_STRICT', ANNOTATION_WRITE_GA_STRICT],
['RULE_SUBMISSION_WRITE_GA_STRICT', RULE_SUBMISSION_WRITE_GA_STRICT],
['PLATFORM_ONLY', PLATFORM_ONLY],
['DELEGATED_HIDDEN', DELEGATED_HIDDEN],
['DELEGATED_ADDED', DELEGATED_ADDED],
@@ -282,7 +301,7 @@ describe('role catalog snapshot — privilege-leak guard', () => {
const registeredDiff = registeredToolNames(true, true).filter((n) => !readerNames.includes(n)).sort();
expect([...GA_STRICT_TOOL_NAMES].sort()).toEqual(registeredDiff);
expect([...GA_STRICT_TOOL_NAMES].sort()).toEqual(
[...RAW_GA_STRICT, ...CONFIG_WRITE_GA_STRICT, ...ANNOTATION_WRITE_GA_STRICT].sort());
[...RAW_GA_STRICT, ...CONFIG_WRITE_GA_STRICT, ...ANNOTATION_WRITE_GA_STRICT, ...RULE_SUBMISSION_WRITE_GA_STRICT].sort());
});
it('the secret-bearing raw tools are a subset of the platform-only tools', () => {
@@ -89,6 +89,9 @@ interface AccessCacheEntry {
// scope and downgrade the caller to home-tenant-only routing.
delegatedTenantIds?: string[];
delegatedRole?: string;
// The backend refused the TOKEN itself (401) — cached like a deny so a replayed bad token costs
// one backend call per TTL, but answered 401 + challenge, never "not enabled".
unauthenticated?: boolean;
expiresAt: number;
}
@@ -109,6 +112,11 @@ interface AccessCheckResult {
// routing bounded to this set; every delegated tool call must name one of these tenants.
delegatedTenantIds?: string[];
delegatedRole?: string;
// The backend — the only party holding the JWKS — rejected the token (signature, issuer,
// audience, lifetime). That is "invalid token": the spec says it MUST be answered 401 with a
// WWW-Authenticate challenge so the client re-authenticates, not 403 ("insufficient
// permissions"), which a client reads as final.
unauthenticated?: boolean;
// Distinguishes a genuine authorization denial (the backend reached a verdict
// and said "no" — e.g. user not on the MCP whitelist) from an infrastructure
// failure (backend unreachable / malformed response). Both fail closed, but
@@ -161,6 +169,7 @@ async function checkAccess(upn: string, token: string, clientIp: string): Promis
isGlobalReader: cached.isGlobalReader,
delegatedTenantIds: cached.delegatedTenantIds,
delegatedRole: cached.delegatedRole,
unauthenticated: cached.unauthenticated,
// Only genuine backend verdicts are ever cached (infra errors return early
// below without caching), so a cache hit is never an infra error.
infraError: false,
@@ -183,6 +192,22 @@ async function checkAccess(upn: string, token: string, clientIp: string): Promis
});
const text = await res.text();
if (res.status === 401) {
// The token itself was refused (see AccessCheckResult.unauthenticated). The envelope's
// message names the cause (expired, wrong audience, bad signature) for the log line.
let reason = 'The backend rejected the token';
try {
const parsed = JSON.parse(text) as Partial<ApiErrorResponse>;
if (typeof parsed.error === 'string' && parsed.error) reason = parsed.error;
} catch {
/* not an error envelope */
}
boundedSet(accessCache, cacheKey, {
allowed: false, reason, isGlobalAdmin: false, isGlobalReader: false, unauthenticated: true,
expiresAt: Date.now() + ACCESS_CACHE_TTL_MS,
}, MAX_ACCESS_CACHE_ENTRIES);
return { allowed: false, reason, isGlobalAdmin: false, isGlobalReader: false, infraError: false, unauthenticated: true };
}
if (!text) {
console.error(`[access-guard] Backend returned empty body for ${upn} (status=${res.status})`);
return { allowed: false, reason: `Backend returned ${res.status} with empty body`, isGlobalAdmin: false, isGlobalReader: false, infraError: true };
@@ -451,6 +476,14 @@ export function accessGuard(req: Request, res: Response, next: NextFunction): vo
return;
}
if (!result.allowed) {
if (result.unauthenticated) {
// Spec: an invalid or expired token MUST get 401 with a challenge, so the client
// re-authenticates instead of reading a final "forbidden".
console.error(`[mcp-auth] 401 backend-rejected-token (method=${rpcMethod}, upn=${upn})`);
res.setHeader('WWW-Authenticate', `Bearer resource_metadata="${resourceMetadataUrl}", error="invalid_token"`);
res.status(401).json({ error: 'Invalid token', reason: result.reason });
return;
}
if (result.infraError) {
// Backend could not reach a verdict (unreachable / malformed). Fail
// closed, but do NOT tell the user they are "not whitelisted" — it is
@@ -484,12 +517,21 @@ export function accessGuard(req: Request, res: Response, next: NextFunction): vo
return;
}
// Cancellation (Streamable HTTP: closing the response stream cancels the request): the
// caller context carries a signal that fires when the client goes away before the
// response is written, so the backend work of an abandoned call stops (client.ts apiFetch).
const cancellation = new AbortController();
res.on('close', () => {
if (!res.writableFinished) cancellation.abort();
});
// Scope the caller context (token + platform role) to this async context
// so concurrent sessions cannot overwrite each other on the event loop,
// and so tools can route based on role without re-checking the JWT.
runWithCaller(
{
token,
signal: cancellation.signal,
isGlobalAdmin: result.isGlobalAdmin,
isGlobalReader: result.isGlobalReader,
delegatedTenantIds: result.delegatedTenantIds,
+19 -15
View File
@@ -1,12 +1,20 @@
/**
* Auth module for the remote MCP server.
*
* In remote mode, the Claude Code client handles OAuth and sends a Bearer token
* with each MCP request. This module provides helpers for token validation and
* extracting user info from the JWT claims.
* The MCP client obtains a Bearer token through this server's OAuth proxy (oauth.ts) and sends it
* with each MCP request. This module reads the JWT claims; the token itself is validated by the
* backend.
*
* The user's token is passed through to the backend API (access_as_user scope),
* so no service principal or separate credentials are needed.
* Token model — a DELIBERATE deviation from the MCP authorization spec, recorded as a decision in
* the internal decision register: the token's audience is the backend API app (access_as_user),
* not this server, and the same token is forwarded to the backend. The spec requires an MCP
* server to accept only tokens issued for itself and never to transit them downstream. The
* compensations: the backend validates signature, issuer, audience and lifetime on EVERY
* forwarded call (this server never treats a token as valid on its own), /api/auth/mcp decides
* MCP eligibility per principal, and every tool reaches only its own backend path (followNextLink
* basePath pinning). Audience separation would need a second app registration with consent in
* every customer tenant plus an on-behalf-of exchange, and would break the app-only
* service-principal path — not built until a reviewer requires it.
*/
import { createDecoder } from './jwt-decode.js';
@@ -30,16 +38,12 @@ export interface TokenClaims {
/** Calling application's client id on a v2.0 token. */
azp?: string;
/**
* Audience. Parsed for observability/diagnostics but intentionally NOT
* validated here — the same Bearer token is passed through to the backend
* API, which enforces the audience cryptographically alongside the
* signature/issuer/lifetime checks. See
* `src/Backend/AutopilotMonitor.Functions/Middleware/AuthenticationMiddleware.cs:200`
* (`ValidateAudience = true`, `ValidAudiences = { clientId, api://clientId }`).
* Duplicating that gate here would only add a second, drift-prone copy of the
* accepted-audience list (RFC 8707 resource indicators are honored by the
* backend, not the proxy). This is spec-conformant token pass-through: the
* user's token is forwarded to the resource it was issued for.
* Audience. Parsed for observability/diagnostics but intentionally NOT validated here — the
* backend enforces it cryptographically alongside the signature/issuer/lifetime checks
* (`AuthenticationMiddleware.cs`: `ValidateAudience = true`, `ValidAudiences = { clientId,
* api://clientId }`); duplicating that gate here would only add a second, drift-prone copy of
* the accepted-audience list. The audience is the backend API, not this server — see the
* module header for why that deviation from the MCP spec is deliberate.
*/
aud?: string;
}
@@ -116,6 +116,13 @@ interface CallerContext {
* wire's gzip does not remove from a model's context.
*/
prettyJson?: boolean;
/**
* Fires when the client closes the HTTP request before the response is written — the transport's
* cancellation signal (spec 2026-07-28: closing the response stream cancels the request). apiFetch
* folds it into every backend call so an abandoned tool call stops its backend work instead of
* running to its own deadline; the timeout-fallback retry and the telemetry read it too.
*/
signal?: AbortSignal;
}
const callerStore = new AsyncLocalStorage<CallerContext>();
@@ -145,6 +152,11 @@ export function getCurrentToken(): string | undefined {
return callerStore.getStore()?.token;
}
/** The current request's cancellation signal (see CallerContext.signal), or undefined without a context. */
export function getCallerSignal(): AbortSignal | undefined {
return callerStore.getStore()?.signal;
}
/**
* Returns true if the current request is being made by a Global Admin.
* Defaults to false when no context is active (e.g. unit tests without
@@ -329,12 +341,30 @@ export interface ToolCallContext {
correlationId: string;
/** Automatic 429/503 retries apiFetch performed during this tool call (counted here, logged on the tool_call line). */
retries: number;
/**
* How the call's arguments are rendered wherever they are echoed — the `tool_call` log line AND the
* "Parameters used" block of an error result (which the log quotes). One declaration at the
* withToolTelemetry call site covers both sinks; without it a clear-text config value masked in
* the args summary would still reach the log through the error text.
*/
argPolicy?: ArgPolicy;
}
/**
* Per-argument echo policy: 'keys' renders only the property NAMES of an object-valued argument
* (update_tenant_config.fields — which fields changed, never their values), 'drop' omits the
* argument entirely. Arguments without a policy are rendered verbatim, size-capped.
*/
export type ArgPolicy = Record<string, 'keys' | 'drop'>;
const toolCallStore = new AsyncLocalStorage<ToolCallContext>();
export function createToolCallContext(toolName: string, correlationId: string): ToolCallContext {
return { toolName, correlationId, retries: 0 };
export function createToolCallContext(toolName: string, correlationId: string, argPolicy?: ArgPolicy): ToolCallContext {
return { toolName, correlationId, retries: 0, argPolicy };
}
export function getCurrentArgPolicy(): ArgPolicy | undefined {
return toolCallStore.getStore()?.argPolicy;
}
/** Run `fn` inside a tool-call context the caller keeps a reference to (withToolTelemetry reads `retries` afterwards). */
@@ -372,7 +402,27 @@ export interface ApiFetchOptions extends RequestInit {
retry?: boolean;
}
const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
/** Sleeps `ms`, or rejects at once with the signal's reason when the caller cancels meanwhile. */
const delay = (ms: number, signal?: AbortSignal) => new Promise<void>((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const onAbort = () => {
clearTimeout(timer);
reject(signal?.reason);
};
const timer = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, ms);
signal?.addEventListener('abort', onAbort, { once: true });
});
/** The per-attempt signal: the call's own deadline plus, when the request has one, the caller's cancellation. */
function withCallerSignal(own: AbortSignal, caller: AbortSignal | undefined): AbortSignal {
return caller ? AbortSignal.any([own, caller]) : own;
}
/** Seconds to wait before the one automatic retry, or null when this answer gets none. */
function autoRetryDelaySeconds(status: number, body: string, retryAfterHeader: string | null): number | null {
@@ -421,8 +471,15 @@ async function apiFetch<T>(path: string, options: ApiFetchOptions = {}): Promise
const method = (init.method ?? 'GET').toUpperCase();
const mayRetry = retry ?? (method === 'GET' && !init.signal);
// Apply timeout to prevent hanging on unresponsive backend; a retry gets a fresh one.
const attempt = () => fetch(url, { ...init, headers, signal: init.signal ?? AbortSignal.timeout(API_TIMEOUT_MS) });
// Every attempt runs under the call's own deadline (a retry gets a fresh one) AND the caller's
// cancellation: when the client has closed the request, the backend work stops here instead of
// running to its timeout — pagination scans and the retry wait included.
const callerSignal = getCallerSignal();
const attempt = () => fetch(url, {
...init,
headers,
signal: withCallerSignal(init.signal ?? AbortSignal.timeout(API_TIMEOUT_MS), callerSignal),
});
let res = await attempt();
if (!res.ok) {
@@ -433,7 +490,7 @@ async function apiFetch<T>(path: string, options: ApiFetchOptions = {}): Promise
throw new ApiError(res.status, text, headerOf(res, 'x-correlation-id'), retryAfterHeader);
}
if (call) call.retries += 1;
await delay(wait * 1000);
await delay(wait * 1000, callerSignal);
res = await attempt();
if (!res.ok) {
throw new ApiError(res.status, await res.text(), headerOf(res, 'x-correlation-id'), headerOf(res, 'retry-after'));
@@ -728,7 +785,9 @@ export async function scanWithTimeoutFallback(
try {
return await scan(firstPath);
} catch (error: unknown) {
if (!isTimeoutError(error) || pageSize <= MIN_FALLBACK_PAGE_SIZE) throw error;
// A caller-cancelled fetch surfaces as the same abort shape as a timeout; never re-fetch for
// a client that has already gone away.
if (!isTimeoutError(error) || pageSize <= MIN_FALLBACK_PAGE_SIZE || getCallerSignal()?.aborted) throw error;
const reduced = Math.max(MIN_FALLBACK_PAGE_SIZE, Math.floor(pageSize / 2));
const page = await scan(withQueryOverrides(firstPath, { pageSize: reduced }));
return {
@@ -470,6 +470,8 @@ export interface AppAnalyticsSummary {
skipped: number;
unmeasured: number;
failed: number;
/** Still installing when the session's observation ended — outcome unknown, outside the rate. */
incomplete: number;
failureRate: number;
avgDurationSeconds: number;
p95DurationSeconds: number;
@@ -558,6 +560,8 @@ export interface AppMetricsAppGroup {
skipped: number;
unmeasured: number;
failed: number;
/** Still installing when the session's observation ended — outcome unknown, outside the rate. */
incomplete: number;
/** Failed / (failed + succeeded) as a percentage; skips never count as attempts. */
failureRate: number;
/** Average measured FINAL-attempt duration (whole seconds); 0 with no measured installs. */
@@ -591,6 +595,8 @@ export interface AppMetricsResponse {
totalInstalls: number;
totalSkipped: number;
totalUnmeasured: number;
/** Rows still installing when the session's observation ended — outcome unknown, outside the failure rate. */
totalIncomplete: number;
/** Rows excluded from per-app groups because their name-keyed row merged distinct appIds. */
totalCollisionExcluded: number;
slowestApps: AppMetricsAppGroup[];
@@ -3439,6 +3445,24 @@ export interface RevertTenantConfigurationRequest {
reason?: string | null;
}
/** Body of PATCH global/rule-submissions/{id}. */
export interface ReviewRuleSubmissionRequest {
/** One of All. */
decision: string;
/** Shown to the submitter. Required for decline. */
reviewComment?: string | null;
willBeAdapted?: boolean | null;
/** Reserved-namespace id the rule ships under. Required for approve. */
publishedRuleId?: string | null;
}
/** Success body of PATCH global/rule-submissions/{id}. */
export interface ReviewRuleSubmissionResponse {
success: boolean;
message: string;
submission: RuleSubmissionItem;
}
export interface RevokeTenantManagerRequest {
homeTenantId: string;
}
@@ -3668,6 +3692,83 @@ export interface RuleStatsSummary {
period: RuleStatsPeriod;
}
/** Success body of GET global/rule-submissions/{id}: the submission, the frozen rule typed by kind (exactly one of the two rule properties is set), live fire stats, the suggested reserved id and the repo file built from the assigned (or suggested) id. */
export interface RuleSubmissionDetailResponse {
success: boolean;
submission: RuleSubmissionItem;
analyzeRule?: AnalyzeRule;
gatherRule?: GatherRule;
liveFireStats?: RuleSubmissionFireStats;
suggestedPublishedRuleId?: string;
repoFile?: RuleSubmissionRepoFile;
}
/** A pre-flight finding recorded at submit time. Errors block the submission and are never stored. */
export interface RuleSubmissionFinding {
/** "error" | "warning" | "info". */
level: string;
message: string;
}
/** Fire telemetry of the submitted rule in the submitting tenant over the trailing window. */
export interface RuleSubmissionFireStats {
days: number;
fireCount: number;
sessionsEvaluated: number;
evaluationCount: number;
}
/** Wire shape of one submission (list rows, submit response, detail head). The frozen rule document is not part of it — the detail response carries it typed. */
export interface RuleSubmissionItem {
submissionId: string;
batchId: string;
tenantId: string;
ruleKind: string;
sourceRuleId: string;
title: string;
category: string;
comment?: string;
submittedBy: string;
submittedByName: string;
contactEmail?: string;
attributionMode: string;
attributionName: string;
submittedAt: string;
/** One of All — the effective status, published included. */
status: string;
validationFindings: RuleSubmissionFinding[];
sourceFireStats?: RuleSubmissionFireStats;
reviewedBy?: string;
reviewedAt?: string;
reviewComment?: string;
willBeAdapted: boolean;
publishedRuleId?: string;
derivedFromTemplateRuleId?: string;
}
/** One rule reference in a submit request; the server freezes the rule itself. */
export interface RuleSubmissionItemRef {
/** One of All. */
kind: string;
ruleId: string;
}
/** Success body of GET rules/submissions and GET global/rule-submissions. */
export interface RuleSubmissionListResponse {
success: boolean;
count: number;
submissions: RuleSubmissionItem[];
/** Absolute-path link to the next page; null/absent on the last page and in non-paged responses. */
nextLink?: string;
}
/** The repo-ready file for a submission: where it goes and what it contains. */
export interface RuleSubmissionRepoFile {
/** Repository-relative path, e.g. rules/analyze/ANALYZE-NET-002.json. */
path: string;
content: string;
}
/** One day of a rule's trend ("yyyy-MM-dd"). */
export interface RuleTrendPoint {
date: string;
@@ -4317,6 +4418,27 @@ export interface SubmitOffboardingFeedbackRequest {
comment?: string | null;
}
/** Body of POST rules/submissions: up to MaxItems of the caller's own custom rules. */
export interface SubmitRuleSubmissionsRequest {
tenantId: string;
items: RuleSubmissionItemRef[];
comment?: string | null;
/** Optional reply address; stored for the reviewer, never published. */
email?: string | null;
/** One of All. */
attributionMode: string;
/** Credit text for the person mode; ignored for the other modes. */
attributionName?: string | null;
}
/** Success body of POST rules/submissions. */
export interface SubmitRuleSubmissionsResponse {
success: boolean;
message: string;
batchId: string;
submissions: RuleSubmissionItem[];
}
/** Request to submit a session report for analysis by the Autopilot Monitor team. Sent as JSON from the frontend; the backend creates the ZIP and uploads to central storage. */
export interface SubmitSessionReportRequest {
tenantId: string;
@@ -155,6 +155,38 @@ export const ANNOTATION_VERDICTS = [
] as const;
export type AnnotationVerdict = (typeof ANNOTATION_VERDICTS)[number];
/** Community rule submission kinds (C# RuleSubmissionKinds). */
export const RULE_SUBMISSION_KINDS = [
"gather",
"analyze",
] as const;
export type RuleSubmissionKind = (typeof RULE_SUBMISSION_KINDS)[number];
/** Effective rule submission statuses incl. the derived published (C# RuleSubmissionStatuses). */
export const RULE_SUBMISSION_STATUSES = [
"pending",
"approved",
"declined",
"withdrawn",
"published",
] as const;
export type RuleSubmissionStatus = (typeof RULE_SUBMISSION_STATUSES)[number];
/** How a contributed rule credits its author (C# RuleAttributionModes). */
export const RULE_ATTRIBUTION_MODES = [
"anonymous",
"organization",
"person",
] as const;
export type RuleAttributionMode = (typeof RULE_ATTRIBUTION_MODES)[number];
/** Reviewer decisions on a rule submission (C# RuleSubmissionDecisions). */
export const RULE_SUBMISSION_DECISIONS = [
"approve",
"decline",
] as const;
export type RuleSubmissionDecision = (typeof RULE_SUBMISSION_DECISIONS)[number];
/** Telemetry stores behind the operator KQL proxy — query_backend_logs `source` (C# LogQuerySources). */
export const LOG_SOURCES = [
"backend",
@@ -15,6 +15,7 @@ import { validatePrecomputedIndex } from './precomputed-index.js';
import { buildEventTypeSearchDocs } from './resource-catalog.js';
import { createOAuthRouter } from './oauth.js';
import { accessGuard } from './access-guard.js';
import { originGuard } from './origin-guard.js';
import { toolLoggingEnabled, attachToolCallRejectionSniffer } from './telemetry.js';
import { API_BASE_URL } from './config.js';
import { SERVER_VERSION, BUILD_COMMIT, BUILD_UTC, DOCS_COMMIT } from './build-info.js';
@@ -274,6 +275,10 @@ app.get('/health', (_req, res) => {
});
});
// Origin gate for /mcp (spec MUST): a browser Origin other than this server's own is refused
// before any token work — see origin-guard.ts.
app.use('/mcp', originGuard);
// Access guard for /mcp — validates JWT, checks backend whitelist, enforces rate limits
app.use('/mcp', accessGuard);
@@ -82,7 +82,7 @@ export function buildInstructions(deps: ServerDeps, ga: boolean, strictGa: boole
: []),
'Searching events: use search_events (hybrid keyword+semantic ranking; depth="fast" then "deep" for exhaustive recall) for ranked hits, or get_session_events / query_raw_events for the raw unranked stream.',
'Counting / aggregating: pass a lean `fields=` projection and use `agentVersionPrefix=`/`imeAgentVersionPrefix=` sweeps to stay under the per-response size cap.',
'Pagination: when a response carries `nextLink`, pass that whole string back as `continuation`; stop when it is absent. Results are never silently truncated.',
'Pagination: when a response carries `nextLink`, pass that whole string back as `continuation`; stop when it is absent. Results are never silently truncated: a page above a tool\'s response cap is refused with an overflow error that names the pageSize that fits — re-send the same call with it.',
'Catalogs: call get_resource(name="event_types"|"device_properties") to discover valid eventType strings and deviceProperties keys before filtering.',
'Error codes: lookup_error_code explains one HRESULT / MSI exit code / symbol / IME enforcement state from the shared catalog; search_knowledge finds the rules that name a code.',
scopeLine,
@@ -124,16 +124,26 @@ const ENTRA_TOKEN_TIMEOUT_MS = 15_000;
// binding on every callback, and the client validates its own originalState
// exactly once. Decision reviewed 2026-08-15.
//
// HMAC key: prefer OAuthStateSigningKey from the environment so all replicas
// agree on the signature; fall back to a per-instance random key when unset
// (state has a 10 min lifetime, so per-instance is acceptable for single-
// replica scale=0..1). Format and naming match the backend's
// PaginationTokenSigningKey for consistency: PascalCase env var, base64-
// encoded random bytes, ≥32 bytes after decode. Generate on PowerShell:
// HMAC key: OAuthStateSigningKey from the environment so every replica AND every
// cold start agree on the signature. The signed client_id (below) is derived from
// this key and is meant to outlive the process — with a per-boot random key a
// scale-to-zero restart would invalidate every minted client_id (invalid_client)
// and every in-flight state. So production refuses to boot without the key; the
// per-instance random fallback exists for local development and tests only.
// Format and naming match the backend's PaginationTokenSigningKey: PascalCase env
// var, base64-encoded random bytes, ≥32 bytes after decode. Generate on PowerShell:
// [Convert]::ToBase64String([Security.Cryptography.RandomNumberGenerator]::GetBytes(32))
const OAUTH_STATE_SIGNING_KEY: Buffer = (() => {
const raw = process.env.OAuthStateSigningKey;
if (!raw) return crypto.randomBytes(32);
export function loadSigningKey(raw: string | undefined, nodeEnv: string | undefined): Buffer {
if (!raw) {
if (nodeEnv === 'production') {
throw new Error(
'OAuthStateSigningKey is not set. Production requires it: signed client_ids and OAuth state must ' +
'survive restarts and replicas. Generate one with PowerShell: ' +
'[Convert]::ToBase64String([Security.Cryptography.RandomNumberGenerator]::GetBytes(32))',
);
}
return crypto.randomBytes(32);
}
// Buffer.from(s, 'base64') silently drops invalid chars — the only useful
// signal is the resulting byte length. Anything below 32 bytes is either a
// malformed input or a too-weak key; either way we want to fail loud at
@@ -148,7 +158,9 @@ const OAUTH_STATE_SIGNING_KEY: Buffer = (() => {
);
}
return decoded;
})();
}
const OAUTH_STATE_SIGNING_KEY: Buffer = loadSigningKey(process.env.OAuthStateSigningKey, process.env.NODE_ENV);
const STATE_MAX_AGE_SECONDS = 600;
interface ProxyStatePayload {
@@ -204,6 +216,38 @@ export function sanitizeForLog(value: unknown, maxLength = 200): string {
return cleaned.length > maxLength ? `${cleaned.slice(0, maxLength)}...` : cleaned;
}
/** OAuth error codes (RFC 6749 §5.2, OIDC Core §3.1.2.6) a client acts on; anything else is relayed as invalid_request. */
const OAUTH_ERROR_CODES = new Set([
'invalid_request', 'invalid_client', 'invalid_grant', 'unauthorized_client', 'unsupported_grant_type',
'invalid_scope', 'access_denied', 'server_error', 'temporarily_unavailable',
'interaction_required', 'login_required', 'consent_required',
]);
const TOKEN_ERROR_DESCRIPTION_CAP = 300;
/**
* The token endpoint's error body as the proxy relays it. Entra's own body is a fingerprinting
* surface for an unauthenticated caller — `trace_id`, `correlation_id`, `timestamp`, `error_uri`,
* a `claims` challenge, and an `error_description` that repeats the trace ids in prose — so only
* what a client acts on passes: the OAuth `error` code, the human message (cut before the
* "Trace ID:" tail Entra appends, size-capped) and the numeric AADSTS `error_codes`. The server
* log line keeps the correlation id for a Microsoft support case.
*/
export function sanitizeTokenErrorBody(data: unknown): Record<string, unknown> {
const err = (typeof data === 'object' && data !== null ? data : {}) as Record<string, unknown>;
const error = typeof err.error === 'string' && OAUTH_ERROR_CODES.has(err.error) ? err.error : 'invalid_request';
const out: Record<string, unknown> = { error };
if (typeof err.error_description === 'string' && err.error_description) {
const description = err.error_description.split(/\s*Trace ID:/i)[0].trim();
out.error_description = description.length > TOKEN_ERROR_DESCRIPTION_CAP
? `${description.slice(0, TOKEN_ERROR_DESCRIPTION_CAP)}...`
: description;
}
if (Array.isArray(err.error_codes)) {
out.error_codes = err.error_codes.filter((c): c is number => typeof c === 'number').slice(0, 10);
}
return out;
}
// ---- Client-id signing (HMAC) ---------------------------------------------
//
// The dynamic-registration client_id is a self-describing signed token rather
@@ -909,7 +953,7 @@ export function createOAuthRouter(): Router {
`correlation_id=${sanitizeForLog(err.correlation_id)}`,
);
}
res.status(tokenResponse.status).json(data);
res.status(tokenResponse.status).json(tokenResponse.status === 200 ? data : sanitizeTokenErrorBody(data));
} catch (err) {
// AbortSignal.timeout() rejects with a DOMException named 'TimeoutError'
// (see error-handler.ts) — report that as 504 so a stalled identity
@@ -0,0 +1,43 @@
/**
* Origin gate for the MCP endpoint (Streamable HTTP, spec 2026-07-28 "Security & Endpoint"):
* "Servers MUST validate the Origin header on all incoming connections to prevent DNS rebinding
* attacks. If the Origin header is present and invalid, servers MUST respond with HTTP 403."
*
* Every legitimate client of this server is a non-browser process (Claude Code, the Claude.ai
* connector, VS Code) and sends no Origin at all — such requests pass untouched. A request that
* DOES carry an Origin comes from a browser context; the only one this server can serve is its
* own (there is no CORS layer, so no cross-origin page could complete a call anyway), everything
* else — including the opaque `null` origin — is refused. Mounted on /mcp only: the /oauth
* endpoints are browser-navigated by design.
*/
import type { Request, Response, NextFunction } from 'express';
import { getPublicBaseUrl } from './config.js';
/** True when the request may proceed: no Origin (non-browser client) or exactly this server's origin. */
export function isAllowedOrigin(origin: string | undefined, publicBaseUrl: string): boolean {
if (origin === undefined) return true;
let candidate: URL;
try {
candidate = new URL(origin);
} catch {
return false; // 'null' and malformed values are "present and invalid"
}
return candidate.origin === new URL(publicBaseUrl).origin;
}
/** Log-safe rendering of an attacker-controlled header value. */
function forLog(origin: string): string {
return origin.replace(/[^\x20-\x7e]/g, '?').slice(0, 200);
}
export function originGuard(req: Request, res: Response, next: NextFunction): void {
const origin = req.headers.origin;
if (isAllowedOrigin(origin, getPublicBaseUrl(req))) {
next();
return;
}
const rpcMethod = (req.body as { method?: string } | undefined)?.method ?? '?';
console.error(`[mcp-auth] 403 origin-rejected origin=${forLog(origin as string)} method=${rpcMethod}`);
// The spec allows a JSON-RPC error without id as the 403 body.
res.status(403).json({ jsonrpc: '2.0', error: { code: -32600, message: 'Origin not allowed' }, id: null });
}
@@ -31,6 +31,7 @@ export const COVERAGE_EVENT_TYPES: ReadonlySet<string> = new Set([
'diagnostics_collecting',
'diagnostics_uploaded',
'diagnostics_upload_failed',
'app_tracking_summary',
]);
/**
@@ -44,7 +45,8 @@ export const COVERAGE_EVENT_FIELDS =
'data.file,data.firstSkippedPattern,data.lineBudgetBreaks,data.regexTimeouts,data.oversizedLines,data.unanchoredPatterns,data.linesRead,' +
'data.collector,data.reason,data.errorType,' +
'data.pendingItemCount,data.pendingBytes,data.kind,data.itemCount,data.disk_free_gb,' +
'data.truncated,data.includedFiles,data.includedBytes,data.skippedFiles,data.skippedByReason,data.problemsByKind';
'data.truncated,data.includedFiles,data.includedBytes,data.skippedFiles,data.skippedByReason,data.problemsByKind,' +
'data.installingNames,data.downloadingNames';
export interface CoverageWindow {
/** Timestamp of the first `agent_started` — the earliest moment anything was observed live. */
@@ -111,12 +113,20 @@ export interface DiagnosticsCoverage {
problemsByKind?: Record<string, number>;
}
export interface AppsCoverage {
/** Apps the agent's last summary still listed as installing when observation ended (terminal session only). */
stillInstalling: string[];
/** Same for downloading. */
stillDownloading: string[];
}
export interface SessionCoverage {
window: CoverageWindow;
imeTracker: ImeTrackerCoverage;
collectors: CollectorDegradation[];
upload: UploadCoverage;
diagnostics: DiagnosticsCoverage;
apps: AppsCoverage;
/** One calibrated line per observation gap; empty means nothing reported a gap. */
gaps: string[];
}
@@ -165,12 +175,21 @@ function fmtCounts(m: Record<string, number>): string {
return Object.entries(m).map(([k, n]) => `${k}: ${n}`).join(', ');
}
function names(v: unknown): string[] {
return Array.isArray(v) ? v.map(str).filter((s): s is string => s !== null) : [];
}
/** Mirror of the backend SessionStatus terminal set (utils/sessionStatus.ts in the web app). */
function isTerminalSessionStatus(status: unknown): boolean {
return status === 'Succeeded' || status === 'Failed' || status === 'Incomplete';
}
/**
* Folds the session's events (already stripped of historic-replay rows by the caller) into the
* coverage block. Pure: no fetch, no clock.
*/
export function buildSessionCoverage(
session: { startedAt?: string | null },
session: { startedAt?: string | null; status?: string | null },
events: readonly Ev[],
): SessionCoverage {
const byType = new Map<string, Ev[]>();
@@ -366,6 +385,25 @@ export function buildSessionCoverage(
}
}
// ── Apps without a terminal state ───────────────────────────────────────────
// The agent's last app_tracking_summary (the shutdown emit) names what was still in flight.
// Only a terminal session turns that into a gap — while the session is live those apps are
// simply still installing. Apps that never started are the starved rule's finding, not a gap.
const apps: AppsCoverage = { stillInstalling: [], stillDownloading: [] };
if (isTerminalSessionStatus(session.status)) {
const summary = last('app_tracking_summary');
apps.stillInstalling = names(summary?.data?.installingNames);
apps.stillDownloading = names(summary?.data?.downloadingNames);
const inFlight = (verb: string, list: string[]): void => {
if (list.length === 0) return;
gaps.push(
`${list.length} app(s) still ${verb} when the agent stopped observing (${list.join(', ')}): outcome unknown — not observed to fail, not observed to finish.`,
);
};
inFlight('installing', apps.stillInstalling);
inFlight('downloading', apps.stillDownloading);
}
return {
window: {
observedFrom,
@@ -380,6 +418,7 @@ export function buildSessionCoverage(
collectors,
upload,
diagnostics,
apps,
gaps,
};
}
@@ -1,5 +1,9 @@
import { randomUUID } from 'node:crypto';
import { createToolCallContext, runWithToolCallContext, hasGlobalScope, isDelegated, getCallerUpn } from './client.js';
import {
createToolCallContext, runWithToolCallContext, hasGlobalScope, isDelegated, getCallerUpn, getCallerSignal,
type ArgPolicy,
} from './client.js';
import { OVERFLOW_META_KEY } from './tools/shared.js';
export const toolLoggingEnabled = process.env.MCP_TOOL_LOGGING === 'true';
@@ -15,18 +19,16 @@ function cap(s: string, max: number): string {
}
/**
* Per-argument logging policy, declared at the tool's withToolTelemetry call
* site so schema, handler and log policy are reviewed together.
* - 'keys': log only the property NAMES of an object-valued argument. For
* update_tenant_config.fields this keeps the useful signal (which fields a
* Global Admin changes) while the clear-text values (webhook URLs, SAS URLs,
* custom headers) never reach the container log stream — the backend keeps
* them in the backup snapshot and the audit log, both GA-gated.
* - 'drop': omit the argument entirely (for arguments whose key alone reveals
* something, e.g. a plain-string secret).
* Arguments without a policy are rendered verbatim (capped).
* Per-argument echo policy (see client.ts ArgPolicy), declared at the tool's
* withToolTelemetry call site so schema, handler and policy are reviewed
* together. It travels in the tool-call context, so the SAME policy governs the
* `tool_call` log line and the "Parameters used" block toolError appends to an
* error result. For update_tenant_config.fields this keeps the useful signal
* (which fields a Global Admin changes) while the clear-text values (webhook
* URLs, SAS URLs, custom headers) never reach the container log stream — the
* backend keeps them in the backup snapshot and the audit log, both GA-gated.
*/
export type ArgPolicy = Record<string, 'keys' | 'drop'>;
export type { ArgPolicy };
function renderKeysOnly(value: unknown): string {
if (Array.isArray(value)) return `[array:${value.length}]`;
@@ -98,7 +100,7 @@ export async function withToolTelemetry<T>(
// One correlation id per tool call — sent on every backend request the call makes and written
// into the tool_call line below, so an MCP log line and the backend request rows join on it.
const correlationId = randomUUID();
const context = createToolCallContext(toolName, correlationId);
const context = createToolCallContext(toolName, correlationId, argPolicy);
if (!toolLoggingEnabled) {
return runWithToolCallContext(context, fn) as Promise<T>;
}
@@ -117,9 +119,16 @@ export async function withToolTelemetry<T>(
} finally {
try {
const r = result as ToolResultShape | undefined;
const resultChars = r?.content?.reduce((sum, c) => sum + (c.text?.length ?? 0), 0) ?? 0;
// A page the server refused to send (toolResultText overflow) is logged at the size it
// WOULD have had, so the size distribution keeps naming the offending calls.
const overflow = r?._meta?.[OVERFLOW_META_KEY] as { responseChars?: number } | undefined;
const resultChars = overflow?.responseChars
?? (r?.content?.reduce((sum, c) => sum + (c.text?.length ?? 0), 0) ?? 0);
const capValue = Number(r?._meta?.['anthropic/maxResultSizeChars']);
const isError = threw || r?.isError === true;
// The client closed the request before the result was written: the call was abandoned,
// not failed — it must not count towards the tool's error rate.
const cancelled = getCallerSignal()?.aborted === true;
const isError = !cancelled && (threw || r?.isError === true);
// What actually failed — without this every error drilldown ends at
// guessing from args. Soft errors carry the toolError text (its first
// lines name the error class: HTTP status / timeout / auth / not found).
@@ -133,10 +142,12 @@ export async function withToolTelemetry<T>(
durationMs: Date.now() - start,
isError,
errorMessage,
cancelled: cancelled ? true : undefined,
resultChars,
// Result exceeds the inline-size hint → the host truncates it. A tool
// that is frequently overCap needs tighter defaults or projections.
overCap: Number.isFinite(capValue) && capValue > 0 ? resultChars > capValue : false,
// Result exceeds the tool's size cap: the server answered with an overflow error
// instead of the page (marker), or the advisory hint was exceeded and the host
// truncates. A tool that is frequently overCap needs tighter defaults or projections.
overCap: overflow !== undefined || (Number.isFinite(capValue) && capValue > 0 ? resultChars > capValue : false),
// Automatic 429/503 retries apiFetch made for this call (absent when none): a tool that
// retries often is hitting a rate limit its defaults should avoid.
retries: context.retries > 0 ? context.retries : undefined,
@@ -25,11 +25,50 @@ export const GA_STRICT_TOOL_NAMES: ReadonlySet<string> = new Set([
'update_tenant_config',
'list_tenant_config_backups',
'revert_tenant_config',
'review_rule_submission',
'reseed_rules_from_github',
'delete_rule_submission',
]);
/** Default first-page size of get_fleet_overview's session list (a fleet snapshot, not a sweep). */
const FLEET_OVERVIEW_PAGE_SIZE = 25;
/**
* query_raw_events rows per page when the projection carries DataJson. Measured over 30 days of
* tool telemetry: with the payload a row is p50 0.6 KB, p90 3.3 KB, outliers 21-29 KB, so 100 rows
* keep the p90 page (330 KB) under the 500 KB cap and the outliers are the hard cap's job
* (toolResultText names the exact pageSize that fits). Without DataJson the schema's 1000 stands.
*/
export const RAW_EVENTS_PAYLOAD_PAGE_DEFAULT = 50;
export const RAW_EVENTS_PAYLOAD_PAGE_MAX = 100;
/**
* Whether the EFFECTIVE projection of a query_raw_events call includes DataJson: an explicit
* `fields` naming it; a filtered first page without `fields` (full rows by default, see
* leanFieldSelection); or a nextLink whose echoed `fields` names it — or carries none, which is
* what a filtered page 1 leaves behind and means full rows on the follow-up as well.
*/
export function rawEventsPayloadIncluded(explicitFields: string | undefined, continuation: string | undefined, targeted: boolean): boolean {
const names = (list: string) => list.split(',').map((f) => f.trim().toLowerCase());
if (explicitFields !== undefined) return names(explicitFields).includes('datajson');
if (continuation?.startsWith('/api/')) {
const q = continuation.indexOf('?');
const echoed = q === -1 ? null : new URLSearchParams(continuation.slice(q + 1)).get('fields');
return echoed === null || names(echoed).includes('datajson');
}
return targeted;
}
function assertPayloadPageSize(pageSize: number): void {
if (pageSize <= RAW_EVENTS_PAYLOAD_PAGE_MAX) return;
throw new Error(
`pageSize ${pageSize} exceeds the maximum of ${RAW_EVENTS_PAYLOAD_PAGE_MAX} for a read that includes DataJson: ` +
'the raw payload carries kilobytes per row, so such a page is bounded by rows × payload, not rows. ' +
`Re-send with pageSize ≤ ${RAW_EVENTS_PAYLOAD_PAGE_MAX} (an explicit pageSize overrides the value embedded in a ` +
'nextLink; the cursor stays valid), or pass a fields= projection without DataJson to keep the larger page.',
);
}
/**
* Pure: the get_fleet_overview result. The two backend responses each carry their own
* quotaExcludedTenants (the quota layer decides per request); the union is what the model must know is
@@ -94,7 +133,13 @@ import type {
QueryBackendLogsResponse,
QueryRawSessionsResponse,
QueryRawTableResponse,
ReseedFromGitHubResponse,
RevertTenantConfigurationRequest,
ReviewRuleSubmissionRequest,
ReviewRuleSubmissionResponse,
RuleSubmissionDetailResponse,
RuleSubmissionListResponse,
SuccessMessageResponse,
RuleStatsResponse,
RuleStatsRuleAggregate,
SessionAnnotationListResponse,
@@ -120,6 +165,9 @@ import {
LOG_SOURCES,
OPS_EVENT_CATEGORIES,
OPS_EVENT_SEVERITIES,
RULE_SUBMISSION_DECISIONS,
RULE_SUBMISSION_KINDS,
RULE_SUBMISSION_STATUSES,
SESSION_STATUSES,
} from '../generated/wire-vocabularies.generated.js';
@@ -1114,6 +1162,183 @@ export function registerAdminTools(server: McpServer, ga: boolean, strictGa: boo
})
);
// ── Community rule submissions ────────────────────────────────────────
// The submission id (12 hex chars, the session-report shape) is the handle for the whole
// review: list → get → validate_rule / test_analyze_rule → review → repo commit → reseed.
// Tool 18d: list_rule_submissions — platform scope (GA + Global Reader).
if (ga) server.registerTool(
'list_rule_submissions',
{
title: 'List Rule Submissions',
description:
'List custom gather/analyze rules that tenant admins submitted for the community pool, newest first, with ' +
'the effective status (pending | approved | declined | withdrawn | published — "published" is derived: the ' +
'approved rule\'s published id exists in the global catalog). Platform scope; pass tenantId to filter to one ' +
'tenant and status to one status. Each row carries the submission id — pass it to get_rule_submission for the ' +
'frozen rule, findings, fire stats and the repo-ready file. Fully paginated; pass the whole nextLink as "continuation".',
inputSchema: {
tenantId: TenantGuidSchema.optional().describe('Optional — filter to a single tenant. Omit for the cross-tenant view.'),
status: z.enum(RULE_SUBMISSION_STATUSES).optional()
.describe('Optional — one effective status. "published" lists the approved submissions whose rule is live in the global catalog.'),
pageSize: z.coerce.number().int().min(1).max(1000).optional()
.describe('Page size (1-1000; default ' + DEFAULT_FIRST_PAGE_SIZE + ' on the first page). Follow nextLink for more.'),
continuation: z.string().optional()
.describe('The "continuation" value or the full nextLink path of a prior response; the latter is preferred.'),
},
annotations: READ_ONLY,
},
async (args) => withToolTelemetry('list_rule_submissions', args, async () => {
try {
const { tenantId, continuation } = args;
const pageSize = pageSizeForCall(args.pageSize, continuation, DEFAULT_FIRST_PAGE_SIZE);
// "published" is not a stored status: ask the backend for the approved rows and keep the live ones.
const wantsPublished = args.status === 'published';
const status = wantsPublished ? 'approved' : args.status;
const path = followNextLink(
'/api/global/rule-submissions',
{ tenantId, status, pageSize },
continuation,
{ pageSize },
);
const data = await apiFetch<RuleSubmissionListResponse>(path);
if (wantsPublished) {
const submissions = data.submissions.filter((s) => s.status === 'published');
return toolResultText({ ...data, count: submissions.length, submissions }, MAX_RESULT_SIZE_CHARS.adminStream);
}
return toolResultText(data, MAX_RESULT_SIZE_CHARS.adminStream);
} catch (error: unknown) {
return toolError('list_rule_submissions', args, error);
}
})
);
// Tool 18e: get_rule_submission — platform scope (GA + Global Reader).
if (ga) server.registerTool(
'get_rule_submission',
{
title: 'Get Rule Submission',
description:
'Everything a review needs for one submitted rule: the submission (submitter, comment, attribution, ' +
'effective status, review fields), the frozen rule typed by kind (analyzeRule or gatherRule — pass it to ' +
'validate_rule, and for analyze rules to test_analyze_rule against sessions of the submitting tenant), the ' +
'pre-flight findings recorded at submit time, the rule\'s fire stats in the submitting tenant (frozen and live), ' +
'the suggested reserved rule id (max+1 in the category, gaps are retired ids) and repoFile: the ready-to-commit ' +
'file content plus its path under rules/. After approval, publishing is a repo commit of that file followed by ' +
'reseed_rules_from_github; the status turns "published" once the id is in the global catalog.',
inputSchema: {
submissionId: z.string().trim().regex(/^[0-9a-f]{12}$/i).describe('The 12-character submission id.'),
},
annotations: READ_ONLY,
},
async (args) => withToolTelemetry('get_rule_submission', args, async () => {
try {
const data = await apiFetch<RuleSubmissionDetailResponse>(`/api/global/rule-submissions/${encodeURIComponent(args.submissionId)}`);
return toolResultText(data, MAX_RESULT_SIZE_CHARS.small);
} catch (error: unknown) {
return toolError('get_rule_submission', args, error);
}
})
);
// Tool 18f: review_rule_submission — real Global Admin only (write).
if (strictGa) server.registerTool(
'review_rule_submission',
{
title: 'Review Rule Submission',
description:
'Record the decision on a submitted rule. Global Admin only. approve needs publishedRuleId — the reserved ' +
'built-in id the rule will ship under (ANALYZE-<CAT>-NNN / GATHER-<CAT>-NNN, three digits; take ' +
'suggestedPublishedRuleId from get_rule_submission unless you have a reason not to) — and may set ' +
'willBeAdapted when the published rule will differ from the submitted one. decline needs reviewComment. ' +
'The comment is shown to the submitter in both cases. Transitions: pending → approved | declined; ' +
'approved → declined while not yet published; a published submission is final. Approving does NOT publish: ' +
'commit the repo file (get_rule_submission → repoFile), push, then reseed_rules_from_github.',
inputSchema: {
submissionId: z.string().trim().regex(/^[0-9a-f]{12}$/i).describe('The 12-character submission id.'),
decision: z.enum(RULE_SUBMISSION_DECISIONS).describe('approve or decline.'),
reviewComment: z.string().max(4000).optional()
.describe('Shown to the submitter. Required for decline; for approve it explains the adaptation, if any.'),
willBeAdapted: z.boolean().optional()
.describe('approve only — the published rule will be adapted (generalised) before it ships.'),
publishedRuleId: z.string().trim().optional()
.describe('approve only — the reserved id the rule ships under; must be free in catalog, global partition and other approvals.'),
},
annotations: MUTATING,
},
async (args) => withToolTelemetry('review_rule_submission', args, async () => {
try {
const { submissionId, decision, reviewComment, willBeAdapted, publishedRuleId } = args;
const data = await apiFetch<ReviewRuleSubmissionResponse>(
`/api/global/rule-submissions/${encodeURIComponent(submissionId)}`,
{
method: 'PATCH',
body: jsonBody<ReviewRuleSubmissionRequest>({ decision, reviewComment, willBeAdapted, publishedRuleId }),
},
);
return toolResultText(data, MAX_RESULT_SIZE_CHARS.small);
} catch (error: unknown) {
return toolError('review_rule_submission', args, error);
}
})
);
// Tool 18h: delete_rule_submission — real Global Admin only (write). Test/demo rows, or a tenant's request.
if (strictGa) server.registerTool(
'delete_rule_submission',
{
title: 'Delete Rule Submission',
description:
'Hard-delete one rule submission so it disappears from the operator list and the submitting tenant\'s list ' +
'alike. Global Admin only; not part of normal operations — for test and demo submissions, or when a tenant asks ' +
'for removal. A rule already published from the submission stays in the repository and the catalog.',
inputSchema: {
submissionId: z.string().trim().regex(/^[0-9a-f]{12}$/i).describe('The 12-character submission id.'),
},
annotations: MUTATING,
},
async (args) => withToolTelemetry('delete_rule_submission', args, async () => {
try {
const data = await apiFetch<SuccessMessageResponse>(
`/api/global/rule-submissions/${encodeURIComponent(args.submissionId)}`,
{ method: 'DELETE' },
);
return toolResultText(data, MAX_RESULT_SIZE_CHARS.small);
} catch (error: unknown) {
return toolError('delete_rule_submission', args, error);
}
})
);
// Tool 18g: reseed_rules_from_github — real Global Admin only (write): the publish step.
if (strictGa) server.registerTool(
'reseed_rules_from_github',
{
title: 'Reseed Rules From GitHub',
description:
'Pull the rule catalog of one kind from the public repository\'s main branch (rules/dist) into the global ' +
'rule partition — the step that makes a committed and pushed community rule live for every tenant without a ' +
'backend deploy. Global Admin only. Also sunsets GitHub-sourced rules the repository no longer ships, so run it ' +
'only after the push landed. Returns deleted/written counts; the proof of a publish is get_rule_submission ' +
'showing status "published", not this count.',
inputSchema: {
type: z.enum(RULE_SUBMISSION_KINDS).describe('Which catalog to reseed: analyze or gather.'),
},
annotations: MUTATING,
},
async (args) => withToolTelemetry('reseed_rules_from_github', args, async () => {
try {
const data = await apiFetch<ReseedFromGitHubResponse>(
`/api/rules/reseed-from-github?type=${encodeURIComponent(args.type)}`,
{ method: 'POST' },
);
return toolResultText(data, MAX_RESULT_SIZE_CHARS.small);
} catch (error: unknown) {
return toolError('reseed_rules_from_github', args, error);
}
})
);
// Tool 18a: get_deployment_state — platform scope; every source is a public endpoint, the
// tool only saves the operator six fetches and the drift arithmetic.
if (ga) server.registerTool(
@@ -1321,7 +1546,10 @@ export function registerAdminTools(server: McpServer, ga: boolean, strictGa: boo
'nextLink as "continuation" to keep scanning). ' +
'This endpoint is fully paginated — there is no truncation. The default pageSize=' + DEFAULT_FIRST_PAGE_SIZE + ' is tuned for typical ' +
'interactive queries; raise it (up to 1000) for forensics-grade exact recall. For broad analysis, use ' +
'pageSize=1000 and follow nextLink repeatedly until absent. Pass the whole nextLink string as "continuation" ' +
'pageSize=1000 and follow nextLink repeatedly until absent. EXCEPTION: a page that includes DataJson (named in ' +
'fields, or a filtered read without fields) is capped at pageSize=' + RAW_EVENTS_PAYLOAD_PAGE_MAX + ' (default ' +
RAW_EVENTS_PAYLOAD_PAGE_DEFAULT + ') — the payload carries kilobytes per row, and a larger value is refused before ' +
'any work is done. Pass the whole nextLink string as "continuation" ' +
'so all backend-echoed query params round-trip correctly. Note: pageSize is the index-scan cadence — a single ' +
'indexed session can contribute multiple events, so total events per page may exceed pageSize. ' +
'The server bounds every page by a scan budget: a page that ends early carries "partial": true — nothing is ' +
@@ -1355,9 +1583,16 @@ export function registerAdminTools(server: McpServer, ga: boolean, strictGa: boo
async (args) => withToolTelemetry('query_raw_events', args, async () => {
try {
const { tenantId: rawTenantId, sessionId, eventType, severity, source, startedAfter, startedBefore, fields: explicitFields, continuation } = args;
const pageSize = pageSizeForCall(args.pageSize, continuation, DEFAULT_FIRST_PAGE_SIZE);
const targeted = Boolean(eventType || severity || source);
// A page that carries DataJson is bounded by rows × payload, not rows (measured over 30 d:
// p90 3.3 KB, outliers 21-29 KB per row), so 1000 such rows exceed the cap many times over
// while 1000 lean rows fit. Default and ceiling therefore follow the effective projection,
// and an oversized request is refused BEFORE the backend does the work.
const payload = rawEventsPayloadIncluded(explicitFields, continuation, targeted);
const pageSize = pageSizeForCall(args.pageSize, continuation, payload ? RAW_EVENTS_PAYLOAD_PAGE_DEFAULT : DEFAULT_FIRST_PAGE_SIZE);
if (payload) assertPayloadPageSize(effectivePageSize(pageSize, continuation));
// Default projection follows intent — see leanFieldSelection (DataJson is the raw payload column).
const { fields, leanDefaultApplied } = leanFieldSelection(explicitFields, continuation, Boolean(eventType || severity || source), LEAN_RAW_EVENT_FIELDS);
const { fields, leanDefaultApplied } = leanFieldSelection(explicitFields, continuation, targeted, LEAN_RAW_EVENT_FIELDS);
const tenantId = enforceDelegatedTenantForPage(rawTenantId, continuation);
if (eventType) assertKnownEventType(eventType);
const basePath = pickGlobalOrTenantPath('/api/global/raw/events', '/api/raw/events', tenantId);
@@ -1728,15 +1963,18 @@ export function registerAdminTools(server: McpServer, ga: boolean, strictGa: boo
{
title: 'Revert Tenant Configuration',
description:
'Restore a tenant\'s configuration from a pre-write snapshot (latest by default). Global Admin only. ' +
'The revert snapshots the CURRENT state first, so a revert is itself revertible. Protected fields ' +
'(plan/trial, homedAppClientId, auth provenance, onboarded*) keep their CURRENT values unless ' +
'includeProtectedFields is explicitly true — time-traveling those via an old snapshot is almost never ' +
'intended. Same transactional verify-and-rollback machinery as update_tenant_config.',
'Restore a tenant\'s configuration from a named pre-write snapshot. Global Admin only. ' +
'The revert snapshots the CURRENT state first, so a revert is itself revertible — which is exactly why ' +
'backupId is required and there is no "latest" default: a repeated revert without an id would restore the ' +
'snapshot the previous revert just created and undo it. Reverting the same backupId twice is a no-op. ' +
'Protected fields (plan/trial, homedAppClientId, auth provenance, onboarded*) keep their CURRENT values ' +
'unless includeProtectedFields is explicitly true — time-traveling those via an old snapshot is almost ' +
'never intended. Same transactional verify-and-rollback machinery as update_tenant_config.',
inputSchema: {
tenantId: TenantGuidSchema.describe('Tenant ID (GUID) whose configuration to revert.'),
backupId: z.string().optional()
.describe('Snapshot to restore (from list_tenant_config_backups). Omit for the most recent snapshot.'),
backupId: z.string().min(1)
.describe('REQUIRED: the snapshot to restore — from list_tenant_config_backups, or the backupId an ' +
'update_tenant_config response returned. Never omitted: see the description.'),
includeProtectedFields: z.boolean().optional()
.describe('DANGEROUS, default false: also restore plan/trial, homedAppClientId and auth-provenance fields ' +
'from the snapshot. Only set when the snapshot\'s values for those are explicitly wanted.'),
@@ -1,5 +1,6 @@
import { ApiError, isTimeoutError, type ParsedErrorBody } from '../client.js';
import { ApiError, getCurrentArgPolicy, isTimeoutError, type ParsedErrorBody } from '../client.js';
import type { McpQuotaExceededResponse } from '../generated/wire-types.generated.js';
import { summarizeArgs } from '../telemetry.js';
interface ToolErrorResult {
[x: string]: unknown;
@@ -153,13 +154,13 @@ export function toolError(
}
}
// Include parameter summary so the AI can see what it sent
const argsSummary = Object.entries(args)
.filter(([, v]) => v != null && v !== undefined)
.map(([k, v]) => ` ${k}: ${JSON.stringify(v)}`)
.join('\n');
// Parameter summary so the AI can see what it sent — rendered under the SAME per-argument
// policy as the tool_call log line (withToolTelemetry): an argument declared 'keys' shows only
// its property names here too, so a clear-text config value never travels in an error text
// (the log quotes the first lines of this text).
const argsSummary = summarizeArgs(args, getCurrentArgPolicy());
if (argsSummary) {
parts.push(`**Parameters used**:\n${argsSummary}`);
parts.push(`**Parameters used**:\n${Object.entries(argsSummary).map(([k, v]) => ` ${k}: ${v}`).join('\n')}`);
}
return {
@@ -230,18 +230,92 @@ export function stringifyResult(data: unknown): string {
return PRETTY_JSON || isPrettyJsonRequested() ? JSON.stringify(data, null, 2) : JSON.stringify(data);
}
/**
* `_meta` key of an overflow answer (see toolResultText). The telemetry reads it to log the
* page at the size it WOULD have had, so the size distribution keeps naming the offending calls.
*/
export const OVERFLOW_META_KEY = 'autopilotmonitor.com/overflow';
/** Share of the cap an overflow advice aims at, so the re-sent page lands under it with headroom. */
const OVERFLOW_TARGET_RATIO = 0.9;
/** Fewest rows a page needs before its per-row size is worth projecting into a pageSize advice. */
const OVERFLOW_MIN_ROWS_FOR_ADVICE = 2;
export interface ToolResult {
// Index signature: the SDK's CallToolResult is indexable, and an interface without one is not
// assignable to it (an inline object type would be, implicitly).
[x: string]: unknown;
isError?: true;
content: Array<{ type: 'text'; text: string }>;
_meta: Record<string, unknown>;
}
/**
* Wraps a tool response payload with the Anthropic <c>maxResultSizeChars</c>
* annotation and a single text content block. Use in preference to bare
* <c>{ content: [...] }</c> so the cap travels with every call without
* client-side configuration.
*
* The cap is ENFORCED here, not merely advertised: the hint only tells an Anthropic host how
* much to accept — other hosts cut the JSON somewhere in the middle, and even that host has a
* ceiling. Either way the model would read a page with rows missing and no way to tell which
* (the nextLink at the end is usually the first casualty). So a page above the cap is not sent
* at all: the answer is an error carrying what the page held and, when the payload is a list,
* the exact pageSize that fits — computed from THIS page's measured bytes per row, not guessed.
* Nothing is lost because backend pages are re-requestable: the same continuation with the
* smaller pageSize returns the first rows plus a nextLink to the rest. The oversized page's
* own nextLink is deliberately withheld — following it would skip the rows that were dropped.
*/
export function toolResultText(
data: unknown,
maxResultSizeChars: number,
): { content: Array<{ type: 'text'; text: string }>; _meta: Record<string, unknown> } {
export function toolResultText(data: unknown, maxResultSizeChars: number): ToolResult {
const text = stringifyResult(data);
if (text.length <= maxResultSizeChars) {
return {
content: [{ type: 'text' as const, text }],
_meta: { 'anthropic/maxResultSizeChars': maxResultSizeChars },
};
}
return overflowResult(data, text.length, maxResultSizeChars);
}
/** The top-level list a page carries (its largest array-valued property), if any. */
function largestTopLevelList(data: unknown): { field: string; rows: number } | undefined {
if (typeof data !== 'object' || data === null || Array.isArray(data)) return undefined;
let best: { field: string; rows: number } | undefined;
for (const [field, value] of Object.entries(data as Record<string, unknown>)) {
if (Array.isArray(value) && (best === undefined || value.length > best.rows)) best = { field, rows: value.length };
}
return best;
}
function overflowResult(data: unknown, responseChars: number, maxResultSizeChars: number): ToolResult {
const list = largestTopLevelList(data);
const rowAdvice = list !== undefined && list.rows >= OVERFLOW_MIN_ROWS_FOR_ADVICE;
const rowsThatFit = rowAdvice
? Math.max(1, Math.floor((maxResultSizeChars * OVERFLOW_TARGET_RATIO) / (responseChars / list.rows)))
: undefined;
const body = {
overflow: true,
error:
`Result too large: ${responseChars} characters exceed this tool's ${maxResultSizeChars}-character response cap. ` +
'The page was NOT sent — a cut page would have lost rows without telling you which.',
responseChars,
maxResultSizeChars,
...(rowAdvice ? { rowsField: list.field, rowsFetched: list.rows, rowsThatFit } : {}),
advice: rowAdvice
? `This page held ${list.rows} rows in "${list.field}" at about ${Math.round(responseChars / list.rows)} characters each; ` +
`${rowsThatFit} rows fit the cap. If this tool takes pageSize, re-send the SAME call (same filters, same ` +
`continuation if any) with pageSize=${rowsThatFit} and follow its nextLink for the rest — nothing is skipped. ` +
'Otherwise narrow the query: tighter filters, a fields= projection without the payload column, a smaller date window.'
: 'Narrow the query: tighter filters, a fields= projection without the payload column, a smaller date window, ' +
'or a smaller pageSize if this tool takes one.',
};
return {
content: [{ type: 'text' as const, text: stringifyResult(data) }],
_meta: { 'anthropic/maxResultSizeChars': maxResultSizeChars },
isError: true,
content: [{ type: 'text' as const, text: stringifyResult(body) }],
_meta: {
'anthropic/maxResultSizeChars': maxResultSizeChars,
[OVERFLOW_META_KEY]: { responseChars },
},
};
}
@@ -86,6 +86,15 @@ namespace AutopilotMonitor.DecisionCore.Engine
/// <summary>On <c>DeadlineFired</c>: the deadline name from <see cref="DeadlineNames"/>.</summary>
public const string Deadline = "deadline";
/// <summary>
/// On <c>DeadlineFired</c>: the deadline's <see cref="State.ActiveDeadline.DueAtUtc"/> as an
/// ISO-8601 round-trip string. The signal's <c>OccurredAtUtc</c> is the time the timer
/// actually fired (which trails the due time after standby or an agent restart); stale-fire
/// guards that must identify the deadline incarnation read this key via
/// <c>DecisionEngine.DeadlineDueAtUtc</c>.
/// </summary>
public const string DeadlineDueAtUtc = "deadlineDueAtUtc";
/// <summary>On <c>EspPhaseChanged</c>: the raw phase name as observed by the collector.</summary>
public const string EspPhase = "phase";
@@ -252,10 +252,11 @@ namespace AutopilotMonitor.DecisionCore.Engine
// Third staleness shape (introduced with the activity-based extension): the fire
// belongs to an OLDER deadline incarnation that a re-arm has since replaced —
// recognizable because the armed deadline is due LATER than this fire
// (OccurredAtUtc = DueAtUtc per the scheduler contract). Without this guard the
// recognizable because the armed deadline is due LATER than the due time this fire
// belongs to (payload, see DeadlineDueAtUtc — never the signal time, which is the
// firing clock and trails the due time after standby). Without this guard the
// stale fire would evaluate the timeout/extension decision ahead of schedule.
var supersededByRearm = armedDeadline != null && armedDeadline.DueAtUtc > signal.OccurredAtUtc;
var supersededByRearm = armedDeadline != null && armedDeadline.DueAtUtc > DeadlineDueAtUtc(signal);
if (alreadyResolvedOrTimedOut || armedDeadline == null || supersededByRearm)
{
@@ -255,10 +255,11 @@ namespace AutopilotMonitor.DecisionCore.Engine
// --- Stale-fire guard C: DueAtUtc mismatch ---
// Cancel-then-rearm race: an old DeadlineFired (from a deadline incarnation that was
// replaced by a later HandleDeviceSetupProvisioningCompleteV1 arming) is processed
// after the rearm. DeadlineScheduler posts OccurredAtUtc == deadline.DueAtUtc, so the
// OLD fire carries the OLD DueAtUtc. Dead-end WITHOUT cancelling the active deadline
// (the whole point is to keep the new one for its real fire).
if (activeDeadline.DueAtUtc != signal.OccurredAtUtc)
// after the rearm. The fire carries the due time of the incarnation it belongs to
// (payload, see DeadlineDueAtUtc), so the OLD fire carries the OLD DueAtUtc. Dead-end
// WITHOUT cancelling the active deadline (the whole point is to keep the new one for
// its real fire).
if (activeDeadline.DueAtUtc != DeadlineDueAtUtc(signal))
{
var bookkept = BumpStepBookkeeping(state, signal);
var transition = BuildDeadEndTransition(
@@ -1013,6 +1013,27 @@ namespace AutopilotMonitor.DecisionCore.Engine
return signal.OccurredAtUtc;
}
/// <summary>
/// The due time of the deadline a <c>DeadlineFired</c> signal belongs to. The host stamps the
/// signal with the wall-clock firing time (after Modern Standby or an agent restart that
/// trails the due time by minutes) and carries the due time under
/// <see cref="SignalPayloadKeys.DeadlineDueAtUtc"/>; stale-fire guards compare THIS against
/// the armed <see cref="ActiveDeadline.DueAtUtc"/>, never the signal time. Falls back to
/// <c>signal.OccurredAtUtc</c> for signal logs written before the key existed, where the
/// two were equal by contract.
/// </summary>
internal static DateTime DeadlineDueAtUtc(DecisionSignal signal)
{
if (signal.Payload != null
&& signal.Payload.TryGetValue(SignalPayloadKeys.DeadlineDueAtUtc, out var raw)
&& DateTime.TryParseExact(raw, "o", System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.RoundtripKind, out var due))
{
return due.Kind == DateTimeKind.Utc ? due : due.ToUniversalTime();
}
return signal.OccurredAtUtc;
}
/// <summary>
/// Determine the user-visible enrollment phase implied by an ESP phase-change signal.
/// Plan §2.3 phase-fact mapping. Populated in M3.1 as Classic handlers come online.
@@ -282,11 +282,9 @@ namespace AutopilotMonitor.DecisionCore.Engine
if (!reachedTerminal)
{
// The DeadlineFired signal carries DueAtUtc as OccurredAtUtc, so for a tick
// armed in the current run this is already current-clock-equivalent. The
// EffectiveDeadlineBase guard still fires correctly across restart, where
// a stale DueAtUtc from the prior run could otherwise re-arm the next tick
// in the past.
// The DeadlineFired signal carries the wall-clock firing time, so the next tick
// is armed relative to now — also after a late fire (standby). The
// EffectiveDeadlineBase guard still floors a replayed fire at boot.
var rearm = BuildClassifierTickDeadline(EffectiveDeadlineBase(state, signal));
builder.AddDeadline(rearm);
effects.Add(new DecisionEffect(DecisionEffectKind.ScheduleDeadline, deadline: rearm));
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using AutopilotMonitor.DecisionCore.Signals;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
@@ -46,7 +47,7 @@ namespace AutopilotMonitor.DecisionCore.Serialization
var d = new Dictionary<string, string>();
foreach (var prop in diObj.Properties())
{
d[prop.Name] = prop.Value?.ToString() ?? string.Empty;
d[prop.Name] = StringValue(prop.Value);
}
derivationInputs = d;
}
@@ -64,7 +65,7 @@ namespace AutopilotMonitor.DecisionCore.Serialization
var p = new Dictionary<string, string>();
foreach (var prop in payloadObj.Properties())
{
p[prop.Name] = prop.Value?.ToString() ?? string.Empty;
p[prop.Name] = StringValue(prop.Value);
}
payload = p;
}
@@ -112,6 +113,23 @@ namespace AutopilotMonitor.DecisionCore.Serialization
typedPayload: typedPayload);
}
/// <summary>
/// String-dictionary values (Payload, DerivationInputs) verbatim. The shared reader
/// tokenizes an ISO-8601 string as a Date (<c>DateParseHandling.DateTime</c>), and
/// <c>JValue.ToString()</c> would then render it in the current culture — a replayed
/// <c>deadlineDueAtUtc</c> came back as "4/20/2026 9:55:00 AM". Render a Date token as
/// the round-trip text the writer produced.
/// </summary>
private static string StringValue(JToken? token)
{
if (token is JValue jv && jv.Type == JTokenType.Date && jv.Value is DateTime dt)
{
var utc = dt.Kind == DateTimeKind.Local ? dt.ToUniversalTime() : DateTime.SpecifyKind(dt, DateTimeKind.Utc);
return utc.ToString("O", CultureInfo.InvariantCulture);
}
return token?.ToString() ?? string.Empty;
}
private static T ParseEnum<T>(string? raw, T fallback) where T : struct, Enum
{
if (string.IsNullOrEmpty(raw)) return fallback;
@@ -1276,6 +1276,12 @@ namespace AutopilotMonitor.Shared
// Session reports (feedback from Tenant Admins)
public const string SessionReports = "SessionReports";
// Custom rules submitted for the community pool. PK = "submissions" for every tenant,
// RK = {invertedTicks}_{submissionId} (the SessionReports layout); tenant views and the
// point lookup are property filters — a submission is a rare, deliberate act, so the
// partition stays small enough that a second key layout would cost more than it saves.
public const string RuleSubmissions = "RuleSubmissions";
// Bootstrap sessions (OOBE pre-enrollment agent deployment)
public const string BootstrapSessions = "BootstrapSessions";
@@ -1454,6 +1460,7 @@ namespace AutopilotMonitor.Shared
BlockedDevices,
BlockedVersions,
SessionReports,
RuleSubmissions,
BootstrapSessions,
GlobalNotifications,
TenantNotifications,
@@ -137,6 +137,8 @@ namespace AutopilotMonitor.Shared.DataAccess
Task<SessionTimeBreakdown?> GetSessionTimeBreakdownAsync(string tenantId, string sessionId);
/// <summary>Re-joins the session's app rows against its latest esp_config_detected lists (positive evidence only). Idempotent + fail-soft — the terminal seam runs it once; the sweep re-runs it when late events changed the stream.</summary>
Task ResolveEspBlockingForSessionAsync(string tenantId, string sessionId);
/// <summary>Closes the session's app rows that never reached a terminal state (InProgress → Incomplete, outcome unknown). Idempotent + fail-soft — the terminal seam, the agent-shutdown batch and the sweep all call it; a real terminal arriving later still wins. Returns the number of rows closed.</summary>
Task<int> CloseOpenAppInstallsForSessionAsync(string tenantId, string sessionId);
Task<bool> SaveTimeAttributionAggregateAsync(TimeAttributionDailyAggregate aggregate);
/// <summary>Aggregate rows of one tenant partition ("global" allowed) for an inclusive date range.</summary>
Task<List<TimeAttributionDailyAggregate>> GetTimeAttributionAggregatesAsync(string tenantId, DateTime startDate, DateTime endDate);
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutopilotMonitor.Shared.Models;
using AutopilotMonitor.Shared.Pagination;
namespace AutopilotMonitor.Shared.DataAccess
{
/// <summary>
/// Repository for the <c>RuleSubmissions</c> table (one partition, newest-first RowKeys).
/// Expected volume is small — a submission is a rare, deliberate act — so the tenant view and
/// the point lookup are property filters over the partition rather than a second key layout.
/// </summary>
public interface IRuleSubmissionRepository
{
Task<bool> AddAsync(RuleSubmission submission);
/// <summary>Point lookup by id across all tenants; null when unknown.</summary>
Task<RuleSubmission?> GetAsync(string submissionId);
/// <summary>Every submission of one tenant, newest first.</summary>
Task<List<RuleSubmission>> GetForTenantAsync(string tenantId);
/// <summary>One page newest-first, optionally filtered by tenant and stored status.</summary>
Task<RawPage<RuleSubmission>> GetPageAsync(string? tenantId, string? status, int pageSize, string? continuation);
/// <summary>Replaces the row's mutable review columns; false when the row is gone.</summary>
Task<bool> UpdateAsync(RuleSubmission submission);
/// <summary>The published ids reserved by approved submissions — the third set the id suggestion excludes.</summary>
Task<HashSet<string>> GetReservedPublishedRuleIdsAsync();
/// <summary>Deletes withdrawn and declined rows past <see cref="RuleSubmissionRetention"/>; returns the number deleted.</summary>
Task<int> DeleteExpiredAsync(DateTime nowUtc);
/// <summary>Hard delete of one row (operator action); false when the row is gone.</summary>
Task<bool> DeleteAsync(string submissionId);
}
}
@@ -43,7 +43,12 @@ namespace AutopilotMonitor.Shared.Models
public bool AppIdCollision { get; set; }
/// <summary>
/// Lifecycle status: Succeeded, Failed, InProgress, or empty.
/// Lifecycle status: Succeeded, Failed, InProgress, Incomplete, or empty.
/// "Incomplete" is terminal and non-failure: the row was still InProgress when the
/// session's observation ended (terminal session, agent gone), so no outcome was ever
/// seen. Written only by the observation-end close step, never by an ingest fold;
/// CompletedAt and DurationSeconds stay unset (unknown, reported as unmeasured) and a
/// real terminal arriving later overrides it.
/// Empty (default) is a sentinel meaning "no status-relevant event observed in the current
/// aggregation batch". Aggregators only set a real value when they see started / completed /
/// failed / skipped. The storage layer omits the column from the upsert when this is empty
@@ -16,6 +16,8 @@ namespace AutopilotMonitor.Shared.Models
public int TotalInstalls { get; set; }
public int TotalSkipped { get; set; }
public int TotalUnmeasured { get; set; }
/// <summary>Rows still installing when the session's observation ended — outcome unknown, outside the failure rate.</summary>
public int TotalIncomplete { get; set; }
/// <summary>Rows excluded from per-app groups because their name-keyed row merged distinct appIds.</summary>
public int TotalCollisionExcluded { get; set; }
public IReadOnlyList<AppMetricsAppGroup> SlowestApps { get; set; } = default!;
@@ -32,6 +34,8 @@ namespace AutopilotMonitor.Shared.Models
public int Skipped { get; set; }
public int Unmeasured { get; set; }
public int Failed { get; set; }
/// <summary>Still installing when the session's observation ended — outcome unknown, outside the rate.</summary>
public int Incomplete { get; set; }
/// <summary>Failed / (failed + succeeded) as a percentage; skips never count as attempts.</summary>
public double FailureRate { get; set; }
/// <summary>Average measured FINAL-attempt duration (whole seconds); 0 with no measured installs.</summary>
@@ -82,6 +82,8 @@ namespace AutopilotMonitor.Shared.Models
public int Skipped { get; set; }
public int Unmeasured { get; set; }
public int Failed { get; set; }
/// <summary>Still installing when the session's observation ended — outcome unknown, outside the rate.</summary>
public int Incomplete { get; set; }
public double FailureRate { get; set; }
public double AvgDurationSeconds { get; set; }
public int P95DurationSeconds { get; set; }
@@ -0,0 +1,145 @@
using System;
using System.Collections.Generic;
namespace AutopilotMonitor.Shared.Models
{
/// <summary>One rule reference in a submit request; the server freezes the rule itself.</summary>
[WireContract]
public class RuleSubmissionItemRef
{
/// <summary>One of <see cref="RuleSubmissionKinds.All"/>.</summary>
public string Kind { get; set; } = default!;
public string RuleId { get; set; } = default!;
}
/// <summary>Body of POST rules/submissions: up to <see cref="MaxItems"/> of the caller's own custom rules.</summary>
public class SubmitRuleSubmissionsRequest : IApiRequest
{
public const int MaxItems = 10;
public const int MaxCommentLength = 4000;
public const int MaxAttributionNameLength = 64;
public const int MaxEmailLength = 254;
public string TenantId { get; set; } = default!;
public List<RuleSubmissionItemRef> Items { get; set; } = new List<RuleSubmissionItemRef>();
public string? Comment { get; set; }
/// <summary>Optional reply address; stored for the reviewer, never published.</summary>
public string? Email { get; set; }
/// <summary>One of <see cref="RuleAttributionModes.All"/>.</summary>
public string AttributionMode { get; set; } = RuleAttributionModes.Anonymous;
/// <summary>Credit text for the <c>person</c> mode; ignored for the other modes.</summary>
public string? AttributionName { get; set; }
}
/// <summary>
/// Wire shape of one submission (list rows, submit response, detail head). The frozen rule
/// document is not part of it — the detail response carries it typed.
/// </summary>
// Declaration order == wire order.
[WireContract]
public class RuleSubmissionItem
{
public string SubmissionId { get; set; } = default!;
public string BatchId { get; set; } = default!;
public string TenantId { get; set; } = default!;
public string RuleKind { get; set; } = default!;
public string SourceRuleId { get; set; } = default!;
public string Title { get; set; } = default!;
public string Category { get; set; } = default!;
public string? Comment { get; set; }
public string SubmittedBy { get; set; } = default!;
public string SubmittedByName { get; set; } = default!;
public string? ContactEmail { get; set; }
public string AttributionMode { get; set; } = default!;
public string AttributionName { get; set; } = default!;
public DateTime SubmittedAt { get; set; }
/// <summary>One of <see cref="RuleSubmissionStatuses.All"/> — the effective status, <c>published</c> included.</summary>
public string Status { get; set; } = default!;
public IReadOnlyList<RuleSubmissionFinding> ValidationFindings { get; set; } = default!;
public RuleSubmissionFireStats? SourceFireStats { get; set; }
public string? ReviewedBy { get; set; }
public DateTime? ReviewedAt { get; set; }
public string? ReviewComment { get; set; }
public bool WillBeAdapted { get; set; }
public string? PublishedRuleId { get; set; }
public string? DerivedFromTemplateRuleId { get; set; }
}
/// <summary>Success body of POST rules/submissions.</summary>
// Declaration order == wire order.
public class SubmitRuleSubmissionsResponse : IApiResponse
{
public bool Success { get; set; }
public string Message { get; set; } = default!;
public string BatchId { get; set; } = default!;
public IReadOnlyList<RuleSubmissionItem> Submissions { get; set; } = default!;
}
/// <summary>Success body of GET rules/submissions and GET global/rule-submissions.</summary>
// Declaration order == wire order.
public class RuleSubmissionListResponse : IApiResponse
{
public bool Success { get; set; }
public int Count { get; set; }
public IReadOnlyList<RuleSubmissionItem> Submissions { get; set; } = default!;
/// <summary>Absolute-path link to the next page; null/absent on the last page and in non-paged responses.</summary>
public string? NextLink { get; set; }
}
/// <summary>The repo-ready file for a submission: where it goes and what it contains.</summary>
// Declaration order == wire order.
[WireContract]
public class RuleSubmissionRepoFile
{
/// <summary>Repository-relative path, e.g. <c>rules/analyze/ANALYZE-NET-002.json</c>.</summary>
public string Path { get; set; } = default!;
public string Content { get; set; } = default!;
}
/// <summary>
/// Success body of GET global/rule-submissions/{id}: the submission, the frozen rule typed by
/// kind (exactly one of the two rule properties is set), live fire stats, the suggested
/// reserved id and the repo file built from the assigned (or suggested) id.
/// </summary>
// Declaration order == wire order.
public class RuleSubmissionDetailResponse : IApiResponse
{
public bool Success { get; set; }
public RuleSubmissionItem Submission { get; set; } = default!;
public AnalyzeRule? AnalyzeRule { get; set; }
public GatherRule? GatherRule { get; set; }
public RuleSubmissionFireStats? LiveFireStats { get; set; }
public string? SuggestedPublishedRuleId { get; set; }
public RuleSubmissionRepoFile? RepoFile { get; set; }
}
/// <summary>Body of PATCH global/rule-submissions/{id}.</summary>
public class ReviewRuleSubmissionRequest : IApiRequest
{
public const int MaxReviewCommentLength = 4000;
/// <summary>One of <see cref="RuleSubmissionDecisions.All"/>.</summary>
public string Decision { get; set; } = default!;
/// <summary>Shown to the submitter. Required for <c>decline</c>.</summary>
public string? ReviewComment { get; set; }
public bool? WillBeAdapted { get; set; }
/// <summary>Reserved-namespace id the rule ships under. Required for <c>approve</c>.</summary>
public string? PublishedRuleId { get; set; }
}
/// <summary>Success body of PATCH global/rule-submissions/{id}.</summary>
// Declaration order == wire order.
public class ReviewRuleSubmissionResponse : IApiResponse
{
public bool Success { get; set; }
public string Message { get; set; } = default!;
public RuleSubmissionItem Submission { get; set; } = default!;
}
}
@@ -0,0 +1,155 @@
using System;
using System.Collections.Generic;
namespace AutopilotMonitor.Shared.Models
{
/// <summary>
/// One custom rule a tenant admin submitted for the community pool. Stored in the
/// <c>RuleSubmissions</c> table: PK = <c>"submissions"</c> (one partition for every tenant,
/// the SessionReports layout), RK = <c>{invertedTicks(SubmittedAt)}_{SubmissionId}</c>.
/// <see cref="RuleJson"/> is the server-frozen snapshot of the rule at submit time — the
/// tenant's later edits or deletes never reach it, and the payload never supplies it.
/// The stored <see cref="Status"/> is never <see cref="RuleSubmissionStatuses.Published"/>:
/// that value is derived at read time from the global rule catalog.
/// </summary>
public class RuleSubmission
{
/// <summary>Twelve hex characters, the same shape as a session report id.</summary>
public string SubmissionId { get; set; } = default!;
/// <summary>Groups the rules of one submit action; each rule keeps its own id and status.</summary>
public string BatchId { get; set; } = default!;
public string TenantId { get; set; } = default!;
/// <summary>One of <see cref="RuleSubmissionKinds.All"/>.</summary>
public string RuleKind { get; set; } = default!;
/// <summary>The rule id in the tenant's partition at submit time.</summary>
public string SourceRuleId { get; set; } = default!;
public string Title { get; set; } = default!;
public string Category { get; set; } = default!;
/// <summary>Frozen rule document (wire JSON of the rule minus server and tenant fields).</summary>
public string RuleJson { get; set; } = default!;
public string? Comment { get; set; }
public string SubmittedBy { get; set; } = default!;
public string SubmittedByName { get; set; } = default!;
/// <summary>Optional reply address the submitter entered — a UPN is not always a mailbox. Never published.</summary>
public string? ContactEmail { get; set; }
/// <summary>One of <see cref="RuleAttributionModes.All"/>.</summary>
public string AttributionMode { get; set; } = RuleAttributionModes.Anonymous;
/// <summary>The exact text that becomes the published rule's <c>author</c>. Frozen at submit time.</summary>
public string AttributionName { get; set; } = RuleAttributionModes.AnonymousAuthor;
public DateTime SubmittedAt { get; set; }
/// <summary>One of <see cref="RuleSubmissionStatuses.Stored"/>.</summary>
public string Status { get; set; } = RuleSubmissionStatuses.Pending;
public List<RuleSubmissionFinding> ValidationFindings { get; set; } = new List<RuleSubmissionFinding>();
public RuleSubmissionFireStats? SourceFireStats { get; set; }
public string? ReviewedBy { get; set; }
public DateTime? ReviewedAt { get; set; }
public string? ReviewComment { get; set; }
/// <summary>The reviewer announced that the published rule will differ from the submitted one.</summary>
public bool WillBeAdapted { get; set; }
/// <summary>The reserved-namespace id assigned on approval; the published rule's id.</summary>
public string? PublishedRuleId { get; set; }
public string? DerivedFromTemplateRuleId { get; set; }
}
/// <summary>A pre-flight finding recorded at submit time. Errors block the submission and are never stored.</summary>
[WireContract]
public class RuleSubmissionFinding
{
/// <summary>"error" | "warning" | "info".</summary>
public string Level { get; set; } = default!;
public string Message { get; set; } = default!;
}
/// <summary>Fire telemetry of the submitted rule in the submitting tenant over the trailing window.</summary>
[WireContract]
public class RuleSubmissionFireStats
{
public int Days { get; set; }
public int FireCount { get; set; }
public int SessionsEvaluated { get; set; }
public int EvaluationCount { get; set; }
}
public static class RuleSubmissionKinds
{
public const string Gather = "gather";
public const string Analyze = "analyze";
public static readonly string[] All = { Gather, Analyze };
public static bool IsKnown(string? kind)
=> kind == Gather || kind == Analyze;
}
public static class RuleSubmissionStatuses
{
public const string Pending = "pending";
public const string Approved = "approved";
public const string Declined = "declined";
public const string Withdrawn = "withdrawn";
/// <summary>Derived at read time (approved + the published id exists in the global catalog); never stored.</summary>
public const string Published = "published";
/// <summary>Every wire value, including the derived one.</summary>
public static readonly string[] All = { Pending, Approved, Declined, Withdrawn, Published };
/// <summary>The values a row may carry.</summary>
public static readonly string[] Stored = { Pending, Approved, Declined, Withdrawn };
}
public static class RuleAttributionModes
{
public const string Anonymous = "anonymous";
public const string Organization = "organization";
public const string Person = "person";
public static readonly string[] All = { Anonymous, Organization, Person };
/// <summary>The <c>author</c> text of an anonymously contributed rule.</summary>
public const string AnonymousAuthor = "Community contribution";
public static bool IsKnown(string? mode)
=> mode == Anonymous || mode == Organization || mode == Person;
}
/// <summary>
/// Retention of closed submissions (daily maintenance sweep). Withdrawn rows carry no
/// information beyond "taken back"; declined rows keep the reviewer's reason readable long
/// enough to improve and resubmit. Pending, approved and published rows are never swept —
/// the last two are the provenance of a community rule.
/// </summary>
public static class RuleSubmissionRetention
{
public const int WithdrawnDays = 30;
public const int DeclinedDays = 90;
public static bool IsExpired(RuleSubmission s, DateTime nowUtc)
{
switch (s.Status)
{
case RuleSubmissionStatuses.Withdrawn:
return s.SubmittedAt <= nowUtc.AddDays(-WithdrawnDays);
case RuleSubmissionStatuses.Declined:
return (s.ReviewedAt ?? s.SubmittedAt) <= nowUtc.AddDays(-DeclinedDays);
default:
return false;
}
}
}
public static class RuleSubmissionDecisions
{
public const string Approve = "approve";
public const string Decline = "decline";
public static readonly string[] All = { Approve, Decline };
}
}
@@ -0,0 +1,594 @@
"use client";
import { Suspense, useCallback, useEffect, useRef, useState } from "react";
import { useSearchParams } from "next/navigation";
import { api } from "@/lib/api";
import { apiErrorText, fetchJson, fetchOk, jsonBody, nullOn404 } from "@/lib/apiClient";
import TruncatedLabel from "@/components/TruncatedLabel";
import { extractContinuation } from "@/lib/paginationLink";
import { isGuid } from "@/utils/inputValidation";
import { trackEvent } from "@/lib/appInsights";
import { useCanMutatePlatform } from "@/hooks/useCanMutatePlatform";
import { TableSkeleton } from "@/components/skeletons/TableSkeleton";
import { SectionCardHeader } from "@/components/SectionCardHeader";
import { ModalPortal } from "@/components/ModalPortal";
import { submissionStatusBadge } from "@/components/rules/MySubmissionsList";
import type {
ReseedFromGitHubResponse,
ReviewRuleSubmissionRequest,
ReviewRuleSubmissionResponse,
RuleSubmissionDetailResponse,
RuleSubmissionFireStats,
RuleSubmissionItem,
RuleSubmissionListResponse,
} from "@/utils/wire-types.generated";
const PAGE_SIZE = 20;
const STATUS_FILTERS = ["pending", "approved", "declined", "withdrawn"] as const;
interface RuleSubmissionsSectionProps {
getAccessToken: () => Promise<string | null>;
setError: (error: string | null) => void;
}
function CopyButton({ value, title = "Copy to clipboard" }: { value: string; title?: string }) {
const [copied, setCopied] = useState(false);
const handleCopy = (e: React.MouseEvent) => {
e.stopPropagation();
navigator.clipboard.writeText(value).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1500);
});
};
return (
<button onClick={handleCopy} title={title} className="ml-1.5 p-0.5 rounded text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors">
{copied ? (
<svg className="w-3.5 h-3.5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
) : (
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
)}
</button>
);
}
function StatusBadge({ status }: { status: string }) {
const b = submissionStatusBadge(status);
return <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${b.cls}`}>{b.label}</span>;
}
function KindBadge({ kind }: { kind: string }) {
const cls = kind === "analyze"
? "bg-indigo-100 text-indigo-800 dark:bg-indigo-900/40 dark:text-indigo-300"
: "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300";
return <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${cls}`}>{kind === "analyze" ? "Analyze" : "Gather"}</span>;
}
function fireStatsText(s: RuleSubmissionFireStats | undefined | null): string {
if (!s) return "not available";
return `fired ${s.fireCount}× in ${s.sessionsEvaluated} evaluated sessions (${s.days} days, ${s.evaluationCount} evaluations)`;
}
export function RuleSubmissionsSection(props: RuleSubmissionsSectionProps) {
// useSearchParams() needs a Suspense boundary for the static prerender.
return (
<Suspense fallback={null}>
<RuleSubmissionsSectionInner {...props} />
</Suspense>
);
}
function RuleSubmissionsSectionInner({ getAccessToken, setError }: RuleSubmissionsSectionProps) {
// Decisions and the reseed are GA-only (GlobalAdminOnly routes); a Global Reader may look.
const canMutate = useCanMutatePlatform();
const [items, setItems] = useState<RuleSubmissionItem[]>([]);
const [loading, setLoading] = useState(true);
const [detail, setDetail] = useState<RuleSubmissionDetailResponse | null>(null);
const [detailLoading, setDetailLoading] = useState(false);
const [tenantFilterInput, setTenantFilterInput] = useState("");
const [tenantFilterApplied, setTenantFilterApplied] = useState<string | undefined>(undefined);
const [statusFilter, setStatusFilter] = useState<string>("");
const [continuation, setContinuation] = useState<string | null>(null);
const [nextLink, setNextLink] = useState<string | null>(null);
const [continuationStack, setContinuationStack] = useState<Array<string | null>>([]);
const [pageNumber, setPageNumber] = useState(1);
const openDetail = useCallback(async (submissionId: string) => {
try {
setDetailLoading(true);
const data = await fetchJson<RuleSubmissionDetailResponse>(api.ruleSubmissions.detail(submissionId), getAccessToken);
setDetail(data);
} catch (err) {
setError(apiErrorText(err, "Failed to load the submission"));
} finally {
setDetailLoading(false);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [setError]);
// Deep link from the GA notification: ?submissionId=… opens the detail straight from the
// detail endpoint — no dependency on the row being on the first page.
const searchParams = useSearchParams();
const submissionIdParam = searchParams?.get("submissionId") ?? null;
const autoOpenConsumed = useRef(false);
useEffect(() => {
if (autoOpenConsumed.current || !submissionIdParam) return;
autoOpenConsumed.current = true;
const run = async () => { await openDetail(submissionIdParam); };
void run();
}, [submissionIdParam, openDetail]);
const fetchPage = useCallback(async (cursor: string | null, filterTenantId: string | undefined, status: string) => {
try {
setLoading(true);
const data = await fetchJson<RuleSubmissionListResponse>(
api.ruleSubmissions.list({ tenantId: filterTenantId, status: status || undefined, pageSize: PAGE_SIZE, continuation: cursor ?? undefined }),
getAccessToken,
).catch(nullOn404);
setItems(data?.submissions ?? []);
setNextLink(data?.nextLink ?? null);
} catch (err) {
setError(apiErrorText(err, "Failed to load rule submissions"));
} finally {
setLoading(false);
}
// getAccessToken churns on every MSAL refresh — see SessionReportsSection.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [setError]);
useEffect(() => {
const run = async () => {
setContinuation(null);
setContinuationStack([]);
setPageNumber(1);
await fetchPage(null, tenantFilterApplied, statusFilter);
};
void run();
}, [tenantFilterApplied, statusFilter, fetchPage]);
const handleApplyTenantFilter = () => {
const trimmed = tenantFilterInput.trim();
if (trimmed && !isGuid(trimmed)) {
setError("Tenant ID must be a valid GUID");
return;
}
setError(null);
setTenantFilterApplied(trimmed || undefined);
};
const handleNextPage = () => {
const nextCont = extractContinuation(nextLink);
if (!nextCont) return;
setContinuationStack((stack) => [...stack, continuation]);
setContinuation(nextCont);
setPageNumber((n) => n + 1);
void fetchPage(nextCont, tenantFilterApplied, statusFilter);
};
const handlePrevPage = () => {
if (continuationStack.length === 0) return;
const prev = continuationStack[continuationStack.length - 1];
setContinuationStack((stack) => stack.slice(0, -1));
setContinuation(prev ?? null);
setPageNumber((n) => Math.max(1, n - 1));
void fetchPage(prev ?? null, tenantFilterApplied, statusFilter);
};
const handleRefresh = () => fetchPage(continuation, tenantFilterApplied, statusFilter);
const handleReviewed = (updated: RuleSubmissionItem) => {
setItems((prev) => prev.map((s) => (s.submissionId === updated.submissionId ? updated : s)));
void openDetail(updated.submissionId);
};
const handleDeleted = (submissionId: string) => {
setItems((prev) => prev.filter((s) => s.submissionId !== submissionId));
setDetail(null);
};
return (
<div className="bg-gradient-to-br from-indigo-50 to-purple-50 dark:from-gray-800 dark:to-gray-800 border-2 border-indigo-300 dark:border-indigo-700 rounded-lg shadow-lg">
<SectionCardHeader
tone="adminIndigoPurple"
iconPath="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"
title="Rule Submissions"
subtitle="Custom rules submitted by Tenant Admins for the community pool"
/>
{/* Filters + refresh */}
<div className="px-6 pt-4 pb-2 flex items-center gap-2 flex-wrap">
<span className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide">Filter:</span>
<input
type="text"
placeholder="Tenant ID (GUID)"
value={tenantFilterInput}
onChange={(e) => setTenantFilterInput(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleApplyTenantFilter(); }}
className="w-72 px-2 py-1 text-xs font-mono border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-green-500 focus:border-green-500"
/>
<button onClick={handleApplyTenantFilter} disabled={loading} className="px-2.5 py-1 text-xs font-medium rounded-md border border-indigo-300 dark:border-indigo-700 text-indigo-700 dark:text-indigo-300 hover:bg-indigo-100 dark:hover:bg-indigo-900/40 disabled:opacity-40 transition-colors">
Apply
</button>
{tenantFilterApplied && (
<button onClick={() => { setTenantFilterInput(""); setTenantFilterApplied(undefined); }} disabled={loading} className="px-2.5 py-1 text-xs font-medium rounded-md border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 disabled:opacity-40 transition-colors">
Clear
</button>
)}
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-green-500 focus:border-green-500"
>
<option value="">All statuses</option>
{STATUS_FILTERS.map((s) => <option key={s} value={s}>{submissionStatusBadge(s).label}</option>)}
</select>
<button onClick={handleRefresh} disabled={loading} className="ml-auto px-2.5 py-1 text-xs font-medium rounded-md border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 disabled:opacity-40 transition-colors">
{loading ? "Loading..." : "Refresh"}
</button>
</div>
{/* Table */}
<div className="p-6 pt-2">
{loading && items.length === 0 ? (
<TableSkeleton columns={8} rows={6} />
) : items.length === 0 ? (
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
<p className="text-sm">No rule submissions{statusFilter ? ` with status "${statusFilter}"` : " yet"}.</p>
</div>
) : (
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead className="bg-gray-50 dark:bg-gray-700/50">
<tr>
{["ID", "Date", "Kind", "Rule", "Tenant", "Submitted By", "Credit", "Status", "Comment"].map((h) => (
<th key={h} className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">{h}</th>
))}
</tr>
</thead>
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
{items.map((s) => (
<tr key={s.submissionId} onClick={() => openDetail(s.submissionId)} className="hover:bg-indigo-50 dark:hover:bg-indigo-900/20 cursor-pointer transition-colors">
<td className="px-4 py-3 text-sm font-mono text-gray-900 dark:text-gray-100 whitespace-nowrap">
<span className="inline-flex items-center">{s.submissionId}<CopyButton value={s.submissionId} /></span>
</td>
<td className="px-4 py-3 text-sm text-gray-900 dark:text-gray-100 whitespace-nowrap">{new Date(s.submittedAt).toLocaleString()}</td>
<td className="px-4 py-3 text-sm whitespace-nowrap"><KindBadge kind={s.ruleKind} /></td>
<td className="px-4 py-3 text-sm text-gray-900 dark:text-gray-100 max-w-xs">
<span className="font-mono text-xs">{s.sourceRuleId}</span>
<TruncatedLabel interactive={false} text={s.title} className="block text-xs text-gray-500 dark:text-gray-400" />
</td>
<td className="px-4 py-3 text-sm font-mono text-gray-700 dark:text-gray-300">{s.tenantId.slice(0, 8)}...</td>
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{s.submittedBy}</td>
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">{s.attributionName}</td>
<td className="px-4 py-3 text-sm whitespace-nowrap"><StatusBadge status={s.status} /></td>
<td className="px-4 py-3 max-w-xs">
{s.comment
? <TruncatedLabel interactive={false} text={s.comment} className="block text-sm text-gray-700 dark:text-gray-300" />
: <span className="text-sm text-gray-400 italic">no comment</span>}
</td>
</tr>
))}
</tbody>
</table>
<div className="flex items-center justify-between border-t border-gray-200 dark:border-gray-700 px-4 py-3 bg-gray-50 dark:bg-gray-700/50 rounded-b-md">
<span className="text-xs text-gray-500 dark:text-gray-400">{items.length} on page {pageNumber}{nextLink ? "" : " (last)"}</span>
<div className="flex items-center gap-2">
<button onClick={handlePrevPage} disabled={continuationStack.length === 0 || loading} className="px-2.5 py-1 text-xs font-medium rounded-md border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 disabled:opacity-40 disabled:cursor-not-allowed transition-colors">Previous</button>
<button onClick={handleNextPage} disabled={!nextLink || loading} className="px-2.5 py-1 text-xs font-medium rounded-md border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600 disabled:opacity-40 disabled:cursor-not-allowed transition-colors">Next</button>
</div>
</div>
</div>
)}
</div>
{(detail || detailLoading) && (
<SubmissionDetailModal
detail={detail}
loading={detailLoading}
canMutate={canMutate}
getAccessToken={getAccessToken}
onClose={() => setDetail(null)}
onReviewed={handleReviewed}
onReload={(id) => openDetail(id)}
onDeleted={handleDeleted}
/>
)}
</div>
);
}
// ── Detail modal ──────────────────────────────────────────────────────────
function SubmissionDetailModal({
detail, loading, canMutate, getAccessToken, onClose, onReviewed, onReload, onDeleted,
}: {
detail: RuleSubmissionDetailResponse | null;
loading: boolean;
canMutate: boolean;
getAccessToken: () => Promise<string | null>;
onClose: () => void;
onReviewed: (updated: RuleSubmissionItem) => void;
onReload: (submissionId: string) => void;
onDeleted: (submissionId: string) => void;
}) {
const s = detail?.submission ?? null;
const [publishedRuleId, setPublishedRuleId] = useState("");
const [reviewComment, setReviewComment] = useState("");
const [willBeAdapted, setWillBeAdapted] = useState(false);
const [busy, setBusy] = useState<string | null>(null);
const [message, setMessage] = useState<{ kind: "ok" | "error"; text: string } | null>(null);
const [showRepoFile, setShowRepoFile] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
// Seed the decision form from the loaded submission (adjust-during-render on identity change).
const [seededFor, setSeededFor] = useState<string | null>(null);
if (s && seededFor !== s.submissionId + s.status) {
setSeededFor(s.submissionId + s.status);
setPublishedRuleId(s.publishedRuleId ?? detail?.suggestedPublishedRuleId ?? "");
setReviewComment(s.reviewComment ?? "");
setWillBeAdapted(s.willBeAdapted);
setMessage(null);
}
const rule = detail?.analyzeRule ?? detail?.gatherRule ?? null;
const ruleJson = rule ? JSON.stringify(rule, null, 2) : "";
const decidable = !!s && (s.status === "pending" || s.status === "approved");
const review = async (decision: "approve" | "decline") => {
if (!s) return;
try {
setBusy(decision);
setMessage(null);
const data = await fetchJson<ReviewRuleSubmissionResponse>(
api.ruleSubmissions.review(s.submissionId),
getAccessToken,
{
method: "PATCH",
body: jsonBody<ReviewRuleSubmissionRequest>({
decision,
reviewComment: reviewComment.trim() || undefined,
willBeAdapted: decision === "approve" ? willBeAdapted : undefined,
publishedRuleId: decision === "approve" ? publishedRuleId.trim() : undefined,
}),
},
);
trackEvent("rule_submission_reviewed", { decision, kind: s.ruleKind });
setMessage({ kind: "ok", text: data.message });
onReviewed(data.submission);
} catch (err) {
setMessage({ kind: "error", text: apiErrorText(err, "Review failed") });
} finally {
setBusy(null);
}
};
const reseed = async () => {
if (!s) return;
try {
setBusy("reseed");
setMessage(null);
const type = s.ruleKind === "analyze" ? "analyze" : "gather";
const data = await fetchJson<ReseedFromGitHubResponse>(api.rules.reseedFromGitHub(type), getAccessToken, { method: "POST" });
const counts = type === "analyze" ? data.analyze : data.gather;
setMessage({ kind: "ok", text: `Reseeded ${type} rules from GitHub: ${counts?.written ?? 0} written, ${counts?.deleted ?? 0} deleted.` });
onReload(s.submissionId);
} catch (err) {
setMessage({ kind: "error", text: apiErrorText(err, "Reseed failed") });
} finally {
setBusy(null);
}
};
// Operator hard delete (test/demo rows, or a tenant's request): two clicks, no dialog.
const remove = async () => {
if (!s) return;
if (!confirmDelete) { setConfirmDelete(true); return; }
try {
setBusy("delete");
await fetchOk(api.ruleSubmissions.remove(s.submissionId), getAccessToken, { method: "DELETE" });
trackEvent("rule_submission_deleted", { kind: s.ruleKind, status: s.status });
onDeleted(s.submissionId);
} catch (err) {
setMessage({ kind: "error", text: apiErrorText(err, "Delete failed") });
setConfirmDelete(false);
} finally {
setBusy(null);
}
};
const downloadRepoFile = () => {
if (!detail?.repoFile) return;
const blob = new Blob([detail.repoFile.content], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = detail.repoFile.path.split("/").pop() ?? "rule.json";
a.click();
URL.revokeObjectURL(url);
};
return (
<ModalPortal>
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4" onClick={onClose}>
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-3xl w-full max-h-[90vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
<div className="p-6">
{!s ? (
<p className="text-sm text-gray-500 dark:text-gray-400">{loading ? "Loading submission..." : "Submission not found."}</p>
) : (
<>
<div className="flex items-center justify-between mb-4 gap-3">
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">Rule submission</h3>
<div className="flex items-center gap-2">
<StatusBadge status={s.status} />
<span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-mono bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300">
{s.submissionId}<CopyButton value={s.submissionId} />
</span>
</div>
</div>
{message && (
<div className={`mb-4 p-3 rounded-lg text-sm ${message.kind === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-700 border border-red-200"}`}>
{message.text}
</div>
)}
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-3 text-sm">
<div>
<dt className="font-medium text-gray-500 dark:text-gray-400">Rule</dt>
<dd className="mt-0.5 text-gray-900 dark:text-gray-100"><KindBadge kind={s.ruleKind} /> <span className="font-mono">{s.sourceRuleId}</span> — {s.title} <span className="text-gray-500">({s.category})</span></dd>
</div>
<div>
<dt className="font-medium text-gray-500 dark:text-gray-400">Tenant</dt>
<dd className="mt-0.5 font-mono text-gray-900 dark:text-gray-100 flex items-center">{s.tenantId}<CopyButton value={s.tenantId} /></dd>
</div>
<div>
<dt className="font-medium text-gray-500 dark:text-gray-400">Submitted by</dt>
<dd className="mt-0.5 text-gray-900 dark:text-gray-100">{s.submittedByName} <span className="text-gray-500">({s.submittedBy})</span> · {new Date(s.submittedAt).toLocaleString()}</dd>
</div>
<div>
<dt className="font-medium text-gray-500 dark:text-gray-400">Contact email</dt>
<dd className="mt-0.5 text-gray-900 dark:text-gray-100 flex items-center">
{s.contactEmail
? <>{s.contactEmail}<CopyButton value={s.contactEmail} /></>
: <span className="text-gray-400 italic">not provided</span>}
</dd>
</div>
<div>
<dt className="font-medium text-gray-500 dark:text-gray-400">Credit in the published rule</dt>
<dd className="mt-0.5 text-gray-900 dark:text-gray-100">{s.attributionName} <span className="text-gray-500">({s.attributionMode})</span></dd>
</div>
<div className="sm:col-span-2">
<dt className="font-medium text-gray-500 dark:text-gray-400">Comment</dt>
<dd className="mt-0.5 text-gray-900 dark:text-gray-100 whitespace-pre-wrap">{s.comment || <span className="text-gray-400 italic">no comment</span>}</dd>
</div>
<div>
<dt className="font-medium text-gray-500 dark:text-gray-400">Fire stats in the submitting tenant</dt>
<dd className="mt-0.5 text-gray-900 dark:text-gray-100 text-xs">
<div>At submit: {fireStatsText(s.sourceFireStats)}</div>
<div>Now: {fireStatsText(detail?.liveFireStats)}</div>
</dd>
</div>
<div>
<dt className="font-medium text-gray-500 dark:text-gray-400">Pre-flight findings</dt>
<dd className="mt-0.5 text-xs">
{s.validationFindings.length === 0
? <span className="text-green-700">none</span>
: <ul className="space-y-0.5">{s.validationFindings.map((f, i) => <li key={i} className={f.level === "warning" ? "text-amber-700" : "text-gray-600 dark:text-gray-300"}>{f.message}</li>)}</ul>}
{s.derivedFromTemplateRuleId && <div className="text-gray-500 mt-0.5">Derived from template <span className="font-mono">{s.derivedFromTemplateRuleId}</span></div>}
</dd>
</div>
{(s.reviewedBy || s.reviewComment) && (
<div className="sm:col-span-2">
<dt className="font-medium text-gray-500 dark:text-gray-400">Review</dt>
<dd className="mt-0.5 text-gray-900 dark:text-gray-100 text-xs">
{s.reviewedBy} · {s.reviewedAt ? new Date(s.reviewedAt).toLocaleString() : ""}
{s.publishedRuleId && <> · publishes as <span className="font-mono">{s.publishedRuleId}</span></>}
{s.willBeAdapted && <> · will be adapted</>}
{s.reviewComment && <div className="whitespace-pre-wrap mt-0.5">{s.reviewComment}</div>}
</dd>
</div>
)}
</dl>
{/* Frozen rule */}
<div className="mt-4">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-gray-500 dark:text-gray-400">Submitted rule (frozen at submit time)</span>
<CopyButton value={ruleJson} title="Copy rule JSON" />
</div>
<pre className="mt-1 max-h-64 overflow-auto text-xs font-mono bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded p-3 text-gray-800 dark:text-gray-200">{ruleJson}</pre>
</div>
{/* Repo file */}
{detail?.repoFile && (
<div className="mt-4">
<div className="flex items-center justify-between gap-2">
<span className="text-sm font-medium text-gray-500 dark:text-gray-400">
Repo file · <span className="font-mono text-xs">{detail.repoFile.path}</span>
{!s.publishedRuleId && detail.suggestedPublishedRuleId && <span className="text-xs text-gray-400"> (suggested id)</span>}
</span>
<span className="flex items-center gap-2">
<button onClick={() => setShowRepoFile((v) => !v)} className="text-xs text-indigo-600 hover:text-indigo-800">{showRepoFile ? "Hide" : "Show"}</button>
<CopyButton value={detail.repoFile.content} title="Copy file content" />
<button onClick={downloadRepoFile} className="text-xs text-indigo-600 hover:text-indigo-800">Download</button>
</span>
</div>
{showRepoFile && (
<pre className="mt-1 max-h-64 overflow-auto text-xs font-mono bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded p-3 text-gray-800 dark:text-gray-200">{detail.repoFile.content}</pre>
)}
</div>
)}
{/* Decision */}
{canMutate && decidable && (
<div className="mt-5 pt-4 border-t border-gray-200 dark:border-gray-700">
<p className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Decision</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div>
<label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">Published rule id (approve)</label>
<input
type="text"
value={publishedRuleId}
onChange={(e) => setPublishedRuleId(e.target.value.toUpperCase())}
disabled={s.status !== "pending"}
className="w-full px-2 py-1.5 text-sm font-mono border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 disabled:opacity-60"
/>
<label className="mt-2 flex items-center gap-2 text-xs text-gray-700 dark:text-gray-300">
<input type="checkbox" checked={willBeAdapted} onChange={(e) => setWillBeAdapted(e.target.checked)} disabled={s.status !== "pending"} className="h-4 w-4 text-green-600 border-gray-300 rounded" />
I will adapt the rule before publishing
</label>
</div>
<div>
<label className="block text-xs text-gray-500 dark:text-gray-400 mb-1">Note to the submitter (required to decline)</label>
<textarea
value={reviewComment}
onChange={(e) => setReviewComment(e.target.value)}
rows={3}
maxLength={4000}
className="w-full px-2 py-1.5 text-sm border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
/>
</div>
</div>
<div className="mt-3 flex items-center gap-2">
{s.status === "pending" && (
<button onClick={() => review("approve")} disabled={!!busy || !publishedRuleId.trim()} className="px-4 py-2 bg-green-600 hover:bg-green-700 disabled:bg-green-400 text-white rounded-md text-sm font-medium transition-colors">
{busy === "approve" ? "Approving..." : "Approve"}
</button>
)}
<button onClick={() => review("decline")} disabled={!!busy || !reviewComment.trim()} className="px-4 py-2 bg-red-600 hover:bg-red-700 disabled:bg-red-300 text-white rounded-md text-sm font-medium transition-colors">
{busy === "decline" ? "Declining..." : "Decline"}
</button>
{s.status === "approved" && (
<button onClick={reseed} disabled={!!busy} className="ml-auto px-4 py-2 bg-indigo-600 hover:bg-indigo-700 disabled:bg-indigo-400 text-white rounded-md text-sm font-medium transition-colors" title="After the repo file is committed and pushed: pull rules/dist from GitHub into the global catalog">
{busy === "reseed" ? "Reseeding..." : `Reseed ${s.ruleKind} rules now`}
</button>
)}
</div>
</div>
)}
<div className="mt-6 flex items-center justify-between">
{canMutate ? (
<button
onClick={remove}
disabled={!!busy}
className={`px-3 py-2 rounded-md text-xs font-medium transition-colors ${confirmDelete ? "bg-red-600 hover:bg-red-700 text-white" : "text-red-600 hover:bg-red-50"}`}
title="Removes the submission for the operator and the tenant alike; a published rule in the repo stays"
>
{busy === "delete" ? "Deleting..." : confirmDelete ? "Really delete this submission" : "Delete submission"}
</button>
) : <span />}
<button onClick={onClose} className="px-4 py-2 bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-200 rounded-md hover:bg-gray-300 dark:hover:bg-gray-500 transition-colors text-sm">Close</button>
</div>
</>
)}
</div>
</div>
</div>
</ModalPortal>
);
}
@@ -3,12 +3,14 @@
import { notFound } from "next/navigation";
import { type ReportsSectionId } from "../reportsNavSections";
import { SectionSessionReports } from "../sections/SectionSessionReports";
import { SectionRuleSubmissions } from "../sections/SectionRuleSubmissions";
import { SectionDistressReports } from "../sections/SectionDistressReports";
import { SectionUserFeedback } from "../sections/SectionUserFeedback";
import { SectionSessionExport } from "../sections/SectionSessionExport";
const SECTION_COMPONENTS: Record<ReportsSectionId, React.ComponentType> = {
"session-reports": SectionSessionReports,
"rule-submissions": SectionRuleSubmissions,
"distress-reports": SectionDistressReports,
"user-feedback": SectionUserFeedback,
"session-export": SectionSessionExport,
@@ -1,5 +1,6 @@
export const REPORTS_NAV_SECTIONS = [
{ id: "session-reports", label: "Session Reports", description: "Sessions reported by Tenant Admins for analysis" },
{ id: "rule-submissions", label: "Rule Submissions", description: "Custom rules submitted by Tenant Admins for the community pool" },
{ id: "distress-reports", label: "Distress Reports", description: "Pre-auth agent distress signals (cert/whitelist/registration failures)" },
{ id: "user-feedback", label: "User Feedback", description: "Product feedback from users" },
{ id: "session-export", label: "Session Export", description: "Export session event data" },
@@ -0,0 +1,15 @@
"use client";
import { useAdminConfig } from "../../AdminConfigContext";
import { RuleSubmissionsSection } from "../../components/RuleSubmissionsSection";
import { AdminNotifications } from "../../AdminNotifications";
export function SectionRuleSubmissions() {
const { getAccessToken, setError } = useAdminConfig();
return (
<>
<AdminNotifications />
<RuleSubmissionsSection getAccessToken={getAccessToken} setError={setError} />
</>
);
}
@@ -38,6 +38,9 @@ import { DOCS_PATHS } from "@/lib/docsPaths";
import { DocsLink } from "@/components/DocsLink";
import type { CreateAnalyzeRuleFromTemplateRequest, RuleStatsResponse, TenantConfiguration } from "@/utils/wire-types.generated";
import { fetchJson, jsonBody } from "@/lib/apiClient";
import { CommunityContributionBox } from "@/components/rules/CommunityContributionBox";
import { MySubmissionsList } from "@/components/rules/MySubmissionsList";
import { SubmitRulesModal } from "@/components/rules/SubmitRulesModal";
export default function AnalyzeRulesPage() {
const { user, getAccessToken } = useAuth();
@@ -98,6 +101,9 @@ export default function AnalyzeRulesPage() {
// Tenant notification channels (for the per-rule notify target selector)
const [tenantChannels, setTenantChannels] = useState<{ id: string; name: string }[]>([]);
// Community submissions: the picker modal and a counter that reloads the status list after a submit.
const [showSubmitModal, setShowSubmitModal] = useState(false);
const [submissionsRefreshKey, setSubmissionsRefreshKey] = useState(0);
// Global admin tenant scope (tenant list, selector state, override/effective tenant)
const scope = useGlobalAdminScope();
@@ -412,7 +418,6 @@ export default function AnalyzeRulesPage() {
confidenceFactors: form.confidenceFactors.filter(f => f.signal.trim()),
remediation: form.remediation.filter(r => r.title.trim()),
relatedDocs: form.relatedDocs.filter(d => d.title.trim() && d.url.trim()),
author: user?.displayName || user?.upn || rule.author,
version: bumpVersion(rule.version),
};
@@ -458,6 +463,10 @@ export default function AnalyzeRulesPage() {
};
const rulesList = rules || [];
// Only the tenant's own custom rules can be contributed.
const submittableRules = rulesList
.filter((r) => !r.isBuiltIn && !r.isCommunity)
.map((r) => ({ ruleId: r.ruleId, title: r.title, category: r.category }));
// Map: templateRuleId -> custom copy ruleId (for template rules that already have a tenant copy)
const templateCopyMap = new Map<string, string>();
@@ -600,18 +609,16 @@ export default function AnalyzeRulesPage() {
</div>
) : (
<div className="space-y-6">
{/* Community Contribution Hint */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start space-x-3">
<svg className="w-5 h-5 text-blue-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<p className="text-sm text-blue-800">
Missing a rule, found a bug, or have an improvement idea? Help make Autopilot Monitor better —{" "}
<a href="https://github.com/okieselbach/AutopilotMonitor/issues" target="_blank" rel="noopener noreferrer" className="font-medium underline hover:text-blue-900">
open a GitHub issue
</a>.
</p>
</div>
{/* Community contribution: submit own custom rules for the shared pool; the list shows their status. */}
<CommunityContributionBox onContribute={isReadOnly ? undefined : () => setShowSubmitModal(true)} />
<MySubmissionsList
kind="analyze"
getAccessToken={getAccessToken}
refreshKey={submissionsRefreshKey}
overrideTenantId={isGlobalOverride ? effectiveTenantId : undefined}
readOnly={isReadOnly}
onError={showError}
/>
{/* Summary Stats */}
<div className="grid grid-cols-2 md:grid-cols-6 gap-4">
@@ -928,6 +935,17 @@ export default function AnalyzeRulesPage() {
)}
</main>
{/* Community submission picker — custom rules only; the backend freezes the rule itself. */}
<SubmitRulesModal
show={showSubmitModal}
kind="analyze"
rules={submittableRules}
tenantId={effectiveTenantId ?? ""}
defaultCreditName={user?.displayName || ""}
getAccessToken={getAccessToken}
onClose={() => setShowSubmitModal(false)}
onSubmitted={() => setSubmissionsRefreshKey((k) => k + 1)}
/>
{/* Template Configuration Modal */}
{configureTemplateRule && (
<TemplateConfigModal
@@ -24,6 +24,9 @@ import { DOCS_PATHS } from "@/lib/docsPaths";
import { DocsLink } from "@/components/DocsLink";
import type { TenantFeatureFlagsResponse } from "@/utils/wire-types.generated";
import { fetchJson } from "@/lib/apiClient";
import { CommunityContributionBox } from "@/components/rules/CommunityContributionBox";
import { MySubmissionsList } from "@/components/rules/MySubmissionsList";
import { SubmitRulesModal } from "@/components/rules/SubmitRulesModal";
export default function GatherRulesPage() {
const { user, getAccessToken } = useAuth();
@@ -56,6 +59,9 @@ export default function GatherRulesPage() {
const [showCreateForm, setShowCreateForm] = useState(false);
const [newRule, setNewRule] = useState<NewRuleForm>({ ...EMPTY_FORM });
const [creating, setCreating] = useState(false);
// Community submissions: the picker modal and a counter that reloads the status list after a submit.
const [showSubmitModal, setShowSubmitModal] = useState(false);
const [submissionsRefreshKey, setSubmissionsRefreshKey] = useState(0);
// JSON mode (create + edit)
const [jsonModeCreate, setJsonModeCreate] = useState(false);
@@ -339,6 +345,10 @@ export default function GatherRulesPage() {
// Computed values
const rulesList = rules || [];
// Only the tenant's own custom rules can be contributed.
const submittableRules = rulesList
.filter((r) => !r.isBuiltIn && !r.isCommunity)
.map((r) => ({ ruleId: r.ruleId, title: r.title, category: r.category }));
const filteredRules = rulesList.filter((rule) => {
if (searchQuery) {
const q = searchQuery.toLowerCase().trim();
@@ -433,18 +443,16 @@ export default function GatherRulesPage() {
</div>
)}
{/* Community Contribution Hint */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start space-x-3">
<svg className="w-5 h-5 text-blue-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<p className="text-sm text-blue-800">
Missing a rule, found a bug, or have an improvement idea? Help make Autopilot Monitor better —{" "}
<a href="https://github.com/okieselbach/AutopilotMonitor/issues" target="_blank" rel="noopener noreferrer" className="font-medium underline hover:text-blue-900">
open a GitHub issue
</a>.
</p>
</div>
{/* Community contribution: submit own custom rules for the shared pool; the list shows their status. */}
<CommunityContributionBox onContribute={isReadOnly ? undefined : () => setShowSubmitModal(true)} />
<MySubmissionsList
kind="gather"
getAccessToken={getAccessToken}
refreshKey={submissionsRefreshKey}
overrideTenantId={isGlobalOverride ? effectiveTenantId : undefined}
readOnly={isReadOnly}
onError={showError}
/>
{/* Summary Stats */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
@@ -669,6 +677,17 @@ export default function GatherRulesPage() {
)}
</div>
)}
{/* Community submission picker — custom rules only; the backend freezes the rule itself. */}
<SubmitRulesModal
show={showSubmitModal}
kind="gather"
rules={submittableRules}
tenantId={effectiveTenantId ?? ""}
defaultCreditName={user?.displayName || ""}
getAccessToken={getAccessToken}
onClose={() => setShowSubmitModal(false)}
onSubmitted={() => setSubmissionsRefreshKey((k) => k + 1)}
/>
</main>
</div>
</ProtectedRoute>
@@ -2,7 +2,7 @@ import { LandingNavbar } from "../../components/landing/LandingNavbar";
import { SiteFooter } from "../../components/SiteFooter";
import { DOCS_URL } from "@/utils/config";
const LAST_UPDATED = "2 September 2026";
const LAST_UPDATED = "9 September 2026";
const DOCS_SECURITY_FAQ = `${DOCS_URL}/trust/security-faq`;
const DOCS_DATA_FLOWS = `${DOCS_URL}/trust/data-flows`;
@@ -192,7 +192,7 @@ export default function PrivacyPage() {
</p>
<ul className="list-disc list-inside space-y-2 text-gray-700 ml-4">
<li><strong>Product feedback</strong> you submitted — it is not tied to enrollment data and is what improves the product.</li>
<li><strong>Custom rules and IME log patterns</strong> you authored are archived rather than deleted. Detection knowledge is what makes this product useful, so contributed rules and patterns are subject to entering the community pool — the next organization hitting the same enrollment failure gets a diagnosis instead of a mystery. A rule is a detection definition, not device data.</li>
<li><strong>Custom rules and IME log patterns</strong> you authored are archived rather than deleted. Detection knowledge is what makes this product useful, so contributed rules and patterns are subject to entering the community pool — the next organization hitting the same enrollment failure gets a diagnosis instead of a mystery. A rule is a detection definition, not device data. When you submit a rule from the portal, it is published anonymously unless you choose a credit — your organization name or a name you enter — which then appears as the rule&apos;s author for every tenant.</li>
</ul>
<p className="text-gray-700">
Either can be removed on request.
@@ -4,6 +4,7 @@ import { useState } from "react";
import { Session } from "@/types";
import { SessionStatusBadge } from "@/components/SessionStatusBadge";
import FailureSnapshotBlock from "./FailureSnapshotBlock";
import { formatDuration } from "@/lib/formatting";
interface SessionInfoCardProps {
session: Session;
@@ -12,16 +13,10 @@ interface SessionInfoCardProps {
isGatherRulesSession: boolean;
ntpOffset?: { offsetSeconds: number; ntpServer?: string } | null;
configMgrDetected?: { ccmVersion?: string; ccmServiceState?: string; siteCode?: string; confidenceScore?: number } | null;
/** Total observed sleep/standby seconds (system_sleep_episode ground truth) — explains an inflated wall-clock duration. */
/** Sleep/standby seconds inside the enrollment window (system_sleep_episode ground truth) — explains an inflated wall-clock duration. */
standbySeconds?: number | null;
}
// Compact duration for the standby note: "56m", "1h 2m".
function formatStandby(seconds: number): string {
if (seconds >= 3600) return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
return `${Math.max(1, Math.round(seconds / 60))}m`;
}
export default function SessionInfoCard({ session, enrollmentDuration, displayStatus, isGatherRulesSession, ntpOffset, configMgrDetected, standbySeconds }: SessionInfoCardProps) {
const lastContactTooltip = session.lastEventAt
? `Last contact: ${new Date(session.lastEventAt).toLocaleString([], { dateStyle: "short", timeStyle: "medium" })}`
@@ -72,9 +67,9 @@ export default function SessionInfoCard({ session, enrollmentDuration, displaySt
{enrollmentDuration ?? `${Math.round((session.durationSeconds ?? 0) / 60)} min`}
<span
className="text-indigo-600 font-normal"
title={`The device spent ${formatStandby(standbySeconds)} asleep (standby/hibernate) during this window — the wall-clock duration includes that pause. Subtract it for the active enrollment time.`}
title={`The device spent ${formatDuration(standbySeconds)} asleep (standby/hibernate) during this window — the wall-clock duration includes that pause. Subtract it for the active enrollment time.`}
>
{" "}· 🌙 {formatStandby(standbySeconds)} standby
{" "}· 🌙 {formatDuration(standbySeconds)} standby
</span>
</span>
) : (

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