52da02a76a
Owner decision on #107 (2026-11-13): enabling AuditLog:HashChain must not chain the historical backlog. main chained every unchained row oldest-first. - The first chaining pass on a pristine database (no head, no chained row) writes a chain-start anchor: AuditLogChainTombstone (cutoff month, ChainSeq 0), PurgedAtUtc = DB SYSUTCDATETIME(), RowHash = SHA-256("ScadaBridge.AuditLog.ChainCutoff.v1" || YYYY-MM || ticks). Written once under the exclusive chain lock, so both centrals agree whatever their clocks/config. No migration: existing table + grants. - Only rows with OccurredAtUtc >= cutoff are chained. The anchor hash is the cutoff month's genesis, binding the cutoff into the chain. - AuditLog:HashChain:ChainBacklog (default false) restores chain-everything, read only on the very first enablement. Legacy chains (heads, no anchor) keep chaining everything. - verify-chain splits unchained rows into UnchainedRows vs PreCutoffRows (+ ChainFromUtc); new breaks ChainedBeforeCutoff (row re-dated before the cutoff, or cutoff moved forward) and CutoffAnchorInvalid (anchor hash / month / multiplicity). Archive verify uses the anchor from its own tombstone file or the DB. - Partition switch-out keeps the anchor (deletes ChainSeq > 0 only); the head store / export / verify-heads tombstone count excludes it. - CLI verify-chain table prints Chain from + Pre-cutoff rows. Tests: AuditLogHashChainCutoffTests (7, MSSQL), 6 verifier unit tests, service/CLI/management wire tests; 9 mutations all killed. Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
126 lines
5.9 KiB
C#
126 lines
5.9 KiB
C#
using System.Text.Json;
|
|
using Akka.Actor;
|
|
using Akka.TestKit.Xunit2;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using NSubstitute;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
|
|
|
|
/// <summary>
|
|
/// The <c>VerifyAuditChain</c> management command (ScadaBridge#41): role gate, month
|
|
/// parsing, site-scope refusal, and the verification result reaching the wire with its
|
|
/// enums as names.
|
|
/// </summary>
|
|
public class VerifyAuditChainCommandTests : TestKit
|
|
{
|
|
private readonly IAuditLogHashChain _chain = Substitute.For<IAuditLogHashChain>();
|
|
|
|
private IActorRef CreateActor()
|
|
{
|
|
var services = new ServiceCollection().AddTestConfigurationTransaction();
|
|
services.AddScoped(_ => _chain);
|
|
return Sys.ActorOf(Props.Create(() => new ManagementActor(
|
|
services.BuildServiceProvider(), NullLogger<ManagementActor>.Instance)));
|
|
}
|
|
|
|
private static ManagementEnvelope Envelope(object command, string[] sites, params string[] roles) =>
|
|
new(new AuthenticatedUser("u", "U", roles, sites), command, Guid.NewGuid().ToString("N"));
|
|
|
|
/// <summary>A Viewer gets the verifier's result for the requested month, enums as names.</summary>
|
|
[Fact]
|
|
public void Viewer_GetsVerificationResult_ForTheRequestedMonth()
|
|
{
|
|
var brk = new AuditChainBreak("2026-05", 7, Guid.Parse("11111111-2222-3333-4444-555555555555"),
|
|
AuditChainBreakKind.HashMismatch, "edited");
|
|
_chain.VerifyMonthAsync(Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
|
|
.Returns(new AuditChainVerificationResult("2026-05", AuditChainStatus.Broken, 6, 0, null, 43, 2, brk));
|
|
|
|
CreateActor().Tell(Envelope(new VerifyAuditChainCommand("2026-05"), [], "Viewer"));
|
|
|
|
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
|
using var json = JsonDocument.Parse(response.JsonData);
|
|
Assert.Equal("Broken", json.RootElement.GetProperty("status").GetString());
|
|
Assert.Equal("HashMismatch", json.RootElement.GetProperty("firstBreak").GetProperty("kind").GetString());
|
|
Assert.Equal(7, json.RootElement.GetProperty("firstBreak").GetProperty("chainSeq").GetInt64());
|
|
_chain.Received(1).VerifyMonthAsync(
|
|
new DateTime(2026, 5, 1, 0, 0, 0, DateTimeKind.Utc), Arg.Any<CancellationToken>());
|
|
}
|
|
|
|
/// <summary>
|
|
/// ScadaBridge#139: the cutoff, the pre-cutoff row count and the new break kinds reach the
|
|
/// wire (the CLI renders them; the kinds as names like every other kind).
|
|
/// </summary>
|
|
[Fact]
|
|
public void CutoffFields_AndCutoffBreakKind_ReachTheWire()
|
|
{
|
|
var chainFrom = new DateTime(2026, 11, 13, 9, 30, 0, DateTimeKind.Utc);
|
|
var brk = new AuditChainBreak("2026-11", 4, Guid.NewGuid(), AuditChainBreakKind.ChainedBeforeCutoff, "moved back");
|
|
_chain.VerifyMonthAsync(Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
|
|
.Returns(new AuditChainVerificationResult("2026-11", AuditChainStatus.Broken, 3, 0, null, 9, 0, brk, 3441, chainFrom));
|
|
|
|
CreateActor().Tell(Envelope(new VerifyAuditChainCommand("2026-11"), [], "Viewer"));
|
|
|
|
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
|
using var json = JsonDocument.Parse(response.JsonData);
|
|
Assert.Equal(3441, json.RootElement.GetProperty("preCutoffRows").GetInt64());
|
|
Assert.Equal(chainFrom, json.RootElement.GetProperty("chainFromUtc").GetDateTime().ToUniversalTime());
|
|
Assert.Equal("ChainedBeforeCutoff", json.RootElement.GetProperty("firstBreak").GetProperty("kind").GetString());
|
|
}
|
|
|
|
/// <summary>A Designer/Deployer without an OperationalAudit role is refused.</summary>
|
|
[Fact]
|
|
public void NonAuditRole_IsUnauthorized()
|
|
{
|
|
CreateActor().Tell(Envelope(new VerifyAuditChainCommand("2026-05"), [], "Designer", "Deployer"));
|
|
|
|
ExpectMsg<ManagementUnauthorized>(TimeSpan.FromSeconds(5));
|
|
_chain.DidNotReceiveWithAnyArgs().VerifyMonthAsync(default, default);
|
|
}
|
|
|
|
/// <summary>A site-scoped Viewer is refused: the chain spans every site.</summary>
|
|
[Fact]
|
|
public void SiteScopedViewer_IsRefused()
|
|
{
|
|
CreateActor().Tell(Envelope(new VerifyAuditChainCommand("2026-05"), ["3"], "Viewer"));
|
|
|
|
var response = ExpectMsg<ManagementUnauthorized>(TimeSpan.FromSeconds(5));
|
|
Assert.Contains("spans every site", response.Message);
|
|
_chain.DidNotReceiveWithAnyArgs().VerifyMonthAsync(default, default);
|
|
}
|
|
|
|
/// <summary>A malformed month is a caller error, not an internal fault.</summary>
|
|
[Fact]
|
|
public void MalformedMonth_IsInvalidArgument()
|
|
{
|
|
CreateActor().Tell(Envelope(new VerifyAuditChainCommand("2026-13"), [], "Administrator"));
|
|
|
|
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
|
|
Assert.Equal("INVALID_ARGUMENT", response.ErrorCode);
|
|
}
|
|
|
|
/// <summary>A verification that cannot get the chain lock surfaces as CHAIN_BUSY.</summary>
|
|
[Fact]
|
|
public void BusyChain_IsChainBusy()
|
|
{
|
|
_chain.VerifyMonthAsync(Arg.Any<DateTime>(), Arg.Any<CancellationToken>())
|
|
.Returns<Task<AuditChainVerificationResult>>(_ => throw new TimeoutException("busy"));
|
|
|
|
CreateActor().Tell(Envelope(new VerifyAuditChainCommand("2026-05"), [], "Administrator"));
|
|
|
|
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
|
|
Assert.Equal("CHAIN_BUSY", response.ErrorCode);
|
|
}
|
|
|
|
/// <summary>Verification runs under the long-running Ask timeout, not the 30 s default.</summary>
|
|
[Fact]
|
|
public void VerifyAuditChain_UsesLongRunningAskTimeout()
|
|
{
|
|
Assert.Equal(TimeSpan.FromMinutes(5),
|
|
ManagementEndpoints.ResolveAskTimeout(new ManagementServiceOptions(), typeof(VerifyAuditChainCommand)));
|
|
}
|
|
}
|