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
156 lines
6.7 KiB
C#
156 lines
6.7 KiB
C#
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Microsoft.Extensions.Options;
|
|
using ZB.MOM.WW.ScadaBridge.AuditLog.Central;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.AuditLog.Tests.Central;
|
|
|
|
/// <summary>
|
|
/// Policy tests for <see cref="AuditLogHashChainService"/> (ScadaBridge#41) over a scripted
|
|
/// <see cref="IAuditLogHashChain"/>: default-off, draining a backlog within the per-tick
|
|
/// cap, yielding to the peer node's lock, and containing failures. The SQL chaining itself
|
|
/// is covered by <c>AuditLogHashChainTests</c> in ConfigurationDatabase.Tests.
|
|
/// </summary>
|
|
public class AuditLogHashChainServiceTests
|
|
{
|
|
private sealed class ScriptedChain(params AuditChainBatchResult[] script) : IAuditLogHashChain
|
|
{
|
|
private int _next;
|
|
public int Calls => _next;
|
|
public Exception? Throw { get; init; }
|
|
|
|
public List<bool> ChainBacklogSeen { get; } = [];
|
|
|
|
public Task<AuditChainBatchResult> ChainPendingAsync(int batchSize, bool chainBacklog = false, CancellationToken ct = default)
|
|
{
|
|
ChainBacklogSeen.Add(chainBacklog);
|
|
if (Throw is not null) throw Throw;
|
|
var i = _next++;
|
|
return Task.FromResult(i < script.Length ? script[i] : new AuditChainBatchResult(0, false));
|
|
}
|
|
|
|
public Task<AuditChainVerificationResult> VerifyMonthAsync(DateTime monthStartUtc, CancellationToken ct = default)
|
|
=> throw new NotSupportedException();
|
|
}
|
|
|
|
private static AuditLogHashChainService Create(IAuditLogHashChain chain, AuditLogHashChainOptions options)
|
|
{
|
|
var services = new ServiceCollection();
|
|
services.AddScoped(_ => chain);
|
|
return new AuditLogHashChainService(
|
|
services.BuildServiceProvider().GetRequiredService<IServiceScopeFactory>(),
|
|
Options.Create(options),
|
|
NullLogger<AuditLogHashChainService>.Instance);
|
|
}
|
|
|
|
/// <summary>The job is off by default and starting it then does nothing.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Disabled_ByDefault_StartsNoLoop()
|
|
{
|
|
var chain = new ScriptedChain(new AuditChainBatchResult(5, false));
|
|
Assert.False(new AuditLogHashChainOptions().Enabled);
|
|
using var service = Create(chain, new AuditLogHashChainOptions());
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
await Task.Delay(50);
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
Assert.Equal(0, chain.Calls);
|
|
}
|
|
|
|
/// <summary>A tick drains batches until one comes back empty.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Tick_DrainsUntilEmpty()
|
|
{
|
|
var chain = new ScriptedChain(
|
|
new AuditChainBatchResult(10, false), new AuditChainBatchResult(10, false), new AuditChainBatchResult(3, false));
|
|
using var service = Create(chain, new AuditLogHashChainOptions { Enabled = true, BatchSize = 10 });
|
|
|
|
Assert.Equal(23, await service.TickAsync(CancellationToken.None));
|
|
Assert.Equal(4, chain.Calls); // the 4th returns 0 and ends the tick
|
|
}
|
|
|
|
/// <summary>
|
|
/// ScadaBridge#139: backlog chaining is off by default (owner decision, #107) and the
|
|
/// option reaches every chaining pass when set.
|
|
/// </summary>
|
|
/// <param name="chainBacklog">The configured value, or null to leave the default.</param>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Theory]
|
|
[InlineData(null)]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public async Task Tick_PassesChainBacklog_DefaultOff(bool? chainBacklog)
|
|
{
|
|
var options = new AuditLogHashChainOptions { Enabled = true };
|
|
if (chainBacklog is { } value)
|
|
{
|
|
options.ChainBacklog = value;
|
|
}
|
|
|
|
var chain = new ScriptedChain(new AuditChainBatchResult(4, false));
|
|
using var service = Create(chain, options);
|
|
|
|
await service.TickAsync(CancellationToken.None);
|
|
|
|
Assert.Equal(2, chain.ChainBacklogSeen.Count);
|
|
Assert.All(chain.ChainBacklogSeen, seen => Assert.Equal(chainBacklog ?? false, seen));
|
|
}
|
|
|
|
/// <summary>The peer node holding the lock ends the tick at once.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Tick_StopsWhenPeerHoldsTheLock()
|
|
{
|
|
var chain = new ScriptedChain(new AuditChainBatchResult(0, LockBusy: true), new AuditChainBatchResult(10, false));
|
|
using var service = Create(chain, new AuditLogHashChainOptions { Enabled = true });
|
|
|
|
Assert.Equal(0, await service.TickAsync(CancellationToken.None));
|
|
Assert.Equal(1, chain.Calls);
|
|
}
|
|
|
|
/// <summary>A backlog yields after MaxBatchesPerTick batches.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Tick_RespectsMaxBatchesPerTick()
|
|
{
|
|
var chain = new ScriptedChain(Enumerable.Repeat(new AuditChainBatchResult(10, false), 50).ToArray());
|
|
using var service = Create(chain, new AuditLogHashChainOptions { Enabled = true, MaxBatchesPerTick = 3 });
|
|
|
|
Assert.Equal(30, await service.TickAsync(CancellationToken.None));
|
|
Assert.Equal(3, chain.Calls);
|
|
}
|
|
|
|
/// <summary>A failing tick is contained (logged), never thrown out of the loop.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Tick_ContainsFailures()
|
|
{
|
|
var chain = new ScriptedChain { Throw = new InvalidOperationException("sql down") };
|
|
using var service = Create(chain, new AuditLogHashChainOptions { Enabled = true });
|
|
|
|
Assert.Equal(0, await service.TickAsync(CancellationToken.None));
|
|
}
|
|
|
|
/// <summary>Invalid tuning fails startup validation.</summary>
|
|
/// <param name="interval">IntervalSeconds.</param>
|
|
/// <param name="batch">BatchSize.</param>
|
|
/// <param name="maxBatches">MaxBatchesPerTick.</param>
|
|
[Theory]
|
|
[InlineData(0, 1000, 100)]
|
|
[InlineData(60, 0, 100)]
|
|
[InlineData(60, 10_001, 100)]
|
|
[InlineData(60, 1000, 0)]
|
|
public void Validator_RejectsInvalidTuning(int interval, int batch, int maxBatches)
|
|
{
|
|
var result = new AuditLogHashChainOptionsValidator().Validate(null,
|
|
new AuditLogHashChainOptions { IntervalSeconds = interval, BatchSize = batch, MaxBatchesPerTick = maxBatches });
|
|
Assert.False(result.Succeeded);
|
|
Assert.True(new AuditLogHashChainOptionsValidator().Validate(null, new AuditLogHashChainOptions()).Succeeded);
|
|
}
|
|
}
|