fix(review): full code-review remediation — 5 High + Medium/Low across 16 modules

Remediation from the full per-module code review at 4307c381 (findings recorded
separately in code-reviews/).

Highs fixed:
- DeploymentManager-025/SiteRuntime-031: stop broadcasting notification lists + SMTP
  configs (incl. credentials) to sites; site purges already-persisted rows on apply
  (enforces the central-only delivery design; clears plaintext SMTP creds at rest).
- DataConnectionLayer-023: guard the native-alarm subscribe path against the
  mid-flight-unsubscribe adapter-feed leak (mirrors the DCL-021 tag-path fix).
- SiteEventLogging-024: normalize From/To query bounds to UTC (the -016 fix the
  audit trail claimed but never committed).
- KpiHistory-001: add an in-flight guard to the recorder sample tick.
- ScriptAnalysis-001: harden the trust analyzer's TPA-absent fallback (resolve
  forbidden anchors in the minimal reference set; warn on degraded mode) — anchors
  added to validation references only, never the compile gate.
(InboundAPI-026 left to the feat/ipsen-movein effort per owner decision.)

Medium/Low: DM-026 deterministic deploy-status tiebreaker; SR-027/028/029/030
native-alarm leak/phantom-active/delete-during-redeploy fixes; AL-013/014/016;
TE-024 (folder-mutation audit rows now persisted)/025; SF-025 gauge-provider
clear-on-stop; ESG-025/026; SEC-023/024/025; SCA-007/008/009; plus doc/test
accuracy COM-023/024, HOST-025/026, HM-024/025, NS-027/028.

Full-solution build 0 warnings; ~3560 tests across 18 touched suites green.
This commit is contained in:
Joseph Doherty
2026-06-20 17:55:12 -04:00
parent 4307c38117
commit fd618cf1dc
52 changed files with 2239 additions and 313 deletions
@@ -0,0 +1,117 @@
using Akka.Actor;
using Akka.TestKit.Xunit2;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Security;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
using ZB.MOM.WW.ScadaBridge.Security;
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
/// <summary>
/// Security-023 (membership-validation half): the LDAP-group-mapping <c>Role</c> arrives
/// as a free string over the CLI/Management API. The single server-side write path
/// (<c>ManagementActor.HandleCreateRoleMapping</c> / <c>HandleUpdateRoleMapping</c>) now
/// rejects any role that is not in the canonical <see cref="Roles.All"/> set, returning a
/// <c>COMMAND_FAILED</c> error before any DB write. A non-canonical role never functioned
/// (no authorization policy or ManagementActor check matched it), so rejecting it removes
/// a silent-misconfiguration footgun rather than changing behaviour.
/// </summary>
/// <remarks>
/// Per Security-023's scope: only the membership check is added. The pre-existing
/// case-sensitivity asymmetry (case-sensitive UI <c>RequireClaim</c> vs case-insensitive
/// ManagementActor authz) is a separately-deferred change and is NOT touched — the
/// membership check accepts a correctly-cased canonical role and stores it verbatim.
/// </remarks>
public class RoleMappingValidationTests : TestKit, IDisposable
{
private readonly ISecurityRepository _securityRepo;
private readonly IAuditService _auditService;
private readonly ServiceCollection _services;
public RoleMappingValidationTests()
{
_securityRepo = Substitute.For<ISecurityRepository>();
_auditService = Substitute.For<IAuditService>();
_services = new ServiceCollection();
_services.AddScoped(_ => _securityRepo);
_services.AddScoped(_ => _auditService);
}
private IActorRef CreateActor()
{
var sp = _services.BuildServiceProvider();
return Sys.ActorOf(Props.Create(() => new ManagementActor(
sp, NullLogger<ManagementActor>.Instance)));
}
// CreateRoleMappingCommand / UpdateRoleMappingCommand both require Administrator
// (see ManagementActor.GetRequiredRole), so the test principal carries that role.
private static ManagementEnvelope Envelope(object command) =>
new(new AuthenticatedUser("admin", "admin", new[] { Roles.Administrator }, Array.Empty<string>()),
command, Guid.NewGuid().ToString("N"));
void IDisposable.Dispose() => Shutdown();
[Fact]
public void CreateRoleMapping_UnknownRole_ReturnsError_NoRowInserted()
{
var actor = CreateActor();
actor.Tell(Envelope(new CreateRoleMappingCommand("SCADA-Admins", "Wizard")));
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
Assert.Equal("COMMAND_FAILED", response.ErrorCode);
Assert.Contains("Wizard", response.Error);
_securityRepo.DidNotReceiveWithAnyArgs().AddMappingAsync(default!, default);
}
[Fact]
public void CreateRoleMapping_MisspelledCanonicalRole_ReturnsError_NoRowInserted()
{
// A pure typo of a real role ("Deploer" for "Deployer") is exactly the silent
// footgun Security-023 describes: it would stamp a role claim no policy matches.
var actor = CreateActor();
actor.Tell(Envelope(new CreateRoleMappingCommand("SCADA-Deploy", "Deploer")));
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
Assert.Equal("COMMAND_FAILED", response.ErrorCode);
_securityRepo.DidNotReceiveWithAnyArgs().AddMappingAsync(default!, default);
}
[Fact]
public void UpdateRoleMapping_UnknownRole_ReturnsError_NoRowUpdated()
{
var actor = CreateActor();
actor.Tell(Envelope(new UpdateRoleMappingCommand(7, "SCADA-Admins", "Wizard")));
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
Assert.Equal("COMMAND_FAILED", response.ErrorCode);
Assert.Contains("Wizard", response.Error);
// Rejected before the mapping is even looked up.
_securityRepo.DidNotReceiveWithAnyArgs().GetMappingByIdAsync(default, default);
_securityRepo.DidNotReceiveWithAnyArgs().UpdateMappingAsync(default!, default);
}
[Fact]
public void CreateRoleMapping_CanonicalRole_Succeeds_RowInserted()
{
LdapGroupMapping? inserted = null;
_securityRepo
.When(r => r.AddMappingAsync(Arg.Any<LdapGroupMapping>(), Arg.Any<CancellationToken>()))
.Do(ci => inserted = ci.Arg<LdapGroupMapping>());
var actor = CreateActor();
actor.Tell(Envelope(new CreateRoleMappingCommand("SCADA-Deploy", Roles.Deployer)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
Assert.NotNull(inserted);
// Membership check does not alter the stored value's casing (case-sensitivity
// asymmetry is a separately-deferred change).
Assert.Equal(Roles.Deployer, inserted!.Role);
Assert.Equal("SCADA-Deploy", inserted.LdapGroupName);
}
}