fix(audit): scope audit reads by site identifier, not numeric site id (MGT-2, UI-5, WP1 task 1.6)

PermittedSiteIds / SiteId claims are numeric Site.Id values while
AuditLog.SourceSiteId holds the site identifier. /api/audit/query and
/export compared the two (a scoped query was always empty, an explicit
--site of one's own site was a 403), /api/audit/tree and Flow Debugger
Replay dropped every site-side node, and the Central UI Audit Log grid
applied no scope at all.

New Commons AuditSiteScope: translate permitted ids to identifiers
(Administrator / no claims = unscoped; unresolvable = fail closed) and
apply them to a filter (never an empty SourceSiteIds, which the
repository reads as unfiltered). Used by AuditEndpoints (query, export,
tree), FlowDebugRunner.ReplayAsync, and AuditLogQueryService (grid
QueryAsync - pushed into the query before paging - and the tree).
ApplySiteScope gains the Administrator exemption.

Tests: scoped query filters by identifier, own-site explicit filter
allowed and foreign one 403, admin with claims unscoped, tree/replay get
identifiers, UI grid scoped/out-of-scope/unscoped, tree per-call scope.
This commit is contained in:
Joseph Doherty
2026-12-03 10:10:58 -05:00
parent 8c5d70f687
commit 2162fad8e9
10 changed files with 385 additions and 82 deletions
@@ -120,11 +120,49 @@ public sealed class AuditLogQueryService : IAuditLogQueryService
// Production: a fresh scope (and thus a fresh DbContext) per query so the
// page's auto-load never shares the circuit-scoped context.
await using var scope = _scopeFactory!.CreateAsyncScope();
// Code review 2026-12-02 UI-5: apply the caller's site scope exactly as the
// management API's /api/audit/query does (shared AuditSiteScope helper) — the grid
// and every drill-in that reuses QueryAsync used to show a site-scoped user every
// site's rows. Applied before paging, in the query itself.
// Fail closed: the production ctor is always given the provider by DI.
if (_auth is null) throw new InvalidOperationException("Audit query caller authentication is not configured.");
var caller = (await _auth.GetAuthenticationStateAsync()).User;
if (caller.Identity?.IsAuthenticated != true) throw new UnauthorizedAccessException();
var scoped = AuditSiteScope.Apply(filter, await ResolveSiteScopeAsync(scope.ServiceProvider, caller, ct));
if (scoped is null)
{
// An explicit site filter entirely outside the caller's sites, or a scoped
// caller none of whose sites still exist: nothing they may see.
return Array.Empty<AuditEventView>();
}
var repository = scope.ServiceProvider.GetRequiredService<IAuditLogRepository>();
var result = await repository.QueryAsync(filter, effective, ct);
var result = await repository.QueryAsync(scoped, effective, ct);
return result.Select(AuditEventView.From).ToList();
}
/// <summary>
/// Resolves a caller's audit site scope as site IDENTIFIERS (the values
/// <c>AuditLog.SourceSiteId</c> holds): <c>null</c> for an Administrator or a caller with
/// no <c>SiteId</c> claims. The claims are numeric <c>Site.Id</c> values, so they are
/// translated through <see cref="ISiteRepository"/> (code review 2026-12-02 UI-5/MGT-2).
/// </summary>
/// <param name="services">The per-call scope's services.</param>
/// <param name="principal">The authenticated caller.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The permitted identifiers, or <c>null</c> when unscoped.</returns>
private static async Task<IReadOnlyList<string>?> ResolveSiteScopeAsync(
IServiceProvider services, System.Security.Claims.ClaimsPrincipal principal, CancellationToken ct)
{
var siteClaims = principal.FindAll(JwtTokenService.SiteIdClaimType).Select(c => c.Value).ToArray();
var isAdministrator = principal.HasClaim(JwtTokenService.RoleClaimType, Roles.Administrator);
if (isAdministrator || siteClaims.Length == 0) return null;
return await AuditSiteScope.ResolvePermittedSiteIdentifiersAsync(
services.GetRequiredService<ISiteRepository>(), siteClaims, isAdministrator, ct);
}
/// <inheritdoc/>
public async Task<AuditLogKpiSnapshot> GetKpiSnapshotAsync(CancellationToken ct = default)
{
@@ -181,8 +219,9 @@ public sealed class AuditLogQueryService : IAuditLogQueryService
if (_auth is null) throw new InvalidOperationException("Audit tree caller authentication is not configured.");
var principal = (await _auth.GetAuthoritativeStateAsync()).User;
if (principal.Identity?.IsAuthenticated != true || !principal.FindAll(JwtTokenService.RoleClaimType).Any(c => AuthorizationPolicies.OperationalAuditRoles.Contains(c.Value))) throw new UnauthorizedAccessException();
var sites = principal.FindAll(JwtTokenService.SiteIdClaimType).Select(c => c.Value).ToArray();
var permitted = principal.HasClaim(JwtTokenService.RoleClaimType, Roles.Administrator) || sites.Length == 0 ? null : sites;
// Code review 2026-12-02 UI-5: the scope compares against AuditLog.SourceSiteId (site
// IDENTIFIERS); passing the numeric SiteId claims raw dropped every site-side node.
var permitted = await ResolveSiteScopeAsync(scope.ServiceProvider, principal, ct);
return await repository.GetExecutionTreeAsync(executionId, ct, permitted);
}
@@ -0,0 +1,90 @@
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
namespace ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
/// <summary>
/// Site scoping for audit-log reads (code review 2026-12-02 MGT-2 / UI-5).
/// </summary>
/// <remarks>
/// <para>
/// A caller's permitted sites arrive as <b>numeric</b> <c>Site.Id</c> values rendered as
/// strings (the <c>SiteId</c> claim / <c>AuthenticatedUser.PermittedSiteIds</c>, sourced from
/// <c>SiteScopeRule.SiteId</c>). <c>AuditLog.SourceSiteId</c> holds the site
/// <b>identifier</b> (e.g. <c>site-a</c>). Comparing the two id spaces directly matched
/// nothing — a scoped caller's query returned no site rows, an explicit site filter
/// intersected to empty (403), and the execution tree dropped every site-side node. Every
/// audit read surface therefore translates the permitted ids to identifiers through this one
/// helper first, and applies the same Administrator exemption as every other scope check.
/// </para>
/// </remarks>
public static class AuditSiteScope
{
/// <summary>
/// Translates the caller's permitted numeric site ids to site identifiers.
/// </summary>
/// <param name="sites">Site repository used to look the ids up.</param>
/// <param name="permittedSiteIds">The caller's permitted numeric site ids, as strings.</param>
/// <param name="isAdministrator">Whether the caller holds the Administrator role.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>
/// <c>null</c> when the caller is unscoped (an Administrator, or no site claims at all);
/// otherwise the permitted identifiers. The list may be EMPTY — a scoped caller whose
/// sites no longer exist (or whose claims are not integers) sees no site rows. Null and
/// empty are deliberately different: empty is the fail-closed outcome.
/// </returns>
public static async Task<IReadOnlyList<string>?> ResolvePermittedSiteIdentifiersAsync(
ISiteRepository sites,
IReadOnlyCollection<string> permittedSiteIds,
bool isAdministrator,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(sites);
ArgumentNullException.ThrowIfNull(permittedSiteIds);
if (isAdministrator || permittedSiteIds.Count == 0)
return null;
var identifiers = new List<string>();
foreach (var raw in permittedSiteIds.Distinct(StringComparer.Ordinal))
{
if (!int.TryParse(raw, out var id))
continue;
var site = await sites.GetSiteByIdAsync(id, ct).ConfigureAwait(false);
if (site is not null && !identifiers.Contains(site.SiteIdentifier, StringComparer.OrdinalIgnoreCase))
identifiers.Add(site.SiteIdentifier);
}
return identifiers;
}
/// <summary>
/// Restricts an audit-log query filter to the caller's permitted site identifiers.
/// </summary>
/// <param name="filter">The caller-supplied filter.</param>
/// <param name="permittedIdentifiers">
/// From <see cref="ResolvePermittedSiteIdentifiersAsync"/>; <c>null</c> = unscoped.
/// </param>
/// <returns>
/// The filter unchanged for an unscoped caller; for a scoped caller with no explicit site
/// filter, the filter restricted to the permitted identifiers; for an explicit filter, its
/// intersection with them (identifiers compare case-insensitively, like the database).
/// <c>null</c> when nothing is left — an explicit filter entirely outside the permitted
/// set, or a scoped caller with no resolvable site — so the caller can refuse (403) or
/// return an empty page. Never returns an empty <see cref="AuditLogQueryFilter.SourceSiteIds"/>,
/// which the repository would read as "no site filter".
/// </returns>
public static AuditLogQueryFilter? Apply(AuditLogQueryFilter filter, IReadOnlyList<string>? permittedIdentifiers)
{
ArgumentNullException.ThrowIfNull(filter);
if (permittedIdentifiers is null)
return filter;
if (permittedIdentifiers.Count == 0)
return null;
var permitted = new HashSet<string>(permittedIdentifiers, StringComparer.OrdinalIgnoreCase);
if (filter.SourceSiteIds is null || filter.SourceSiteIds.Count == 0)
return filter with { SourceSiteIds = permitted.ToArray() };
var intersection = filter.SourceSiteIds.Where(permitted.Contains).ToArray();
return intersection.Length == 0 ? null : filter with { SourceSiteIds = intersection };
}
}
@@ -143,7 +143,7 @@ public static class AuditEndpoints
return BadFilter(ex);
}
var restricted = ApplySiteScope(filter, auth.User!);
var restricted = ApplySiteScope(filter, await ResolveScopeAsync(context, auth.User!));
if (restricted is null)
{
return Forbidden("OperationalAudit");
@@ -225,7 +225,7 @@ public static class AuditEndpoints
return BadFilter(ex);
}
var restricted = ApplySiteScope(filter, auth.User!);
var restricted = ApplySiteScope(filter, await ResolveScopeAsync(context, auth.User!));
if (restricted is null)
{
return Forbidden("AuditExport");
@@ -300,8 +300,10 @@ public static class AuditEndpoints
}
var repo = context.RequestServices.GetRequiredService<IAuditLogRepository>();
var permitted = auth.User!.Roles.Contains("Administrator", StringComparer.OrdinalIgnoreCase)
|| auth.User.PermittedSiteIds.Length == 0 ? null : auth.User.PermittedSiteIds;
// MGT-2: the tree's scope compares against AuditLog.SourceSiteId (site IDENTIFIERS),
// so translate the numeric permitted ids first — passing them raw dropped every
// site-side node from a scoped caller's tree.
var permitted = await ResolveScopeAsync(context, auth.User!);
var nodes = await repo.GetExecutionTreeAsync(executionId, context.RequestAborted, permitted);
return Results.Json(nodes, JsonOptions);
@@ -580,50 +582,43 @@ public static class AuditEndpoints
new { error = ex.Message, code = "BAD_REQUEST" }, statusCode: 400);
/// <summary>
/// Applies the caller's <see cref="AuthenticatedUser.PermittedSiteIds"/> to the
/// audit-log filter. System-wide callers (empty PermittedSiteIds —
/// Admin or a Deployment-style role with no scope rules attached to its mapping)
/// see the filter unchanged. A scoped caller has any caller-supplied
/// <c>sourceSiteId</c> intersected with their permitted set: an empty caller filter
/// is replaced by the permitted set; an explicit out-of-scope filter (no overlap
/// with the permitted set) returns <c>null</c> so the caller gets a 403 rather
/// than silently empty results.
/// Resolves the caller's audit site scope: <c>null</c> for an unscoped caller (an
/// Administrator, or no site claims), otherwise the permitted site IDENTIFIERS — the
/// values <c>AuditLog.SourceSiteId</c> holds. <c>PermittedSiteIds</c> are numeric
/// <c>Site.Id</c> values, so they are translated through <see cref="ISiteRepository"/>
/// (code review 2026-12-02 MGT-2; shared helper <see cref="AuditSiteScope"/>).
/// </summary>
/// <param name="context">The request context (services + abort token).</param>
/// <param name="user">The authenticated caller.</param>
/// <returns>The permitted identifiers, or <c>null</c> when unscoped.</returns>
internal static Task<IReadOnlyList<string>?> ResolveScopeAsync(HttpContext context, AuthenticatedUser user)
{
var isAdministrator = user.Roles.Contains("Administrator", StringComparer.OrdinalIgnoreCase);
if (isAdministrator || user.PermittedSiteIds.Length == 0)
return Task.FromResult<IReadOnlyList<string>?>(null);
return AuditSiteScope.ResolvePermittedSiteIdentifiersAsync(
context.RequestServices.GetRequiredService<ISiteRepository>(),
user.PermittedSiteIds, isAdministrator, context.RequestAborted);
}
/// <summary>
/// Applies the caller's permitted site identifiers (from <see cref="ResolveScopeAsync"/>)
/// to the audit-log filter. An unscoped caller (<c>null</c>) sees the filter unchanged.
/// A scoped caller has any caller-supplied <c>sourceSiteId</c> intersected with their
/// permitted set: an empty caller filter is replaced by the permitted set; an explicit
/// out-of-scope filter (no overlap), or a scoped caller none of whose sites resolve,
/// returns <c>null</c> so the caller gets a 403 rather than silently empty — or, worse,
/// unfiltered — results.
/// </summary>
/// <param name="filter">The caller-supplied audit-log query filter to scope.</param>
/// <param name="user">The authenticated user whose permitted site IDs constrain the filter.</param>
/// <param name="permittedIdentifiers">The caller's permitted site identifiers; <c>null</c> = unscoped.</param>
/// <returns>
/// The restricted filter, or <c>null</c> if the caller explicitly asked for
/// sites entirely outside their permitted set.
/// </returns>
public static AuditLogQueryFilter? ApplySiteScope(AuditLogQueryFilter filter, AuthenticatedUser user)
{
// Empty PermittedSiteIds is the system-wide signal (Administrator,
// system-wide Deployer). System-wide audit roles also fall here — the
// design treats Administrator/Viewer (the audit roles) as
// non-site-scoped unless an operator attaches scope rules to the LDAP
// mapping; if they do, this helper enforces them.
if (user.PermittedSiteIds.Length == 0)
{
return filter;
}
var permitted = new HashSet<string>(user.PermittedSiteIds, StringComparer.Ordinal);
if (filter.SourceSiteIds is null || filter.SourceSiteIds.Count == 0)
{
// No explicit filter — restrict to permitted set.
return filter with { SourceSiteIds = permitted.ToArray() };
}
// Explicit filter — intersect.
var intersection = filter.SourceSiteIds.Where(permitted.Contains).ToArray();
if (intersection.Length == 0)
{
return null;
}
return filter with { SourceSiteIds = intersection };
}
public static AuditLogQueryFilter? ApplySiteScope(AuditLogQueryFilter filter, IReadOnlyList<string>? permittedIdentifiers)
=> AuditSiteScope.Apply(filter, permittedIdentifiers);
// ─────────────────────────────────────────────────────────────────────
// Query-string parsing
@@ -639,8 +639,12 @@ public sealed class FlowDebugRunner
ArgumentNullException.ThrowIfNull(sp);
ArgumentNullException.ThrowIfNull(cmd);
var startedAt = DateTimeOffset.UtcNow;
// Code review 2026-12-02 MGT-2: the trace scope compares against AuditLog.SourceSiteId
// (site IDENTIFIERS); PermittedSiteIds are numeric Site.Id values, so translate them
// first — passing them raw dropped every site-side row from a scoped Replay.
var scope = await ResolvePermittedSiteIdentifiersAsync(sp, user, ct).ConfigureAwait(false);
var events = await sp.GetRequiredService<IAuditLogRepository>()
.GetTraceEventsAsync(cmd.ExecutionId, ct, user.Roles.Contains("Administrator", StringComparer.OrdinalIgnoreCase) || user.PermittedSiteIds.Length == 0 ? null : user.PermittedSiteIds).ConfigureAwait(false);
.GetTraceEventsAsync(cmd.ExecutionId, ct, scope?.ToList()).ConfigureAwait(false);
if (events.Count == 0 && events is not ZB.MOM.WW.ScadaBridge.Commons.Types.Audit.TraceEventBatch { Truncated: true })
{
return new FlowDebugRunResult(cmd.ExecutionId, false,