From 2162fad8e984ebc1b527d1ea781c75934c67712a Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:10:58 -0500 Subject: [PATCH] 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. --- docs/requirements/Component-CentralUI.md | 1 + .../Component-ManagementService.md | 2 +- .../Services/AuditLogQueryService.cs | 45 ++++++- .../Types/Audit/AuditSiteScope.cs | 90 ++++++++++++++ .../AuditEndpoints.cs | 79 ++++++------ .../FlowDebug/FlowDebugRunner.cs | 6 +- .../Services/AuditLogQueryServiceTests.cs | 109 ++++++++++++++++- .../Services/AuditTreeScopeTests.cs | 11 +- .../AuditEndpointsTests.cs | 112 +++++++++++++----- .../FlowDebugRunnerTests.cs | 12 +- 10 files changed, 385 insertions(+), 82 deletions(-) create mode 100644 src/ZB.MOM.WW.ScadaBridge.Commons/Types/Audit/AuditSiteScope.cs diff --git a/docs/requirements/Component-CentralUI.md b/docs/requirements/Component-CentralUI.md index f3fe895b..a1d98b6f 100644 --- a/docs/requirements/Component-CentralUI.md +++ b/docs/requirements/Component-CentralUI.md @@ -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. - **"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. +- **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) - 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. diff --git a/docs/requirements/Component-ManagementService.md b/docs/requirements/Component-ManagementService.md index 97799cd5..d4782044 100644 --- a/docs/requirements/Component-ManagementService.md +++ b/docs/requirements/Component-ManagementService.md @@ -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/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 ` 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). diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Services/AuditLogQueryService.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Services/AuditLogQueryService.cs index 66016414..0c3336ed 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Services/AuditLogQueryService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Services/AuditLogQueryService.cs @@ -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(); + } + var repository = scope.ServiceProvider.GetRequiredService(); - var result = await repository.QueryAsync(filter, effective, ct); + var result = await repository.QueryAsync(scoped, effective, ct); return result.Select(AuditEventView.From).ToList(); } + /// + /// Resolves a caller's audit site scope as site IDENTIFIERS (the values + /// AuditLog.SourceSiteId holds): null for an Administrator or a caller with + /// no SiteId claims. The claims are numeric Site.Id values, so they are + /// translated through (code review 2026-12-02 UI-5/MGT-2). + /// + /// The per-call scope's services. + /// The authenticated caller. + /// Cancellation token. + /// The permitted identifiers, or null when unscoped. + private static async Task?> 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(), siteClaims, isAdministrator, ct); + } + /// public async Task 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); } diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Audit/AuditSiteScope.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Audit/AuditSiteScope.cs new file mode 100644 index 00000000..468d3cf8 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Audit/AuditSiteScope.cs @@ -0,0 +1,90 @@ +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories; + +namespace ZB.MOM.WW.ScadaBridge.Commons.Types.Audit; + +/// +/// Site scoping for audit-log reads (code review 2026-12-02 MGT-2 / UI-5). +/// +/// +/// +/// A caller's permitted sites arrive as numeric Site.Id values rendered as +/// strings (the SiteId claim / AuthenticatedUser.PermittedSiteIds, sourced from +/// SiteScopeRule.SiteId). AuditLog.SourceSiteId holds the site +/// identifier (e.g. site-a). 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. +/// +/// +public static class AuditSiteScope +{ + /// + /// Translates the caller's permitted numeric site ids to site identifiers. + /// + /// Site repository used to look the ids up. + /// The caller's permitted numeric site ids, as strings. + /// Whether the caller holds the Administrator role. + /// Cancellation token. + /// + /// null 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. + /// + public static async Task?> ResolvePermittedSiteIdentifiersAsync( + ISiteRepository sites, + IReadOnlyCollection permittedSiteIds, + bool isAdministrator, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(sites); + ArgumentNullException.ThrowIfNull(permittedSiteIds); + if (isAdministrator || permittedSiteIds.Count == 0) + return null; + + var identifiers = new List(); + 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; + } + + /// + /// Restricts an audit-log query filter to the caller's permitted site identifiers. + /// + /// The caller-supplied filter. + /// + /// From ; null = unscoped. + /// + /// + /// 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). + /// null 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 , + /// which the repository would read as "no site filter". + /// + public static AuditLogQueryFilter? Apply(AuditLogQueryFilter filter, IReadOnlyList? permittedIdentifiers) + { + ArgumentNullException.ThrowIfNull(filter); + if (permittedIdentifiers is null) + return filter; + if (permittedIdentifiers.Count == 0) + return null; + + var permitted = new HashSet(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 }; + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/AuditEndpoints.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/AuditEndpoints.cs index 01c44dce..00dce574 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ManagementService/AuditEndpoints.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/AuditEndpoints.cs @@ -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(); - 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); /// - /// Applies the caller's 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 - /// sourceSiteId 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 null so the caller gets a 403 rather - /// than silently empty results. + /// Resolves the caller's audit site scope: null for an unscoped caller (an + /// Administrator, or no site claims), otherwise the permitted site IDENTIFIERS — the + /// values AuditLog.SourceSiteId holds. PermittedSiteIds are numeric + /// Site.Id values, so they are translated through + /// (code review 2026-12-02 MGT-2; shared helper ). + /// + /// The request context (services + abort token). + /// The authenticated caller. + /// The permitted identifiers, or null when unscoped. + internal static Task?> ResolveScopeAsync(HttpContext context, AuthenticatedUser user) + { + var isAdministrator = user.Roles.Contains("Administrator", StringComparer.OrdinalIgnoreCase); + if (isAdministrator || user.PermittedSiteIds.Length == 0) + return Task.FromResult?>(null); + + return AuditSiteScope.ResolvePermittedSiteIdentifiersAsync( + context.RequestServices.GetRequiredService(), + user.PermittedSiteIds, isAdministrator, context.RequestAborted); + } + + /// + /// Applies the caller's permitted site identifiers (from ) + /// to the audit-log filter. An unscoped caller (null) sees the filter unchanged. + /// A scoped caller has any caller-supplied sourceSiteId 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 null so the caller gets a 403 rather than silently empty — or, worse, + /// unfiltered — results. /// /// The caller-supplied audit-log query filter to scope. - /// The authenticated user whose permitted site IDs constrain the filter. + /// The caller's permitted site identifiers; null = unscoped. /// /// The restricted filter, or null if the caller explicitly asked for /// sites entirely outside their permitted set. /// - 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(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? permittedIdentifiers) + => AuditSiteScope.Apply(filter, permittedIdentifiers); // ───────────────────────────────────────────────────────────────────── // Query-string parsing diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/FlowDebug/FlowDebugRunner.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/FlowDebug/FlowDebugRunner.cs index 24976d3f..6e9af218 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ManagementService/FlowDebug/FlowDebugRunner.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/FlowDebug/FlowDebugRunner.cs @@ -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() - .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, diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Services/AuditLogQueryServiceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Services/AuditLogQueryServiceTests.cs index f0c1a01c..a69b8fbb 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Services/AuditLogQueryServiceTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Services/AuditLogQueryServiceTests.cs @@ -24,6 +24,111 @@ namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Services; /// public class AuditLogQueryServiceTests { + /// A principal with the given role and (numeric) SiteId scope claims. + private static Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider Auth(string role, params string[] siteIds) + { + var claims = new List + { + 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(); + auth.GetAuthenticationStateAsync().Returns(Task.FromResult(state)); + return auth; + } + + /// + /// Builds the production-ctor service over a substitute repository and a site repository + /// that resolves site id N to identifier site-N. + /// + private static (AuditLogQueryService Sut, IAuditLogRepository Repo, ServiceProvider Provider) Scoped( + Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider auth) + { + var repo = Substitute.For(); + repo.QueryAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromResult>(Array.Empty())); + repo.GetExecutionTreeAsync(Arg.Any(), Arg.Any(), Arg.Any?>()) + .Returns(Task.FromResult>(Array.Empty())); + var sites = Substitute.For(); + sites.GetSiteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ci => new ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site($"Site {ci.Arg()}", $"site-{ci.Arg()}") { Id = ci.Arg() }); + var services = new ServiceCollection(); + services.AddScoped(_ => repo); + services.AddScoped(_ => sites); + var provider = services.BuildServiceProvider(); + return (new AuditLogQueryService(provider.GetRequiredService(), EmptyAggregator(), auth), repo, provider); + } + + // ── Code review 2026-12-02 UI-5: the grid applies site scope, by identifier ── + + /// A site-scoped caller's grid query is restricted to their sites' identifiers, before paging. + /// A task that represents the asynchronous operation. + [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(f => f.SourceSiteIds != null + && f.SourceSiteIds.OrderBy(x => x).SequenceEqual(new[] { "site-3", "site-7" }) + && f.Channels!.SequenceEqual(new[] { AuditChannel.ApiOutbound })), + Arg.Any(), Arg.Any()); + } + + /// An explicit site filter outside the caller's scope returns nothing without querying. + /// A task that represents the asynchronous operation. + [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); + } + + /// An Administrator (or a caller without site claims) is unscoped. + /// The caller's role. + /// Comma-separated site claims (may be empty). + /// A task that represents the asynchronous operation. + [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(), Arg.Any()); + } + + /// The execution tree's scope is translated to site identifiers, not passed as raw numeric ids. + /// A task that represents the asynchronous operation. + [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(), + Arg.Is?>(s => s != null && s.SequenceEqual(new[] { "site-3" }))); + } + private static ICentralHealthAggregator EmptyAggregator() { var agg = Substitute.For(); @@ -201,7 +306,7 @@ public class AuditLogQueryServiceTests } var scopeFactory = provider.GetRequiredService(); - 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 }); @@ -238,7 +343,7 @@ public class AuditLogQueryServiceTests await using var provider = services.BuildServiceProvider(); var sut = new AuditLogQueryService( provider.GetRequiredService(), - EmptyAggregator()); + EmptyAggregator(), Auth(ZB.MOM.WW.ScadaBridge.Security.Roles.Viewer)); await sut.QueryAsync(new AuditLogQueryFilter()); await sut.QueryAsync(new AuditLogQueryFilter()); diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Services/AuditTreeScopeTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Services/AuditTreeScopeTests.cs index bf1a8c63..f16f5af7 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Services/AuditTreeScopeTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Services/AuditTreeScopeTests.cs @@ -18,7 +18,12 @@ public class AuditTreeScopeTests public async Task ProductionTreeRead_UsesFreshCallerScope_EveryTime() { var repo = Substitute.For(); - 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(); + sites.GetSiteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ci => new ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site($"Site {ci.Arg()}", $"site-{ci.Arg()}") { Id = ci.Arg() }); + using var provider = new ServiceCollection().AddSingleton(repo).AddSingleton(sites).BuildServiceProvider(); var auth = new ChangingAuth(); var service = new AuditLogQueryService(provider.GetRequiredService(), Substitute.For(), auth); @@ -28,9 +33,9 @@ public class AuditTreeScopeTests auth.Site = "43"; await service.GetExecutionTreeAsync(execution); await repo.Received(1).GetExecutionTreeAsync(execution, Arg.Any(), - Arg.Is?>(x => x != null && x.SequenceEqual(new[] { "42" }))); + Arg.Is?>(x => x != null && x.SequenceEqual(new[] { "site-42" }))); await repo.Received(1).GetExecutionTreeAsync(execution, Arg.Any(), - Arg.Is?>(x => x != null && x.SequenceEqual(new[] { "43" }))); + Arg.Is?>(x => x != null && x.SequenceEqual(new[] { "site-43" }))); } private sealed class ChangingAuth : AuthenticationStateProvider diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/AuditEndpointsTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/AuditEndpointsTests.cs index 2155e718..647633b8 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/AuditEndpointsTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/AuditEndpointsTests.cs @@ -832,18 +832,15 @@ public class AuditEndpointsTests // ApplySiteScope // ───────────────────────────────────────────────────────────────────── - /// Verifies that a system-wide user's filter is returned unchanged by site scoping. + /// Verifies that an unscoped caller's filter is returned unchanged by site scoping. [Fact] - public void ApplySiteScope_SystemWideUser_ReturnsFilterUnchanged() + public void ApplySiteScope_UnscopedCaller_ReturnsFilterUnchanged() { - // Empty PermittedSiteIds is the system-wide signal (Administrator, - // system-wide Deployer, audit roles with no scope rules attached). The - // 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()); + // null permitted identifiers is the unscoped signal (Administrator, or no site + // claims). The filter should pass through with no restriction added. var filter = new AuditLogQueryFilter(SourceSiteIds: new[] { "plant-a" }); - var result = AuditEndpoints.ApplySiteScope(filter, user); + var result = AuditEndpoints.ApplySiteScope(filter, null); Assert.NotNull(result); Assert.Same(filter, result); @@ -856,29 +853,23 @@ public class AuditEndpointsTests // No explicit sourceSiteId from the caller — the helper must restrict // the query to the user's permitted set, otherwise a site-scoped audit // user could read every site's rows. - var user = new ZB.MOM.WW.ScadaBridge.Commons.Messages.Management.AuthenticatedUser( - "alice", "Alice", new[] { "Viewer" }, new[] { "plant-a", "plant-b" }); - var filter = new AuditLogQueryFilter(); - - var result = AuditEndpoints.ApplySiteScope(filter, user); + var result = AuditEndpoints.ApplySiteScope(new AuditLogQueryFilter(), new[] { "plant-a", "plant-b" }); Assert.NotNull(result); Assert.NotNull(result!.SourceSiteIds); Assert.Equal(new[] { "plant-a", "plant-b" }, result.SourceSiteIds!.OrderBy(s => s).ToArray()); } - /// Verifies that an explicit in-scope filter is kept unchanged for a scoped user. + /// Verifies that an explicit in-scope filter is kept for a scoped user (identifiers compare case-insensitively). [Fact] public void ApplySiteScope_ScopedUser_ExplicitInScopeFilter_KeptVerbatim() { - var user = new ZB.MOM.WW.ScadaBridge.Commons.Messages.Management.AuthenticatedUser( - "alice", "Alice", new[] { "Viewer" }, new[] { "plant-a", "plant-b" }); - 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, new[] { "plant-a", "plant-b" }); Assert.NotNull(result); - Assert.Equal(new[] { "plant-a" }, result!.SourceSiteIds); + Assert.Equal(new[] { "Plant-A" }, result!.SourceSiteIds); } /// Verifies that an explicit out-of-scope filter yields null for a scoped user. @@ -887,29 +878,87 @@ public class AuditEndpointsTests { // Caller explicitly asked for a site they cannot see — the helper signals // "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 result = AuditEndpoints.ApplySiteScope(filter, user); - - Assert.Null(result); + Assert.Null(AuditEndpoints.ApplySiteScope(filter, new[] { "plant-a" })); } /// Verifies that a mixed filter is reduced to its in-scope sites for a scoped user. [Fact] 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 result = AuditEndpoints.ApplySiteScope(filter, user); + var result = AuditEndpoints.ApplySiteScope(filter, new[] { "plant-a" }); Assert.NotNull(result); Assert.Equal(new[] { "plant-a" }, result!.SourceSiteIds); } + /// + /// 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. + /// + [Fact] + public void ApplySiteScope_ScopedUser_NoResolvableSite_ReturnsNull() + { + Assert.Null(AuditEndpoints.ApplySiteScope(new AuditLogQueryFilter(), Array.Empty())); + } + + /// + /// Code review 2026-12-02 MGT-2: a scoped caller's NUMERIC permitted ids reach the + /// repository as the site IDENTIFIERS AuditLog.SourceSiteId holds; before the fix + /// the query filtered SourceSiteId IN ('3') and always came back empty. + /// + /// A task that represents the asynchronous operation. + [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(f => f.SourceSiteIds != null && f.SourceSiteIds.SequenceEqual(new[] { "plant-3" })), + Arg.Any(), Arg.Any()); + } + } + + /// + /// An explicit --site 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. + /// + /// A task that represents the asynchronous operation. + [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); + } + } + + /// An Administrator who also carries site claims is unscoped, like every other scope check. + /// A task that represents the asynchronous operation. + [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(f => f.SourceSiteIds == null || f.SourceSiteIds.Count == 0), + Arg.Any(), Arg.Any()); + } + } + // ───────────────────────────────────────────────────────────────────── // /api/audit/tree // ───────────────────────────────────────────────────────────────────── @@ -951,6 +1000,11 @@ public class AuditEndpointsTests services.AddSingleton(repo); services.AddSingleton(ldap); services.AddSingleton(roleMapper); + // Site N resolves to identifier "plant-N" (MGT-2 id → identifier translation). + var sites = Substitute.For(); + sites.GetSiteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(ci => new ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites.Site($"Plant {ci.Arg()}", $"plant-{ci.Arg()}") { Id = ci.Arg() }); + services.AddSingleton(sites); // ManagementAuthenticator now consults the login throttle before the bind. services.AddSingleton(TimeProvider.System); services.AddSingleton>(Options.Create(new SecurityOptions())); @@ -990,8 +1044,10 @@ public class AuditEndpointsTests { var response = await client.SendAsync(Get($"/api/audit/tree?executionId={execution:D}")); 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(), - Arg.Is>(sites => sites.SequenceEqual(new[] { "42" }))); + Arg.Is>(sites => sites.SequenceEqual(new[] { "plant-42" }))); } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/FlowDebugRunnerTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/FlowDebugRunnerTests.cs index c6d24f67..1f39e8f8 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/FlowDebugRunnerTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/FlowDebugRunnerTests.cs @@ -514,9 +514,14 @@ public class FlowDebugRunnerTests public async Task Replay_ThreadsScopeAndRetainsTruncatedRootWithoutRows() { var repo = Substitute.For(); var root = Guid.NewGuid(); var child = Guid.NewGuid(); - repo.GetTraceEventsAsync(child, Arg.Any(), Arg.Is>(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(), Arg.Is>(s => s.SequenceEqual(new[] { "plant-42" }))) .Returns(new ZB.MOM.WW.ScadaBridge.Commons.Types.Audit.TraceEventBatch(root, Array.Empty(), true)); _services.AddSingleton(repo); + var sites = Substitute.For(); + sites.GetSiteByIdAsync(42, Arg.Any()).Returns(new Site("Plant 42", "plant-42") { Id = 42 }); + _services.AddSingleton(sites); var result = await Runner().ReplayAsync(_services.BuildServiceProvider(), new FlowDebugReplayCommand(child), CancellationToken.None, new AuthenticatedUser("scoped", "Scoped", new[] { "Viewer" }, new[] { "42" })); 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), }; - repo.GetTraceEventsAsync(root, Arg.Any(), Arg.Is>(s => s.SequenceEqual(new[] { "1" }))) + repo.GetTraceEventsAsync(root, Arg.Any(), Arg.Is>(s => s.SequenceEqual(new[] { "site-a" }))) .Returns(new ZB.MOM.WW.ScadaBridge.Commons.Types.Audit.TraceEventBatch(root, rows, false)); _services.AddSingleton(repo); + var sites = Substitute.For(); + sites.GetSiteByIdAsync(1, Arg.Any()).Returns(new Site("Site A", "site-a") { Id = 1 }); + _services.AddSingleton(sites); var scoped = new AuthenticatedUser("ops", "Ops", new[] { "Deployer" }, new[] { "1" }); var result = await Runner().ReplayAsync(_services.BuildServiceProvider(), new FlowDebugReplayCommand(root), CancellationToken.None, scoped);