Files
AutopilotMonitor/src/Backend/AutopilotMonitor.Functions/Functions/Raw/QueryRawSessionsFunction.cs
T
Oliver Kieselbach 1c5f69a9fe w365: CloudPc device validator — cert-CN-bound fallback for Cloud PCs (#127)
* w365: CloudPc device validator — cert-CN-bound fallback for Cloud PCs

Windows 365 Cloud PCs are never Autopilot-registered, so the serial lookup
(and the Corporate Identifier fallback) structurally reject them and Cloud PC
first-connect enrollment could not be monitored. New stage-3 fallback in the
device-validation chain: extract the Intune device id from the chain-validated
MDM client certificate's Subject CN (field-verified: CN == managedDevice id ==
cloudPC.managedDeviceId) and require a matching cloudPC object in the claimed
tenant (Graph v1.0 virtualEndpoint/cloudPCs, $filter=managedDeviceId eq).
Only service-provisioned Cloud PCs have such an object — a regular enrolled
non-Autopilot device still ends in the 403, and local W365 markers are never
consulted for auth.

- Shared: ValidatorType.CloudPc = 5, TenantConfiguration.ValidateCloudPcDevice
  (default false, tenant-admin writable), GraphAppPermissions.CloudPCReadAll,
  GraphFeatureCatalog feature W365CloudPcValidation -> CloudPC.Read.All
- Backend: CloudPcDeviceValidator (AutopilotDeviceValidator sibling contract:
  30/5 min cache, 2 attempts, transient->503; GUID gate before the OData
  filter; exact-match guard; Graph 403 = definitive "grant missing", not
  transient), SecurityValidator CN extraction + fallback stage + hard gate,
  wiring through the 5 agent endpoints, TableConfigRepository persistence
- Consent script: W365CloudPcValidation in catalog/ValidateSet/help; NEW
  GraphFeatureCatalogSyncTests pins C# catalog <-> grant script (previously
  comment-only lock-step)
- Bootstrap dev script v2.3-dev.3: guard 4 (uptime window) exempted while the
  Cloud-PC relax is active — Cloud PCs run headless for days before first
  connect; the fresh-profile window is the time anchor there (+ Pester tests)
- Web: validation toggle + context plumbing, ValidatedBy "CloudPc" label,
  privacy-page validation claim generalized (Last updated bumped)
- Docs: OKF concept doc backend/cloudpc-device-validation.md + index + log

Verified: web tsc clean, ESLint 0 errors (99 pre-existing warnings = ratchet
cap, none added). .NET build/tests and Pester run in CI — SDK download and
pwsh are unavailable in this sandbox's network policy.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqEFrcAHhWgCvgJgHGzMuv

* w365: agent-side IsCloudPc flag + engine expectation "no Device-ESP phase"

Companion to the CloudPc validator: the agent now classifies Windows 365
Cloud PCs locally with the bootstrap's field-verified marker AND
(HKLM\SOFTWARE\Microsoft\Windows365 key + installed
CloudManagedDesktopExtension service, probed via its Services registry key
so net48 needs no System.ServiceProcess). SKIP-safe: any error resolves
false. Never an auth input - backend admission stays exclusively the
cert-CN-bound Graph lookup (ValidatedBy=CloudPc); the two signals are
independent and may disagree.

Two transport rails:

- Session metadata: SessionRegistration.IsCloudPc -> Sessions table
  (sticky-true OR across re-registrations, IsSelfDeployingProfile pattern)
  -> SessionsIndex full mirror -> SessionSummary -> new isCloudPc search
  filter end to end (SearchSessions + QueryRawSessions + pagination
  fingerprint + all three in-memory predicates; MCP search_sessions /
  query_raw_sessions params + summary projection; web type, Cloud PC pill,
  SessionInfoCard enrollment label, CSV export appended column).
- Decision engine: isCloudPc rides the EnrollmentFactsObserved payload,
  recorded set-once for BOTH values in EnrollmentScenarioObservations.CloudPc
  and annotates the scenario profile reason
  cloud_pc_first_connect:no_device_esp_expected - the engine-recorded
  expectation that Device-ESP already ran headless at provisioning and the
  session starts at Account Setup. Deliberately reason+observation only:
  no completion arm depends on DeviceSetup, Mode stays AccountSetup/IME-
  classified (Classic), EspConfig keeps configured-FirstSync semantics.
  Positive marker surfaces as cloud_pc_marker in the audit-trail census.
  Updater idempotency: the cloudPcAnnotates gate keeps the generic v1
  reason branch from re-claiming the slot on repeat posts (would bump
  EvidenceOrdinal every post). Additive-nullable observation - no state
  schema bump (v4 convention), serializer roundtrip pinned.

Tests: CloudPcDetector resolver (marker AND, throwing probe), registration
body, facts-signal payload shape, updater annotation/idempotency/
self-deploying interplay, reducer observation both values + census fold,
serializer roundtrip, index projection superset, sticky-true both
directions. Suites: DecisionCore 500, Functions 3941, Agent V2 2154,
vitest 632 - all green; tsc web+MCP clean; ESLint 0 errors (cap 99).

Docs: cloudpc-device-validation.md follow-up section replaced with the
shipped mechanism + log entry.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-07 12:31:08 +02:00

183 lines
9.0 KiB
C#

using System.Net;
using System.Web;
using AutopilotMonitor.Functions.Helpers;
using AutopilotMonitor.Functions.Pagination;
using AutopilotMonitor.Shared.DataAccess;
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.Raw
{
public class QueryRawSessionsFunction
{
private readonly ILogger<QueryRawSessionsFunction> _logger;
private readonly ISessionRepository _sessionRepo;
public QueryRawSessionsFunction(ILogger<QueryRawSessionsFunction> logger, ISessionRepository sessionRepo)
{
_logger = logger;
_sessionRepo = sessionRepo;
}
/// <summary>
/// GET /api/raw/sessions — Tenant-scoped raw session query
/// </summary>
[Function("QueryRawSessions")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "raw/sessions")] HttpRequestData req)
{
try
{
var tenantId = TenantHelper.GetTenantId(req);
return await QuerySessions(req, tenantId, scope: "raw-sessions:tenant",
basePath: "/api/raw/sessions", filterTenantId: null);
}
catch (UnauthorizedAccessException)
{
var err = req.CreateResponse(HttpStatusCode.Unauthorized);
await err.WriteAsJsonAsync(new { error = "Unauthorized" });
return err;
}
catch (Exception ex)
{
return await req.InternalServerErrorAsync(_logger, ex, "Query raw sessions");
}
}
/// <summary>
/// GET /api/global/raw/sessions — Cross-tenant raw session query (GlobalAdminOnly)
/// </summary>
[Function("QueryRawSessionsGlobal")]
public async Task<HttpResponseData> RunGlobal(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "global/raw/sessions")] HttpRequestData req)
{
try
{
var filterTenantId = req.Query["tenantId"];
var effectiveTenantId = string.IsNullOrEmpty(filterTenantId) ? null : filterTenantId;
return await QuerySessions(req, effectiveTenantId, scope: "raw-sessions:global",
basePath: "/api/global/raw/sessions", filterTenantId: effectiveTenantId);
}
catch (Exception ex)
{
return await req.InternalServerErrorAsync(_logger, ex, "Query global raw sessions");
}
}
private async Task<HttpResponseData> QuerySessions(
HttpRequestData req, string? tenantId, string scope, string basePath, string? filterTenantId)
{
var query = HttpUtility.ParseQueryString(req.Url.Query ?? string.Empty);
var status = query["status"];
var startedAfter = query["startedAfter"];
var startedBefore = query["startedBefore"];
var serialNumber = query["serialNumber"];
var agentVersion = query["agentVersion"];
var agentVersionPrefix = query["agentVersionPrefix"];
var imeAgentVersion = query["imeAgentVersion"];
var imeAgentVersionPrefix = query["imeAgentVersionPrefix"];
// Device/hardware scalar filters — parity with search_sessions so the raw tool is a true
// superset, not a subset. All are already supported by SessionSearchFilter +
// BuildSearchScanFilter / MatchesScanClientFilters; we only plumb the query params through.
var manufacturer = query["manufacturer"];
var model = query["model"];
var enrollmentType = query["enrollmentType"];
var deviceName = query["deviceName"];
var osBuild = query["osBuild"];
var geoCountry = query["geoCountry"];
var isPreProvisioned = query["isPreProvisioned"];
var isHybridJoin = query["isHybridJoin"];
var isSelfDeployingProfile = query["isSelfDeployingProfile"];
var isCloudPc = query["isCloudPc"];
var fieldsParam = query["fields"];
var pagination = SearchSessionsPagination.ParsePagination(query);
if (pagination.Error != null)
{
var bad = req.CreateResponse(HttpStatusCode.BadRequest);
await bad.WriteAsJsonAsync(new { error = pagination.Error });
return bad;
}
// Build search filter — Limit is ignored, pagination owns size.
var filter = new SessionSearchFilter
{
Status = string.IsNullOrEmpty(status) ? null : status,
SerialNumber = string.IsNullOrEmpty(serialNumber) ? null : serialNumber,
AgentVersion = string.IsNullOrEmpty(agentVersion) ? null : agentVersion,
AgentVersionPrefix = string.IsNullOrEmpty(agentVersionPrefix) ? null : agentVersionPrefix,
ImeAgentVersion = string.IsNullOrEmpty(imeAgentVersion) ? null : imeAgentVersion,
ImeAgentVersionPrefix = string.IsNullOrEmpty(imeAgentVersionPrefix) ? null : imeAgentVersionPrefix,
Manufacturer = string.IsNullOrEmpty(manufacturer) ? null : manufacturer,
Model = string.IsNullOrEmpty(model) ? null : model,
EnrollmentType = string.IsNullOrEmpty(enrollmentType) ? null : enrollmentType,
DeviceName = string.IsNullOrEmpty(deviceName) ? null : deviceName,
OsBuild = string.IsNullOrEmpty(osBuild) ? null : osBuild,
GeoCountry = string.IsNullOrEmpty(geoCountry) ? null : geoCountry,
};
if (!string.IsNullOrEmpty(startedAfter) && DateTime.TryParse(startedAfter, out var after))
filter.StartedAfter = after;
if (!string.IsNullOrEmpty(startedBefore) && DateTime.TryParse(startedBefore, out var before))
filter.StartedBefore = before;
if (!string.IsNullOrEmpty(isPreProvisioned) && bool.TryParse(isPreProvisioned, out var pp))
filter.IsPreProvisioned = pp;
if (!string.IsNullOrEmpty(isHybridJoin) && bool.TryParse(isHybridJoin, out var hj))
filter.IsHybridJoin = hj;
if (!string.IsNullOrEmpty(isSelfDeployingProfile) && bool.TryParse(isSelfDeployingProfile, out var sdp))
filter.IsSelfDeployingProfile = sdp;
if (!string.IsNullOrEmpty(isCloudPc) && bool.TryParse(isCloudPc, out var icp))
filter.IsCloudPc = icp;
if (int.TryParse(query["rebootCountMin"], out var rcMin)) filter.RebootCountMin = rcMin;
if (int.TryParse(query["rebootCountMax"], out var rcMax)) filter.RebootCountMax = rcMax;
var connectionType = query["connectionType"];
if (!string.IsNullOrEmpty(connectionType)) filter.ConnectionType = connectionType;
var callerTenantId = TenantHelper.GetTenantId(req);
string? azureToken = null;
if (pagination.Continuation != null)
{
if (!SearchSessionsPagination.TryAcceptContinuation(
pagination.Continuation, scope, callerTenantId, filterTenantId, filter,
out azureToken, out var rejectReason))
{
_logger.LogWarning("QueryRawSessions: continuation rejected ({Reason})", rejectReason);
var bad = req.CreateResponse(HttpStatusCode.BadRequest);
await bad.WriteAsJsonAsync(new
{
error = $"Invalid continuation token ({rejectReason}). Restart pagination from the first page.",
});
return bad;
}
}
var page = await _sessionRepo.SearchSessionsRawPageAsync(tenantId, filter, pagination.PageSize, azureToken);
// Raw projection: the rows are the literal SessionsIndex columns. Optional fields= is a
// pure pass-through (narrow, never silently drop a real column); empty fields= returns
// every stored column. It's presentation-only and doesn't touch cursor mechanics.
var sessionsPayload = RawEntityProjection.Project(page.Items, fieldsParam);
string? nextLink = null;
if (!string.IsNullOrEmpty(page.NextRawToken))
{
var fp = SearchSessionsPagination.Fingerprint(scope, callerTenantId, filterTenantId, filter);
var wireToken = ContinuationToken.Encode(page.NextRawToken!, callerTenantId, fp);
nextLink = SearchSessionsPagination.BuildNextLink(basePath, pagination.PageSize, wireToken, query);
}
return await req.OkAsync(new
{
tenantId,
count = page.Items.Count,
sessions = sessionsPayload,
nextLink,
});
}
}
}