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:
@@ -336,6 +336,7 @@ Per-leaf alarm rendering (leaf nodes are individual conditions for native alarms
|
|||||||
- **"Copy as cURL"** action on `ApiOutbound` and `ApiInbound` rows.
|
- **"Copy as cURL"** action on `ApiOutbound` and `ApiInbound` rows.
|
||||||
- **"Show all events for this operation"** link — re-applies the current view filtered by the row's `CorrelationId`.
|
- **"Show all events for this operation"** link — re-applies the current view filtered by the row's `CorrelationId`.
|
||||||
- **Export** button on the page header streams a server-side CSV of the current filter (default cap 100k rows; larger exports go through the CLI). Requires the `AuditExport` permission.
|
- **Export** button on the page header streams a server-side CSV of the current filter (default cap 100k rows; larger exports go through the CLI). Requires the `AuditExport` permission.
|
||||||
|
- **Site scope (code review 2026-12-02 UI-5).** The grid, every drill-in that reuses `AuditLogQueryService.QueryAsync`, and the Execution Tree apply the caller's site scope exactly as `/api/audit/query` and `/api/audit/tree` do: the numeric `SiteId` claims are translated to site identifiers (`AuditSiteScope`, the value `AuditLog.SourceSiteId` holds) and pushed into the query before paging; an Administrator, or a user with no `SiteId` claims, is unscoped; an explicit site filter outside the caller's sites returns no rows. Before this the grid showed a scoped user every site's rows and the tree compared numeric ids to identifiers, dropping the user's own site-side nodes.
|
||||||
|
|
||||||
### Configuration Audit Log Viewer (Admin Role)
|
### Configuration Audit Log Viewer (Admin Role)
|
||||||
- Pre-existing viewer for the `IAuditService` configuration-change log (template / instance / site / etc. before-after edits). Lives under the same **Audit** nav group as the operational Audit Log above.
|
- Pre-existing viewer for the `IAuditService` configuration-change log (template / instance / site / etc. before-after edits). Lives under the same **Audit** nav group as the operational Audit Log above.
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ In addition to `/management`, the Management Service exposes a dedicated REST su
|
|||||||
- `GET /api/audit/query` — keyset-paged JSON query over the central `AuditLog` table. Authenticated via HTTP Basic Auth (shared with `/management`); gated on the `OperationalAudit` permission (Admin / Audit / AuditReadOnly roles).
|
- `GET /api/audit/query` — keyset-paged JSON query over the central `AuditLog` table. Authenticated via HTTP Basic Auth (shared with `/management`); gated on the `OperationalAudit` permission (Admin / Audit / AuditReadOnly roles).
|
||||||
- `GET /api/audit/export` — server-side streaming bulk export (CSV or JSONL) of the filtered rows. Gated on the `AuditExport` permission (Admin / Audit).
|
- `GET /api/audit/export` — server-side streaming bulk export (CSV or JSONL) of the filtered rows. Gated on the `AuditExport` permission (Admin / Audit).
|
||||||
|
|
||||||
Both endpoints honour any site-scope rules attached to the caller's audit role by intersecting the caller-supplied `sourceSiteId` filter with the user's `PermittedSiteIds` (out-of-scope requests yield HTTP 403). Permission denial returns HTTP 403 with the same envelope shape used by `/management`.
|
Both endpoints honour any site-scope rules attached to the caller's audit role by intersecting the caller-supplied `sourceSiteId` filter with the user's permitted sites (out-of-scope requests yield HTTP 403). `PermittedSiteIds` are numeric `Site.Id` values while `AuditLog.SourceSiteId` holds the site **identifier**, so the permitted ids are translated to identifiers first (shared `Commons.Types.Audit.AuditSiteScope`, also used by `/api/audit/tree`, Flow Debugger Replay and the Central UI Audit Log grid/tree); an Administrator is unscoped, as on every other scope check; and a scoped caller none of whose sites resolve is refused rather than handed an empty — i.e. unfiltered — site list. Before code review 2026-12-02 MGT-2 the raw numeric ids were compared against identifiers, so a scoped `audit query` always came back empty, `--site <own site>` was a 403, and `audit tree` dropped every site-side node. Permission denial returns HTTP 403 with the same envelope shape used by `/management`.
|
||||||
|
|
||||||
**Filter parsing is strict on the enum dimensions** (`channel`, `kind`, `status`; register row 99). Values are matched **case-insensitively** against the enum member names, and an unrecognised value returns **HTTP 400** `{ error, code: "BAD_REQUEST" }` naming the full valid set — it is not silently dropped. Silently dropping a filter would leave that dimension unconstrained and hand the caller a plausible, complete-looking page that does not answer the question they asked (the same failure row 88 fixed for `deploy status`). **Ordinals are rejected**: a filter is a name-based contract, so `status=3` is an error even though `Enum.TryParse` would accept it and `3` is a real member. The `correlationId`/`executionId`/`parentExecutionId`/date dimensions stay **lax** (unparseable values are dropped).
|
**Filter parsing is strict on the enum dimensions** (`channel`, `kind`, `status`; register row 99). Values are matched **case-insensitively** against the enum member names, and an unrecognised value returns **HTTP 400** `{ error, code: "BAD_REQUEST" }` naming the full valid set — it is not silently dropped. Silently dropping a filter would leave that dimension unconstrained and hand the caller a plausible, complete-looking page that does not answer the question they asked (the same failure row 88 fixed for `deploy status`). **Ordinals are rejected**: a filter is a name-based contract, so `status=3` is an error even though `Enum.TryParse` would accept it and `3` is a real member. The `correlationId`/`executionId`/`parentExecutionId`/date dimensions stay **lax** (unparseable values are dropped).
|
||||||
|
|
||||||
|
|||||||
@@ -120,11 +120,49 @@ public sealed class AuditLogQueryService : IAuditLogQueryService
|
|||||||
// Production: a fresh scope (and thus a fresh DbContext) per query so the
|
// Production: a fresh scope (and thus a fresh DbContext) per query so the
|
||||||
// page's auto-load never shares the circuit-scoped context.
|
// page's auto-load never shares the circuit-scoped context.
|
||||||
await using var scope = _scopeFactory!.CreateAsyncScope();
|
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 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();
|
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/>
|
/// <inheritdoc/>
|
||||||
public async Task<AuditLogKpiSnapshot> GetKpiSnapshotAsync(CancellationToken ct = default)
|
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.");
|
if (_auth is null) throw new InvalidOperationException("Audit tree caller authentication is not configured.");
|
||||||
var principal = (await _auth.GetAuthoritativeStateAsync()).User;
|
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();
|
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();
|
// Code review 2026-12-02 UI-5: the scope compares against AuditLog.SourceSiteId (site
|
||||||
var permitted = principal.HasClaim(JwtTokenService.RoleClaimType, Roles.Administrator) || sites.Length == 0 ? null : sites;
|
// 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);
|
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);
|
return BadFilter(ex);
|
||||||
}
|
}
|
||||||
|
|
||||||
var restricted = ApplySiteScope(filter, auth.User!);
|
var restricted = ApplySiteScope(filter, await ResolveScopeAsync(context, auth.User!));
|
||||||
if (restricted is null)
|
if (restricted is null)
|
||||||
{
|
{
|
||||||
return Forbidden("OperationalAudit");
|
return Forbidden("OperationalAudit");
|
||||||
@@ -225,7 +225,7 @@ public static class AuditEndpoints
|
|||||||
return BadFilter(ex);
|
return BadFilter(ex);
|
||||||
}
|
}
|
||||||
|
|
||||||
var restricted = ApplySiteScope(filter, auth.User!);
|
var restricted = ApplySiteScope(filter, await ResolveScopeAsync(context, auth.User!));
|
||||||
if (restricted is null)
|
if (restricted is null)
|
||||||
{
|
{
|
||||||
return Forbidden("AuditExport");
|
return Forbidden("AuditExport");
|
||||||
@@ -300,8 +300,10 @@ public static class AuditEndpoints
|
|||||||
}
|
}
|
||||||
|
|
||||||
var repo = context.RequestServices.GetRequiredService<IAuditLogRepository>();
|
var repo = context.RequestServices.GetRequiredService<IAuditLogRepository>();
|
||||||
var permitted = auth.User!.Roles.Contains("Administrator", StringComparer.OrdinalIgnoreCase)
|
// MGT-2: the tree's scope compares against AuditLog.SourceSiteId (site IDENTIFIERS),
|
||||||
|| auth.User.PermittedSiteIds.Length == 0 ? null : auth.User.PermittedSiteIds;
|
// 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);
|
var nodes = await repo.GetExecutionTreeAsync(executionId, context.RequestAborted, permitted);
|
||||||
|
|
||||||
return Results.Json(nodes, JsonOptions);
|
return Results.Json(nodes, JsonOptions);
|
||||||
@@ -580,50 +582,43 @@ public static class AuditEndpoints
|
|||||||
new { error = ex.Message, code = "BAD_REQUEST" }, statusCode: 400);
|
new { error = ex.Message, code = "BAD_REQUEST" }, statusCode: 400);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Applies the caller's <see cref="AuthenticatedUser.PermittedSiteIds"/> to the
|
/// Resolves the caller's audit site scope: <c>null</c> for an unscoped caller (an
|
||||||
/// audit-log filter. System-wide callers (empty PermittedSiteIds —
|
/// Administrator, or no site claims), otherwise the permitted site IDENTIFIERS — the
|
||||||
/// Admin or a Deployment-style role with no scope rules attached to its mapping)
|
/// values <c>AuditLog.SourceSiteId</c> holds. <c>PermittedSiteIds</c> are numeric
|
||||||
/// see the filter unchanged. A scoped caller has any caller-supplied
|
/// <c>Site.Id</c> values, so they are translated through <see cref="ISiteRepository"/>
|
||||||
/// <c>sourceSiteId</c> intersected with their permitted set: an empty caller filter
|
/// (code review 2026-12-02 MGT-2; shared helper <see cref="AuditSiteScope"/>).
|
||||||
/// is replaced by the permitted set; an explicit out-of-scope filter (no overlap
|
/// </summary>
|
||||||
/// with the permitted set) returns <c>null</c> so the caller gets a 403 rather
|
/// <param name="context">The request context (services + abort token).</param>
|
||||||
/// than silently empty results.
|
/// <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>
|
/// </summary>
|
||||||
/// <param name="filter">The caller-supplied audit-log query filter to scope.</param>
|
/// <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>
|
/// <returns>
|
||||||
/// The restricted filter, or <c>null</c> if the caller explicitly asked for
|
/// The restricted filter, or <c>null</c> if the caller explicitly asked for
|
||||||
/// sites entirely outside their permitted set.
|
/// sites entirely outside their permitted set.
|
||||||
/// </returns>
|
/// </returns>
|
||||||
public static AuditLogQueryFilter? ApplySiteScope(AuditLogQueryFilter filter, AuthenticatedUser user)
|
public static AuditLogQueryFilter? ApplySiteScope(AuditLogQueryFilter filter, IReadOnlyList<string>? permittedIdentifiers)
|
||||||
{
|
=> AuditSiteScope.Apply(filter, permittedIdentifiers);
|
||||||
// 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 };
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────────────
|
||||||
// Query-string parsing
|
// Query-string parsing
|
||||||
|
|||||||
@@ -639,8 +639,12 @@ public sealed class FlowDebugRunner
|
|||||||
ArgumentNullException.ThrowIfNull(sp);
|
ArgumentNullException.ThrowIfNull(sp);
|
||||||
ArgumentNullException.ThrowIfNull(cmd);
|
ArgumentNullException.ThrowIfNull(cmd);
|
||||||
var startedAt = DateTimeOffset.UtcNow;
|
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>()
|
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 })
|
if (events.Count == 0 && events is not ZB.MOM.WW.ScadaBridge.Commons.Types.Audit.TraceEventBatch { Truncated: true })
|
||||||
{
|
{
|
||||||
return new FlowDebugRunResult(cmd.ExecutionId, false,
|
return new FlowDebugRunResult(cmd.ExecutionId, false,
|
||||||
|
|||||||
@@ -24,6 +24,111 @@ namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Services;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class AuditLogQueryServiceTests
|
public class AuditLogQueryServiceTests
|
||||||
{
|
{
|
||||||
|
/// <summary>A principal with the given role and (numeric) SiteId scope claims.</summary>
|
||||||
|
private static Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider Auth(string role, params string[] siteIds)
|
||||||
|
{
|
||||||
|
var claims = new List<System.Security.Claims.Claim>
|
||||||
|
{
|
||||||
|
new(ZB.MOM.WW.ScadaBridge.Security.JwtTokenService.RoleClaimType, role),
|
||||||
|
};
|
||||||
|
claims.AddRange(siteIds.Select(id => new System.Security.Claims.Claim(
|
||||||
|
ZB.MOM.WW.ScadaBridge.Security.JwtTokenService.SiteIdClaimType, id)));
|
||||||
|
var state = new Microsoft.AspNetCore.Components.Authorization.AuthenticationState(
|
||||||
|
new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity(claims, "test")));
|
||||||
|
var auth = Substitute.For<Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider>();
|
||||||
|
auth.GetAuthenticationStateAsync().Returns(Task.FromResult(state));
|
||||||
|
return auth;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds the production-ctor service over a substitute repository and a site repository
|
||||||
|
/// that resolves site id N to identifier <c>site-N</c>.
|
||||||
|
/// </summary>
|
||||||
|
private static (AuditLogQueryService Sut, IAuditLogRepository Repo, ServiceProvider Provider) Scoped(
|
||||||
|
Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider auth)
|
||||||
|
{
|
||||||
|
var repo = Substitute.For<IAuditLogRepository>();
|
||||||
|
repo.QueryAsync(Arg.Any<AuditLogQueryFilter>(), Arg.Any<AuditLogPaging>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Task.FromResult<IReadOnlyList<AuditEvent>>(Array.Empty<AuditEvent>()));
|
||||||
|
repo.GetExecutionTreeAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>(), Arg.Any<IReadOnlyList<string>?>())
|
||||||
|
.Returns(Task.FromResult<IReadOnlyList<ExecutionTreeNode>>(Array.Empty<ExecutionTreeNode>()));
|
||||||
|
var sites = Substitute.For<ISiteRepository>();
|
||||||
|
sites.GetSiteByIdAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(ci => new ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site($"Site {ci.Arg<int>()}", $"site-{ci.Arg<int>()}") { Id = ci.Arg<int>() });
|
||||||
|
var services = new ServiceCollection();
|
||||||
|
services.AddScoped(_ => repo);
|
||||||
|
services.AddScoped(_ => sites);
|
||||||
|
var provider = services.BuildServiceProvider();
|
||||||
|
return (new AuditLogQueryService(provider.GetRequiredService<IServiceScopeFactory>(), EmptyAggregator(), auth), repo, provider);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Code review 2026-12-02 UI-5: the grid applies site scope, by identifier ──
|
||||||
|
|
||||||
|
/// <summary>A site-scoped caller's grid query is restricted to their sites' identifiers, before paging.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task QueryAsync_ScopedCaller_FiltersBySiteIdentifier()
|
||||||
|
{
|
||||||
|
var (sut, repo, provider) = Scoped(Auth(ZB.MOM.WW.ScadaBridge.Security.Roles.Viewer, "3", "7"));
|
||||||
|
await using var _ = provider;
|
||||||
|
|
||||||
|
await sut.QueryAsync(new AuditLogQueryFilter(Channels: new[] { AuditChannel.ApiOutbound }));
|
||||||
|
|
||||||
|
await repo.Received(1).QueryAsync(
|
||||||
|
Arg.Is<AuditLogQueryFilter>(f => f.SourceSiteIds != null
|
||||||
|
&& f.SourceSiteIds.OrderBy(x => x).SequenceEqual(new[] { "site-3", "site-7" })
|
||||||
|
&& f.Channels!.SequenceEqual(new[] { AuditChannel.ApiOutbound })),
|
||||||
|
Arg.Any<AuditLogPaging>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An explicit site filter outside the caller's scope returns nothing without querying.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task QueryAsync_ScopedCaller_OutOfScopeSiteFilter_ReturnsEmpty()
|
||||||
|
{
|
||||||
|
var (sut, repo, provider) = Scoped(Auth(ZB.MOM.WW.ScadaBridge.Security.Roles.Viewer, "3"));
|
||||||
|
await using var _ = provider;
|
||||||
|
|
||||||
|
var rows = await sut.QueryAsync(new AuditLogQueryFilter(SourceSiteIds: new[] { "site-9" }));
|
||||||
|
|
||||||
|
Assert.Empty(rows);
|
||||||
|
await repo.DidNotReceiveWithAnyArgs().QueryAsync(default!, default!, default);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An Administrator (or a caller without site claims) is unscoped.</summary>
|
||||||
|
/// <param name="role">The caller's role.</param>
|
||||||
|
/// <param name="siteIds">Comma-separated site claims (may be empty).</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Administrator", "3")]
|
||||||
|
[InlineData("Viewer", "")]
|
||||||
|
public async Task QueryAsync_UnscopedCaller_FilterUnchanged(string role, string siteIds)
|
||||||
|
{
|
||||||
|
var (sut, repo, provider) = Scoped(Auth(role, siteIds.Split(',', StringSplitOptions.RemoveEmptyEntries)));
|
||||||
|
await using var _ = provider;
|
||||||
|
var filter = new AuditLogQueryFilter();
|
||||||
|
|
||||||
|
await sut.QueryAsync(filter);
|
||||||
|
|
||||||
|
await repo.Received(1).QueryAsync(filter, Arg.Any<AuditLogPaging>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The execution tree's scope is translated to site identifiers, not passed as raw numeric ids.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task GetExecutionTreeAsync_ScopedCaller_PassesSiteIdentifiers()
|
||||||
|
{
|
||||||
|
var auth = Auth(ZB.MOM.WW.ScadaBridge.Security.Roles.Viewer, "3");
|
||||||
|
var (sut, repo, provider) = Scoped(auth);
|
||||||
|
await using var _ = provider;
|
||||||
|
var id = Guid.NewGuid();
|
||||||
|
|
||||||
|
await sut.GetExecutionTreeAsync(id);
|
||||||
|
|
||||||
|
await repo.Received(1).GetExecutionTreeAsync(id, Arg.Any<CancellationToken>(),
|
||||||
|
Arg.Is<IReadOnlyList<string>?>(s => s != null && s.SequenceEqual(new[] { "site-3" })));
|
||||||
|
}
|
||||||
|
|
||||||
private static ICentralHealthAggregator EmptyAggregator()
|
private static ICentralHealthAggregator EmptyAggregator()
|
||||||
{
|
{
|
||||||
var agg = Substitute.For<ICentralHealthAggregator>();
|
var agg = Substitute.For<ICentralHealthAggregator>();
|
||||||
@@ -201,7 +306,7 @@ public class AuditLogQueryServiceTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
var scopeFactory = provider.GetRequiredService<IServiceScopeFactory>();
|
var scopeFactory = provider.GetRequiredService<IServiceScopeFactory>();
|
||||||
var sut = new AuditLogQueryService(scopeFactory, EmptyAggregator());
|
var sut = new AuditLogQueryService(scopeFactory, EmptyAggregator(), Auth(ZB.MOM.WW.ScadaBridge.Security.Roles.Viewer));
|
||||||
|
|
||||||
var filter = new AuditLogQueryFilter(Channels: new[] { AuditChannel.ApiOutbound });
|
var filter = new AuditLogQueryFilter(Channels: new[] { AuditChannel.ApiOutbound });
|
||||||
|
|
||||||
@@ -238,7 +343,7 @@ public class AuditLogQueryServiceTests
|
|||||||
await using var provider = services.BuildServiceProvider();
|
await using var provider = services.BuildServiceProvider();
|
||||||
var sut = new AuditLogQueryService(
|
var sut = new AuditLogQueryService(
|
||||||
provider.GetRequiredService<IServiceScopeFactory>(),
|
provider.GetRequiredService<IServiceScopeFactory>(),
|
||||||
EmptyAggregator());
|
EmptyAggregator(), Auth(ZB.MOM.WW.ScadaBridge.Security.Roles.Viewer));
|
||||||
|
|
||||||
await sut.QueryAsync(new AuditLogQueryFilter());
|
await sut.QueryAsync(new AuditLogQueryFilter());
|
||||||
await sut.QueryAsync(new AuditLogQueryFilter());
|
await sut.QueryAsync(new AuditLogQueryFilter());
|
||||||
|
|||||||
@@ -18,7 +18,12 @@ public class AuditTreeScopeTests
|
|||||||
public async Task ProductionTreeRead_UsesFreshCallerScope_EveryTime()
|
public async Task ProductionTreeRead_UsesFreshCallerScope_EveryTime()
|
||||||
{
|
{
|
||||||
var repo = Substitute.For<IAuditLogRepository>();
|
var repo = Substitute.For<IAuditLogRepository>();
|
||||||
using var provider = new ServiceCollection().AddSingleton(repo).BuildServiceProvider();
|
// Code review 2026-12-02 UI-5: the numeric SiteId claim is translated to the site
|
||||||
|
// IDENTIFIER AuditLog.SourceSiteId holds before it reaches the repository.
|
||||||
|
var sites = Substitute.For<ISiteRepository>();
|
||||||
|
sites.GetSiteByIdAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(ci => new ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site($"Site {ci.Arg<int>()}", $"site-{ci.Arg<int>()}") { Id = ci.Arg<int>() });
|
||||||
|
using var provider = new ServiceCollection().AddSingleton(repo).AddSingleton(sites).BuildServiceProvider();
|
||||||
var auth = new ChangingAuth();
|
var auth = new ChangingAuth();
|
||||||
var service = new AuditLogQueryService(provider.GetRequiredService<IServiceScopeFactory>(),
|
var service = new AuditLogQueryService(provider.GetRequiredService<IServiceScopeFactory>(),
|
||||||
Substitute.For<ICentralHealthAggregator>(), auth);
|
Substitute.For<ICentralHealthAggregator>(), auth);
|
||||||
@@ -28,9 +33,9 @@ public class AuditTreeScopeTests
|
|||||||
auth.Site = "43";
|
auth.Site = "43";
|
||||||
await service.GetExecutionTreeAsync(execution);
|
await service.GetExecutionTreeAsync(execution);
|
||||||
await repo.Received(1).GetExecutionTreeAsync(execution, Arg.Any<CancellationToken>(),
|
await repo.Received(1).GetExecutionTreeAsync(execution, Arg.Any<CancellationToken>(),
|
||||||
Arg.Is<IReadOnlyList<string>?>(x => x != null && x.SequenceEqual(new[] { "42" })));
|
Arg.Is<IReadOnlyList<string>?>(x => x != null && x.SequenceEqual(new[] { "site-42" })));
|
||||||
await repo.Received(1).GetExecutionTreeAsync(execution, Arg.Any<CancellationToken>(),
|
await repo.Received(1).GetExecutionTreeAsync(execution, Arg.Any<CancellationToken>(),
|
||||||
Arg.Is<IReadOnlyList<string>?>(x => x != null && x.SequenceEqual(new[] { "43" })));
|
Arg.Is<IReadOnlyList<string>?>(x => x != null && x.SequenceEqual(new[] { "site-43" })));
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed class ChangingAuth : AuthenticationStateProvider
|
private sealed class ChangingAuth : AuthenticationStateProvider
|
||||||
|
|||||||
@@ -832,18 +832,15 @@ public class AuditEndpointsTests
|
|||||||
// ApplySiteScope
|
// ApplySiteScope
|
||||||
// ─────────────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
/// <summary>Verifies that a system-wide user's filter is returned unchanged by site scoping.</summary>
|
/// <summary>Verifies that an unscoped caller's filter is returned unchanged by site scoping.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ApplySiteScope_SystemWideUser_ReturnsFilterUnchanged()
|
public void ApplySiteScope_UnscopedCaller_ReturnsFilterUnchanged()
|
||||||
{
|
{
|
||||||
// Empty PermittedSiteIds is the system-wide signal (Administrator,
|
// null permitted identifiers is the unscoped signal (Administrator, or no site
|
||||||
// system-wide Deployer, audit roles with no scope rules attached). The
|
// claims). The filter should pass through with no restriction added.
|
||||||
// filter should pass through with no restriction added.
|
|
||||||
var user = new ZB.MOM.WW.ScadaBridge.Commons.Messages.Management.AuthenticatedUser(
|
|
||||||
"alice", "Alice", new[] { "Administrator" }, Array.Empty<string>());
|
|
||||||
var filter = new AuditLogQueryFilter(SourceSiteIds: new[] { "plant-a" });
|
var filter = new AuditLogQueryFilter(SourceSiteIds: new[] { "plant-a" });
|
||||||
|
|
||||||
var result = AuditEndpoints.ApplySiteScope(filter, user);
|
var result = AuditEndpoints.ApplySiteScope(filter, null);
|
||||||
|
|
||||||
Assert.NotNull(result);
|
Assert.NotNull(result);
|
||||||
Assert.Same(filter, result);
|
Assert.Same(filter, result);
|
||||||
@@ -856,29 +853,23 @@ public class AuditEndpointsTests
|
|||||||
// No explicit sourceSiteId from the caller — the helper must restrict
|
// No explicit sourceSiteId from the caller — the helper must restrict
|
||||||
// the query to the user's permitted set, otherwise a site-scoped audit
|
// the query to the user's permitted set, otherwise a site-scoped audit
|
||||||
// user could read every site's rows.
|
// user could read every site's rows.
|
||||||
var user = new ZB.MOM.WW.ScadaBridge.Commons.Messages.Management.AuthenticatedUser(
|
var result = AuditEndpoints.ApplySiteScope(new AuditLogQueryFilter(), new[] { "plant-a", "plant-b" });
|
||||||
"alice", "Alice", new[] { "Viewer" }, new[] { "plant-a", "plant-b" });
|
|
||||||
var filter = new AuditLogQueryFilter();
|
|
||||||
|
|
||||||
var result = AuditEndpoints.ApplySiteScope(filter, user);
|
|
||||||
|
|
||||||
Assert.NotNull(result);
|
Assert.NotNull(result);
|
||||||
Assert.NotNull(result!.SourceSiteIds);
|
Assert.NotNull(result!.SourceSiteIds);
|
||||||
Assert.Equal(new[] { "plant-a", "plant-b" }, result.SourceSiteIds!.OrderBy(s => s).ToArray());
|
Assert.Equal(new[] { "plant-a", "plant-b" }, result.SourceSiteIds!.OrderBy(s => s).ToArray());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that an explicit in-scope filter is kept unchanged for a scoped user.</summary>
|
/// <summary>Verifies that an explicit in-scope filter is kept for a scoped user (identifiers compare case-insensitively).</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ApplySiteScope_ScopedUser_ExplicitInScopeFilter_KeptVerbatim()
|
public void ApplySiteScope_ScopedUser_ExplicitInScopeFilter_KeptVerbatim()
|
||||||
{
|
{
|
||||||
var user = new ZB.MOM.WW.ScadaBridge.Commons.Messages.Management.AuthenticatedUser(
|
var filter = new AuditLogQueryFilter(SourceSiteIds: new[] { "Plant-A" });
|
||||||
"alice", "Alice", new[] { "Viewer" }, new[] { "plant-a", "plant-b" });
|
|
||||||
var filter = new AuditLogQueryFilter(SourceSiteIds: new[] { "plant-a" });
|
|
||||||
|
|
||||||
var result = AuditEndpoints.ApplySiteScope(filter, user);
|
var result = AuditEndpoints.ApplySiteScope(filter, new[] { "plant-a", "plant-b" });
|
||||||
|
|
||||||
Assert.NotNull(result);
|
Assert.NotNull(result);
|
||||||
Assert.Equal(new[] { "plant-a" }, result!.SourceSiteIds);
|
Assert.Equal(new[] { "Plant-A" }, result!.SourceSiteIds);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that an explicit out-of-scope filter yields null for a scoped user.</summary>
|
/// <summary>Verifies that an explicit out-of-scope filter yields null for a scoped user.</summary>
|
||||||
@@ -887,29 +878,87 @@ public class AuditEndpointsTests
|
|||||||
{
|
{
|
||||||
// Caller explicitly asked for a site they cannot see — the helper signals
|
// Caller explicitly asked for a site they cannot see — the helper signals
|
||||||
// "403" by returning null rather than silently producing an empty page.
|
// "403" by returning null rather than silently producing an empty page.
|
||||||
var user = new ZB.MOM.WW.ScadaBridge.Commons.Messages.Management.AuthenticatedUser(
|
|
||||||
"alice", "Alice", new[] { "Viewer" }, new[] { "plant-a" });
|
|
||||||
var filter = new AuditLogQueryFilter(SourceSiteIds: new[] { "plant-b" });
|
var filter = new AuditLogQueryFilter(SourceSiteIds: new[] { "plant-b" });
|
||||||
|
|
||||||
var result = AuditEndpoints.ApplySiteScope(filter, user);
|
Assert.Null(AuditEndpoints.ApplySiteScope(filter, new[] { "plant-a" }));
|
||||||
|
|
||||||
Assert.Null(result);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that a mixed filter is reduced to its in-scope sites for a scoped user.</summary>
|
/// <summary>Verifies that a mixed filter is reduced to its in-scope sites for a scoped user.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ApplySiteScope_ScopedUser_MixedInAndOutOfScopeFilter_IntersectedToInScopeOnly()
|
public void ApplySiteScope_ScopedUser_MixedInAndOutOfScopeFilter_IntersectedToInScopeOnly()
|
||||||
{
|
{
|
||||||
var user = new ZB.MOM.WW.ScadaBridge.Commons.Messages.Management.AuthenticatedUser(
|
|
||||||
"alice", "Alice", new[] { "Viewer" }, new[] { "plant-a" });
|
|
||||||
var filter = new AuditLogQueryFilter(SourceSiteIds: new[] { "plant-a", "plant-b" });
|
var filter = new AuditLogQueryFilter(SourceSiteIds: new[] { "plant-a", "plant-b" });
|
||||||
|
|
||||||
var result = AuditEndpoints.ApplySiteScope(filter, user);
|
var result = AuditEndpoints.ApplySiteScope(filter, new[] { "plant-a" });
|
||||||
|
|
||||||
Assert.NotNull(result);
|
Assert.NotNull(result);
|
||||||
Assert.Equal(new[] { "plant-a" }, result!.SourceSiteIds);
|
Assert.Equal(new[] { "plant-a" }, result!.SourceSiteIds);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A scoped caller none of whose sites resolve is refused (null), never handed an EMPTY
|
||||||
|
/// site list — which the repository would read as "no site filter" and return everything.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void ApplySiteScope_ScopedUser_NoResolvableSite_ReturnsNull()
|
||||||
|
{
|
||||||
|
Assert.Null(AuditEndpoints.ApplySiteScope(new AuditLogQueryFilter(), Array.Empty<string>()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Code review 2026-12-02 MGT-2: a scoped caller's NUMERIC permitted ids reach the
|
||||||
|
/// repository as the site IDENTIFIERS <c>AuditLog.SourceSiteId</c> holds; before the fix
|
||||||
|
/// the query filtered <c>SourceSiteId IN ('3')</c> and always came back empty.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task Query_ScopedCaller_FiltersBySiteIdentifier_NotNumericId()
|
||||||
|
{
|
||||||
|
var (client, repo, host) = await BuildHostWithTreeAsync(new[] { "Viewer" }, permittedSites: new[] { "3" });
|
||||||
|
using (host)
|
||||||
|
{
|
||||||
|
var response = await client.SendAsync(Get("/api/audit/query"));
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
await repo.Received().QueryAsync(
|
||||||
|
Arg.Is<AuditLogQueryFilter>(f => f.SourceSiteIds != null && f.SourceSiteIds.SequenceEqual(new[] { "plant-3" })),
|
||||||
|
Arg.Any<AuditLogPaging>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// An explicit <c>--site</c> filter naming the caller's own site (by identifier) is
|
||||||
|
/// honoured; before the fix it intersected with the numeric ids to empty and returned 403.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task Query_ScopedCaller_ExplicitOwnSiteIdentifier_IsAllowed()
|
||||||
|
{
|
||||||
|
var (client, repo, host) = await BuildHostWithTreeAsync(new[] { "Viewer" }, permittedSites: new[] { "3" });
|
||||||
|
using (host)
|
||||||
|
{
|
||||||
|
var response = await client.SendAsync(Get("/api/audit/query?sourceSiteId=plant-3"));
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
var other = await client.SendAsync(Get("/api/audit/query?sourceSiteId=plant-9"));
|
||||||
|
Assert.Equal(HttpStatusCode.Forbidden, other.StatusCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An Administrator who also carries site claims is unscoped, like every other scope check.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task Query_AdministratorWithSiteClaims_IsUnscoped()
|
||||||
|
{
|
||||||
|
var (client, repo, host) = await BuildHostWithTreeAsync(new[] { "Administrator" }, permittedSites: new[] { "3" });
|
||||||
|
using (host)
|
||||||
|
{
|
||||||
|
var response = await client.SendAsync(Get("/api/audit/query"));
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
await repo.Received().QueryAsync(
|
||||||
|
Arg.Is<AuditLogQueryFilter>(f => f.SourceSiteIds == null || f.SourceSiteIds.Count == 0),
|
||||||
|
Arg.Any<AuditLogPaging>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────────────
|
||||||
// /api/audit/tree
|
// /api/audit/tree
|
||||||
// ─────────────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────────────
|
||||||
@@ -951,6 +1000,11 @@ public class AuditEndpointsTests
|
|||||||
services.AddSingleton(repo);
|
services.AddSingleton(repo);
|
||||||
services.AddSingleton(ldap);
|
services.AddSingleton(ldap);
|
||||||
services.AddSingleton(roleMapper);
|
services.AddSingleton(roleMapper);
|
||||||
|
// Site N resolves to identifier "plant-N" (MGT-2 id → identifier translation).
|
||||||
|
var sites = Substitute.For<ISiteRepository>();
|
||||||
|
sites.GetSiteByIdAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(ci => new ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site($"Plant {ci.Arg<int>()}", $"plant-{ci.Arg<int>()}") { Id = ci.Arg<int>() });
|
||||||
|
services.AddSingleton(sites);
|
||||||
// ManagementAuthenticator now consults the login throttle before the bind.
|
// ManagementAuthenticator now consults the login throttle before the bind.
|
||||||
services.AddSingleton(TimeProvider.System);
|
services.AddSingleton(TimeProvider.System);
|
||||||
services.AddSingleton<IOptions<SecurityOptions>>(Options.Create(new SecurityOptions()));
|
services.AddSingleton<IOptions<SecurityOptions>>(Options.Create(new SecurityOptions()));
|
||||||
@@ -990,8 +1044,10 @@ public class AuditEndpointsTests
|
|||||||
{
|
{
|
||||||
var response = await client.SendAsync(Get($"/api/audit/tree?executionId={execution:D}"));
|
var response = await client.SendAsync(Get($"/api/audit/tree?executionId={execution:D}"));
|
||||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
// MGT-2: the numeric permitted id is translated to the site identifier the
|
||||||
|
// AuditLog.SourceSiteId column holds (raw "42" matched no site row at all).
|
||||||
await repo.Received().GetExecutionTreeAsync(execution, Arg.Any<CancellationToken>(),
|
await repo.Received().GetExecutionTreeAsync(execution, Arg.Any<CancellationToken>(),
|
||||||
Arg.Is<IReadOnlyList<string>>(sites => sites.SequenceEqual(new[] { "42" })));
|
Arg.Is<IReadOnlyList<string>>(sites => sites.SequenceEqual(new[] { "plant-42" })));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -514,9 +514,14 @@ public class FlowDebugRunnerTests
|
|||||||
public async Task Replay_ThreadsScopeAndRetainsTruncatedRootWithoutRows()
|
public async Task Replay_ThreadsScopeAndRetainsTruncatedRootWithoutRows()
|
||||||
{
|
{
|
||||||
var repo = Substitute.For<IAuditLogRepository>(); var root = Guid.NewGuid(); var child = Guid.NewGuid();
|
var repo = Substitute.For<IAuditLogRepository>(); var root = Guid.NewGuid(); var child = Guid.NewGuid();
|
||||||
repo.GetTraceEventsAsync(child, Arg.Any<CancellationToken>(), Arg.Is<IReadOnlyList<string>>(s => s.SequenceEqual(new[] { "42" })))
|
// Code review 2026-12-02 MGT-2: the numeric permitted id "42" reaches the repository
|
||||||
|
// as the site IDENTIFIER AuditLog.SourceSiteId holds, not as "42".
|
||||||
|
repo.GetTraceEventsAsync(child, Arg.Any<CancellationToken>(), Arg.Is<IReadOnlyList<string>>(s => s.SequenceEqual(new[] { "plant-42" })))
|
||||||
.Returns(new ZB.MOM.WW.ScadaBridge.Commons.Types.Audit.TraceEventBatch(root, Array.Empty<AuditEvent>(), true));
|
.Returns(new ZB.MOM.WW.ScadaBridge.Commons.Types.Audit.TraceEventBatch(root, Array.Empty<AuditEvent>(), true));
|
||||||
_services.AddSingleton(repo);
|
_services.AddSingleton(repo);
|
||||||
|
var sites = Substitute.For<ISiteRepository>();
|
||||||
|
sites.GetSiteByIdAsync(42, Arg.Any<CancellationToken>()).Returns(new Site("Plant 42", "plant-42") { Id = 42 });
|
||||||
|
_services.AddSingleton(sites);
|
||||||
var result = await Runner().ReplayAsync(_services.BuildServiceProvider(), new FlowDebugReplayCommand(child), CancellationToken.None,
|
var result = await Runner().ReplayAsync(_services.BuildServiceProvider(), new FlowDebugReplayCommand(child), CancellationToken.None,
|
||||||
new AuthenticatedUser("scoped", "Scoped", new[] { "Viewer" }, new[] { "42" }));
|
new AuthenticatedUser("scoped", "Scoped", new[] { "Viewer" }, new[] { "42" }));
|
||||||
Assert.True(result.Completed); Assert.True(result.Truncated); Assert.Equal(root, result.RootExecutionId);
|
Assert.True(result.Completed); Assert.True(result.Truncated); Assert.Equal(root, result.RootExecutionId);
|
||||||
@@ -618,9 +623,12 @@ public class FlowDebugRunnerTests
|
|||||||
{
|
{
|
||||||
ScadaBridgeAuditEventFactory.Create(AuditChannel.ApiInbound, AuditKind.InboundRequest, AuditStatus.Delivered, executionId: root),
|
ScadaBridgeAuditEventFactory.Create(AuditChannel.ApiInbound, AuditKind.InboundRequest, AuditStatus.Delivered, executionId: root),
|
||||||
};
|
};
|
||||||
repo.GetTraceEventsAsync(root, Arg.Any<CancellationToken>(), Arg.Is<IReadOnlyList<string>>(s => s.SequenceEqual(new[] { "1" })))
|
repo.GetTraceEventsAsync(root, Arg.Any<CancellationToken>(), Arg.Is<IReadOnlyList<string>>(s => s.SequenceEqual(new[] { "site-a" })))
|
||||||
.Returns(new ZB.MOM.WW.ScadaBridge.Commons.Types.Audit.TraceEventBatch(root, rows, false));
|
.Returns(new ZB.MOM.WW.ScadaBridge.Commons.Types.Audit.TraceEventBatch(root, rows, false));
|
||||||
_services.AddSingleton(repo);
|
_services.AddSingleton(repo);
|
||||||
|
var sites = Substitute.For<ISiteRepository>();
|
||||||
|
sites.GetSiteByIdAsync(1, Arg.Any<CancellationToken>()).Returns(new Site("Site A", "site-a") { Id = 1 });
|
||||||
|
_services.AddSingleton(sites);
|
||||||
var scoped = new AuthenticatedUser("ops", "Ops", new[] { "Deployer" }, new[] { "1" });
|
var scoped = new AuthenticatedUser("ops", "Ops", new[] { "Deployer" }, new[] { "1" });
|
||||||
|
|
||||||
var result = await Runner().ReplayAsync(_services.BuildServiceProvider(), new FlowDebugReplayCommand(root), CancellationToken.None, scoped);
|
var result = await Runner().ReplayAsync(_services.BuildServiceProvider(), new FlowDebugReplayCommand(root), CancellationToken.None, scoped);
|
||||||
|
|||||||
Reference in New Issue
Block a user